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 +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 thread tests/pytorch/test_grouped_linear.py Resolved
Comment thread tests/pytorch/test_grouped_linear.py Resolved
Signed-off-by: Tim Moon <4406448+timmoon10@users.noreply.github.com>
@timmoon10

Copy link
Copy Markdown
Member

/te-ci

- 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

@timmoon10 timmoon10 left a comment

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.

Overall LGTM, pending CI.

Comment on lines +1455 to +1459
if isinstance(weight_quantizer, NVFP4Quantizer):
raise NotImplementedError(
"single_grouped_weight with high-precision weights is not supported for "
"NVFP4; use per-expert weights."
)

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.

Why is this path not supported? We are just calling tex.group_quantize, which supports both tensor-scaled NVFP4 and row-scaled NVFP4. If it's easy, it would be nice to get rid of this check:

Suggested change
if isinstance(weight_quantizer, NVFP4Quantizer):
raise NotImplementedError(
"single_grouped_weight with high-precision weights is not supported for "
"NVFP4; use per-expert weights."
)

@timmoon10

Copy link
Copy Markdown
Member

/te-ci

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