Repository navigation
Conversation
| ``(batch, seq_len, num_heads * head_dim)`` — ready for | ||
| ``output.view(bs, seqlen, -1)`` in GQAttention.forward | ||
| """ | ||
| if attention_masks is not None: |
There was a problem hiding this comment.
I'm adding this to explicit tell people attention_masks doesn't work with vllm wrapper. I don't know what would be the solution.
155ffbd to
8624f92
Compare
| # FunctionalTensor on its own"). This combination (flex + CP + | ||
| # regional_inductor) is not yet supported; re-enable once fixed upstream. | ||
| # cudagraph is also disabled here: CUDA-graph replay of the coalesced | ||
| # FSDP collectives fails under CP with "CUDA error: invalid argument". |
There was a problem hiding this comment.
bug between CP and compile
There was a problem hiding this comment.
I'll take a look when doing graph_trainer + spmd_types.
| # TODO: Disabled because the default attention backend is now | ||
| # FlexAttention (SDPA is no longer a language-model backend). | ||
| # AutoParallel's dynamo export (_dynamo_graph_capture_for_export) | ||
| # pytree-flattens the FlexAttention BlockMask to plain (Fake)Tensors, | ||
| # so flex_attention then fails with "'FakeTensor' object has no | ||
| # attribute 'BLOCK_SIZE'". flex + AutoParallel is not yet supported; | ||
| # re-enable once BlockMask survives AutoParallel graph capture. |
There was a problem hiding this comment.
bug between Flex and AutoParallel
cc @xmfan @sanketpurandare
| # TODO: flex + AutoParallel is unsupported — dynamo export flattens the | ||
| # FlexAttention BlockMask to (Fake)Tensors and flex_attention then fails on | ||
| # missing BlockMask.BLOCK_SIZE. The default LM backend is now flex (SDPA was | ||
| # removed), so re-enable once BlockMask survives AutoParallel graph capture. | ||
| @unittest.skip("flex BlockMask not supported under AutoParallel graph capture") |
There was a problem hiding this comment.
bug between Flex + AutoParallel
cc @xmfan @sanketpurandare
| # TODO: This "full recompute saves memory vs default SAC" invariant was | ||
| # calibrated for SDPA, whose attention activations are materialized and | ||
| # freed by recompute. With the FlexAttention default (SDPA was removed for | ||
| # language models), attention is a fused HOP, so on the tiny debug model | ||
| # full recompute no longer beats default (full active peak > default). Full | ||
| # recompute is still numerically correct (see ...full_ac_numerics_match_eager). | ||
| # Re-enable by recalibrating for flex (e.g. larger model / flex-aware | ||
| # threshold) or after the memory_policy="full" pass frees flex activations. | ||
| @unittest.skip( | ||
| "flex memory profile differs from SDPA; invariant needs recalibration" | ||
| ) |
There was a problem hiding this comment.
full AC memory saving broken when Flex is used
cc @SherlockNoMad
| # TODO: This validates CP all_gather-before-SDPA codegen, but the default | ||
| # LM backend is now FlexAttention (SDPA was removed for language models), | ||
| # which has no SDPA op and where CP + flex is unsupported anyway: torch's | ||
| # _create_cp_block_mask requires seq_len divisible by 2 * BLOCK_SIZE (here | ||
| # 128 < 256), and flex + CP is otherwise gated (see the disabled | ||
| # aot_fx_trace_llama3_fsdp_tp_cp integration flavor). Re-enable by either | ||
| # pinning this to an SDPA-inner model or rewriting it for the flex CP | ||
| # all_gather codegen once flex + CP is supported. | ||
| @unittest.skip("flex is the default LM backend; SDPA + CP codegen N/A") |
There was a problem hiding this comment.
Used to test CP + SDPA, but should test CP + Flex, which doesn't work with compile.
cc @fegin @SherlockNoMad
There was a problem hiding this comment.
will take a look of graph_trainer + CP problems.
| # Bump mtime so the hot-reload check reaches the content-hash compare. | ||
| # _check_file_modified short-circuits when the mtime is unchanged; on a | ||
| # coarse-granularity filesystem the rewrite can land in the same mtime | ||
| # tick as the cached value (a real edit always lands in a later tick). | ||
| bumped = custom_gm._code_mtime + 1 | ||
| os.utime(custom_gm._code_path, (bumped, bumped)) |
There was a problem hiding this comment.
from claude:
This is a pre-existing flaky test, unrelated to the SDPA→Flex migration. Two independent reasons it's not from my changes:
- The test exercises a SimpleModule that does x * 2 — no attention, no Decoder, no positions/masks. Nothing my PR touched is in the path.
- The failure is in _check_file_modified (custom_codegen.py:539-541):
current_mtime = os.path.getmtime(self._code_path)
if hasattr(self, "_code_mtime") and current_mtime == self._code_mtime:
return False # short-circuits BEFORE the hash check - The test writes the modified code and immediately calls _check_file_modified(). On a fast machine / coarse-mtime filesystem, the rewrite lands in the same mtime tick as the cached _code_mtime, so the mtime short-circuit returns False and the content-hash check (which would catch the change) is never reached. It's a classic mtime-granularity race — environment/timing dependent, which is why it surfaces intermittently in CI and has nothing to do with this PR.
In real hot-reload use, a human edit lands in a later mtime tick, so the short-circuit is fine; only the too-fast test write trips it.
What I did
Added an os.utime mtime bump in test_custom_codegen_with_profiler_and_hot_reload right after the test rewrites the codegen file.
This makes the test deterministically exercise the content-hash path in _check_file_modified instead of racing the filesystem mtime granularity — mirroring a real edit, which always lands in a later mtime tick. No production code changed; the _check_file_modified mtime short-circuit (a perf optimization) stays intact.
|
|
||
|
|
||
| @unittest.skipUnless(torch.cuda.is_available(), "CUDA required") | ||
| def _disable_flex_autotune(): |
There was a problem hiding this comment.
from claude
What the failure was and the fix
The 5 failures (TestTraceModels + TestTraceFSDP × {qwen3, qwen3_moe, deepseek_v3}) were all:
InductorError: out of resource: triton_tem_fused_flex_attention ... Required: 131072/196608, Hardware limit: 101376
FlexAttention's default inductor_configs enable max_autotune + coordinate_descent_tuning, and the autotuner sometimes selects flex block configs whose shared-memory need exceeds the H100 limit (~99 KB) for larger head_dims (qwen3 head_dim=128 → 128 KB, deepseek qk_head_dim=192 → 192 KB). test_llama3 (smaller head_dim) didn't hit it. It's flaky — autotune kernel selection is timing-dependent, which is why these passed in my earlier local run but failed in this CI run.
Fix (mirrors the established test_bitwise_deterministic.setUp pattern): added a _disable_flex_autotune() helper that sets max_autotune=False/coordinate_descent_tuning=False and rebuilds _compiled_flex_attn, applied via:
- TestTraceModels.setUp/tearDown (single process — set + restore).
- inside TestTraceFSDP._run_fsdp_model_test (child process — FSDPTest.setUp runs in the parent, so the override must happen in the test body; no restore needed since each rank is a fresh subprocess).
This makes the flex kernel use the default block config that fits in shared memory, eliminating both the OOM and the autotune nondeterminism. Verified: the 5 previously-failing tests pass, and the full file passes (43 passed, 3 skipped — including test_llama3, which still passes with autotune disabled).
pre-commit clean. Per the earlier "skip flex+CP" decision, the 3 skips are the CP-codegen test plus the 2 pre-existing gpt_oss scatter-dtype skips.
tianyu-l
left a comment
There was a problem hiding this comment.
OK, I ended up using SDPA for graph trainer tests, leaving Flex enablement as several TODOs, under this set of comments. cc @fegin @SherlockNoMad @sanketpurandare
| # Uses the SDPA backend: AutoParallel's dynamo export | ||
| # (_dynamo_graph_capture_for_export) pytree-flattens the default | ||
| # FlexAttention BlockMask to plain (Fake)Tensors, so flex_attention then | ||
| # fails with "'FakeTensor' object has no attribute 'BLOCK_SIZE'". SDPA is | ||
| # maskless (is_causal) and carries no BlockMask, and its input_fn | ||
| # (tokens, positions) binds correctly now that Decoder.forward lists | ||
| # positions before attention_masks. | ||
| # TODO: re-test on FlexAttention once BlockMask survives AutoParallel | ||
| # graph capture. |
| # Uses the SDPA backend: the default FlexAttention + CP + | ||
| # regional_inductor combination is not yet supported — the CP load | ||
| # balancer injects an index-rearrange constant (torch | ||
| # _context_parallel/_attention.py qkv_rearrange_indices) that | ||
| # regional_inductor's make_fx re-trace cannot lift ("Attempting to use | ||
| # FunctionalTensor on its own"). SDPA has native CP support and no such | ||
| # constant, so it exercises the CP graph path. cudagraph is disabled | ||
| # here: CUDA-graph replay of the coalesced FSDP collectives fails under | ||
| # CP with "CUDA error: invalid argument". | ||
| # TODO: re-test on FlexAttention once flex + CP + regional_inductor is | ||
| # supported upstream. |
| # Uses the SDPA backend: the default FlexAttention backend bakes a | ||
| # BlockMask into the precompiled artifact, whose mask_mod closures are | ||
| # Python code objects that pickle.dumps cannot serialize ("TypeError: | ||
| # cannot pickle code objects" in precompile_fx_trace_save). SDPA carries | ||
| # no such object, so it exercises the precompile machinery cleanly. | ||
| # TODO: re-test on FlexAttention once BlockMask is excluded/rebuilt at | ||
| # load time (or becomes picklable). |
| AutoParallel is unsupported on the default FlexAttention backend (dynamo | ||
| export flattens the BlockMask), so both sides use the test-only SDPA backend. | ||
| The eager baseline runs the same SDPA model through GraphTrainer with | ||
| ``mode=None`` (delegates to the core eager path). |
|
|
||
| from torchtitan.experiments.graph_trainer.llama3.config_registry import ( | ||
| graph_trainer_llama3_debugmodel, | ||
| graph_trainer_llama3_debugmodel_sdpa, |
Today, text dataloader and chat dataloader always output `positions` for `Decoder` to consume, which SDPA could not handle. Making FlexAttention the default (instead of Varlen) because - it doesn't require extra package - it supports CP (varlen CP support is WIP) - some models could only work with Flex, e.g. gpt-oss, which needs beyond document masking Also - deduplicating tests under sdpa and flex - removing `_ep` variants in config_registry.py files, as it's outdated - removing unused torchtitan/experiments/rl/models/parallelize.py - removing scripts/generate/, use the vllm generation script instead https://github.com/pytorch/torchtitan/blob/main/torchtitan/experiments/rl/generate.py Note - Loss curves in CI are updated because SDPA is replaced by Flex (and at the same time causal is replaced by block_causal). - **Graph trainer CI failed on FlexCP** which is expected because core trainer CI also fails on that. The test entry is disabled with a TODO. There are several other breakages I marked in inline comments. cc @SherlockNoMad @fegin - **Flex + AutoParallel doesn't work** cc @xmfan @sanketpurandare - It seems Flex + PP doesn't work for split-backward schedules. Temporarily disabled the tests and tracking in #3584 cc @fegin @sanketpurandare - RL failures are pre-existing. cc @wwwjn
…#3571) Today, text dataloader and chat dataloader always output `positions` for `Decoder` to consume, which SDPA could not handle. Making FlexAttention the default (instead of Varlen) because - it doesn't require extra package - it supports CP (varlen CP support is WIP) - some models could only work with Flex, e.g. gpt-oss, which needs beyond document masking Also - deduplicating tests under sdpa and flex - removing `_ep` variants in config_registry.py files, as it's outdated - removing unused torchtitan/experiments/rl/models/parallelize.py - removing scripts/generate/, use the vllm generation script instead https://github.com/pytorch/torchtitan/blob/main/torchtitan/experiments/rl/generate.py Note - Loss curves in CI are updated because SDPA is replaced by Flex (and at the same time causal is replaced by block_causal). - **Graph trainer CI failed on FlexCP** which is expected because core trainer CI also fails on that. The test entry is disabled with a TODO. There are several other breakages I marked in inline comments. cc @SherlockNoMad @fegin - **Flex + AutoParallel doesn't work** cc @xmfan @sanketpurandare - It seems Flex + PP doesn't work for split-backward schedules. Temporarily disabled the tests and tracking in pytorch#3584 cc @fegin @sanketpurandare - RL failures are pre-existing. cc @wwwjn
Upstream `[BE] deprecate SDPA and causal mask_type for language models (pytorch#3571, 2026-06-09)` removed the `mask_type` field from `GQAttention.Config` and changed `get_attention_config()` / `make_gqa_config()` to drop both `mask_type` and the tuple return-shape. The merge tripped `TypeError: make_gqa_config() got an unexpected keyword argument 'mask_type'` on first import. Replay: - `ezpz/agpt/__init__.py` - `_ezpz_get_attention_config()` now returns just the config (was a `(config, mask_type)` tuple). Keeps the XPU SDPA branch alive — upstream removed SDPA entirely from language models but XPU lacks a working FlexAttention backend, so we still need it. - `_build_agpt_layers()` drops the local `mask_type` variable and the `mask_type=...` kwarg passed to `make_gqa_config()`. - `ezpz/moe/__init__.py` - Same `_ezpz_get_attention_config()` API change rippled through — use single-return-value pattern, then synthesize `_mask = "causal"` locally. ezpz/moe's `Attention.Config` (MLA, defined in `moe/model.py`) is OUR own class and still has its own `mask_type` field — upstream's removal only affected `GQAttention.Config`, so this preserves moe behavior. Behavior unchanged: all our existing configs implicitly defaulted to `mask_type="causal"` and we still build the same `inner_attention` classes (XPU SDPA on the agpt side, MLA on the moe side). The bitwise sync check will confirm. PR pytorch#3447 (Full DTensor for MoE) also landed in this merge but requires no replay — it adds a `--training.spmd_backend=full_dtensor` opt-in path to deepseek_v3's parallelize; ezpz/moe's parallelize doesn't go through that branch.
moe/__init__.py's _ezpz_get_attention_config returned `(config, "causal")` — a tuple. The agpt sibling has been updated to return just `config` since the upstream PR pytorch#3571 replay (commit `db3b916a8`, "drop GQAttention mask_type field"). The two siblings drifted; the moe copy stayed on the old tuple-return signature. The caller in _build_moe_layers (line 283) already expects just a config — it sets `_mask = "causal"` separately on the next line. With the function returning a tuple, the tuple gets assigned to `_inner` and propagated all the way to the `Attention.Config( inner_attention=_inner, ...)` constructor, where the tuple ends up as the `inner_attention` field. Eventually `moe/sharding.py:_set_moe_layer_sharding` calls `set_gqa_inner_attention_local_map(attention.inner_attention)` which does `inner_attention_cfg.sharding_config = ShardingConfig(...)` — that fails with: AttributeError: 'tuple' object has no attribute 'sharding_config' and no __dict__ for setting new attributes Found via 2N moe_debugmodel_ep smoke test against the patched branch. Fix: match agpt's signature exactly — return just the Module.Config, no tuple wrapping. Caller already supplies the mask_type ("causal"). This is exactly the duplicate-class drift hazard I flagged in review finding saforem2#15 on saforem2#14 — the SDPA / attention helper functions exist in both `moe/__init__.py` and `agpt/__init__.py` with identical names but separate sources of truth. The 06-09 upstream pytorch#3571 replay only updated the agpt copy because the moe copy was inside this PR's modifications. Discovered + fixed before pushing back to the PR branch.
SDPA is deprecated in core (LM default moved to flex, pytorch#3571) and flex now works for every architecture this backend supports -- GQA, MLA (all rope variants), and DSA (GLM-5) -- with DSA verified causal on flex (SDPA+DSA was non-causal: create_causal_mask returns None for the custom impl, so DSA's combined_mask dropped the causal term). One path is simpler and removes a silently-wrong mode. - Dropped the attn_implementation config knob (only one valid value now). Flex is wired unconditionally via an internal _ATTN_IMPLEMENTATION="flex_torchtitan" constant; removed _uses_flex_attention and all flex/sdpa branching. - model.py: removed the sdpa_attention_forward import, the SDPA branch in _configure_hf_attention, the block_causal-requires-flex guard (moot), and the flex early-return / SDPA branches in get_attention_masks / forward. Kept _uses_dsa / _build_dense_attention_mask (DSA dense causal mask). - parallelize.py: removed _wire_sdpa_attention_cp, _cp_sdpa, the SDPA+CP ring block and the SDPA+TP+CP guard; kept _wrap_flex_kernel_cp. - hf_sharding.py: dropped the use_flex param; always attach the flex kernel. - __init__.py / config_registry.py: base flavors (debugmodel, debugmodel_moe, full, full_moe) are flex by default; removed the redundant _flex flavors/configs. - trainer.py: headtail CP load balancer rejected whenever CP is on. - tests: dropped the SDPA FSDP+CP integration entry, the sdpa cp_pp_numerical case, the --no_flex option, and the SDPA-must-raise unit test. Verified flex-only across GQA/MLA/DSA/Gemma4/dense/SFT (FSDP/TP/EP/CP/PP combos); all train with decreasing loss. No SDPA wiring references remain in the backend.
Today, text dataloader and chat dataloader always output
positionsforDecoderto consume, which SDPA could not handle.Making FlexAttention the default (instead of Varlen) because
Also
_epvariants in config_registry.py files, as it's outdatedNote
BlockMaskbreaks Pipeline Parallelism with split-backward (zero-bubble / multi) schedules #3584 cc @fegin @sanketpurandare