Skip to content

[attention] Flex attention: recompile limit 16, and fail instead of running eager - #5442

Merged
felipemello1 merged 2 commits into
mainfrom
felipemello1/flex-fixes/1-recompile-limit
Oct 20, 2026
Merged

felipemello1 merged 2 commits into
mainfrom
felipemello1/flex-fixes/1-recompile-limit

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

TLDR: Compiled flex attention now uses fullgraph=True and recompile_limit=16, in the default compile and in deterministic mode. Today, after 8 graphs, flex silently runs eagerly. Muse Spark needs 10 graphs across training, prefill and decode, so its short-query shapes ran eager flex and CUDA-graph capture failed. With this PR they compile, and a 17th graph raises instead of falling back.

Problem

  1. One compiled flex for every layer. FlexInnerAttention._compiled_flex_attn is a single torch.compile(flex_attention), shared by every layer in the process.
  2. Graphs multiply. Each graph is keyed on the mask kind (sliding window vs global), grad mode, the first static token count, size-1 queries, and Inductor's short-query (decode) kernel.
  3. Muse Spark needs 10. 2 mask kinds x (train static, train dynamic, no_grad dynamic, no_grad 1 token, no_grad short query).
  4. Silent eager fallback. Without fullgraph, Dynamo logs hit config.recompile_limit (8) and runs flex eagerly: slow, and CUDA-graph capture of those shapes fails.
  5. Who hits it. A process that runs flex at both training and inference shapes, like the Muse 2-layer benchmark. Training-only runs skip the short-query graphs; the RL generator uses vLLM, not flex.

Solution

  1. fullgraph=True: flex never runs eagerly. A graph break or the limit raises FailOnRecompileLimitHit.
  2. recompile_limit=16: room for 2 mask kinds across training and inference shapes.
  3. Deterministic mode too: --debug.deterministic recompiles flex without autotuning (distributed/utils.py); it gets the same two settings.
  4. Unchanged: kernels, block masks, kernel options.

Results

Numerics: bitwise identical wherever main compiled (same graphs, same kernels). Shapes that main
          ran eagerly after the limit now run the compiled kernel.

Muse Spark inner attention, layer 0 (sliding 2048) + layer 1 (global), 128/16 heads x 64,
GB300, CUDA graphs, us; all 9 shapes in one process
mode              T          main           this PR
train fwd+bwd     2k/4k/16k  compiled       compiled (same graphs)
prefill no_grad   2k         603.9          604.0
                  16k        6484.1         6483.4
decode no_grad    1          16.5           16.5
                  8          capture fails  30.9
                  256        40.3           41.1
flex graphs                  8, then eager  10, 0 graph breaks

DeepSeek-V3 16B (one mask kind, no GQA): 5 graphs on main and this PR, all 9 shapes compile.

Forcing more graphs (a new mask_mod per call):
main:     "hit config.recompile_limit (8)", then 24 calls run, 16 of them eagerly
this PR:  FailOnRecompileLimitHit: Hard failure due to fullgraph=True   (on the 17th graph)

You may ask: why not reduce the graphs instead? They are real kernel differences (mask kind, grad mode, decode kernel); dynamic=True still made 8 and fell back.
NOTE: decode with 17-127 query tokens and 8 query heads per KV head (Muse decode 64) now raises InductorError on stock PyTorch: Inductor's flex decode kernel rejects that shape. On main it ran eagerly because the limit was hit first. A separate PyTorch fix makes it compile. Only flex inference hits it.
NOTE: a model with more mask kinds can now hit the limit and crash where it used to run eagerly; that's intended. Not tested: the CP flex subclasses and the FA4 flex backend (they share this compile), multi-GPU, GraphTrainer.

Test plan

  • pytest tests/unit_tests/cpu/models/common/test_flex_attention.py tests/unit_tests/cpu/models/common/test_cp_attention.py tests/unit_tests/gpu/models/common/test_varlen_attention.py: same results on main and this PR (40 pass; 16 fail in both from the local environment).
  • TODO before merge: one training step of a Dist-MoE scale recipe (they keep flex, on the FA4 backend). It covers training shapes only.
  • TODO before merge: the no_grad graph-limit check (a new mask per call, no_grad, T=256) at the scale recipe's block sizes: (256, 256) global, (256, 128) sliding, FA4 backend. Expected: the error fires only where main silently ran eager.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 16, 2026
@felipemello1
felipemello1 changed the base branch from main to felipemello1/muse-spark/5-rope-in-qk-region October 18, 2026 05:31
@felipemello1
felipemello1 added this pull request to stack #5499 October 18, 2026 05:31
@felipemello1
felipemello1 marked this pull request as ready for review October 18, 2026 05:42
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 18, 2026
wwwjn added a commit that referenced this pull request Oct 19, 2026
…x per layer (#5547)

**TLDR:** Two CI fixes for the GraphTrainer and 8 GPU Integration jobs.
1. Fixes #5366. The Flex eager-vs-trace bitwise tests compiled flex once
per layer in the eager reference, and after 8 graphs Dynamo silently ran
unfused eager flex. The traced side was correct; the eager reference
changed. With this PR the eager reference compiles flex once, like the
core and RL trainers, and hitting the recompile limit raises instead of
falling back.
2. Fixes PP after #3980. #3980 made PP preprocessing return 4 values,
but two callers still unpacked 3, so every PP + CUDA graph integration
test and the GraphTrainer PP numerics test fail on main with
`ValueError: too many values to unpack (expected 3)`.

## 1. Flex bitwise tests compiled flex per layer (#5366)

**Problem**
1. **The eager reference was annotated.** `_run_steps` called
`annotate_graph_trainer_model` for both `Trainer` and `GraphTrainer`. It
wraps every submodule's forward with `annotate_fn({"module_fqn": fqn})`.
Only GraphTrainer's graph passes read these tags. The core and RL
trainers never set them.
2. **Dynamo now guards on the annotation.** pytorch/pytorch#198959
(October 10 nightly, the first failing one) adds an `FX_ANNOTATION`
guard. Each layer's `inner_attention` has a different `module_fqn`, so
the eager compiled flex compiles once per layer: 8 graphs for Qwen3
debugmodel_moe, all identical.
3. **The graphs carry over between tests.** Dynamo caches them on
`flex_attention`'s code object, which outlives the `torch.compile`
wrapper rebuilt in `setUp`. Llama3 Flex leaves 6. Qwen3 MoE Flex then
passes the limit of 8 at its third layer.
4. **Silent fallback.** Past the limit, Dynamo runs flex eagerly, which
is the unfused implementation, so the eager loss changes: `hit
config.recompile_limit (8)`, then `eager vs aot_fx_trace: loss
mismatch`.

**Solution**
1. **Annotate only GraphTrainer runs.** The eager reference stays
unannotated, like the core and RL trainers.
2. **`fullgraph=True` and `recompile_limit=16`** on the test's flex
compile, the same settings as #5442. Hitting the limit raises instead of
falling back.
3. **`torch._dynamo.reset()` in `setUp`.** Tests no longer share flex
graphs.
4. **Unchanged:** the GraphTrainer runs, their annotations, and every
assertion.

## 2. PP callers still unpacked 3 values after #3980

**Problem**
1. #3980 made `TrainingEngine._preprocess_microbatch_group` return
`(arg_mbs, kwarg_mbs, target_mbs, loss_kwarg_mbs)` under PP.
2. `prepare_for_capture` (PP + CUDA graphs, added by #5241 before #3980
landed) still unpacked 3 values. Every PP test in the 8 GPU features job
fails there: 3d, pp_1f1b, pp_dp_tp, pp_looped_zero_bubble, lora, and
others. On main, that job passes at #3980's parent `efdde5eda` and fails
at #3980 `a4a62b349`.
3. GraphTrainer PP reuses the core preprocessing, and its
forward-backward loop also unpacked 3 values, so
`test_dense_llama3_hsdp_graph_pp_vs_eager` fails. The GraphTrainer job
uses `set -eux`, so it stops there and never reaches
`test_bitwise_deterministic.py`.
4. The CPU test for `prepare_for_capture` still fed the old 3-tuple,
which hid the mismatch.

**Solution**
1. **`prepare_for_capture`** unpacks 4 values and passes the first
microbatch's loss arguments plus `global_loss_token_counts` to schedule
initialization. Initialization calls the loss on that microbatch, as the
real step does.
2. **GraphTrainer PP** drops the fourth element. GraphTrainer rejects
per-microbatch loss arguments earlier, so it is always empty, and both
paths now return `(arg_mbs, kwarg_mbs, target_mbs)`, as before #3980.
3. **The CPU test** feeds the PP layout with a per-microbatch loss
argument and checks the loss arguments passed to initialization. It
fails without the fix with the same `ValueError`.

## Results
```text
torch 2.16.0.dev20261019+cu132, GB200 (2 GPUs), flash-attn-4

1. Llama3 Flex -> Qwen3 MoE Flex test_aot_fx_trace_vs_eager, in one process
main:     "hit config.recompile_limit (8)", then
          eager vs aot_fx_trace: loss mismatch: 6.995096683502197 vs 6.995151519775391
this PR:  pass, 1 flex graph per test, eager == traced == 6.995151519775391

flex graphs after the Qwen3 MoE Flex eager run (test run alone)
annotated eager (main):  8 (one per layer)
unannotated eager:       1, same loss

Full test_bitwise_deterministic.py
main:     recompile limit hit once; on GB200 it breaks
          TestDSv3FlexAttnBitwiseDeterministic::test_aot_fx_trace_vs_eager and
          ::test_ep_chunk_matches_eager_chunking_bitwise
this PR:  16 passed (Varlen and Flex), 9 skipped, no recompile limit hit

2. PP
pp_1f1b integration test (2 GPUs, PP + CUDA graphs)
main:     ValueError in prepare_for_capture
this PR:  10 steps pass

GraphTrainer PP (the HSDP+PP numerics config reduced to PP=2, 2 GPUs)
main:     ValueError in GraphTrainer _forward_backward_body
this PR:  trains
```

You may ask: does the core trainer recompile flex per layer too? No.
Llama3 1B (16 layers) with flex on the core `Trainer` compiles flex once
and never recompiles. Only an annotated eager model recompiles per
layer.

NOTE: GraphTrainer's validator runs the annotated model eagerly, so Flex
validation on a model with more than 8 layers should hit the same
per-layer recompiles. Not covered here.
NOTE: `test_dense_llama3_hsdp_graph_pp_vs_eager` needs 8 GPUs, so I
could not run it locally. On the PP=2 reduction, eager PP vs GraphPP
misses its grad_norm tolerance (max 1.7e-4) both with this PR and at
#3980's parent, so that gap comes from the reduced config, not this PR.
The full 8 GPU test passed on main before #3980.

**Test plan**
- `pytest
torchtitan/experiments/graph_trainer/tests/test_bitwise_deterministic.py`:
16 passed, 9 skipped.
- The Llama3 Flex -> Qwen3 MoE Flex pair from #5366 passes in one
process.
- `python -m tests.integration_tests.run_tests <out> --test_suite
features --test_name pp_1f1b --ngpu 2`: passes; fails on main.
- `pytest tests/unit_tests/cpu/test_trainer.py
tests/unit_tests/cpu/distributed/test_cuda_graph.py
tests/unit_tests/cpu/components/test_validator.py
tests/unit_tests/cpu/distributed/test_pipeline_parallel.py`: 135 passed.
- CI: GraphTrainer 8 GPU and 8 GPU Integration (features) jobs.
Base automatically changed from felipemello1/muse-spark/5-rope-in-qk-region to main October 20, 2026 15:52
@felipemello1
felipemello1 force-pushed the felipemello1/flex-fixes/1-recompile-limit branch from ba9d814 to f7f63ef Compare October 20, 2026 15:52
@felipemello1
felipemello1 merged commit aabe6ef into main Oct 20, 2026
acisseJZhong pushed a commit that referenced this pull request Oct 21, 2026
…unning eager (#5442)

**TLDR:** Compiled flex attention now uses `fullgraph=True` and
`recompile_limit=16`, in the default compile and in deterministic mode.
Today, after 8 graphs, flex silently runs eagerly. Muse Spark needs 10
graphs across training, prefill and decode, so its short-query shapes
ran eager flex and CUDA-graph capture failed. With this PR they compile,
and a 17th graph raises instead of falling back.

**Problem**
1. **One compiled flex for every layer.**
`FlexInnerAttention._compiled_flex_attn` is a single
`torch.compile(flex_attention)`, shared by every layer in the process.
2. **Graphs multiply.** Each graph is keyed on the mask kind (sliding
window vs global), grad mode, the first static token count, size-1
queries, and Inductor's short-query (decode) kernel.
3. **Muse Spark needs 10.** 2 mask kinds x (train static, train dynamic,
no_grad dynamic, no_grad 1 token, no_grad short query).
4. **Silent eager fallback.** Without `fullgraph`, Dynamo logs `hit
config.recompile_limit (8)` and runs flex eagerly: slow, and CUDA-graph
capture of those shapes fails.
5. **Who hits it.** A process that runs flex at both training and
inference shapes, like the Muse 2-layer benchmark. Training-only runs
skip the short-query graphs; the RL generator uses vLLM, not flex.

**Solution**
1. **`fullgraph=True`:** flex never runs eagerly. A graph break or the
limit raises `FailOnRecompileLimitHit`.
2. **`recompile_limit=16`:** room for 2 mask kinds across training and
inference shapes.
3. **Deterministic mode too:** `--debug.deterministic` recompiles flex
without autotuning (`distributed/utils.py`); it gets the same two
settings.
4. **Unchanged:** kernels, block masks, kernel options.

**Results**
```text
Numerics: bitwise identical wherever main compiled (same graphs, same kernels). Shapes that main
          ran eagerly after the limit now run the compiled kernel.

Muse Spark inner attention, layer 0 (sliding 2048) + layer 1 (global), 128/16 heads x 64,
GB300, CUDA graphs, us; all 9 shapes in one process
mode              T          main           this PR
train fwd+bwd     2k/4k/16k  compiled       compiled (same graphs)
prefill no_grad   2k         603.9          604.0
                  16k        6484.1         6483.4
decode no_grad    1          16.5           16.5
                  8          capture fails  30.9
                  256        40.3           41.1
flex graphs                  8, then eager  10, 0 graph breaks

DeepSeek-V3 16B (one mask kind, no GQA): 5 graphs on main and this PR, all 9 shapes compile.

Forcing more graphs (a new mask_mod per call):
main:     "hit config.recompile_limit (8)", then 24 calls run, 16 of them eagerly
this PR:  FailOnRecompileLimitHit: Hard failure due to fullgraph=True   (on the 17th graph)
```

You may ask: why not reduce the graphs instead? They are real kernel
differences (mask kind, grad mode, decode kernel); `dynamic=True` still
made 8 and fell back.
NOTE: decode with 17-127 query tokens and 8 query heads per KV head
(Muse decode 64) now raises `InductorError` on stock PyTorch: Inductor's
flex decode kernel rejects that shape. On main it ran eagerly because
the limit was hit first. A separate PyTorch fix makes it compile. Only
flex inference hits it.
NOTE: a model with more mask kinds can now hit the limit and crash where
it used to run eagerly; that's intended. Not tested: the CP flex
subclasses and the FA4 flex backend (they share this compile),
multi-GPU, GraphTrainer.

**Test plan**
- `pytest tests/unit_tests/cpu/models/common/test_flex_attention.py
tests/unit_tests/cpu/models/common/test_cp_attention.py
tests/unit_tests/gpu/models/common/test_varlen_attention.py`: same
results on main and this PR (40 pass; 16 fail in both from the local
environment).
- TODO before merge: one training step of a Dist-MoE scale recipe (they
keep flex, on the FA4 backend). It covers training shapes only.
- TODO before merge: the no_grad graph-limit check (a new mask per call,
no_grad, T=256) at the scale recipe's block sizes: (256, 256) global,
(256, 128) sliding, FA4 backend. Expected: the error fires only where
main silently ran eager.

---------

Co-authored-by: Felipe Mello <[email protected]>
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.

2 participants