Skip to content

[graph_trainer][graph_pp] Bind dW live-in symbols across the dI/dW split - #5109

Merged
aditvenk merged 1 commit into
mainfrom
aditvenk/graphpp-didw-symbol-bindings
Oct 7, 2026
Merged

aditvenk merged 1 commit into
mainfrom
aditvenk/graphpp-didw-symbol-bindings

Conversation

@aditvenk

@aditvenk aditvenk commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

The H100 GraphTrainer CI fails in three GraphPP full_inductor tests (DeepSeek-V3 with Interleaved1F1B, ZBVZeroBubble, and DualPipeV) while compiling the stage 1 backward-weight (bw_dw) graph:

torch._inductor.exc.InductorError: AssertionError: For u6 + u7,
expected [u6, u7] to have been codegen-ed.

Latent bug

There are two gaps. Together they leave Inductor unable to bind symbols that appear only inside compound shape expressions of bw_dw inputs.

  1. split_di_dw_graph only forwards SymInt nodes that dW ops read directly. For routed MoE experts the dW live-ins are the received tokens, the recomputed SwiGLU activations, and the per-expert output grads, all shaped (u6 + u7, D). u6 and u7 are the EP all-to-all receive counts (output_splits in token_dispatcher.py), one per EP peer. No dW op reads u6 or u7 directly, so bw_dw received no SymInt inputs at all, even though the full backward graph had them as placeholders. Upstream _extract_fwd_bwd_modules has an explicit step that binds every symbol referenced by backward inputs; the dI/dW split skipped it.

  2. Even with those SymInts present, upstream regional_inductor, which GraphTrainer uses for both the "full" and "regional" modes, scoops regions with fuse_by_partitions. That turns only nodes used by region ops into region inputs. The binding SymInts have no FX users, since only tensor shapes reference their symbols, so they were dropped from the compiled region. Inductor's codegen_inputs then sees inputs shaped (u6 + u7, D), with no input whose dim is u6 or u7 alone and no SymInt input, and raises the assertion above.

What exposed it

Bisecting torchtitan with the torch nightly pinned at 20260926 finds f2b9625 ("[2/2] [graph_trainer] PP=1 GA schedule with FSDP overlap", #4927) as the first bad commit. a6aa607 and f2b9625^ pass. Reverting only that commit's split_fsdp_collectives.py hunk on top of f2b9625 makes the test pass again.

That hunk removed the _is_expert_fsdp_reduce_grad exclusion, so extract_fsdp_reduce_grad_graph now also extracts expert-FSDP (edp_shard) reduce-scatters into the separate REDUCE_GRAD graph.

Before #4927, the expert reduce-scatter stayed inside the backward graph. When split_di_dw_graph extracts the dI graph, _extract_graph_with_inputs_outputs copies every computable node and then runs eliminate_dead_code(). wait_tensor is registered as side-effectful, so DCE kept the whole expert weight-grad chain (_grouped_mm -> reduce_scatter -> wait_tensor) in dI. bw_dw only received the already-reduced, static-shaped gradients (for example f32[2, 256, 256]) and never saw an unbacked shape.

After #4927 the expert weight-grad _grouped_mm is pure, so it moves to dW, which is where zero-bubble schedules want weight-grad work. A weight gradient contracts over the token dimension (dW = dy^T x), so bw_dw now needs the per-token tensors shaped (u6 + u7, D) as live-ins. That exposed both gaps above.

Fix

Both changes are in graph_pp/split_di_dw.py; regional_inductor and the Inductor passes are unchanged.

  • After _collect_saved_values_for_dw collects the dW live-ins, it also saves the binding node (a SymInt placeholder or an unbacked-binding node in the backward graph) for every symbol, replaced or unreplaced, that those live-ins reference. This mirrors the backward-input symbol binding in _extract_fwd_bwd_modules. The binders are deduplicated with the existing SymInt live-ins and flow from bw_di to bw_dw like any other SymInt live-in.

  • _add_symint_live_in_uses gives every SymInt input of the dW graph that has no users an explicit use: aten.sym_constrain_range_for_size(sym). That states a true invariant (token counts are non-negative). The op is registered as side-effectful, so DCE keeps it. Inductor decomposes it to a no-op, and in eager (regional mode) it is a ~1 us range check. Because an op now consumes the SymInt, regional_inductor's region extraction makes it a region input, and Inductor can bind the symbol. A TODO notes that this can be dropped once upstream regional_inductor passes symbol-binding inputs into regions itself.

Both parts are required; removing either one reproduces the original InductorError.

Test Plan:

  • The three failing tests now pass, e.g. python -m torchtitan.experiments.graph_trainer.tests.integration_tests --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_graph_pp_interleaved_1f1b_full_inductor <out_dir> --ngpu 8 (and the zbv_zero_bubble and dual_pipe_v variants).
  • Numerics: the same GraphPP config switched to regional Inductor, which runs before and after this change, with debug.seed = 42 and debug.deterministic = True. Loss and grad_norm from TensorBoard are bitwise identical to main on all 8 ranks for 10 steps, for ZBVZeroBubble and DualPipeV.
  • New unit tests in GraphPPSplitDiDwTest, both runnable on CPU:
    • test_split_forwards_symbol_bindings_for_dw_live_ins checks that bw_dw receives the u0/u1 binders, that each has a sym_constrain_range_for_size use, and that dI/dW still reconstruct the full backward.
    • test_dw_graph_with_routed_token_live_ins_compiles_with_inductor compiles bw_dw with full_inductor_compilation_pass and checks the result. Without either part of the fix it fails with the original InductorError.
  • pytest test_graph_pp_passes.py, test_graph_pp_runner.py and test_passes.py pass, except test_dist_moe_slot_is_an_explicit_stage_graph_input, which also fails on main because the optional dist_moe package is not installed.
  • ufmt, flake8 and codespell pass on the changed files.

The H100 GraphTrainer CI fails in three GraphPP full_inductor tests
(DeepSeek-V3 with Interleaved1F1B, ZBVZeroBubble, and DualPipeV) while
compiling the stage 1 backward-weight (bw_dw) graph:

  torch._inductor.exc.InductorError: AssertionError: For u6 + u7,
  expected [u6, u7] to have been codegen-ed.

This is a torchtitan regression, not a PyTorch one. The failure
reproduces with torch nightlies 20260926, 20261005 and 20261006.

Latent bug
----------

There are two gaps. Together they leave Inductor unable to bind
symbols that appear only inside compound shape expressions of bw_dw
inputs.

1. split_di_dw_graph only forwards SymInt nodes that dW ops read
   directly. For routed MoE experts the dW live-ins are the received
   tokens, the recomputed SwiGLU activations, and the per-expert output
   grads, all shaped (u6 + u7, D). u6 and u7 are the EP all-to-all
   receive counts (output_splits in token_dispatcher.py), one per EP
   peer. No dW op reads u6 or u7 directly, so bw_dw received no SymInt
   inputs at all, even though the full backward graph had them as
   placeholders. Upstream _extract_fwd_bwd_modules has an explicit step
   that binds every symbol referenced by backward inputs; the dI/dW
   split skipped it.

2. Even with those SymInts present, upstream regional_inductor, which
   GraphTrainer uses for both the "full" and "regional" modes, scoops
   regions with fuse_by_partitions. That turns only nodes used by
   region ops into region inputs. The binding SymInts have no FX users,
   since only tensor shapes reference their symbols, so they were
   dropped from the compiled region. Inductor's codegen_inputs then
   sees inputs shaped (u6 + u7, D), with no input whose dim is u6 or u7
   alone and no SymInt input, and raises the assertion above.

What exposed it
---------------

Bisecting torchtitan with the torch nightly pinned at 20260926 finds
f2b9625 ("[2/2] [graph_trainer] PP=1 GA schedule with FSDP overlap",
#4927) as the first bad commit. a6aa607 and f2b9625^ pass.
Reverting only that commit's split_fsdp_collectives.py hunk on top of
f2b9625 makes the test pass again.

That hunk removed the _is_expert_fsdp_reduce_grad exclusion, so
extract_fsdp_reduce_grad_graph now also extracts expert-FSDP
(edp_shard) reduce-scatters into the separate REDUCE_GRAD graph.

Before #4927, the expert reduce-scatter stayed inside the backward
graph. When split_di_dw_graph extracts the dI graph,
_extract_graph_with_inputs_outputs copies every computable node and
then runs eliminate_dead_code(). wait_tensor is registered as
side-effectful, so DCE kept the whole expert weight-grad chain
(_grouped_mm -> reduce_scatter -> wait_tensor) in dI. bw_dw only
received the already-reduced, static-shaped gradients (for example
f32[2, 256, 256]) and never saw an unbacked shape.

After #4927 the expert weight-grad _grouped_mm is pure, so it moves
to dW, which is where zero-bubble schedules want weight-grad work. A
weight gradient contracts over the token dimension (dW = dy^T x), so
bw_dw now needs the per-token tensors shaped (u6 + u7, D) as live-ins.
That exposed both gaps above.

Fix
---

Both changes are in graph_pp/split_di_dw.py; regional_inductor and the
Inductor passes are unchanged.

- After _collect_saved_values_for_dw collects the dW live-ins, it also
  saves the binding node (a SymInt placeholder or an unbacked-binding
  node in the backward graph) for every symbol, replaced or
  unreplaced, that those live-ins reference. This mirrors the
  backward-input symbol binding in _extract_fwd_bwd_modules. The
  binders are deduplicated with the existing SymInt live-ins and flow
  from bw_di to bw_dw like any other SymInt live-in.

- _add_symint_live_in_uses gives every SymInt input of the dW graph
  that has no users an explicit use:
  aten.sym_constrain_range_for_size(sym). That states a true invariant
  (token counts are non-negative). The op is registered as
  side-effectful, so DCE keeps it. Inductor decomposes it to a no-op,
  and in eager (regional mode) it is a ~1 us range check. Because an
  op now consumes the SymInt, regional_inductor's region extraction
  makes it a region input, and Inductor can bind the symbol. A TODO
  notes that this can be dropped once upstream regional_inductor
  passes symbol-binding inputs into regions itself.

Both parts are required; removing either one reproduces the original
InductorError.

Test Plan:

- The three failing tests now pass, e.g.
  python -m torchtitan.experiments.graph_trainer.tests.integration_tests
  --test_suite graph_trainer_h100
  --test_name aot_fx_trace_deepseek_v3_graph_pp_interleaved_1f1b_full_inductor
  <out_dir> --ngpu 8
  (and the zbv_zero_bubble and dual_pipe_v variants).
- Numerics: the same GraphPP config switched to regional Inductor,
  which runs before and after this change, with debug.seed = 42 and
  debug.deterministic = True. Loss and grad_norm from TensorBoard are
  bitwise identical to main on all 8 ranks for 10 steps, for
  ZBVZeroBubble and DualPipeV.
- New unit tests in GraphPPSplitDiDwTest, both runnable on CPU:
  - test_split_forwards_symbol_bindings_for_dw_live_ins checks that
    bw_dw receives the u0/u1 binders, that each has a
    sym_constrain_range_for_size use, and that dI/dW still reconstruct
    the full backward.
  - test_dw_graph_with_routed_token_live_ins_compiles_with_inductor
    compiles bw_dw with full_inductor_compilation_pass and checks the
    result. Without either part of the fix it fails with the original
    InductorError.
- pytest test_graph_pp_passes.py, test_graph_pp_runner.py and
  test_passes.py pass, except
  test_dist_moe_slot_is_an_explicit_stage_graph_input, which also fails
  on main because the optional dist_moe package is not installed.
- ufmt, flake8 and codespell pass on the changed files.
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 7, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 7, 2026
@aditvenk aditvenk added the ciflow/h100.8 Trigger H100.8 CI label Oct 7, 2026
aditvenk added a commit that referenced this pull request Oct 7, 2026
The dense Llama3 and Qwen3 AOT FX trace comparisons currently diverge
from eager on PyTorch nightly. Mark them as strict expected failures
until the underlying issue is fixed.

Track the proper fix in #5109.
@aditvenk
aditvenk merged commit 1472b07 into main Oct 7, 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/h100.8 Trigger H100.8 CI 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.

2 participants