Skip to content

[PyTorch] Honor optimize_for_gemm in quantized outputs - #3817

Merged
pggPL merged 37 commits into
NVIDIA:mainfrom
pggPL:quantizer_gemm_ready_outputs
Nov 12, 2026
Merged

pggPL merged 37 commits into
NVIDIA:mainfrom
pggPL:quantizer_gemm_ready_outputs

Conversation

@pggPL

@pggPL pggPL commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Some native operations return compact MXFP8 or NVFP4 scales even when their quantizer has optimize_for_gemm=True. Callers and fake implementations must then predict the selected kernel's output layout.

Honor the requested GEMM scale layout at the native operation boundary. When a kernel can only emit compact scales, a local tensor descriptor shares the output's data and amax buffers but uses scratch scales. The operation then explicitly swizzles those scales into the output's own buffers. Output buffers are never reallocated, so their addresses stay stable. Kernels that already emit GEMM-swizzled scales skip the conversion.

Type of change

  • Documentation change (change only to the documentation, either a fix or a new content)
  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Infra/Build change
  • Code refactoring

Changes

  • Handle compact scale scratch and swizzle calls explicitly in NVFP4 quantization, NVFP4 multi-tensor quantization, and cuDNN MXFP8 normalization. Keep the final output descriptors and buffer addresses unchanged.
  • NVFP4 quantization: use compact scratch scales only when the kernel cannot emit GEMM-swizzled scales (e.g. 1D quantization without RHT cast fusion, row-scaled, 4over6, unaligned shapes). With a noop_flag, the previous scales are unswizzled into the scratch buffers first, so a GPU no-op leaves the output unchanged.
  • Multi/split quantization: decide per tensor whether compact scratch scales are needed. Those tensors share one scratch allocation and one swizzle kernel per usage; tensors whose kernel emits GEMM-swizzled scales, or that do not request them, are quantized directly.
  • Normalization: add Impl::FUSED_NORM_QUANT_UNSWIZZLED for cuDNN MXFP8 LayerNorm/RMSNorm with optimize_for_gemm, preparing compact scales and explicitly swizzling them within the existing intermediate-output switches. Keep 2D MXFP8 normalization on the compatible unfused path.
  • GEMM: convert a provided quantized output to the quantizer's layout where it is constructed when unfused quantization is needed.
  • Remove post-quantize inplace_swizzle_scale_for_gemm calls, which replaced the scale buffers of the output.
  • Simplify fake_bgrad to derive the layout directly from the quantizer and remove the unused layout-query binding.
  • Cover native producers, multi/split quantization layouts (including mixed usages, formats and empty tensors), compiled bias gradients, and NVFP4 no-op graph replays with stable output buffers.

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

pggPL and others added 11 commits November 2, 2026 19:20
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
…to quantizer_gemm_ready_outputs

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>

# Conflicts:
#	transformer_engine/pytorch/csrc/common.h
#	transformer_engine/pytorch/csrc/extensions/cast.cpp
#	transformer_engine/pytorch/csrc/extensions/pybind.cpp
#	transformer_engine/pytorch/csrc/quantizer.cpp

@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.

Good catch, it definitely is hacky that we sometimes ignore optimize_for_gemm. I'm skeptical about the changes to the C++ infrastructure since QuantizationWorkspace's design is rather ad hoc.

GRAD_INPUT3 = 5
};

struct QuantizationWorkspace {

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 class seems overengineered and ad hoc. The purpose is to handle a few kernels that require compact scales (cuDNN RMSNorm/LayerNorm and some NVFP4 quant configs) and it seems simpler to put this workspace logic there rather than expose it in all of the quantizer interfaces.

Comment on lines 147 to 150
QuantizationWorkspace scale_workspace;
if (cudnn_mxfp8_output && quantizer_cpp->optimize_for_gemm) {
scale_workspace.prepare(out_nvte);
}

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 redundant with the existing logic to instantiate an intermediate tensor when we can't output directly into the output tensor:

// Construct unquantized output tensor if needed
TensorWrapper unquantized_out_nvte;
py::object unquantized_out;
at::Tensor amax_buf;
TensorWrapper *kernel_out_nvte = &out_nvte;
switch (impl) {
case Impl::UNFUSED: {
NoneQuantizer q{none};
std::tie(unquantized_out_nvte, unquantized_out) = q.create_tensor(shape, out_dtype);
kernel_out_nvte = &unquantized_out_nvte;
} break;
case Impl::FUSED_NORM_AMAX_FP8: {
auto fp8_quantizer_cpp = static_cast<Float8CurrentScalingQuantizer *>(quantizer_cpp.get());
std::tie(unquantized_out_nvte, unquantized_out, amax_buf) =
fp8_quantizer_cpp->create_unquantized_tensor_with_amax(shape, out_dtype);
kernel_out_nvte = &unquantized_out_nvte;
} break;
case Impl::FUSED_NORM_AMAX_NVFP4: {
auto nvfp4_quantizer_cpp = static_cast<NVFP4Quantizer *>(quantizer_cpp.get());
std::tie(unquantized_out_nvte, unquantized_out) =
nvfp4_quantizer_cpp->create_unquantized_tensor_with_amax(out_nvte, out_dtype);
kernel_out_nvte = &unquantized_out_nvte;
} break;
default: {
}
}

Better to fix the existing logic so it's not specific to high-precision intermediates, rather than creating a side path.

pggPL and others added 14 commits November 5, 2026 12:11
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Add FUSED_NORM_QUANT_UNSWIZZLED to layernorm_fwd and handle compact
scale views and swizzling in the existing Impl switches of both
normalization functions instead of a separate optional path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Convert a reused GEMM output with the quantizer where the output tensor is
constructed instead of after the GEMM. Limit compact scale views and
batched swizzling to the grouped NVFP4 split-quantize kernel; other
multi-tensor paths swizzle per tensor in quantize().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Quantize NVFP4 outputs whose kernel cannot write GEMM-swizzled scales
into compact scratch views and swizzle them with one kernel in
multi_tensor_quantize and split_quantize, while outputs with in-kernel
swizzling are written directly. Declare the internal swizzle helpers in
util.h next to the existing ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
@pggPL

pggPL commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

My agent says:

Scale corruption on main with noop_flag (fixed by this PR)

On main, an in-place NVFP4 weight update with optimize_for_gemm=True corrupts the scales when noop_flag skips quantization.

  • It happens when the quantization kernel can't emit GEMM-swizzled scales itself, e.g. 1D quantization without RHT cast fusion, row-scaled NVFP4, 4over6, or shapes that aren't 128-aligned.
  • The first quantization writes compact scales, and the post-quantize inplace_swizzle_scale_for_gemm swizzles them.
  • On the next update, convert_and_update_tensor resets _with_gemm_swizzled_scales to False, but the buffer still holds swizzled scales.
  • If noop_flag skips the kernel (CUDA graphs with weight caching), the fallback swizzles these already-swizzled scales a second time. The FP4 data stays intact, but ~90% of the scale bytes are wrong and GEMM output is off by ~33% relative norm (fprop and dgrad).

In this PR the output's scales are redirected to scratch buffers during quantization. With noop_flag, the current scales are first unswizzled into the scratch, so a skipped update reproduces them exactly. The cost is one small scale-only kernel per update, and only when noop_flag is passed. MXFP8 is not affected, because its kernel always emits swizzled scales.

@pggPL
pggPL marked this pull request as ready for review November 5, 2026 19:23
@pggPL
pggPL requested a review from ksivaman as a code owner November 5, 2026 19:23
@greptile-apps

greptile-apps Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no new actionable issue was found in the latest attention-test change.

Summary

Native quantized outputs now honor optimize_for_gemm without replacing their scale buffers.

  • NVFP4 outputs keep the GEMM scale layout their quantizer requests.
  • MXFP8 normalization writes the requested GEMM scale layout.
  • GEMM and compiled gradients follow the quantizer's output layout.

The earlier no-op coverage finding is addressed by the expanded replay test. The fused FP8 transpose finding is addressed by rejecting unsupported columnwise output. The earlier rejection-test coverage thread was manually resolved by timmoon10 without explanation.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Quantizer requests output layout] --> B{Kernel emits that layout?}
  B -->|Yes| C[Write directly to output]
  B -->|No| D[Write compact scratch scales]
  D --> E[Swizzle into existing output scale buffers]
  C --> F[Return requested layout]
  E --> F
Loading

Reviews (14) · Last reviewed commit: "Request rowwise QKV output in custom FP8..." · Reviewed by Greptile

Comment thread tests/pytorch/test_quantized_tensor.py Resolved
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
@pggPL

pggPL commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

/te-ci pytorch L1

Comment thread transformer_engine/pytorch/csrc/util.h Resolved
Replace RedirectedScales and paired redirect/restore helpers with local
intermediate tensor descriptors and explicit swizzle calls in MXFP8
normalization and NVFP4 quantization. Keep the final output descriptors
and buffers unchanged.

Prepare NVFP4 compact scales inside the existing multi-tensor dispatchers
and retain one batched swizzle per populated orientation. Preserve cached
scales when a GPU noop skips quantization, and extend the existing graph
replay test to cover GEMM layouts and stable buffer addresses.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Replace enum-based descriptor copies with explicit MXFP8 and NVFP4 data,
scale and amax setters. Use named rowwise and columnwise scratch buffers,
and prepare mixed-path intermediates only for NVFP4 outputs that need them.

Pass the original tensor directly as the swizzle destination and as the
no-op preservation unswizzle source. Keep directional compact scale views,
batched conversion, format metadata and stable output buffers.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Add a stateless helper for one orientation of data, scale and amax fields.
Reuse it for compact kernel outputs and swizzle source views in MXFP8
normalization and NVFP4 single and batched quantization.

Keep scratch ownership, layout policy and GPU operations at the call sites.
The helper neither allocates storage nor redirects the original tensor.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Prepare batched output descriptors, scale storage and swizzle pointer
lists in one private helper used by multi-tensor and split quantization.
Return plain owning records and leave quantization and swizzle launches
explicit at the call sites.

Preserve complete descriptors for unselected and empty outputs, including
the global scale used by per-tensor FP8. Keep original wrappers unchanged.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Keep scratch storage in caller-owned vectors and share ordinary preparation
functions. Leave batched scale swizzles explicit at both quantization call
sites, without introducing wrapper classes or aggregate state types.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Use a plain helper to prepare MXFP8 scratch scales and directional views
for LayerNorm and RMSNorm. Keep storage in caller-owned vectors and leave
normalization and scale swizzle calls explicit.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Use convert_and_update_tensor for every supplied output, including fused
FP8 GEMM and unquantized outputs, as suggested in review. Keep the choice
of fused or unfused quantization independent from output preparation.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Check the delayed-scaling output quantizer before creating or updating D.
Reject requests requiring a separate transpose when fused GEMM only writes
rowwise data. Allow columnwise usage when the hardware can consume that
same representation, and leave unfused quantization unchanged.

Extend the existing GEMM numerical test to cover both output usages and
the expected error on architectures requiring a separate transpose.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Drop the added columnwise parameterization and error assertions at the
author's request. Keep the original numerical case with a rowwise-only
output quantizer, matching the supported fused GEMM output representation.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Comment thread tests/pytorch/test_numerics.py Resolved
Request rowwise-only dgrad output with a private quantizer copy, leaving consumer transpose requirements intact. Align fake backward output usage and enable delayed-scaling coverage.

Preserve supplied quantized output storage when no quantizer is provided by reusing the existing tensor conversion. Add an exact FP8 output reuse regression.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
timmoon10
timmoon10 previously approved these changes Nov 11, 2026

@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.

LGTM

for (size_t i = 0; i < num_tensors; ++i) {
quantizer_cpp_list[i]->quantize(input_list[i], output_list[i]);
quantizer_cpp_list[i]->quantize(input_list[i], kernel_outputs[i]);
}

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: Instead of adding NVFP4-specific logic to the general case, it may be cleaner to have a dedicated NVFP4 code path.

switch (impl) {
case Impl::FP8_FUSED_QUANT:
  nvte_multi_cast_transpose(...);
  break;
case Impl::NVFP4_QUANT_MULTI_SWIZZLE:
  prepare_compact_quantization_outputs(...);
  for (size_t i = 0; i < num_tensors; ++i) {
    quantizer_cpp_list[i]->quantize(input_list[i], output_list[i]);
  }
  nvte_multi_tensor_swizzle_scaling_factors(...);
  break;
default:
  for (size_t i = 0; i < num_tensors; ++i) {
    quantizer_cpp_list[i]->quantize(input_list[i], output_list[i]);
  }
}

Comment on lines +2591 to +2599
if (noop_flag) {
// Preserve cached scales when the quantization kernel is a GPU no-op.
for (auto& scale_view : scale_inputs) {
NVTE_SCOPED_GIL_RELEASE({
nvte_unswizzle_scaling_factors(out.data(), scale_view.data(),
at::cuda::getCurrentCUDAStream());
});
}
}

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 extra kernel is unfortunate. That said, handling this properly may be outside the scope of this PR:

  • Supporting the noop flag in the swizzle kernels is not hard, but would require an API change.
  • Quantized weights are preferable to using cached quantized weights, which is the case where the noop flag is relevant.
  • This extra swizzling is mostly relevant when the tensor sizes are too small to be well aligned, in which case NVFP4 may not be the best choice.

The custom MHA path passes QKV directly to fused attention and never uses its transpose. Match its GEMM output usage to the rowwise representation that fused GEMM produces, retaining the guard against unwritten columnwise output.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants