Repository navigation
Add HiMidLoLinear for the LM head and router gate; delete CastLinear and RouterGateLinear - #4923
Conversation
| grad_weight_ED = torch.mm( | ||
| grad_output_fp32_TE.T, input_forward_TD.float() | ||
| ).to(ctx.weight_dtype) | ||
| class Fp32OutputLinear(Linear): |
There was a problem hiding this comment.
Nit - I don't have good options either but Fp32OutputLinear is not accurate, given most of the fun stuff is in backward. Perhaps Bf16x2Linear or EmulatedFp32Linear?
There was a problem hiding this comment.
Whatever you choose, it feels to me that we should use "FP32" / "BF16" over "Fp32" / "Bf16"
| ).to(ctx.weight_dtype) | ||
| class Fp32OutputLinear(Linear): | ||
| """``Linear`` with close to fp32 precision at close to bf16 speed. Useful for layers that need | ||
| to operate at higher precision, e.g. an LM head or a MoE router gate. |
There was a problem hiding this comment.
Can you check if this class works with Quantization? Megatron perfmax run quantizes LM head but keeps router in fp32, so we might need a way to distinguish the two.
| hi_TO, lo_TO = _split_into_bf16_hi_lo(grad_output_TO) | ||
| num_tokens, out_features = hi_TO.shape | ||
|
|
||
| if out_features > num_tokens: |
There was a problem hiding this comment.
Perhaps we can have RouterLinear and LmHeadLinear as two different classes and just have the relevant backward there? This will resolve the quantization concern as well.
There was a problem hiding this comment.
I'm not convinced that one would ever quantize either of them
torchtitan/torchtitan/overrides/README.md
Lines 303 to 304 in 9b8b9d2
so I'm currently on the side of "we only need one class"
|
Great work! The backward trick is clever! |
| grad_weight_ED = torch.mm( | ||
| grad_output_fp32_TE.T, input_forward_TD.float() | ||
| ).to(ctx.weight_dtype) | ||
| class Fp32OutputLinear(Linear): |
There was a problem hiding this comment.
Whatever you choose, it feels to me that we should use "FP32" / "BF16" over "Fp32" / "Bf16"
| if bias is not None: | ||
| output_TE = output_TE + bias.float() | ||
| return output_TE | ||
| output = _Fp32OutputLinearFunction.apply( |
There was a problem hiding this comment.
should call this function before compute https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/linear.py#L82-L88
There was a problem hiding this comment.
| input.reshape(-1, input.shape[-1]), weight | ||
| ) | ||
| output = output.reshape(*input.shape[:-1], -1) | ||
| return output if bias is None else output + bias.float() |
There was a problem hiding this comment.
| hi_TO, lo_TO = _split_into_bf16_hi_lo(grad_output_TO) | ||
| num_tokens, out_features = hi_TO.shape | ||
|
|
||
| if out_features > num_tokens: |
There was a problem hiding this comment.
I'm not convinced that one would ever quantize either of them
torchtitan/torchtitan/overrides/README.md
Lines 303 to 304 in 9b8b9d2
so I'm currently on the side of "we only need one class"
| # Two GEMMs with small [O, D] fp32 outputs. | ||
| grad_weight_OD = torch.mm(hi_TO.T, input_TD, out_dtype=torch.float32) | ||
| grad_weight_OD += torch.mm(lo_TO.T, input_TD, out_dtype=torch.float32) | ||
| grad_weight_OD = grad_weight_OD.to(weight_OD.dtype) |
There was a problem hiding this comment.
This doesn't need to be the weight_OD's dtype? E.g. fwd dtype could be bf16, while grad dtype could be fp32.
Also, should we apply the grad accum addmm trick here #4911
cc @anijain2305
| ) | ||
|
|
||
|
|
||
| @spmd.register_local_autograd_function |
There was a problem hiding this comment.
we should also remove
torchtitan/torchtitan/distributed/utils.py
Line 487 in 46ec3f2
| return [ | ||
| hi.to(torch.bfloat16), | ||
| mid.to(torch.bfloat16), | ||
| (rest - mid).to(torch.bfloat16), |
There was a problem hiding this comment.
For exact
- Option 1 - I would prefer to use the standard a0, a1 and a2 because (a) its standard, and (b) it also represents subnormal numbers.
- Option 2- If we dont like Option 1 for any reason, we should add this in the comment with some explanation (e.g. it is slower than current approach and subnormal does not buy us anything practically ).
| grad_weight_OD = torch.mm( | ||
| stacked_PTO.T, torch.cat([input_TD] * num_pieces) | ||
| ) |
There was a problem hiding this comment.
Curious - is this really faster than two mms?
Update - Answering my own question - Yes, it might be avoiding the overhead of an extra add in case of two mms. But cat is mysterious to me. Does it actually materialize the [input_TD, input_TD] in which case we have not really saved much?
- mark_static comment: the slowdown it prevents is both dims symbolic, 1.3-3.8x on GB300. - The backward docstring points to _split_into_bf16_pieces_eager, which holds the split's docs. - The shape legend is scoped to FP32OutputLinear; __all__ is sorted again. - Muse Glimmer TODO: the converter raises on a SoftCappedLinear head rather than skipping it. - GPU tests: the toy third-piece test resets Dynamo, so its compiled cases really run the compiled split; the outer-compile test's comment says what it checks now. - Tests carried over from the router gate use O suffixes and an spmd-types test name.
Pure move: FP32OutputLinear, its autograd Function, the backward paths and the grad_output split move out of linear.py, with their shape legend, the two imports only they use, and their __all__ entry. Imports are updated; linear.py does not re-export it.
The comment gave the wrong reason: an outer torch.compile works without the custom op. What needs it is tracing inside the backward: real-mode make_fx records the compiled kernel's output as a constant, and fake tracing crashes.
hi = bf16(x), mid = bf16(x - hi), lo = bf16(x - hi - mid): cuBLAS BF16x9's a0, a1, a2 without their 2^8 and 2^16 scales, rounding to nearest with ties to even. It replaces the integer bit-op rounding (ties away from zero), which was there only because Inductor drops the .to(bf16).float() round trip; emulate_precision_casts keeps it. Compiled, the split matches eager bit for bit and is faster than the bit ops. The 3-piece sum and the errors are unchanged; only exact ties round differently.
The split was always compiled with torch.compile. It is now the "fp32_output_split" local_compile region, so models opt in like any other compiled function, and it runs eagerly when the region is off. The LM-head converter adds the region, and the models whose routers are FP32OutputLinear (qwen3, qwen3_5, deepseek_v3, deepseek_v4, gpt_oss, kimi_k3) list it by default. local_compile uses fullgraph=True, so past Dynamo's recompile limit the split would raise instead of running eagerly. dynamic=True keeps it far below the limit: one graph per (number of pieces, dim), at most 4, however many layers or shapes use it. Symbolic shapes cost nothing for this split, so mark_static goes.
backward_mode: Literal["bf16x2", "bf16x3"] = "bf16x2" names how many bf16 pieces grad_output is split into, and leaves room for more modes. It maps to num_pieces once in __init__; the Function, the backward paths and the split take the int. Routers use "bf16x3", as before.
The qwen3_5 models enable the fp32_output_split region by default, and this test pins their region list.
LinearLoRAHandler.make_config now requires them.
Pure rename of the class, its module and its tests. LMHeadFP32OutputConverter keeps its name: it exists for the fp32 logits.
graph_trainer requires local_compile regions off, so it never traces the compiled split. The op also hid the split from Inductor when it compiles the whole backward (graph_trainer's full mode, an outer torch.compile), where dropping the .to(bf16).float() round trip zeroes every piece after the first. An integer-shift upcast leaves no round trip to drop, so emulate_precision_casts goes too. Also renames the region to fp32_to_bf16_split and the split's argument to tensor, and tests that the split compiles at most 4 graphs.
- grad_input TODO: say why chunking helps when the GEMM already accumulates in fp32. - split: state when hi, mid, lo equal a0, 2^-8 a1, 2^-16 a2 bit for bit.
The LM head's grad_weight is now fp32, where CastLinear rounded it to bf16, and FSDP2 in recent torch nightlies keeps it fp32. Steps 1-2 match; from step 3 the rollouts differ. Values from the loss_compare output of this branch's RL CI run.
Drop the split's section comment: the decorator names the region and the backward's TODO says why only the split is compiled. The graph-count comment now counts the 0- and 1-token graphs that Dynamo specializes.
Names the modes after the pieces, so the 2-piece split is hi + mid, and drops the note that told our "bf16x3" apart from Triton's.
776da23 to
4dace1c
Compare
The router gates' backward changed (RouterGateLinear -> HiMidLoLinear, 3 pieces), which moves these configs' losses from step 2 or 3. Exact values from this branch's CI run (its TensorBoard artifacts).
…5133) test_moe_qwen3_aot_fx_trace_vs_eager fails on the H100 GraphTrainer CI (AssertionError: False is not true). It runs after the GraphTrainer H100 integration tests, in the same workflow step under bash -eo pipefail. Those integration tests failed on main until #5109, so this test only started running once they passed. This change makes the test's eager baseline config match GraphTrainer, then marks the test as a strict expected failure, like the dense tests in #5110. Two gradient mismatches remain. In both, eager FSDP2 keeps a gradient in fp32 where SimpleFSDP rounds it to bf16. Eager config fix ---------------- qwen3_moe_eager_numerics compiled the model's local compile regions (loss, fused_binary_activation, cos_sin_rope, fp32_to_bf16_split). GraphTrainer requires model.local_compile_regions = [] and runs that code uncompiled. The dense eager configs already set it to [] to match GraphTrainer; the MoE one did not. As a result, the step-1 loss differed by 3.9e-5 before any gradient was involved. With the regions off, step 1 matches eager bitwise and the losses diverge from step 2, which isolates the two gradient issues below. Issue 1: TP-reduced norm weight gradients (same as the dense tests) ------------------- This is the issue #5106 identified for the dense Llama3 and Qwen3 tests. - Each RMSNorm weight is replicated over TP (typed spmd.R), while its input is sharded over TP: on the sequence for attention_norm, ffn_norm and the final norm (sequence parallel), and on heads for the Qwen3 QK norms (q_norm, k_norm). So each TP rank computes a partial gradient, and the partials are summed over TP. - Since the dev20261002 nightly, PyTorch sets grad_dtype = reduce_dtype (fp32) on FSDP2's unsharded parameter (pytorch 38d3f6fd0d6e, "[FSDP2] Separate sharded and unsharded gradient dtypes", per #5106). Eager FSDP2 therefore sums the partials in fp32 and reduce-scatters the fp32 sum. - SimpleFSDP also sums them in fp32, in the backward of spmd.convert(I -> R). But the sum flows into the bf16 all-gathered weight, and autograd casts a gradient to its tensor's dtype, so it is rounded to bf16 before the reduce-scatter. Evidence, comparing every parameter's gradient after step 1 (eager vs GraphTrainer, dp_shard=4, tp=2, ep=2, eager regions off): - The 33 norm weights (attention_norm, ffn_norm, q_norm and k_norm in each of the 8 layers, plus the final norm) differ by about 1e-3 relative. Every matmul weight is bitwise equal. - Locally applying the #5106 workaround makes all 33 match bitwise. The workaround all-gathers parameters that have an R axis outside DP in fp32 and lets spmd.convert cast them to bf16, so the TP-reduced gradient stays fp32. With it, the dense Llama3 and Qwen3 tests also match eager bitwise for all 20 steps on 8 GPUs. Issue 2: router gate grad_weight -------------------------------- - The MoE router gate is a HiMidLoLinear, whose backward returns grad_weight in fp32 by design. - In eager FSDP2 the gate weight is the unsharded parameter itself: an autograd leaf whose grad_dtype is fp32 (the same FSDP2 change). So the fp32 grad_weight is kept. - In SimpleFSDP the gate weight is computed from the parameter (it is all-gathered and cast to bf16), so it is a bf16 non-leaf. Autograd therefore rounds the fp32 grad_weight to bf16. This is pytorch/pytorch#189633, also noted in HiMidLoLinear's TODO and in _run_qwen3_moe_loss_compare. - The rounding happens on each TP rank's partial gradient, before the TP sum, so the #5106 approach does not reach it. With the workaround applied, the 8 router gate weights (one per layer) still differ in every element, by about 1e-3 relative, and they are the only gradients that still differ. Since #4923, this test compares losses with run_loss_compare_close (rtol=1e-4) to tolerate the router difference. Together, the two issues now push the losses past that tolerance. Results (8x H100, torch 2.16.0.dev20261007, 20 steps, eager vs GraphTrainer): config first diff max |loss diff| MoE, eager regions on (before) step 1 1.39e-3 MoE, eager regions off (this change) step 2 1.50e-3 MoE, regions off + #5106 workaround step 2 1.86e-3 dense Llama3 / Qwen3 + #5106 workaround bitwise 0 Test Plan: - Ran _run_qwen3_moe_loss_compare on this branch (8x H100, torch 2.16.0.dev20261007): step 1 matches eager bitwise, and the losses diverge from step 2 (max 1.50e-3 at step 19, above rtol=1e-4). The test still fails, so the strict xfail holds. - The gradient comparisons and #5106 workaround runs above were local experiments and are not part of this change. - ufmt, flake8 and codespell pass on the changed files.
Update after review 5 (rebased on main):
FP32OutputLineartoHiMidLoLinear(torchtitan/models/common/hi_mid_lo_linear.py), after the hi, mid and lo pieces of its backward.LMHeadFP32OutputConverterkeeps its name: it exists for the fp32 logits.torch.compile), where dropping the.to(bf16).float()round trip zeroes every piece after the first. The split now upcasts its pieces with an integer shift, which leaves no round trip to drop, soemulate_precision_castsis gone too. Run uncompiled (graph_trainer's regional mode), the layer's backward is 5-7% slower; graph_trainer's full mode gets faster (LM-head forward + backward 20.5 -> 16.5 ms, H100).fp32_to_bf16_split, and the split's argument istensor.backward_mode: Literal["hi_mid", "hi_mid_lo"], default "hi_mid", named after the pieces (the 2-piece split is hi + mid); the router gates set "hi_mid_lo".CastLinearrounded it to bf16, and FSDP2 in recent torch nightlies keeps it, so the rollouts diverge from step 3.Update after review 4:
FP32OutputLinearmoved totorchtitan/models/common/fp32_output_linear.py.higher_precision_bwd->backward_mode: Literal["bf16x2", "bf16x3"], default "bf16x2"; the router gates set "bf16x3"..to(torch.bfloat16), ties to even: cuBLAS BF16x9's a0, a1, a2 without their scales. It is compiled withemulate_precision_casts, so it matches eager bit for bit, with the same errors as before and faster than the integer bit ops it replaces.fp32_output_splitlocal_compile region. The LM-head converter and the models with FP32OutputLinear routers turn it on. It usesdynamic=True, so at most 4 graphs.Update after review 3 (rebased on main):
exact_grad_output_split->higher_precision_bwd, default False; the router gates set it to True.torchtitan::split_into_bf16_pieces).TLDR:
(Check the tables below)
torch.mm(out_dtype=float32), which does the GEMM in bf16, but accumulates in fp32 (check the table).RouterGateLineardoesRouterGateLinear's BF16x9 backward) to 18.9 ms, or 18.0 ms compiledCastLinearandRouterGateLinear, and unified the code underHiMidLoLinearControlled results
1x GB300, the real Qwen3.5-27B lm_head weight (vocab 248320, hidden 5120) and hidden states from 2048 tokens of text. Tokens are sampled from the model's fp64 distribution, like the generator samples them. Logprob error is the mean |error| of the sampled token's logprob vs fp64.
Inference, LM head alone, per call
Training, one 2048-token chunk of
ChunkedLossWrapper(forward + CE + backward). Gradient errors are vs exact fp64 gradients; rounding those to bf16 alone gives 1.66e-03 (dh) and 1.65e-03 (dW).Validation
Qwen3-30B-A3B, 2 nodes x 4 GB300 (PP2 x DP4, EP4, HybridEP + CUDA graphs, no AC), random init, c4, 1M tokens/step, 100 and 300 steps, seeds 42 / 777 (each cell is
seed 42 / seed 777). tps is the median over steps 21-300.fp32 lm_head, old vs new
main_head-fp32cast_gate-oldCastLinear)pr_head-fp32_gate-newHiMidLoLinear)Seed 777

Seed 42

Router gate backward, old vs new (bf16 lm_head)
main_head-bf16_gate-oldpr_head-bf16_gate-newSeed 777

Seed 42

How the backward trick works
More details in the docstring
2 vs 3 pieces of grad_output
backward_mode("hi_mid_lo" for routers, "hi_mid" for the LM head) splits the fp32 grad_output into 3 bf16 pieces (exact) instead of 2 (~16 bits):LMHeadFP32OutputConverterdefaults it to "hi_mid" (configurable).Relative error vs fp64, and backward time as a multiple of a bf16 Linear's (GB300; Qwen3-8B LM head on 2048 tokens; a 2048 -> 128 router, errors on 16k tokens, times on 64k). Same table as the docstring:
NOTE: the validation runs above predate review 3: 2 truncated pieces for the head and the router, an eager split, and a bf16
grad_weight. In the Controlled results, grad_weight is bf16 except in the fp32.gradrow; the table above keeps it in fp32.Q&A
dh1.66e-03 vs 1.69e-03,dWequal), but 2.9x slower eager (55.7 vs 18.9 ms per chunk) and 3.0x compiled (53.4 vs 18.0 ms).RouterGateLinearis replaced, not just the LM head.Code changes
HiMidLoLinear(Linear), inhi_mid_lo_linear.py, replacesCastLinearandRouterGateLinear. bf16 operands on CUDA take the bf16-GEMM path (see the docstring). CPU and fp32 or mixed dtypes upcast to fp32, asRouterGateLineardid; batch-invariant mode also upcasts (see the last bullet).fp32_to_bf16_splitlocal_compile region; it upcasts its pieces with an integer shift, so no compiler can drop its.to(bf16).float()round trip. The router gates setbackward_mode="hi_mid_lo"explicitly.LMHeadFP32OutputConverter(replacingLMHeadCastConverter) swaps thelm_headconfig toHiMidLoLinear.Config. Quantization rejects the class through its allowlist, as it didCastLinearandRouterGateLinear.Linearhead now usesLMHeadFP32OutputConverter; the GPT-OSS, Qwen3 MoE, Qwen3-30B-A3B and search_r1 configs didn't before. Muse Glimmer's head is aSoftCappedLinearand is unchanged.enable_fp32_matmul_emulation_with_bf16x9(the globalfp32_precision = "bfx9", added forRouterGateLinear). After this PR it only affected fp32-weight training and DeepSeek V4's mHC fp32F.linear, on Blackwell.grad_weightnow comes back in fp32;grad_inputis still rounded once to bf16. FSDP2 keeps it in torch nightlies since 2026-10-02, so the LM head (eager inChunkedLossWrapper) gets an fp32dW: 2.5e-06 error vs fp64, against the 1.66e-03 bf16 floor (H100, 2 GPUs, toy shape). Compiled code still rounds it to bf16 (an open PyTorch fix). On older torch, autograd casts it back to bf16: same bits as before, +0.6 ms per Qwen3-8B head chunk on GB300.batch_invariant_ops(Triton runs them in TF32) instead of cuBLAS'sout_dtypeGEMM, which is not batch-invariant.