Skip to content

Add HiMidLoLinear for the LM head and router gate; delete CastLinear and RouterGateLinear - #4923

Merged
felipemello1 merged 20 commits into
pytorch:mainfrom
felipemello1:fp32-output-linear
Oct 6, 2026
Merged

felipemello1 merged 20 commits into
pytorch:mainfrom
felipemello1:fp32-output-linear

Conversation

@felipemello1

@felipemello1 felipemello1 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Update after review 5 (rebased on main):

  • Renamed FP32OutputLinear to HiMidLoLinear (torchtitan/models/common/hi_mid_lo_linear.py), after the hi, mid and lo pieces of its backward. LMHeadFP32OutputConverter keeps its name: it exists for the fp32 logits.
  • The split's custom op is gone. graph_trainer runs with 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. The split now upcasts its pieces with an integer shift, which leaves no round trip to drop, so emulate_precision_casts is 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).
  • The region is fp32_to_bf16_split, and the split's argument is tensor.
  • 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".
  • RL loss reference, steps 3-10: the LM head's grad_weight is now fp32, where CastLinear rounded it to bf16, and FSDP2 in recent torch nightlies keeps it, so the rollouts diverge from step 3.
  • Docstrings: why chunking the grad_input sum helps when the GEMM already accumulates in fp32, and when our pieces equal cuBLAS BF16x9's a0, a1, a2 bit for bit.

Update after review 4:

  • FP32OutputLinear moved to torchtitan/models/common/fp32_output_linear.py.
  • higher_precision_bwd -> backward_mode: Literal["bf16x2", "bf16x3"], default "bf16x2"; the router gates set "bf16x3".
  • The split rounds each piece with .to(torch.bfloat16), ties to even: cuBLAS BF16x9's a0, a1, a2 without their scales. It is compiled with emulate_precision_casts, so it matches eager bit for bit, with the same errors as before and faster than the integer bit ops it replaces.
  • The split is the fp32_output_split local_compile region. The LM-head converter and the models with FP32OutputLinear routers turn it on. It uses dynamic=True, so at most 4 graphs.
  • NOTE: the split timings in the docstrings and the tables below are being regenerated on GB300.

Update after review 3 (rebased on main):

  • Every piece is rounded to nearest instead of truncated: LM-head grad_weight error 1.6e-5 -> 8.4e-6, router grad_input 4.9e-6 -> 2.4e-6 (2 pieces, GB300).
  • exact_grad_output_split -> higher_precision_bwd, default False; the router gates set it to True.
  • The backward has one function per layout, and the split runs as one compiled kernel behind a custom op (torchtitan::split_into_bf16_pieces).
  • NOTE: CI compares golden losses exactly, so the MoE goldens need regenerating from this PR's CI run.

TLDR:

(Check the tables below)

  • We want some layers to be computed in Fp32, e.g. lm_head and router gate
  • For the head, we use CastLinear, which sets weight.to(fp32) every forward
  • The weight is a huge matrix (248k vocab for Qwen3.5), so each forward copies it to fp32 and runs a slow fp32 GEMM
  • BF16x9 (the trainer's fp32 matmul emulation) is faster, but still slow
  • TF32 is faster, but imprecise
  • This PR instead does torch.mm(out_dtype=float32), which does the GEMM in bf16, but accumulates in fp32 (check the table).
  • This is already what RouterGateLinear does
  • However, in this PR we improved the backward by running only 2 out of the 9 GEMMs: fwd/bwd go from 55.7 ms (RouterGateLinear's BF16x9 backward) to 18.9 ms, or 18.0 ms compiled
  • We deleted CastLinear and RouterGateLinear, and unified the code under HiMidLoLinear
  • The router splits grad_output into 3 bf16 pieces (exact), the LM head into 2; see "2 vs 3 pieces" below

Controlled 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

                                          1 seq (us)  16 seq (us)   logprob |err|
upcast + IEEE GEMM (generator before)           1850         2720         8.9e-06
upcast + BF16x9 GEMM                            1850         2720         2.2e-06
upcast + TF32 GEMM                              1868         1815         1.9e-05
bf16 GEMM, fp32 out (this PR)                    362          368         1.0e-05
bf16 GEMM, bf16 out (bf16 head)                  360          364         1.7e-02

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

                                                       ms   logprob |err|     dh err     dW err
upcast + IEEE GEMM                                  229.5         8.9e-06   1.66e-03   1.65e-03
upcast + BF16x9 GEMM (trainer before)                77.5         2.2e-06   1.66e-03   1.65e-03
upcast + TF32 GEMM                                   20.3         1.9e-05   1.71e-03   1.66e-03
bf16 GEMM, fp32 out, BF16x9 bwd (router)             55.7         1.0e-05   1.66e-03   1.65e-03
bf16 GEMM, fp32 out, bf16 bwd (megatron)             12.0         1.0e-05   2.23e-03   2.13e-03
bf16 GEMM, fp32 out, hi+mid bwd (this PR)             18.9         1.0e-05   1.69e-03   1.65e-03
bf16 GEMM, fp32 out, hi+mid bwd, fp32 .grad           18.5         1.0e-05   1.69e-03   2.78e-05
bf16 GEMM, bf16 out (bf16 head)                      12.3         1.7e-02   1.14e-02   1.24e-02
(compile) bf16 GEMM, fp32 out, BF16x9 bwd (router)   53.4         1.0e-05   1.66e-03   1.65e-03
(compile) bf16 GEMM, fp32 out, bf16 bwd (megatron)   10.0         1.0e-05   2.23e-03   2.13e-03
(compile) bf16 GEMM, fp32 out, hi+mid bwd (this PR)   18.0         1.0e-05   1.69e-03   1.65e-03

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

run lm_head gate bwd MFU tps/GPU vs old lm_head-stage mem loss@300
main_head-fp32cast_gate-old fp32 (CastLinear) old (BF16x9) 15.3 / 15.2% 13,686 / 13,606 149.4 GiB 6.145 / 6.228
pr_head-fp32_gate-new fp32 (HiMidLoLinear) new (hi+mid) 18.8 / 18.6% 16,822 / 16,684 +22.9 / +22.6% 148.7 GiB 6.164 / 5.997

Seed 777
image

Seed 42
image

Router gate backward, old vs new (bf16 lm_head)

run lm_head gate bwd MFU tps/GPU vs old lm_head-stage mem loss@300
main_head-bf16_gate-old bf16 old (BF16x9) 19.4 / 19.4% 17,410 / 17,409 148.0 GiB 6.128 / 6.119
pr_head-bf16_gate-new bf16 new (hi+mid) 19.6 / 19.5% 17,516 / 17,492 +0.6 / +0.5% 148.0 GiB 6.180 / 6.019

Seed 777
image

Seed 42
image

  • tps moves at most 0.8% between seeds for the same run.
  • Loss is worse on the 100 step run, maybe due to an unlucky peak? 300 step looks fine and better.

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):

  • Router (grad_input sums over its experts): the split sets the error, so a 3rd piece cuts it ~7x for a small op.
  • LM head (sums over the vocab): tensor-core accumulation sets the error, so a 3rd piece doesn't help and costs ~1.5x backward. LMHeadFP32OutputConverter defaults 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:

                            relative error             backward time
                            grad_input  grad_weight    eager   compiled
LM head (bf16 backward: 2.8 ms)
  bf16 grad_output          1.5e-3      1.3e-3          1.0x    1.0x
  2 pieces (default)        2.1e-4      8.4e-6          2.4x    2.5x
  3 pieces                  2.1e-4      8.6e-6          3.6x    3.8x
  fp32 matmul (IEEE)        7.9e-5      2.3e-6         26.2x   27.4x
router (bf16 backward: 0.24 ms)
  bf16 grad_output          1.7e-3      1.2e-3          1.0x    1.0x
  2 pieces                  2.4e-6      2.9e-6          2.2x    1.6x
  3 pieces (routers)        3.5e-7      2.1e-6          2.8x    1.7x
  fp32 matmul (IEEE)        5.1e-8      2.9e-7          5.1x    4.5x

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 .grad row; the table above keeps it in fp32.

Q&A

  • Why not keep the router's BF16x9 backward? Same gradients (dh 1.66e-03 vs 1.69e-03, dW equal), but 2.9x slower eager (55.7 vs 18.9 ms per chunk) and 3.0x compiled (53.4 vs 18.0 ms).
  • Does the router get the same gradient error with this? Yes. Qwen3.5-35B-A3B router shape (2048 -> 256 experts, 40 layers, 64k tokens, GB300), with 3 pieces: grad_input error 1.66e-03 for both, 100.0% of grad_input elements bitwise equal, GPU time 44.6 -> 15.8 ms. grad_weight now stays fp32: 1.66e-03 -> 8.1e-06. So RouterGateLinear is replaced, not just the LM head.

Code changes

  • HiMidLoLinear(Linear), in hi_mid_lo_linear.py, replaces CastLinear and RouterGateLinear. bf16 operands on CUDA take the bf16-GEMM path (see the docstring). CPU and fp32 or mixed dtypes upcast to fp32, as RouterGateLinear did; batch-invariant mode also upcasts (see the last bullet).
  • The backward has one function per layout (wide, e.g. an LM head; narrow, e.g. a router). The grad_output split is the fp32_to_bf16_split local_compile region; it upcasts its pieces with an integer shift, so no compiler can drop its .to(bf16).float() round trip. The router gates set backward_mode="hi_mid_lo" explicitly.
  • LMHeadFP32OutputConverter (replacing LMHeadCastConverter) swaps the lm_head config to HiMidLoLinear.Config. Quantization rejects the class through its allowlist, as it did CastLinear and RouterGateLinear.
  • Every RL config with a plain Linear head now uses LMHeadFP32OutputConverter; the GPT-OSS, Qwen3 MoE, Qwen3-30B-A3B and search_r1 configs didn't before. Muse Glimmer's head is a SoftCappedLinear and is unchanged.
  • Removed enable_fp32_matmul_emulation_with_bf16x9 (the global fp32_precision = "bfx9", added for RouterGateLinear). After this PR it only affected fp32-weight training and DeepSeek V4's mHC fp32 F.linear, on Blackwell.
  • grad_weight now comes back in fp32; grad_input is still rounded once to bf16. FSDP2 keeps it in torch nightlies since 2026-10-02, so the LM head (eager in ChunkedLossWrapper) gets an fp32 dW: 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.
  • Behavior changes for MoE: router gradients change slightly (3 bf16 pieces instead of BF16x9: closer to fp32, not bitwise), and in batch-invariant mode the router now computes with fp32 inputs through batch_invariant_ops (Triton runs them in TF32) instead of cuBLAS's out_dtype GEMM, which is not batch-invariant.

@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Sep 28, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 28, 2026
Comment thread torchtitan/models/common/linear.py Outdated
grad_weight_ED = torch.mm(
grad_output_fp32_TE.T, input_forward_TD.float()
).to(ctx.weight_dtype)
class Fp32OutputLinear(Linear):

@anijain2305 anijain2305 Sep 28, 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.

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?

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.

Whatever you choose, it feels to me that we should use "FP32" / "BF16" over "Fp32" / "Bf16"

Comment thread torchtitan/models/common/linear.py Outdated
).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.

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

Comment thread torchtitan/models/common/linear.py Outdated
hi_TO, lo_TO = _split_into_bf16_hi_lo(grad_output_TO)
num_tokens, out_features = hi_TO.shape

if out_features > num_tokens:

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.

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.

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'm not convinced that one would ever quantize either of them

# NVFP4 on every in-layer linear, leaving the top-level LM head ("...output")
# untouched (required for NVFP4; useful for MXFP8)

so I'm currently on the side of "we only need one class"

@tianyu-l
tianyu-l requested a review from ngimel September 28, 2026 18:30
@anijain2305

Copy link
Copy Markdown
Contributor

Great work! The backward trick is clever!

@tianyu-l
tianyu-l requested a review from BoyuanFeng September 28, 2026 20:15
Comment thread torchtitan/models/common/linear.py Outdated
grad_weight_ED = torch.mm(
grad_output_fp32_TE.T, input_forward_TD.float()
).to(ctx.weight_dtype)
class Fp32OutputLinear(Linear):

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.

Whatever you choose, it feels to me that we should use "FP32" / "BF16" over "Fp32" / "Bf16"

Comment thread torchtitan/models/common/linear.py Outdated
if bias is not None:
output_TE = output_TE + bias.float()
return output_TE
output = _Fp32OutputLinearFunction.apply(

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread torchtitan/models/common/linear.py Outdated
input.reshape(-1, input.shape[-1]), weight
)
output = output.reshape(*input.shape[:-1], -1)
return output if bias is None else output + bias.float()

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.

Comment thread torchtitan/models/common/linear.py Outdated
hi_TO, lo_TO = _split_into_bf16_hi_lo(grad_output_TO)
num_tokens, out_features = hi_TO.shape

if out_features > num_tokens:

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'm not convinced that one would ever quantize either of them

# NVFP4 on every in-layer linear, leaving the top-level LM head ("...output")
# untouched (required for NVFP4; useful for MXFP8)

so I'm currently on the side of "we only need one class"

Comment thread torchtitan/models/common/linear.py Outdated
# 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)

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.

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

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 should also remove

enable_fp32_matmul_emulation_with_bf16x9()

Comment thread torchtitan/models/common/linear.py Outdated
return [
hi.to(torch.bfloat16),
mid.to(torch.bfloat16),
(rest - mid).to(torch.bfloat16),

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

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

Comment thread torchtitan/models/common/linear.py Outdated
Comment on lines +471 to +473
grad_weight_OD = torch.mm(
stacked_PTO.T, torch.cat([input_TD] * num_pieces)
)

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

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?

@felipemello1 felipemello1 changed the title Add Fp32OutputLinear for the LM head and router gate; delete CastLinear and RouterGateLinear Add FP32OutputLinear for the LM head and router gate; delete CastLinear and RouterGateLinear Oct 2, 2026
Felipe Mello added 14 commits October 6, 2026 10:33
- 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.
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).
@felipemello1
felipemello1 merged commit 36adc3a into pytorch:main Oct 6, 2026
aditvenk added a commit that referenced this pull request Oct 8, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl 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.

3 participants