Skip to content

[PyTorch][common] Support row-scaled NVFP4 in GroupedLinear - #3776

Open
cael-ling wants to merge 14 commits into
NVIDIA:mainfrom
cael-ling:pr/nvfp4-row-scaled-grouped-linear
Open

cael-ling wants to merge 14 commits into
NVIDIA:mainfrom
cael-ling:pr/nvfp4-row-scaled-grouped-linear

Conversation

@cael-ling

@cael-ling cael-ling commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR enables row-scaled NVFP4 forward and backward in GroupedLinear (row_scaled_activation=True), with the same RHT and stochastic rounding defaults as per-tensor NVFP4. It also adds row-scaled NVFP4 weights (row_scaled_weight=True) for Linear, LayerNormLinear, LayerNormMLP and GroupedLinear.

Changes

  • Grouped row-scaled NVFP4 quantization supports stochastic rounding and RHT on the column-wise output, so grad_output can be row-scaled when backward is quantized.
  • Add row_scaled_weight to NVFP4BlockScaling (NVTE_NVFP4_ROW_SCALED_WEIGHT): 1x16 weight blocks with one global scale per output channel for fprop and per input channel for dgrad.
  • GroupedLinear grouped-tensor path supports row-scaled activations and weights.
  • When use_grouped_tensor is not set, row-scaled NVFP4 recipes default to the grouped-tensor path if it is supported and its 128 alignment can be confirmed without a device synchronization. The split-quantize path quantizes row-scaled inputs one split at a time, so it is much slower for these recipes. Explicit use_grouped_tensor=True/False and the environment variable keep their existing behavior.
  • In general_grouped_gemm, row-scaled NVFP4 groups run as one tensor-scaled grouped GEMM into FP32 buffers, followed by the row/column global scales and bias. Results match per-group general_gemm bit for bit. GELU, bias gradient, output quantization, and non-NVFP4 operands still call general_gemm per group.
  • single_grouped_weight with NVFP4 weights without RHT raises NotImplementedError up front, instead of failing inside tex.group_quantize (whose non-RHT NVFP4 grouped kernel is not available).
  • te.ops.GroupedLinear raises NotImplementedError for row_scaled_activation and row_scaled_weight.

Supported configurations

Row-scaled activations are enabled with NVFP4BlockScaling(row_scaled_activation=True) (or NVTE_NVFP4_ROW_SCALED_ACTIVATION=1). When backward is quantized, grad_output follows the forward scaling mode.

Forward (activations) Backward: quantized (backward_override=None) Backward: high_precision Backward: dequantized
Per-tensor NVFP4 (default) Per-tensor NVFP4 BF16 BF16
Row-scaled NVFP4 Row-scaled NVFP4 (new in this PR) BF16 BF16

Weight scaling is selected independently of the activation scaling:

Weight scaling How to enable Global scale Block scales
Per-tensor 2D (default) Default One per tensor 16x16
Per-tensor 1D disable_2d_quantization=True (or NVTE_NVFP4_DISABLE_2D_QUANTIZATION=1) One per tensor 1x16
Row-scaled 1D (new in this PR) row_scaled_weight=True (or NVTE_NVFP4_ROW_SCALED_WEIGHT=1) One per output channel (fprop) and one per input channel (dgrad) 1x16

Row-scaled weights require BF16 weights with both dimensions divisible by 32. They do not support 4over6 on weights or quantized primary weights (quantized_model_init).

Options that can be combined with the configurations above:

Option Default Applies to Notes
RHT (disable_rht) On Column-wise input and grad_output (wgrad) Incompatible with 4over6 on activations
Stochastic rounding (disable_stochastic_rounding) On grad_output Now also supported by grouped row-scaled quantization
4over6 (nvfp4_4over6) none Forward tensors only (weights, activations, all); never gradients Requires RHT off when activations are included; incompatible with UE5M3 scales; weights/all is incompatible with row_scaled_weight

Module support for row-scaled NVFP4

Module / path Supported Notes
Linear, LayerNormLinear, LayerNormMLP Yes
GroupedLinear, grouped-tensor path Yes Requires SM100+, cuBLASLt 13.4+ and E4M3 scales. Row-scaled activations also require 4over6 none; per-tensor activations still require RHT. Discrete weights only. Default for row-scaled activations when use_grouped_tensor is unset (see below)
GroupedLinear, split-quantize path Yes All options above. Quantization runs per split; GEMMs run as one grouped GEMM
te.ops.GroupedLinear No Raises NotImplementedError
Sequence parallelism, Userbuffers overlap No

Testing

  • Unit tests on GB200 (cuBLASLt 13.8), all passing:
    • test_grouped_linear.py (whole file), including automatic path selection (selected for aligned shapes and bit-exact with explicit use_grouped_tensor=True; not selected for unaligned shapes or 4over6) and row-scaled quantized backward against per-expert Linear.
    • test_nvfp4_gemm_exact.py -k row_scaled, including row-scaled general_grouped_gemm matching per-group general_gemm with zero tolerance for single and list outputs, bias, FP32/BF16 outputs, 4over6, and row-scaled activations, weights, or both.
    • test_cuda_graphs.py -k "RowScaled or grouped_linear", including a new GroupedLinear test with host m_splits that captures the row-scaled grouped GEMM and matches eager results exactly.
    • test_nvfp4_group_row_scaled_quantize.py, test_nvfp4_sr_quantize.py, test_nvfp4_rht_quantize_exact.py, test_nvfp4_module_exact.py, test_recipe.py -k row_scaled, test_sanity.py -k nvfp4.
  • Row-scaled weights: grouped GEMM (split-quantize and grouped-tensor paths, fprop and dgrad) matches per-expert GEMM; Linear/LayerNormLinear forward and backward match the NVFP4 reference; error is no worse than per-tensor for Linear, LayerNormLinear, LayerNormMLP and both GroupedLinear paths.
  • Row-scaled general_grouped_gemm on the split-quantize path (BF16 output, 8–32 experts): 2.6–4.0x faster than per-group GEMMs.
  • Megatron-Core MoE (64 experts, top-8, seq 4096) with row-scaled activations, unmodified Megatron-Core: loss and step time match per-tensor NVFP4. DP=4 x EP=2 matches the single-GPU curve. Row-scaled weights have not been evaluated end to end yet.

Checklist:

  • I have read and followed the contributing guidelines
  • The functionality is complete
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

@github-actions github-actions Bot added the community-contribution PRs from external contributor outside the core maintainers, representing community-driven work. label Oct 29, 2026
@greptile-apps

greptile-apps Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5 · The PR still needs the previously reported fix for groups with different bias widths before merging.RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The changes affect opt-in NVFP4 quantization and grouped linear workflows.

The PR still needs the previously reported fix for groups with different bias widths before merging.

Findings

  1. P1 Different bias widths fail. ▶

Summary

Adds row-scaled NVFP4 weights and quantized backward support for GroupedLinear.

  • GroupedLinear carries row-scaled NVFP4 through forward and quantized backward.
  • Supported linear modules can use row-scaled NVFP4 weights.
  • Grouped GEMM applies row-scaled NVFP4 operand scales to its results.

Reviews (5) · Last reviewed commit: "Document that row-scaled NVFP4 weights s..." · Reviewed by Greptile

@cael-ling cael-ling closed this Oct 30, 2026
@cael-ling cael-ling reopened this Oct 30, 2026
@cael-ling
cael-ling marked this pull request as draft October 30, 2026 01:53
cael-ling and others added 5 commits November 9, 2026 17:37
Enable row-scaled NVFP4 forward and backward in GroupedLinear with
stochastic rounding, columnwise RHT and bias. Row-scaled recipes use the
grouped-tensor path by default; te.ops.GroupedLinear rejects them.

Signed-off-by: Cael Ling <caell@nvidia.com>
Keep the split-quantize path for shapes the grouped-tensor path cannot
handle, keep rowwise grad-output usage for weight-only backward, and leave
spare output capacity rows untouched in the row-scaled grouped GEMM.

Signed-off-by: Cael Ling <caell@nvidia.com>
Add NVFP4BlockScaling(row_scaled_weight=True) (NVTE_NVFP4_ROW_SCALED_WEIGHT=1)
so weights can use per-row/per-column global amax with 1x16 block scales.
Weights can now be quantized as row-scaled 1D, per-tensor 2D (default), or
per-tensor 1D (disable_2d_quantization=True), independent of
row_scaled_activation. Row-scaled weights require BF16 weights with both
dimensions divisible by 32.

- Apply the weight amax vectors as output column scales in the legacy
  single-output grouped GEMM and in grouped-tensor GEMM with discrete weights.
- Reject 4over6 on row-scaled weights and quantized primary weights.
- Also reject row_scaled_weight in te.ops.GroupedLinear and skip the fused
  grouped MLP for it.
- Use the weight columnwise amax for DGRAD in the NVFP4 reference GEMM.
- Update the backward grad_output expectation in the row-scaled recipe test.

Signed-off-by: Cael Ling <caell@nvidia.com>
Row-scaled NVFP4 GroupedLinear now uses the native grouped tensor path
only when requested with use_grouped_tensor=True. Remove the automatic
path switch and the legacy general_grouped_gemm row-scaled fast path;
the legacy path falls back to per-GEMM general_gemm calls.

Signed-off-by: Cael Ling <caell@nvidia.com>
@cael-ling
cael-ling force-pushed the pr/nvfp4-row-scaled-grouped-linear branch from a4710f5 to 183f82d Compare November 10, 2026 09:52
Run row-scaled NVFP4 groups as one tensor-scaled grouped GEMM into FP32
buffers and apply the row/column global scales and bias afterwards,
matching per-group general_gemm results. Configurations with GELU,
bias gradient, output quantization, or non-NVFP4 operands still call
general_gemm per group.

Signed-off-by: Cael Ling <caell@nvidia.com>
@cael-ling cael-ling mentioned this pull request Nov 11, 2026
1 of 13 tasks
The split-quantize path quantizes row-scaled NVFP4 inputs one split at a
time. When the caller does not set use_grouped_tensor, use the native
grouped tensor path for row-scaled NVFP4 recipes if it is supported and
the 128 alignment of the feature dimensions, token count, and host
m_splits can be confirmed without a device synchronization. Host
m_splits are copied to the device outside CUDA Graph capture.

Signed-off-by: Cael Ling <caell@nvidia.com>
@cael-ling
cael-ling marked this pull request as ready for review November 11, 2026 10:41
Comment on lines +112 to +114
* For row-scaled NVFP4 output, the row-wise amax is per row of the input and the column-wise
* amax is per column of the transposed RHT output; random_sign_mask must be 0.
*

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • This is mangling the Doxygen formatting.
  • Describing the amax shape requirements is not really relevant since they apply to any NVTETensor or NVTEGroupedTensor in row-scaled NVFP4 format and aren't specific to this function.
  • The handling of random_sign_mask is confused since random_sign_mask=0 corresponds to the default Hadamard transform, not to no Hadamard transform. This is a general problem with this API, but row-scaled NVFP4 shouldn't imply it's doing something special.
Suggested change
* For row-scaled NVFP4 output, the row-wise amax is per row of the input and the column-wise
* amax is per column of the transposed RHT output; random_sign_mask must be 0.
*

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, I'll remove the paragraph. The amax shape is a property of the row-scaled format rather than of this function.

Comment on lines +172 to +174
* For row-scaled NVFP4 output, the row-wise data is quantized without RHT using per-row amax,
* the column-wise data uses RHT with per-column amax, and quant_workspace may be null.
*

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mangling Doxygen formatting.

Suggested change
* For row-scaled NVFP4 output, the row-wise data is quantized without RHT using per-row amax,
* the column-wise data uses RHT with per-column amax, and quant_workspace may be null.
*

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, I'll remove it.

Comment on lines +195 to +203
#pragma unroll
for (int c = 0; c < SCALE_DIM; ++c) {
float acc = 0.0f;
#pragma unroll
for (int r = 0; r < SCALE_DIM; ++r) {
acc = fmaf(x[r], rht_matrix[r * SCALE_DIM + c], acc);
}
v[c] = static_cast<IType>(acc);
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Beyond the scope of this PR, but this could be optimized by performing the matmul with a WMMA instruction (like other RHT kernels) or changing to a butterfly Hadamard transform (avoids need for instantiating RHT matrix).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, agreed it's out of scope here

Comment on lines +589 to +592
If set to `True`, weight quantizers emit row-scaled NVFP4 tensors
with 1D (1x16) block scales, i.e. one global scale per output
channel for the forward GEMM and per input channel for the dgrad
GEMM. Weight 2D quantization is disabled in this mode. If `False`,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Weight 2D quantization is disabled in this mode.

This implies that it's valid for the user to enable row-scaled weights and 2D weights together, and that we will silently disable 2D weights. Better to say the combination is not supported and to error out in that case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. I plan to document that row-scaled weights require disable_2d_quantization=True, and assert in post_init when both are enabled.

Comment on lines +589 to +595
If set to `True`, weight quantizers emit row-scaled NVFP4 tensors
with 1D (1x16) block scales, i.e. one global scale per output
channel for the forward GEMM and per input channel for the dgrad
GEMM. Weight 2D quantization is disabled in this mode. If `False`,
weights use a single per-tensor global scale with 16x16 (2D)
block scales, or 1x16 (1D) block scales when
``disable_2d_quantization=True``. Row-scaled weights require BF16

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Too much unnecessary detail. This is reexplaining basic things about NVFP4, when the row scaling is the important thing.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll trim it to what row scaling changes.

Comment thread tests/pytorch/test_grouped_linear.py Outdated


@pytest.mark.skipif(not _nvfp4_available, reason=_reason_for_no_nvfp4)
def test_op_grouped_linear_rejects_row_scaled_nvfp4():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't want to maintain this contract.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll remove it.

Comment thread tests/pytorch/test_grouped_linear.py Outdated

@pytest.mark.skipif(not _nvfp4_available, reason=_reason_for_no_nvfp4)
@pytest.mark.parametrize("bias", _ALL_BOOLEAN)
def test_grouped_linear_row_scaled_nvfp4_selects_grouped_tensor_path(bias, monkeypatch):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't make this specific to row-scaled NVFP4. Make it general or remove it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll remove it, since the auto-selection it tested is going away.

Comment on lines +254 to +255
if row_scaled:
pytest.skip("Row-scaled NVFP4 quantization requires rowwise usage")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should remove this requirement.

Suggested change
if row_scaled:
pytest.skip("Row-scaled NVFP4 quantization requires rowwise usage")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Once the kernels handle rowwise_usage=False, I'll remove this skip.

Comment on lines +188 to +189
use_tex_split_quantize (bool): Toggle method. If True, use tex.split_quantize (or
tex.group_quantize for row-scaled), else use manual split and per-quantizer invocation.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a landmine. The honest thing is to admit we don't support tex.split_quantize for row-scaled NVFP4. This helper function should error out if use_tex_split_quantize=True and row_scaled=True, and we should skip that case in test_group_stochastic_rounding_quantization_versus_reference.

def test_group_stochastic_rounding_quantization_versus_reference(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, the silent switch was misleading. I'll make the helper raise for use_tex_split_quantize=True with row_scaled=True and skip that case.

amax_list.append(row_amaxes(x_nvfp4_sut))

return qx_list, sx_list, qx_t_list, sx_t_list
return qx_list, sx_list, qx_t_list, sx_t_list, amax_list

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's confusing that we're returning row amaxes even with tensor-scaled NVFP4. For the sake of logical consistency, it would be nicer to return the tensor amax if row_scaled=False and the row amaxes if row_scaled=True. Concentrating the row-scale NVFP4 logic into this function also means that callers don't need special logic to distinguish between tensor amaxes and row amaxes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense. I'll return the tensor amax when row_scaled=False and the row amaxes when row_scaled=True, so callers don't need to branch.

Signed-off-by: Tim Moon <4406448+timmoon10@users.noreply.github.com>
@timmoon10

Copy link
Copy Markdown
Member

/te-ci

torch._foreach_mul_(fp32_out, row_scales)
torch._foreach_mul_(fp32_out, col_scales)
if bias is not None:
torch._foreach_add_(fp32_out, list(torch.stack(bias).to(dtype=torch.float32)))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Different bias widths fail. With single_output=False, general_grouped_gemm supports groups with different output widths. For example, groups producing 128 and 256 columns need bias vectors of those respective lengths. The new row-scaled path calls torch.stack(bias), which raises because their sizes differ. The previous per-group general_gemm calls accepted them.

Convert each bias separately before passing the list to torch._foreach_add_, rather than stacking them.

Suggested change
torch._foreach_add_(fp32_out, list(torch.stack(bias).to(dtype=torch.float32)))
torch._foreach_add_(fp32_out, [b.to(dtype=torch.float32) for b in bias])

- Error out when row-scaled weights are combined with 2D quantization
  instead of silently disabling 2D quantization.
- Apply row_scaled_activation to the grad_input quantizer as well.
- Respect use_grouped_tensor in GroupedLinear instead of auto-selecting
  the grouped tensor path for row-scaled NVFP4, and require CUDA
  m_splits on that path for every recipe.
- Remove contract tests the module should not maintain, and make the SR
  test helper reject tex.split_quantize with row-scaled NVFP4.
- Trim recipe, envvar and Hadamard API docs.
- Restore the get_cached_ones_tensor import lost in the main merge.

Signed-off-by: Cael Ling <caell@nvidia.com>
- Allow row-scaled NVFP4 quantizers to allocate columnwise-only outputs
  for single, grouped and bulk-allocated tensors.
- Add a RETURN_ROWWISE switch to the graph-safe grouped row-scaled cast
  kernel so the RHT and non-RHT grouped paths can skip the rowwise output.
- Stop forcing rowwise grad_output usage in GroupedLinear when dgrad is
  not required.
- Add columnwise-only cases to the grouped row-scaled cast C++ and
  PyTorch tests.

Signed-off-by: Cael Ling <caell@nvidia.com>
- Add a RETURN_ROWWISE switch to the tuned 1D NVFP4 quantize kernel so
  row-scaled quantization can skip the rowwise output.
- Compute only the amaxes of the requested directions and route
  columnwise-only row-scaled quantization to the optimized kernel.
- Allow columnwise-only usage in the row-scaled NVFP4 reference quantizer
  and in wgrad input reconstruction from the original input.
- Remove the columnwise-only row-scaled test skips and add a C++ test
  comparing columnwise-only output with the both-directions output.

Signed-off-by: Cael Ling <caell@nvidia.com>
- Remove the check that rejected quantized primary weights for row-scaled
  NVFP4 weight quantizers. Quantized initialization and training already
  work; only quantize_master_weights is unsupported, and it already
  rejects NVFP4 weights without 2D quantization.
- Add a test comparing row-scaled primary weights against a module with
  the same high-precision weights, and checking that
  quantize_master_weights still raises.

Signed-off-by: Cael Ling <caell@nvidia.com>
- Make the nvfp4_row_scaled test recipe enable RHT, row-scaled activations
  and weights, and the default quantized backward, and use it across the
  numerics, sanity, CUDA graph, grouped linear and backward override tests.
- Drop the dedicated row-scaled quantized backward tests and special cases
  now covered by the general tests.
- Skip non-BF16 inputs for RHT recipes and require 128-aligned K for grouped
  row-scaled activations.
- Fix the error message for NVFP4 single grouped weights with high-precision
  weights, which is unsupported regardless of RHT.

Signed-off-by: Cael Ling <caell@nvidia.com>
Quantized primary weights work with row-scaled NVFP4 weights; only casting master weights with quantize_master_weights is unsupported.

Signed-off-by: Cael Ling <caell@nvidia.com>
@cael-ling

Copy link
Copy Markdown
Contributor Author

Hi @timmoon10, thanks for the review. I've pushed an update addressing your comments and reviewed each single code of the fix for each one.

Change highlights:

  • The row-scaled quantize kernels (grouped and single-tensor) now respect rowwise_usage=False, so the special cases in the module code are gone.
  • Quantized primary weights now work with row-scaled weights. Only quantize_master_weights is still unsupported, because its NVFP4 path is 2D-only.
  • The row-scaled test recipe now matches the target use case and runs through the general tests. The dedicated tests and files are removed.

Open items:

  • te.ops.GroupedLinear support: whether to do it in this PR or as a follow-up (asked in the thread).
  • NVFP4 single grouped weights with quantized primary weights fail with "scales must be swizzled". This also happens on main for all NVFP4 recipes, so I'd do it in a follow-up.

Please take a look when you get a chance.

@cael-ling
cael-ling requested a review from timmoon10 November 27, 2026 03:38

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution PRs from external contributor outside the core maintainers, representing community-driven work.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants