Skip to content

[BE] deprecate SDPA and causal mask_type for language models - #3571

Merged
tianyu-l merged 1 commit into
mainfrom
attention
Jun 9, 2026
Merged

tianyu-l merged 1 commit into
mainfrom
attention

Conversation

@tianyu-l

@tianyu-l tianyu-l commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

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

Note

@tianyu-l
tianyu-l requested review from drisspg and liangel-02 June 8, 2026 05:43
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jun 8, 2026
``(batch, seq_len, num_heads * head_dim)`` — ready for
``output.view(bs, seqlen, -1)`` in GQAttention.forward
"""
if attention_masks is not None:

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.

is this bc of #3572?

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.

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.

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

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.

bug between CP and compile

cc @SherlockNoMad @fegin

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.

thanks. noted.

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'll take a look when doing graph_trainer + spmd_types.

Comment on lines +462 to +468
# 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.

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.

bug between Flex and AutoParallel
cc @xmfan @sanketpurandare

Comment on lines +369 to +373
# 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")

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.

bug between Flex + AutoParallel
cc @xmfan @sanketpurandare

Comment on lines +169 to +179
# 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"
)

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.

full AC memory saving broken when Flex is used
cc @SherlockNoMad

Comment on lines +1789 to +1797
# 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")

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.

Used to test CP + SDPA, but should test CP + Flex, which doesn't work with compile.
cc @fegin @SherlockNoMad

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.

will take a look of graph_trainer + CP problems.

Comment on lines +164 to +169
# 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))

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.

from claude:

This is a pre-existing flaky test, unrelated to the SDPA→Flex migration. Two independent reasons it's not from my changes:

  1. The test exercises a SimpleModule that does x * 2 — no attention, no Decoder, no positions/masks. Nothing my PR touched is in the path.
  2. 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
  3. 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():

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.

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 tianyu-l left a comment

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.

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

Comment on lines +463 to +471
# 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.

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.

flex todo

Comment on lines +181 to +191
# 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.

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.

flex todo

Comment on lines +50 to +56
# 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).

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.

flex todo

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.

flex todo

Comment on lines +249 to +252
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).

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.

flex todo


from torchtitan.experiments.graph_trainer.llama3.config_registry import (
graph_trainer_llama3_debugmodel,
graph_trainer_llama3_debugmodel_sdpa,

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.

flex todo

@tianyu-l
tianyu-l merged commit 1695457 into main Jun 9, 2026
25 of 30 checks passed
@tianyu-l
tianyu-l deleted the attention branch June 9, 2026 22:25
wwwjn pushed a commit that referenced this pull request Jun 10, 2026
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
saforem2 pushed a commit to saforem2/torchtitan that referenced this pull request Jun 10, 2026
…#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
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 10, 2026
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.
saforem2 added a commit to nscottnichols/torchtitan that referenced this pull request Jun 11, 2026
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.
mreso added a commit to mreso/torchtitan that referenced this pull request Jul 17, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl 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.

4 participants