Skip to content

[PyTorch] Add MXFP4 weight x MXFP8 activation (W4A8) support for Linear modules - #3810

Open
cael-ling wants to merge 12 commits into
NVIDIA:mainfrom
cael-ling:feat/w4a8-mxfp4-mxfp8
Open

cael-ling wants to merge 12 commits into
NVIDIA:mainfrom
cael-ling:feat/w4a8-mxfp4-mxfp8

Conversation

@cael-ling

Copy link
Copy Markdown
Contributor

Description

Adds W4A8 training: MXFP4 weights with MXFP8 activations and gradients in Linear, LayerNormLinear and GroupedLinear, exposed as a quantizer factory for CustomRecipe.

Motivation: RL pipelines whose rollout engine serves MXFP4 weights. Training with the same MXFP4 weight values removes the weight-side mismatch between the policy that generates samples and the policy that is trained. The weight is quantized independently for each GEMM direction from the high-precision parameter, and the row-wise MXFP4 data used by fprop is what a rollout engine would load.

GEMM Weight-side operand Activation-side operand Backend
fprop (TN) MXFP4 row-wise MXFP8 input row-wise CUTLASS SM100
dgrad (NN) MXFP4 column-wise MXFP8 grad_output row-wise CUTLASS SM100
wgrad (NT) MXFP8 input column-wise MXFP8 grad_output column-wise cuBLASLt

Usage:

from transformer_engine.common.recipe import CustomRecipe
from transformer_engine.pytorch.custom_recipes.quantizer_factory_zoo import (
    mxfp4_weight_mxfp8_activation_factory,
)
recipe = CustomRecipe(qfactory=mxfp4_weight_mxfp8_activation_factory)
with te.autocast(enabled=True, recipe=recipe):
    y = layer(x)

With Megatron-LM, no Megatron changes are required:

--fp8-format e4m3 --fp8-recipe custom \
--fp8-quantizer-factory transformer_engine.pytorch.custom_recipes.quantizer_factory_zoo.mxfp4_weight_mxfp8_activation_factory

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

Please list the changes introduced in this PR:

  • Change A
  • Change B

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 Nov 4, 2026
… modules

Add an MXFP4 quantized tensor type and a custom-recipe quantizer factory
that uses MXFP4 weights with MXFP8 activations and gradients in Linear,
LayerNormLinear and GroupedLinear:

  * fprop: weight.row(MXFP4) x input.row(MXFP8)
  * dgrad: weight.col(MXFP4) x grad_output.row(MXFP8)
  * wgrad: input.col(MXFP8) x grad_output.col(MXFP8)

MXFP4 is represented as NVTE_MXFP8_1D_SCALING with kFloat4E2M1 data:
E2M1 values in blocks of 32 with E8M0 scales rounded up. Row-wise and
column-wise data are each quantized from the high-precision weight.

Common:
  * MXFP4 quantize and dequantize kernels, dispatched from the MXFP8
    scaling path by output dtype, with optional GEMM-swizzled scales.
  * CUTLASS SM100 block-scaled GEMM for MXFP4 x MXFP8 (TN and NN),
    selected in cublas_gemm; the GEMM reduction dimension and, for dgrad,
    the weight input dimension must be multiples of 128.
  * Tensor validation and scale swizzling for FP4 MXFP8-scaled tensors.

PyTorch:
  * MXFP4Quantizer, MXFP4Tensor and MXFP4TensorStorage with C++
    quantizer bindings.
  * mxfp4_weight_mxfp8_activation_factory in quantizer_factory_zoo,
    usable through CustomRecipe. With Megatron-LM:
      --fp8-format e4m3 --fp8-recipe custom
      --fp8-quantizer-factory transformer_engine.pytorch.custom_recipes.quantizer_factory_zoo.mxfp4_weight_mxfp8_activation_factory
  * GroupedLinear falls back to per-GEMM execution for MXFP4 weights.

Tests cover bitwise-exact quantization, GEMM and module forward/backward
against Python references, CPU offload, backward_override, and TP/SP
distributed numerics.

Signed-off-by: Cael Ling <caell@nvidia.com>
@cael-ling
cael-ling force-pushed the feat/w4a8-mxfp4-mxfp8 branch from eb4514f to be50b44 Compare November 4, 2026 06:10
@cael-ling
cael-ling marked this pull request as ready for review November 4, 2026 06:17
@greptile-apps

greptile-apps Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The change adds an opt-in mixed-precision training path for three PyTorch linear modules.

Fix the early bias rounding before merging.

Findings

  1. P1 Bias rounds too early ▶

Summary

Adds MXFP4 weights with MXFP8 activations and gradients for Linear modules.

  • MXFP4 tensors store packed values and scales for both GEMM directions.
  • Blackwell GEMMs now multiply MXFP4 weights by MXFP8 activations and gradients.
  • Linear modules can train with MXFP4 weights and MXFP8 activations through a custom recipe.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  W[High-precision weight] --> WR[Row-wise MXFP4]
  W --> WC[Column-wise MXFP4]
  X[Input] --> XR[Row-wise MXFP8]
  X --> XC[Column-wise MXFP8]
  G[Output gradient] --> GR[Row-wise MXFP8]
  G --> GC[Column-wise MXFP8]
  WR --> F[Forward CUTLASS GEMM]
  XR --> F
  WC --> D[Input-gradient CUTLASS GEMM]
  GR --> D
  XC --> B[Weight-gradient cuBLASLt GEMM]
  GC --> B
Loading

Reviews (7) · Last reviewed commit: "Merge branch 'main' into feat/w4a8-mxfp4..." · Reviewed by Greptile

@vthumbe1503 vthumbe1503 self-assigned this Nov 5, 2026
MXFP4Tensor inherited the storage view(), which returned a bare
MXFP4TensorStorage without autograd and accepted only a single shape
argument. Add view() and reshape() through an autograd function that
returns an MXFP4Tensor and handle aten.view in __torch_dispatch__.

copy_() between MXFP4 tensors copied raw buffers even when one side
had GEMM-swizzled scales and the other compact scales, leaving the
destination with scales in the wrong order. Requantize the destination
when the scale layouts differ.

Add tests for view/reshape with gradients and for copies across all
combinations of scale layouts.

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

Copy link
Copy Markdown

@cael-ling thx for implementing this. Do you know when will this PR be merged?

@cael-ling

Copy link
Copy Markdown
Contributor Author

@crazyguitar Thanks for your interest. The PR is currently under review, and I'm working with the maintainers to get it merged. Out of curiosity, could you share a bit about your use case — e.g., which model / training setup you're planning to use this with, and roughly what scale? That would help us prioritize and make sure the feature covers what you need.

@crazyguitar

crazyguitar commented Nov 6, 2026 •

Copy link
Copy Markdown

@crazyguitar Thanks for your interest. The PR is currently under review, and I'm working with the maintainers to get it merged. Out of curiosity, could you share a bit about your use case — e.g., which model / training setup you're planning to use this with, and roughly what scale? That would help us prioritize and make sure the feature covers what you need.

Yeah, we are investigating open weight model + QAT like kimi or DSv4. Most of these models are using MXFP4 rather than NVFP4, so we are in favor of using MXFP4 for QAT.

This is kimi k3 roadmap:

NVIDIA/Megatron-LM#6872

Area Status Priority Current focus
Native MXFP4 training 📋 P1 Add the K3 MXFP4-weight / MXFP8-activation QAT, optimizer, and checkpoint path

We are excited if NV can native support it.

Signed-off-by: Varun Thumbe <vthumbe@nvidia.com>
@vthumbe1503

vthumbe1503 commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Thanks for the PR @cael-ling. I have merged in a commit to address a few minor issues.

--> Move scale-layout copy tests to test_quantized_tensor.py.
--> Handle scale-layout mismatches for copy implementation in base QuantizedTensor instead of MXFP4 class. Since all Subclasses can reuse it.
--> Add the is_mxfp4_available() API so we can infer in python whether mxfp4 is available and update MXFP4 test gates.
--> Guard MXFP4 x MXFP8 CUTLASS GEMM compilation with FP4_TYPE_SUPPORTED.

@vthumbe1503

Copy link
Copy Markdown
Collaborator

I think there are some merge conflicts we need to resolve. But could we also add tests for transformer_engine/common with respect to the nvte APIs for mxfp4 quantize/dequantize and the cutlass GGEMM?

cael-ling and others added 5 commits November 15, 2026 22:56
Signed-off-by: Cael Ling <caell@nvidia.com>

# Conflicts:
#	tests/pytorch/test_quantized_tensor.py
#	transformer_engine/common/cast/dispatch/dequantize.cuh
#	transformer_engine/pytorch/cpp_extensions/gemm.py
Signed-off-by: Cael Ling <caell@nvidia.com>
Signed-off-by: Cael Ling <caell@nvidia.com>
Signed-off-by: Cael Ling <caell@nvidia.com>
@cael-ling

Copy link
Copy Markdown
Contributor Author

I think there are some merge conflicts we need to resolve. But could we also add tests for transformer_engine/common with respect to the nvte APIs for mxfp4 quantize/dequantize and the cutlass GGEMM?

Done in d557c33 for merge the upstream/main;
Done in 194de07:

  • tests/cpp/operator/test_cast_mxfp4.cu: nvte_quantize / nvte_dequantize checked against a CPU reference. Covers rowwise / columnwise / both, compact and GEMM-swizzled scales, FP32/BF16/FP16 inputs, and 2D/3D shapes.
  • tests/cpp/operator/test_gemm.cu (MXFP4MXFP8GemmTestSuite): MXFP4 x MXFP8 through nvte_cublas_gemm_v2, with inputs exactly representable in MX formats so the comparison is exact. Covers BF16/FP32 outputs, transa on/off (fprop/dgrad layouts), and no C / out-of-place C / in-place accumulation.

All tests pass on SM100.

@cael-ling

Copy link
Copy Markdown
Contributor Author

Hi @vthumbe1503, thanks for the review and for the fixes you pushed to the PR, I've addressed the remaining comments, all pushed to the branch.

Signed-off-by: Varun Thumbe <vthumbe@nvidia.com>
@vthumbe1503
vthumbe1503 requested a review from ptrendx as a code owner November 18, 2026 22:49
Quantizing into an existing MXFP4 tensor of a different shape launched
the kernels with the input dimensions and wrote past the destination
data and scale buffers.

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

negvet commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator

cc @rybakov

@negvet

negvet commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator

Is it possible to generalize GEMM dispatch to accept both operands as MXFP4?

@cael-ling

Copy link
Copy Markdown
Contributor Author

Is it possible to generalize GEMM dispatch to accept both operands as MXFP4?

@negvet Yes, I think so. The CUTLASS SM100 kernel is already templated on the operand types, so most of it would carry over. I'd prefer to keep this PR scoped to W4A8, since it has already been reviewed in that form, and do MXFP4 x MXFP4 in a follow-up PR. Does that work for you? cc @vthumbe1503

@vthumbe1503

vthumbe1503 commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

@negvet / @cael-ling it seems like CUBLAS already supports MXFP4 GEMM and GGEMM https://docs.nvidia.com/cuda/cublas/index.html#using-the-cublaslt-api. So we can use that directly. But deferring that to different PR makes sense to me.

@vthumbe1503

Copy link
Copy Markdown
Collaborator

/te-ci L0 L1

__global__ void broadcast_bias_kernel(OType *out, const BiasType *bias, size_t rows, size_t cols) {
const size_t idx = blockIdx.x * static_cast<size_t>(blockDim.x) + threadIdx.x;
if (idx < rows * cols) {
out[idx] = static_cast<OType>(static_cast<float>(bias[idx % cols]));

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 Bias rounds too early

With BF16 output and FP32 bias, general_gemm rounds the bias to BF16 before adding the matrix product. A product of -1 and bias 1.00390625 should produce 0.00390625, but the bias becomes 1 here and the result becomes zero. Add the bias in FP32 before the final output cast.

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.

4 participants