Skip to content

[graph_trainer] Fix DTensor shadow-node embedding OOB; re-enable 14 disabled tests - #3480

Merged
SherlockNoMad merged 6 commits into
mainfrom
bahuang/graph_trainer_enable_fsdp_tp_cp
Jun 2, 2026
Merged

SherlockNoMad merged 6 commits into
mainfrom
bahuang/graph_trainer_enable_fsdp_tp_cp

Conversation

@SherlockNoMad

@SherlockNoMad SherlockNoMad commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Root-causes and fixes the bug behind a large batch of graph_trainer tests disabled in #3432, then re-enables the ones it actually explains (14 tests across 4 files).

Most failures in #3432 were filed as assorted "upstream nightly regressions" (cuDNN, FlexAttention, histc-int64, mixed-dtype mm, CUDA-graph device-asserts). They turned out to be a single bug: make_fx traced DTensor shard propagation. ShardingPropagator._propagate_tensor_meta_non_cached runs each op on fake global-shape tensors to derive output metadata; when an enclosing make_fx tracer captures that inference, it leaves a dead "shadow" node for every DTensor op — backed by uninitialized empty_strided placeholders — that no real local-shard output consumes. Harmless for most ops, but bounds-checked ops like aten.embedding read the uninitialized empty_strided index and trigger an out-of-bounds gather on the TP-sharded weight → device-side assert. It's nondeterministic (garbage indices occasionally land in-bounds), and under cudagraph/cuDNN/FlexAttention/precompile it surfaced as different-looking errors — which is why it was misfiled as many separate regressions. Any tensor_parallel_degree > 1 trace is affected.

Fix

  • make_fx_tracer.py: _remove_dead_empty_strided_chains — a targeted DCE that strips the dead empty_strided shadow chains from the traced graph. This lets the tests be re-enabled now, without waiting for the upstream PyTorch fix to reach the CI nightly. It becomes a no-op once the upstream fix is present, and should be removed then (noted in its docstring).
  • The proper upstream fix wraps shard propagation's fake-tensor inference in disable_proxy_modes_tracing so it never enters the graph (separate pytorch/pytorch change).

Tests re-enabled (14)

Verified on 8×H100 against unfixed PyTorch, with controls confirming each fails with the same vectorized_gather_kernel index out of bounds without the fix and passes with it.

integration_tests.py (7) — llama3_fsdp_tp_flexattn, llama3_fsdp_tp_sac_and_offload, qwen3_moe_fsdp_tp_ep, deepseek_v3_fsdp_tp_ep_flexattn, deepseek_v3_fsdp_tp_ep_full_inductor, and the two CP tests llama3_fsdp_tp_cp / qwen3_fsdp_tp_cp (these run with cudagraph disabled — see caveat).

test_trace_module.py (6 classes) — TestTraceDTensor, TestMetadataPropagation, TestTraceModels, etc. (were @unittest.skip("upstream DTensor+Embedding device-side assert regression")). Full file: 46 passed, 2 skipped (2 remaining = unrelated test_gpt_oss scatter-dtype).

test_numerics.py (4) — test_{dense_llama3,moe_dsv3,dense_qwen3,moe_qwen3}_aot_fx_trace_vs_eager (were "DTensor mixed-dtype mm sharding-prop regression"). These are --assert-equal loss compares, so they confirm bitwise numerics match eager.

run_precompile_tests.py (1) — aot_fx_trace_llama3_precompile_fsdp_tp (was "CUDA graph device-side assert regression").

Left disabled (genuinely separate; comments corrected)

  • deepseek_v3_fsdp_tp_cp_ep — aten.add got mixed torch.Tensor and DTensor (CP+EP bug)
  • deepseek_v3_precompile_fsdp_tp_ep — precompile unbacked-symint failure (Could not extract specialized integer from u13, sharding prop on aten.view)
  • deepseek_v3_hybridep — requires the deep_ep package
  • DSv3 test_bitwise_deterministic (2) — stale golden hashes (need re-blessing; not a code bug)
  • AutoParallel tests — require the autoparallel package
  • JIT-mode / partitioner [full DTensor] Use all DTensor for Qwen3 and llama4 at TP region #2149 tests — separate partitioner regression

Caveat: cudagraph + context parallelism

The two CP tests are enabled with --compile.disable_passes cudagraph_pass. CUDA-graph replay of the coalesced FSDP collectives still fails under context parallelism with CUDA error: invalid argument — a separate, pre-existing issue. Each carries a TODO to drop the flag once that's fixed.

Test plan

# llama3 suite (passes end-to-end on 8xH100)
python torchtitan/experiments/graph_trainer/tests/integration_tests.py <out> \
  --test_suite graph_trainer_default --ngpu 8
# qwen3 / deepseek_v3 configs run individually on 8xH100
pytest torchtitan/experiments/graph_trainer/tests/test_trace_module.py   # 46 passed, 2 skipped
pytest torchtitan/experiments/graph_trainer/tests/test_numerics.py -k aot_fx_trace  # 4 passed

🤖 Generated with Claude Code

…ing OOB

The aot_fx_trace_llama3_fsdp_tp_cp integration test was disabled because
any tensor_parallel_degree > 1 trace crashed with a device-side assert.

Root cause: DTensor shard propagation runs each op on fake global-shape
tensors to derive output metadata. make_fx traced that inference, leaving
a dead "shadow" node for every DTensor op (global shape, backed by
empty_strided placeholders) that no real local-shard output consumes.
Mostly harmless, but bounds-checked ops like aten.embedding read the
uninitialized empty_strided index and trigger an out-of-bounds gather on
the TP-sharded weight.

The proper fix is upstream in PyTorch (wrap shard propagation's
fake-tensor inference in disable_proxy_modes_tracing). Until that lands in
the graph_trainer CI nightly, _remove_dead_empty_strided_chains strips the
dead empty_strided chains from the traced graph so this can land now. It
becomes a no-op once the upstream fix is present, and should be removed
then.

cudagraph is disabled for this test: CUDA-graph replay of the coalesced
FSDP collectives still fails under context parallelism with
"CUDA error: invalid argument" (a separate, pre-existing issue). The rest
of the aot_fx_trace path is exercised.

Test:
  python torchtitan/experiments/graph_trainer/tests/integration_tests.py \
    <out> --test_suite graph_trainer_default \
    --test_name aot_fx_trace_llama3_fsdp_tp_cp --ngpu 8
Passes on both fixed and unfixed PyTorch (validated by toggling the
upstream fix).
The empty_strided shadow-node OOB (fixed by _remove_dead_empty_strided_chains,
and upstream by the DTensor sharding-prop change) was the actual cause behind
several tests disabled in #3432 under various 'regression' labels. Verified on
unfixed PyTorch with controls (each fails with the same vectorized_gather_kernel
OOB without the fix, passes with it):

Re-enabled as-is (cudagraph unchanged):
  - aot_fx_trace_llama3_fsdp_tp_flexattn        (was: 'FlexAttention regression')
  - aot_fx_trace_llama3_fsdp_tp_sac_and_offload (was: 'cuDNN CPU-offload regression')
  - aot_fx_trace_qwen3_moe_fsdp_tp_ep           (was: 'histc int64 regression')
  - aot_fx_trace_deepseek_v3_fsdp_tp_ep_flexattn
  - aot_fx_trace_deepseek_v3_fsdp_tp_ep_full_inductor

Re-enabled with cudagraph disabled (separate, still-open cudagraph+CP collective
replay bug; see TODO on the test):
  - aot_fx_trace_qwen3_fsdp_tp_cp

Left disabled with corrected reasons:
  - aot_fx_trace_deepseek_v3_fsdp_tp_cp_ep  (separate 'mixed Tensor/DTensor' CP+EP bug)
  - aot_fx_trace_deepseek_v3_hybridep       (requires deep_ep package)

Validated: graph_trainer_default suite passes end-to-end on 8xH100.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jun 2, 2026
reach a GPU node with downstream users, and erases the whole chain.

TODO: figure out a way to avoid tracing them into graph in the first place.
def _remove_dead_empty_strided_chains(gm: torch.fx.GraphModule) -> None:

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.

The fundamental fix is in pytorch/pytorch#185865

and I will remove _remove_dead_empty_strided_chains utils when the above is in pytorch nightly ....

So don't worry about the slop here.

These unit-test classes (TestTraceDTensor, TestMetadataPropagation,
TestTraceModels, and others) were skipped with 'upstream DTensor+Embedding
device-side assert regression' — the same empty_strided shadow-node OOB fixed
in this PR. The shadow embedding reads uninitialized empty_strided memory, so
the crash is nondeterministic (garbage indices occasionally land in-bounds).

Control on unfixed PyTorch: TestTraceDTensor fails 5/5 with the OOB
device-side assert without _remove_dead_empty_strided_chains, and the full
file passes (46 passed, 2 skipped) with it. The 2 remaining skips are the
unrelated test_gpt_oss scatter-dtype issue.
…precompile)

More tests disabled in #3432 under mislabeled 'regressions' that were actually
the empty_strided shadow-node OOB. Verified on unfixed PyTorch + the DCE fix:

test_numerics.py (aot_fx_trace vs eager, --assert-equal — bitwise match):
  - test_dense_llama3_aot_fx_trace_vs_eager
  - test_moe_dsv3_aot_fx_trace_vs_eager
  - test_dense_qwen3_aot_fx_trace_vs_eager
  - test_moe_qwen3_aot_fx_trace_vs_eager
  (were labeled 'DTensor mixed-dtype mm sharding-prop regression')

run_precompile_tests.py:
  - aot_fx_trace_llama3_precompile_fsdp_tp re-enabled (was 'CUDA graph
    device-side assert regression'; passes, loss 4.227)

Left disabled with corrected reason:
  - aot_fx_trace_deepseek_v3_precompile_fsdp_tp_ep — separate precompile
    unbacked-symint failure ('Could not extract specialized integer from u13',
    sharding prop on aten.view), not the empty_strided fix.
@SherlockNoMad SherlockNoMad changed the title [graph_trainer] Fix TP embedding OOB and re-enable aot_fx_trace tests [graph_trainer] Fix DTensor shadow-node embedding OOB; re-enable 14 disabled tests Jun 2, 2026

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

Can we file a follow-up issues for the TODOs ?

…le 'outputs' in CI

run_loss_compare() relied on loss_compare.py's default --job-dump-folder
('outputs'), created relative to cwd. In CI containers that path isn't
writable, so the seed-checkpoint step failed with
'PermissionError: [Errno 13] Permission denied: outputs', surfacing as
'AssertionError: False is not true' in the re-enabled
test_{dense,moe}_*_aot_fx_trace_vs_eager tests.

Route the run through a tempfile.TemporaryDirectory and pass
--job-dump-folder, matching run_loss_compare_close().
@SherlockNoMad
SherlockNoMad merged commit faa96e7 into main Jun 2, 2026
14 of 16 checks passed
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 2, 2026
…orch#3436 thread

Merged 7 upstream commits (b72d986..04a3098). Headline is PR
pytorch#3450 — the upstream-canonical fix for the histc->scatter swap
that our PR pytorch#3436 was tracking. Approach: build boolean
routing_map_BLE via scatter_ in router, compute
num_tokens_per_expert via routing_map.sum, thread the map through
to dispatcher. Same scatter direction we recommended, done better
(computed once, reused).

API change at the boundary: router returns 4-tuple; dispatch()
takes new num_local_tokens_per_expert_E positional arg. ezpz
doesn't override these methods or unpack router output directly,
inherits cleanly. set_moe_sharding_config call into upstream's
helper picks up the new shard declaration automatically. No
ezpz replay needed.

Other 6 commits: HybridEP compile (pytorch#3360), MXFP8 consolidation
(pytorch#3473), graph_trainer DTensor fix (pytorch#3480), graph_trainer test
skips (pytorch#3432), two CI migrations (pytorch#3464, pytorch#3479). None touch ezpz.

Live 2N smoke deferred to Aurora: the project .venv/bin/python
symlinks at an Aurora-only Spack hash (python-3.12.12-5zo3wzv)
that Sunspot doesn't have (Sunspot equivalent is the nvje3vk
hash). Smoke per the journal's "always smoke after GroupedExperts
touches" lesson should run on Aurora.

Also: updated ~/.ezpz/utils.sh from bit.ly canonical (now exposes
unified ezpz_setup; backup at utils.sh-20260602-065437).
SherlockNoMad added a commit that referenced this pull request Jun 3, 2026
…y_strided shadow-node bug)

The skip on `test_llama3_aot_fx_trace_autoparallel_vs_eager` (and the
integration test `autoparallel_llama3_fsdp_tp`) blamed an "upstream
AutoParallel nll_loss assertion regression" / "incorrect loss partitioning".
That was a misattribution: it is the same empty_strided dead-shadow-node bug
that #3480 root-caused and fixed with `_remove_dead_empty_strided_chains`.

AutoParallel produces a model-only graph (vocab-sharded DTensor logits); the
loss op is applied afterwards inside graph_trainer's `make_fwd_bwd_step`, which
is traced by `minimal_fx_tracer` -- exactly the graph the DCE cleans. Under the
unfixed nightly, DTensor shard propagation leaves a dead `nll_loss` shadow node
reading an uninitialized `empty_strided` target, which trips the bounds check
`t >= 0 && t < n_classes` at runtime (same failure class as the embedding OOB).
`_remove_dead_empty_strided_chains` strips that dead chain. The upstream fix is
pytorch/pytorch #185865.

Verified on 8xH100 (autoparallel installed): the loss matches eager (max diff
1.3e-4), `1 passed`. CI runs this unit test on the unfixed nightly
(integration_test_8gpu_graph_trainer.yaml), so it exercises the DCE path
directly -- keep `_remove_dead_empty_strided_chains` until #185865 lands.

The DSv3 AutoParallel and JIT (#2149) tests remain disabled: separate,
still-open bugs (confirmed #2149 still reproduces "Node tangents_2 was invalid,
but is output").

Test plan:
  pytest torchtitan/experiments/graph_trainer/tests/test_numerics.py::TestGraphTrainerAutoParallelNumerics::test_llama3_aot_fx_trace_autoparallel_vs_eager

🤖 Generated with [Claude Code](https://claude.com/claude-code)
SherlockNoMad added a commit that referenced this pull request Jun 4, 2026
DO NOT MERGE until pytorch/pytorch #185865 (or a reland) is in the CI nightly.

#3480 added `_remove_dead_empty_strided_chains` as a workaround: DTensor shard
propagation ran each op on fake global-shape tensors for metadata, and when
make_fx captured that inference it left a dead `empty_strided`-backed "shadow"
node for every DTensor op. Bounds-checked ops (`aten.embedding`, `nll_loss`)
read the uninitialized `empty_strided` index/target and tripped device-side
asserts for any `tensor_parallel_degree > 1` aot_fx_trace config.

The proper upstream fix wraps the fake-tensor metadata inference in
`disable_proxy_modes_tracing` inside
`ShardingPropagator._propagate_tensor_meta_non_cached`, so the shadow nodes
never enter the make_fx graph (pytorch/pytorch #185865). That makes this DCE a
no-op, so remove it.

Caveat: #185865 is not yet in the cu130 nightly that graph_trainer CI installs
(unpinned `--pre torch`). Until it lands there, this PR's CI will fail with the
shadow-node asserts (e.g. the bitwise-deterministic and AutoParallel TP tests).
Hold until the nightly contains the fix.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
SherlockNoMad added a commit that referenced this pull request Jun 4, 2026
…y_strided shadow-node bug)

The skip on `test_llama3_aot_fx_trace_autoparallel_vs_eager` (and the
integration test `autoparallel_llama3_fsdp_tp`) blamed an "upstream
AutoParallel nll_loss assertion regression" / "incorrect loss partitioning".
That was a misattribution: it is the same empty_strided dead-shadow-node bug
that #3480 root-caused and fixed with `_remove_dead_empty_strided_chains`.

AutoParallel produces a model-only graph (vocab-sharded DTensor logits); the
loss op is applied afterwards inside graph_trainer's `make_fwd_bwd_step`, which
is traced by `minimal_fx_tracer` -- exactly the graph the DCE cleans. Under the
unfixed nightly, DTensor shard propagation leaves a dead `nll_loss` shadow node
reading an uninitialized `empty_strided` target, which trips the bounds check
`t >= 0 && t < n_classes` at runtime (same failure class as the embedding OOB).
`_remove_dead_empty_strided_chains` strips that dead chain. The upstream fix is
pytorch/pytorch #185865.

Verified on 8xH100 (autoparallel installed): the loss matches eager (max diff
1.3e-4), `1 passed`. CI runs this unit test on the unfixed nightly
(integration_test_8gpu_graph_trainer.yaml), so it exercises the DCE path
directly -- keep `_remove_dead_empty_strided_chains` until #185865 lands.

The DSv3 AutoParallel and JIT (#2149) tests remain disabled: separate,
still-open bugs (confirmed #2149 still reproduces "Node tangents_2 was invalid,
but is output").

Test plan:
  pytest torchtitan/experiments/graph_trainer/tests/test_numerics.py::TestGraphTrainerAutoParallelNumerics::test_llama3_aot_fx_trace_autoparallel_vs_eager

🤖 Generated with [Claude Code](https://claude.com/claude-code)
SherlockNoMad added a commit that referenced this pull request Jun 4, 2026
…y_strided shadow-node bug) (#3495)

## Summary

The skip on `test_llama3_aot_fx_trace_autoparallel_vs_eager` and the
integration test `autoparallel_llama3_fsdp_tp` blamed an *"upstream
AutoParallel nll_loss assertion regression"* / *"incorrect loss
partitioning"*. That was a **misattribution** — it is the same
`empty_strided` dead-shadow-node bug that #3480 root-caused and fixed
with `_remove_dead_empty_strided_chains`.

## Root cause

AutoParallel produces a **model-only** graph (vocab-sharded DTensor
logits); the loss op is applied afterwards inside graph_trainer's
`make_fwd_bwd_step`, which is traced by `minimal_fx_tracer` — **exactly
the graph the DCE cleans**. Under the unfixed nightly, DTensor shard
propagation leaves a dead `nll_loss` shadow node reading an
uninitialized `empty_strided` target, which trips the bounds check `t >=
0 && t < n_classes` at runtime — the same failure class as the embedding
OOB in #3480. `_remove_dead_empty_strided_chains` strips that dead
chain. The upstream fix is pytorch/pytorch #185865.

Minimal isolation (simulating the unfixed nightly by restoring the
pre-fix `_propagate_tensor_meta_non_cached`) confirms the DCE removes
the dead bounds-checked shadow op:
```
before: empty_strided=2, embedding=2   # dead aten.embedding(empty_strided_w, empty_strided_idx) [num_users=0]
after _remove_dead_empty_strided_chains: empty_strided=0, embedding=1
```

## Verification

Ran on 8×H100 with `autoparallel` installed — loss matches eager:
```
Max loss difference: step=11 baseline=3.6115226 test=3.6113948 diff=0.000128
1 passed in 226.67s
```

CI runs this unit test on the **unfixed** nightly
(`integration_test_8gpu_graph_trainer.yaml`), so it exercises the DCE
path directly. Keep `_remove_dead_empty_strided_chains` until #185865
lands.

## Left disabled (verified separate, still-open bugs)

- **DSv3 AutoParallel** — different failure, not the shadow-node bug.
- **JIT (#2149)** — confirmed still reproduces `AssertionError: Node
tangents_2 was invalid, but is output` in
`torch/_functorch/partitioners.py`.

## Test plan

```bash
pytest torchtitan/experiments/graph_trainer/tests/test_numerics.py::TestGraphTrainerAutoParallelNumerics::test_llama3_aot_fx_trace_autoparallel_vs_eager
```

🤖 Generated with [Claude Code](https://claude.com/claude-code)
SherlockNoMad added a commit that referenced this pull request Jun 4, 2026
…3496)

> [!WARNING]
> **DO NOT MERGE** until pytorch/pytorch #185865 (or a reland) is in the
`cu130` nightly that graph_trainer CI installs. Until then, CI on this
PR **will fail** with the shadow-node device-side asserts.

## Summary

#3480 added `_remove_dead_empty_strided_chains` as a workaround for a
DTensor + make_fx bug: shard propagation runs each op on fake
global-shape tensors to derive metadata, and when make_fx captured that
inference it left a dead `empty_strided`-backed "shadow" node for every
DTensor op. Bounds-checked ops (`aten.embedding`, `nll_loss`) read the
uninitialized `empty_strided` index/target and tripped `device-side
assert` for any `tensor_parallel_degree > 1` `aot_fx_trace` config.

The proper upstream fix wraps the fake-tensor metadata inference in
`disable_proxy_modes_tracing` inside
`ShardingPropagator._propagate_tensor_meta_non_cached`, so the shadow
nodes never enter the make_fx graph — pytorch/pytorch #185865. That
makes this DCE a no-op, so this PR removes it (per the workaround's own
docstring: *"Remove this pass once that fix lands in the graph_trainer
CI nightly."*).

## Blocking dependency

- pytorch/pytorch #185865 must be **merged and present in the nightly**
first. As of this PR it is **not** (the nightly is installed unpinned
via `--pre torch`).
- Symptom if merged early: `embedding`/`nll_loss` OOB device-side
asserts return for TP `aot_fx_trace` paths — e.g.
`test_bitwise_deterministic.py` and the AutoParallel TP tests.

## Test plan

Once #185865 is in the CI nightly, the existing graph_trainer suites are
the validation (no behavior change expected):
```bash
pytest torchtitan/experiments/graph_trainer/tests/test_bitwise_deterministic.py
pytest torchtitan/experiments/graph_trainer/tests/test_trace_module.py
pytest torchtitan/experiments/graph_trainer/tests/test_numerics.py
```

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

3 participants