Repository navigation
Conversation
[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
SummaryAdds row-scaled NVFP4 weights and quantized backward support for
Reviews (5) · Last reviewed commit: "Document that row-scaled NVFP4 weights s..." · Reviewed by Greptile |
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>
for more information, see https://pre-commit.ci
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>
a4710f5 to
183f82d
Compare
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>
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>
| * 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. | ||
| * |
There was a problem hiding this comment.
- This is mangling the Doxygen formatting.
- Describing the amax shape requirements is not really relevant since they apply to any
NVTETensororNVTEGroupedTensorin row-scaled NVFP4 format and aren't specific to this function. - The handling of
random_sign_maskis confused sincerandom_sign_mask=0corresponds 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.
| * 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. | |
| * |
There was a problem hiding this comment.
Agreed, I'll remove the paragraph. The amax shape is a property of the row-scaled format rather than of this function.
| * 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. | ||
| * |
There was a problem hiding this comment.
Mangling Doxygen formatting.
| * 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. | |
| * |
There was a problem hiding this comment.
Agreed, I'll remove it.
| #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); | ||
| } |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
Thanks, agreed it's out of scope here
| 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`, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Agreed. I plan to document that row-scaled weights require disable_2d_quantization=True, and assert in post_init when both are enabled.
| 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 |
There was a problem hiding this comment.
Nit: Too much unnecessary detail. This is reexplaining basic things about NVFP4, when the row scaling is the important thing.
There was a problem hiding this comment.
I'll trim it to what row scaling changes.
|
|
||
|
|
||
| @pytest.mark.skipif(not _nvfp4_available, reason=_reason_for_no_nvfp4) | ||
| def test_op_grouped_linear_rejects_row_scaled_nvfp4(): |
There was a problem hiding this comment.
We don't want to maintain this contract.
|
|
||
| @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): |
There was a problem hiding this comment.
Don't make this specific to row-scaled NVFP4. Make it general or remove it.
There was a problem hiding this comment.
I'll remove it, since the auto-selection it tested is going away.
| if row_scaled: | ||
| pytest.skip("Row-scaled NVFP4 quantization requires rowwise usage") |
There was a problem hiding this comment.
We should remove this requirement.
| if row_scaled: | |
| pytest.skip("Row-scaled NVFP4 quantization requires rowwise usage") |
There was a problem hiding this comment.
Agreed. Once the kernels handle rowwise_usage=False, I'll remove this skip.
| 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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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>
|
/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))) |
There was a problem hiding this comment.
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.
| 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>
|
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:
Open items:
Please take a look when you get a chance. |
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) forLinear,LayerNormLinear,LayerNormMLPandGroupedLinear.Changes
grad_outputcan be row-scaled when backward is quantized.row_scaled_weighttoNVFP4BlockScaling(NVTE_NVFP4_ROW_SCALED_WEIGHT): 1x16 weight blocks with one global scale per output channel for fprop and per input channel for dgrad.GroupedLineargrouped-tensor path supports row-scaled activations and weights.use_grouped_tensoris 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. Explicituse_grouped_tensor=True/Falseand the environment variable keep their existing behavior.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-groupgeneral_gemmbit for bit. GELU, bias gradient, output quantization, and non-NVFP4 operands still callgeneral_gemmper group.single_grouped_weightwith NVFP4 weights without RHT raisesNotImplementedErrorup front, instead of failing insidetex.group_quantize(whose non-RHT NVFP4 grouped kernel is not available).te.ops.GroupedLinearraisesNotImplementedErrorforrow_scaled_activationandrow_scaled_weight.Supported configurations
Row-scaled activations are enabled with
NVFP4BlockScaling(row_scaled_activation=True)(orNVTE_NVFP4_ROW_SCALED_ACTIVATION=1). When backward is quantized,grad_outputfollows the forward scaling mode.backward_override=None)high_precisiondequantizedWeight scaling is selected independently of the activation scaling:
disable_2d_quantization=True(orNVTE_NVFP4_DISABLE_2D_QUANTIZATION=1)row_scaled_weight=True(orNVTE_NVFP4_ROW_SCALED_WEIGHT=1)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:
disable_rht)grad_output(wgrad)disable_stochastic_rounding)grad_outputnvfp4_4over6)noneweights,activations,all); never gradientsweights/allis incompatible withrow_scaled_weightModule support for row-scaled NVFP4
Linear,LayerNormLinear,LayerNormMLPGroupedLinear, grouped-tensor pathnone; per-tensor activations still require RHT. Discrete weights only. Default for row-scaled activations whenuse_grouped_tensoris unset (see below)GroupedLinear, split-quantize pathte.ops.GroupedLinearNotImplementedErrorTesting
test_grouped_linear.py(whole file), including automatic path selection (selected for aligned shapes and bit-exact with explicituse_grouped_tensor=True; not selected for unaligned shapes or 4over6) and row-scaled quantized backward against per-expertLinear.test_nvfp4_gemm_exact.py -k row_scaled, including row-scaledgeneral_grouped_gemmmatching per-groupgeneral_gemmwith 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 newGroupedLineartest with hostm_splitsthat 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.Linear/LayerNormLinearforward and backward match the NVFP4 reference; error is no worse than per-tensor forLinear,LayerNormLinear,LayerNormMLPand bothGroupedLinearpaths.general_grouped_gemmon the split-quantize path (BF16 output, 8–32 experts): 2.6–4.0x faster than per-group GEMMs.Checklist: