Skip to content

Overhaul MxFP8 support - #4203

Merged
anijain2305 merged 2 commits into
mainfrom
mxfp8-training
Sep 4, 2026
Merged

anijain2305 merged 2 commits into
mainfrom
mxfp8-training

Conversation

@anijain2305

@anijain2305 anijain2305 commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR overhauls MXFP8 linear training in TorchTitan. The key design choice is a narrow TorchAO/TorchTitan boundary: TorchTitan relies on TorchAO only for MXFP8 quantization and layout kernels, while TorchTitan owns autograd, FSDP cache management, and model policy. Thanks to Vasiliy Kuznetsov for adding the TorchAO kernel support used here.

The main changes are:

  • FSDP owns the quantized weights and scales, so their lifetime follows the normal FSDP unshard/reshard lifecycle and composes with both values of reshard_after_forward.
  • Weight quantization is pluggable. The built-in strategy uses 2D 32x32 scaling for weights, while inputs use standard 1D scaling.
  • MXFP8Linear can save either the original BF16 input or its columnwise-quantized representation for WGRAD. TorchTitan model configs select the optimized policy only where the BF16 input is not retained elsewhere.

TorchAO and TorchTitan boundary

TorchTitan currently uses the following kernel-level operations from TorchAO:

  • mxfp8_quantize_cuda for rowwise and columnwise activation quantization.
  • triton_to_mxfp8_32x32_swizzle_dim0_and_dim1 for 2D weight quantization and Blackwell-ready layouts.
  • triton_mx_block_rearrange for scale layout conversion.

TorchTitan owns everything that interacts with training structure:

  • _MXFP8LinearFunction and MXFP8Linear.
  • FSDP tensor subclasses and pre/post-all-gather hooks.
  • Quantized-weight storage and lifetime.
  • The pluggable weight strategy.
  • Model-specific activation-storage policy.

The current kernels are sufficient for this integration. More heavily fused kernels can be added later as small, independent TorchAO changes without moving FSDP or parallelism policy into TorchAO.

FSDP-managed quantized weights

The FSDP post-all-gather hook quantizes the unsharded BF16 weight and returns the independent MXFP8 qdata and scale tensors for FSDP to manage. There is no separate module-level or autograd-level weight cache.

This gives the quantized representation the same lifecycle as the unsharded FSDP parameter:

reshard_after_forward Behavior
False Quantize on the first unshard and reuse the MXFP8 operands across PP microbatches. PP can retain them through the microbatch sequence and release them after the final backward.
True Reshard after forward. Backward performs another BF16 all-gather and post-all-gather quantization.

FSDP keeps the compute-weight object stable and allocates, frees, or refills its inner tensors through the post-all-gather out= contract. This lets us reuse the existing FSDP state machine instead of maintaining a second cache lifecycle in MXFP8Linear.

The implementation also uses the tensor-subclass API from pytorch/pytorch#194114, which allows FSDP to release the BF16 all-gather output after the independent MXFP8 representation has been constructed.

Pluggable quantization strategy

The practical default used by this PR is:

Operand Scaling
Weights 2D 32x32
FPROP inputs 1D 1x32
WGRAD inputs 1D 32x1

There are two reasons for this choice:

  1. With 1D weight scaling, the scale groups needed by FPROP and DGRAD have different orientations. The two weight representations must therefore be quantized separately and may contain different quantized values. With square 32x32 tiles, the quantization groups are invariant under transpose, so DGRAD qdata can be a transpose view of the FPROP qdata.
  2. Inputs remain one-dimensional because a 2D activation scale may span multiple sequence positions. In causal attention, that would allow a token's quantization scale to depend on future tokens.

The PR intentionally provides only the built-in 2D weight strategy. The implementation remains extensible through MXFP8WeightQuantizationStrategy: a different strategy supplies its quantization implementation, and strategies with aliased storage can additionally describe how their logical GEMM operands are reconstructed from the independent tensors managed by FSDP.

Every strategy must return qdata and blocked scales compatible with the scaled_mm scaling and swizzle contract used by MXFP8Linear.

Revamped MXFP8Linear

The previous activation path was:

Forward:  rowwise-quantize X + save BF16 X
Backward: retrieve BF16 X + columnwise-quantize X for WGRAD

This remains the conservative default, but the PR adds an optimized policy:

Forward:  rowwise- and columnwise-quantize X + save columnwise MXFP8 X
Backward: retrieve the saved columnwise MXFP8 X
wgrad_input_storage Forward quantization Saved for WGRAD Backward work
high_precision (default) Rowwise only Original BF16 X Columnwise-quantize X
quantized Fused rowwise + columnwise Columnwise qdata and scales Reuse saved operand

The quantized policy can reduce saved-activation memory and avoids a quantization pass during backward. It also allows the rowwise and columnwise outputs to be produced in one kernel call, reducing HBM traffic. This design is similar to the activation handling used by NVIDIA Transformer Engine.

The important caveat is that this saves memory only when no other operation retains the same BF16 X. If BF16 X is already retained elsewhere, saving an additional quantized representation increases memory. We therefore keep high_precision as the default to avoid an unexpected memory regression or OOM, and select quantized explicitly for audited modules.

Is the same BF16 input retained elsewhere? Policy Reason
Yes or unknown high_precision Avoid keeping both BF16 and quantized WGRAD inputs.
No quantized Replace the saved BF16 WGRAD input with the smaller quantized representation.

The current TorchTitan policies are:

Model Modules using quantized
Llama 3 attention.qkv_linear.wqkv, feed_forward.w2
DeepSeek V3 attention.wkv_b, feed_forward.w2, shared_experts.w2
Flux None; it retains the conservative default

All other converted linears use high_precision. The standard Trainer and GraphTrainer share these model policies. The grouped-expert/Grouped GEMM path is unchanged by this PR.

Testing

  • Unit coverage for activation policies, pluggable weight strategies, and FSDP tensor reconstruction.
  • FSDP lifecycle coverage for both values of reshard_after_forward, including PP cache reuse and final-backward release.
  • Compiled FSDP, PP, and GraphTrainer training runs.

Appendix: RAF and activation-checkpointing trade-offs

Activation checkpointing affects which weight representations are needed during the backward unshard. It does not change the WGRAD input-storage policy described above.

The current post-all-gather hook constructs both FPROP and DGRAD weight operands on every actual unshard:

RAF AC Current behavior Ideal behavior
False Off Construct both once and reuse Construct both once and reuse
False On Construct both once and reuse Construct both once and reuse
True Off Construct both in forward and both again in backward FPROP in forward, DGRAD in backward
True On Construct both in forward and both again before backward FPROP in forward, both before backward

For RAF=False, the current behavior is already ideal because both representations are constructed once and reused.

For RAF=True, the initial forward only needs FPROP. Without AC, the backward unshard only needs DGRAD. With AC, however, the backward unshard must support both the recomputed forward and DGRAD.

FSDP internally knows its training phase and RAF setting, but this context is not currently exposed through the post-all-gather hook. In addition, checkpoint recomputation is not always known when the backward unshard begins. This PR deliberately keeps the hook simple and correct by constructing both representations. A future FSDP hook extension could expose the unshard context and enable phase-specific construction.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 18, 2026
@anijain2305 anijain2305 changed the title Add optimized MXFP8 training paths [Do not review] Add optimized MXFP8 training paths Aug 18, 2026
@anijain2305
anijain2305 force-pushed the mxfp8-training branch 4 times, most recently from dac2861 to cf54484 Compare August 18, 2026 21:29
# The policy only selects the collective dtype; there is no side metadata.
return (self._data.to(param_dtype),), ()

def fsdp_post_all_gather(

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.

@tianyu-l fsdp_post_all_gather this is the hook i am talking about. we won't bake in mxfp8 logic into fsdp2 because we have such hook

del metadata, outer_size, outer_stride
return cls(inner_tensors["_data"])

def fsdp_pre_all_gather(

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.

do we need fsdp_pre_all_gather at all if tensor subclass support __torch_dispatch__ or __torch_function__ for self._data.to(param_dtype) ?

i also am fine if you want to keep it this way. which ever feel more elegant to you

assert hasattr(mxfp8_cls.Config, "swiglu_limit")
assert hasattr(float8_cls.Config, "swiglu_limit")


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.

we proabbaly don't need state dict load/save for perf runs, but need it if landing officially to titan

there are 2 approach

  • mxfp8-quantize-then-fsdp2-chunk
  • fsdp2-chunk-then-mxfp8-quantize

pasting TorchAO + TorchTune NF4 quantization + fsdp2 here, as it's similar to mxfp8:

  • when loading from high precision (bf16) checkpoints, we first quantize unsharded bf16 tensor into NF4, and perform torch.chunk(NF4)
  • another possible way torch.chunk(bf16) then quantize sharded bf16 tensors


mxfp8.load_state_dict(stock.state_dict())
assert isinstance(mxfp8.weight, MXFP8FSDPWeight)
assert torch.equal(mxfp8.weight._data, stock.weight)

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.

checkpoint happens in high precision, not raw mxfp8

@anijain2305
anijain2305 force-pushed the mxfp8-training branch 3 times, most recently from abfb0d4 to bc7f3bd Compare August 19, 2026 17:32
s_weight_fprop_blocked,
_,
s_weight_dgrad_blocked,
) = triton_to_mxfp8_32x32_swizzle_dim0_and_dim1(weight_NK.contiguous())

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.

triton_to_mxfp8_32x32_swizzle_dim0_and_dim1 should not return the transposed quantized weight. Currently it calls contiguous on it, this means we will have two different mxfp8 tensors. I have done experiments where passing strided tensor q_weight_dgrad_NK.t() directly into the scaled_mm is as fast as contiguous. This is because blackwell has faster support for all different transpose configurations for inputs.

x_MK, num_rows = _pad_rows(x.reshape(-1, input_shape[-1]).contiguous())
requires_wgrad = ctx.needs_input_grad[1]

x_row_MK, x_col_MK, x_row_scales, x_col_scales = mxfp8_quantize_cuda(

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.

An AO kernel that fuses this and the followup triton rearrange would be ideal.

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.

2 directions

This is inly for 1D quantiztion - 32x1 or 1x32.

  • If I can figure out how to fool autograd engine in not saving the high precision activation, then one AO kernel that does rowwise, colwise and swizzled activation is ideal.

  • If I cannot fool autograd engine, then two kernels are needed - (1) fused rowwise + swizzel, (2) fused colwise + swizzle.

@anijain2305 anijain2305 Aug 19, 2026 •

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.

After spending more time, I conclude that we need to support both the cases. The point is that bf16 input x might already be stashed because the previous layer might need it for its backward op (for example output attention is followed by Flex or flash-attn which stashes flex output for its backward). In such cases, it is better NOT to save the colwise quantized for backward.

So I am planning for MxFP8Linear to be configurable and support both the cases. We need both the above kernels.

@anijain2305
anijain2305 force-pushed the mxfp8-training branch 3 times, most recently from 25defa7 to 96fecec Compare August 19, 2026 23:17
@anijain2305 anijain2305 changed the title [Do not review] Add optimized MXFP8 training paths [Do not review] Overhaul MXFP8 support Aug 20, 2026
@anijain2305 anijain2305 changed the title [Do not review] Overhaul MXFP8 support [Do not review] Overhaul MxFP8 support Aug 20, 2026

@tianyu-l tianyu-l left a comment

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.

last questions

a fresh operands dataclass, or with ``out`` set refills that one's
existing tensors in place instead of allocating.

logical weight

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.

let's avoid using "weight"

operands: Any,
**logical_metadata: Any,
) -> None:
del metadata_source, logical_metadata

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.

earlier you said

unsharded tensor
The _UnshardedFSDPTensor that holds the operands and presents the
parameter's logical high-precision metadata. "C" below.

But now you are deling the metadata during construction.

@anijain2305 anijain2305 Sep 2, 2026 •

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.

Its not discarded. Its used by the __new__ in the base class _FSDPTensorBase.

Here it just means "unused". Adding a comment. We could just delete it but this seems like a convention used in other __init__ methods of tensor subclasses as well (maybe its cargo culting or maybe its just being more explicit so that one does not do self.metadaata_source = metadata_source), and therefore codex decided to keep it.


The unsharded half of the lifecycle, built by
:class:`_ShardedFSDPTensor`'s post-all-gather hook and alive until the
final reshard. Carries no high-precision storage -- that is what lets FSDP

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.

Curious why couldn't it carry low-precision storage, aka what managed tensor carries.

My guess is that this has something to do with FSDP2 resize_ mechanism and being abled to be reused in backward, etc.

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.

It does carry the low precision storage.

        for name in _managed_tensor_names(type(operands)):
            setattr(self, f"_{name}", getattr(operands, name))

Just that there is not one low precision tensor, there are many.

It carries no high-precision storage so that we can release the bf16 unsharded weights.

The resize_ mechanism is still valid and it applies to the low precision tensors.

The unsharded high-precision weight handed to the quantizer. "Logical"
because it excludes any padding the all-gather added.

managed tensors

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.

I don't know the full history of FSDP2, but here why don't we follow FSDP2 and call it "unsharded inner tensor"

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 considered "unshared inner tensor", but to me it made sense in the fsdp code, but not here. Unsharded inner tensors sounded opaque. Here, managed tensors sounds more meaningful.

But let me know if you want consistency.

@anijain2305
anijain2305 changed the base branch from main to moe-grouped-mm-seam September 2, 2026 06:39
Comment on lines +72 to +76
weight_NK: torch.Tensor,
weight_qdata_fprop_KN: torch.Tensor,
weight_scale_fprop_swizzled: torch.Tensor,
weight_qdata_dgrad_NK: torch.Tensor,
weight_scale_dgrad_swizzled: torch.Tensor,

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.

IMO a bit confusing to have both weight_NK and the underlying quantized data here, can we either document why we have both (weight_NK needs grad to flow) or pass a single data structure which encapsulated both?

weight_qdata_dgrad_NK,
weight_scale_fprop_swizzled,
weight_scale_dgrad_swizzled,
) = triton_to_mxfp8_32x32_swizzle_dim0_qdata_dim01_scale(weight_NK.contiguous())

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.

is the contiguous call here doing anything?

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.

removed

model_compile_enabled=model_compile_enabled,
fqns=["attention", "shared_experts", "feed_forward"],
linears_saving_inputs_for_backward_in_mxfp8=[
"attention.wkv_b",

@vkuzo vkuzo Sep 2, 2026 •

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.

can we specify this in a regex pattern to avoid confusion with actual FQNs? I think the scheme used in vllm such as "re:.*attention.wkv_b" has been well received by customers.

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.

let me follow up in a separate PR because there might be unification required in other places.

Base automatically changed from moe-grouped-mm-seam to main September 2, 2026 15:50
@anijain2305
anijain2305 force-pushed the mxfp8-training branch 6 times, most recently from d31e36e to f4c8013 Compare September 3, 2026 05:28
# parameter, so read the subclass off it and derive from both. A
# parameter with no operands passes straight through, so
# this costs nothing when nothing is quantized.
source = x._local_tensor

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.

@anijain2305 anijain2305 Sep 3, 2026 •

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.

This is the not replicate_compute output. This is the input to this function forward - x which is still a DTensor (L365)

def forward(self, x: DTensor) -> torch.Tensor:

return config


def deepseek_v3_debugmodel_mxfp8(seq_len: int | None = None) -> Trainer.Config:

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.

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.

This requires MoE converting to MxFP8 as well. This PR is just about linear.

Lets discuss offline and I can take this if required in a separate PR.

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.

For now, I am adding a llama3x one to the B200 CI.

bias=config.bias,
)
try:
from .linear import MXFP8Linear

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.

Will this import ever fail? I think we always instantiate this class now whether or not torchao is installed?

@anijain2305 anijain2305 Sep 3, 2026 •

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.

Adding comment. The import can fail but because we are building an older version of ao that does not have the kernels used in the titan codebase. So even though it looks like MxFP8Linear import is failing, it is is actually because of the missing kernels.

"torchao is not installed. Please install it to use MXFP8 linear layers."
)
"TorchAO with the MXFP8 32x32 swizzled cast kernels is required "
"for MXFP8 linear layers. Install TorchAO from source."

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.

Same here, I think this error will never trigger. Maybe throw when importing triton_to_mxfp8_32x32_swizzle_dim0_qdata_dim01_scale instead?

# The save format controls both computation and saved state. BF16 mode
# requests only the rowwise FPROP operand here; backward produces the
# columnwise WGRAD operand from the saved BF16 input.
x_qdata_row_MK, x_qdata_col_MK, x_scale_row, x_scale_col = mxfp8_quantize_cuda(

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.

Wondering if you've tried mxfp8_quantize_2d_1x32_cutedsl instead? It may be faster since it does quant + swizzle in 1 kernel

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 tried this but found an annoying problem.

  • We need to install cutlass package.
  • It seems cutlass packages are not BC, so this kernel fails with cutlass=4.6 (which happened to be the one I installed for something else on my env) which is too new for the kernel. So, we need to make this op in AO version tolerant.

for now, I am adding a TODO here and moving on.

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.

Ah I see, yeah I ran into the same 4.6 problem, I actually have a fix here: pytorch/ao#4766

Keep the TorchAO boundary kernel-only while TorchTitan owns the MXFP8 linear autograd function, tensor subclasses, FSDP hooks, and model policy.

Quantize dense weights with square 32x32 blocks in the FSDP post-all-gather hook. FSDP manages the resulting qdata and scale tensors across resharding and pipeline microbatches, and releases the temporary BF16 all-gather output after constructing the independent MXFP8 representation.

Add configurable BF16 or MXFP8 input-activation storage for WGRAD. Built-in model policies use MXFP8 storage only for audited unique-input projections and conservatively retain BF16 elsewhere.

Organize the implementation under the quantization/mxfp8 package and add focused coverage for compilation, activation checkpointing, FSDP lifecycle behavior, pipeline cache reuse, CUDA graph cache stability, checkpoint loading, and model policy.
Keep the TorchAO boundary kernel-only while TorchTitan owns the MXFP8 linear autograd function, tensor subclasses, FSDP hooks, and model policy.

Quantize dense weights with square 32x32 blocks in the FSDP post-all-gather hook. FSDP manages the resulting qdata and scale tensors across resharding and pipeline microbatches, and releases the temporary BF16 all-gather output after constructing the independent MXFP8 representation.

Use one tensor subclass per lifecycle state rather than one class discriminating on runtime state. _ShardedFSDPWeight is the persistent parameter and owns the FSDP hooks; _ComputeFSDPWeight holds one unshard lifetime's operands and is generic, deriving its FSDP-managed inner tensors from the representation's dataclass fields. A format therefore implements a single method, __torch_dispatch__ splits into two single-mode implementations, and "does this weight carry operands?" is a type test rather than a state check.

Add configurable BF16 or MXFP8 input-activation storage for WGRAD. Built-in model policies use MXFP8 storage only for audited unique-input projections and conservatively retain BF16 elsewhere.

Organize the implementation under the quantization/mxfp8 package and add focused coverage for compilation, activation checkpointing, FSDP lifecycle behavior, pipeline cache reuse, CUDA graph cache stability, checkpoint loading, and model policy.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI ciflow/rl ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants