Repository navigation
Overhaul MxFP8 support - #4203
Conversation
dac2861 to
cf54484
Compare
| # The policy only selects the collective dtype; there is no side metadata. | ||
| return (self._data.to(param_dtype),), () | ||
|
|
||
| def fsdp_post_all_gather( |
There was a problem hiding this comment.
@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( |
There was a problem hiding this comment.
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") | ||
|
|
||
|
|
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
checkpoint happens in high precision, not raw mxfp8
abfb0d4 to
bc7f3bd
Compare
| s_weight_fprop_blocked, | ||
| _, | ||
| s_weight_dgrad_blocked, | ||
| ) = triton_to_mxfp8_32x32_swizzle_dim0_and_dim1(weight_NK.contiguous()) |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
An AO kernel that fuses this and the followup triton rearrange would be ideal.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
25defa7 to
96fecec
Compare
8b0efdb to
95a917e
Compare
| a fresh operands dataclass, or with ``out`` set refills that one's | ||
| existing tensors in place instead of allocating. | ||
|
|
||
| logical weight |
There was a problem hiding this comment.
let's avoid using "weight"
| operands: Any, | ||
| **logical_metadata: Any, | ||
| ) -> None: | ||
| del metadata_source, logical_metadata |
There was a problem hiding this comment.
earlier you said
unsharded tensor
The_UnshardedFSDPTensorthat holds the operands and presents the
parameter's logical high-precision metadata. "C" below.
But now you are deling the metadata during construction.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
I don't know the full history of FSDP2, but here why don't we follow FSDP2 and call it "unsharded inner tensor"
There was a problem hiding this comment.
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.
95a917e to
8b3aafe
Compare
| 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, |
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
is the contiguous call here doing anything?
| model_compile_enabled=model_compile_enabled, | ||
| fqns=["attention", "shared_experts", "feed_forward"], | ||
| linears_saving_inputs_for_backward_in_mxfp8=[ | ||
| "attention.wkv_b", |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
let me follow up in a separate PR because there might be unification required in other places.
d31e36e to
f4c8013
Compare
| # 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 |
There was a problem hiding this comment.
spmd_types backend will output a plain tensor, which won't have _local_tensor attribute.
There was a problem hiding this comment.
This is the not replicate_compute output. This is the input to this function forward - x which is still a DTensor (L365)
| return config | ||
|
|
||
|
|
||
| def deepseek_v3_debugmodel_mxfp8(seq_len: int | None = None) -> Trainer.Config: |
There was a problem hiding this comment.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
For now, I am adding a llama3x one to the B200 CI.
| bias=config.bias, | ||
| ) | ||
| try: | ||
| from .linear import MXFP8Linear |
There was a problem hiding this comment.
Will this import ever fail? I think we always instantiate this class now whether or not torchao is installed?
There was a problem hiding this comment.
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." |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
Wondering if you've tried mxfp8_quantize_2d_1x32_cutedsl instead? It may be faster since it does quant + swizzle in 1 kernel
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Ah I see, yeah I ran into the same 4.6 problem, I actually have a fix here: pytorch/ao#4766
f4c8013 to
d40eefe
Compare
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.
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:
reshard_after_forward.32x32scaling for weights, while inputs use standard 1D scaling.MXFP8Linearcan 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_cudafor rowwise and columnwise activation quantization.triton_to_mxfp8_32x32_swizzle_dim0_and_dim1for 2D weight quantization and Blackwell-ready layouts.triton_mx_block_rearrangefor scale layout conversion.TorchTitan owns everything that interacts with training structure:
_MXFP8LinearFunctionandMXFP8Linear.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_forwardFalseTrueFSDP 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 inMXFP8Linear.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:
32x321x3232x1There are two reasons for this choice:
32x32tiles, the quantization groups are invariant under transpose, so DGRAD qdata can be a transpose view of the FPROP qdata.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_mmscaling and swizzle contract used byMXFP8Linear.Revamped
MXFP8LinearThe previous activation path was:
This remains the conservative default, but the PR adds an optimized policy:
wgrad_input_storagehigh_precision(default)XXquantizedThe 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 BF16Xis already retained elsewhere, saving an additional quantized representation increases memory. We therefore keephigh_precisionas the default to avoid an unexpected memory regression or OOM, and selectquantizedexplicitly for audited modules.high_precisionquantizedThe current TorchTitan policies are:
quantizedattention.qkv_linear.wqkv,feed_forward.w2attention.wkv_b,feed_forward.w2,shared_experts.w2All 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
reshard_after_forward, including PP cache reuse and final-backward release.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:
FalseFalseTrueTrueFor
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.