Skip to content

[spmd_types] FlexAttention: remove hardcoded spmd_types of FlexAttention._complex_flex_attn output - #3924

Merged
fegin merged 4 commits into
pytorch:mainfrom
jinsooihm:inner-attention-spmd
Jul 16, 2026
Merged

fegin merged 4 commits into
pytorch:mainfrom
jinsooihm:inner-attention-spmd

Conversation

@jinsooihm

@jinsooihm jinsooihm commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

FlexAttention.compiled_flex_attn runs the compiled flex kernel under spmd.no_typecheck() and then re-stamps output's SPMD type.
It previously hardcoded PartitionSpec("dp","tp","cp",None) for out (and "dp","tp","cp" for lse), which bakes in the DP/TP/CP axes and forces CP sharding on the sequence dim regardless of how the layer is actually sharded.

Attention preserves the query's layout (output shape is (B,N,L,H) with the same batch/head/seq sharding as q), so derive the output type from q instead: copy q's local type + shard-dim PartitionSpec onto out, and the same minus the trailing (unsharded) head-dim entry onto lse.

spmd_types has a function assert_type_like that can copy local types, without PartitionSpec.
But using that would only preserve correctness when FlexAttention is used inside a local_map region, so it is not used here.

Edit: spmd_types 0.2.2 assert_type_like does have PartitionSpec, but this cannot handle the dimension mismatch for lse.

Test plan: existing attention/spmd unit suites pass. Validated e2e under spmd_types + --debug.spmd_typechecking:

  • llama3 debugmodel + flex, context_parallel_degree 2 and 1 (out path)
  • gpt_oss debugmodel + flex (out + lse path via the sink out_transform) all complete step 1 with no SpmdTypeError.

… PartitionSpec

FlexAttention.compiled_flex_attn runs the compiled flex kernel under
spmd.no_typecheck() and then re-stamps the opaque output's SPMD type. It
previously hardcoded PartitionSpec("dp","tp","cp",None) for out (and
"dp","tp","cp" for lse), which bakes in the DP/TP/CP axes and forces CP
sharding on the sequence dim regardless of how the layer is actually sharded.

Attention preserves the query's layout (output is (B,N,L,H) with the same
batch/head/seq sharding as q), so derive the output type from q instead:
copy q's local type + shard-dim PartitionSpec onto out, and the same minus
the trailing (unsharded) head-dim entry onto lse. This is self-contained
(correct even when the module is not wrapped in an outer local_map boundary),
customizable (follows q's actual sharding, including layers that opt out of
CP), and cannot drift from q.

Test plan: existing attention/spmd unit suites pass. Validated e2e under
spmd_types + --debug.spmd_typechecking:
  - llama3 debugmodel + flex, context_parallel_degree 2 and 1 (out path)
  - gpt_oss debugmodel + flex (out + lse path via the sink out_transform)
all complete step 1 with no SpmdTypeError.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 16, 2026
@pytorch-bot

pytorch-bot Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@fegin
fegin requested a review from pianpwk July 16, 2026 00:52
@fegin

fegin commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

@pianpwk The PR matches what we discussed, but please take a look. We may miss something.

Comment thread torchtitan/models/common/attention.py Outdated

import torch
import torch.nn.functional as F
from spmd_types.runtime import get_local_type, get_partition_spec

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.

nit:

import spmd_types as spmd
from spmd_types.runtime import get_partition_spec

# later call spmd.get_local_type

Comment thread torchtitan/models/common/attention.py Outdated
if return_aux.lse:
spmd.assert_type(aux.lse, spmd.V, spmd.PartitionSpec("dp", "tp", "cp"))
# lse is (B, N, L) = q minus the trailing (unsharded) head dim.
lse_ps = None if q_ps is None else spmd.PartitionSpec(*tuple(q_ps)[:-1])

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.

nit: don't need the tuple cast

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

thanks!

…nt tuple cast

Summary:
Addresses code review feedback on the flex SPMD typing change. Prefers the
spmd_types package's public API surface for retrieving a tensor's local type
instead of reaching into the internal runtime submodule, which keeps the code
on the supported/stable interface. Also drops an unnecessary tuple conversion
when deriving the LSE partition spec, since the partition spec is already a
tuple and slicing it directly yields the same result.

Test Plan:
Ran the attention-importing unit tests (test_fused_qkv, test_tp_kv_heads_validation,
test_rope, test_compile_regional_inductor): 34 passed.
Ran the gpt_oss debug model with flex attention and SPMD typechecking enabled
(--parallelism.spmd_backend spmd_types --debug.spmd_typechecking) for 1 step on
2 H100s: training completed cleanly with step 1 loss 8.24132, exercising the
changed spmd.get_local_type / get_partition_spec typing path.
@jinsooihm

Copy link
Copy Markdown
Contributor Author

I made the changes. Thank you!

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

Thanks for the fix. Please check the comments before merging. You also need to rebase your PR as it conflicts with your previous one.

We should also do the same for VarlenAttention as a followup PR.

Comment thread torchtitan/models/common/attention.py Outdated
takes ``q``'s full SPMD type (local type + shard-dim PartitionSpec), and
``lse`` takes the same minus the trailing (unsharded) head dim. Copying
``q``'s full type keeps this correct even when the module is not wrapped
in an outer ``local_map`` boundary that would otherwise restamp ``out``.

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.

nit: Remove Copying ``q``'s full type keeps this correct ..... This last statement just refornce the previous attention preserve the query's sharding ...

if get_spmd_backend() == "spmd_types" and spmd.is_type_checking():
spmd.assert_type(out, spmd.V, spmd.PartitionSpec("dp", "tp", "cp", None))
q_local = spmd.get_local_type(q)
q_ps = get_partition_spec(q)

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.

nit: I feel this is a bit asymmetric, directly import get_partition_spec while get_local_type is accessed through spmd.get_local_type.

cc., @pianpwk Should get_partition_spec be exported to the top level just like get_local_type.

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.

spmd types 0.2.3 sir

@fegin
fegin merged commit fc5a729 into pytorch:main Jul 16, 2026
17 of 19 checks passed
mreso added a commit to mreso/torchtitan that referenced this pull request Jul 17, 2026
Absorbs 3 upstream commits: RL CI fix (pytorch#3930), the FlexAttention spmd_types
output typing change (pytorch#3924), and pytorch#3859 ("[MoE] sibling token_dispatcher +
grouped_experts for composable override"), which refactored the core MoE.

pytorch#3859 required adapting the HF backend (no git conflicts, but silent API/struct
breakage):
- moe_replacement.py: make_experts_config -> make_routed_experts_config +
  make_moe_config(routed_experts=...); dropped the token_dispatcher kwarg from
  the GroupedExperts.Config probe (token_dispatcher moved to RoutedExperts).
- parallelize.py: FSDP expert sharding reads moe.routed_experts.inner_experts
  (was moe.experts).
- state_dict_adapter.py: titan MoE expert FQNs moved experts.* ->
  routed_experts.inner_experts.*; the adapter still emitted the old prefix, so
  load_state_dict(strict=False) silently skipped the expert weights (random init
  -> HF-vs-titan forward cos ~= 0 while the round-trip still passed). Route the
  routed-expert keys through the new prefix; also tighten the gate_up/down
  special-cases to ".experts." so shared_experts can't be misrouted.

Verified: MoE numerical equivalence restored (qwen3_moe/deepseek_v2/olmoe PASS
cos ~= 1.0; mixtral WARN at cos 0.999996 -- the documented bf16-combine band, not
structural); round-trips max_diff=0.00; MoE EP=2 trains 12.33 -> 6.72.
kernel_options=kernel_options,
)
if get_spmd_backend() == "spmd_types" and spmd.is_type_checking():
spmd.assert_type(out, spmd.V, spmd.PartitionSpec("dp", "tp", "cp", 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.

It previously hardcoded PartitionSpec("dp","tp","cp",None) for out (and "dp","tp","cp" for lse), which bakes in the DP/TP/CP axes and forces CP sharding on the sequence dim regardless of how the layer is actually sharded.

From the motivation I wasn't able to tell what's wrong. Without this PR, what error would you hit and when does that happen?

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.

There is no error that would happen with current parallelism configuration of the models.
But it could occur if one wanted to apply CP only on some parts of the model, such as only in the decoder part of a multimodal model.

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.

But it could occur if one wanted to apply CP only on some parts of the model, such as only in the decoder part of a multimodal model.

What error are you getting in this case?

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.

When flex attention is used as inner_attention, and if you set the ShardingConfig of inner_attention to be R on CP, it would not propagate correctly because it gets hard coded to be V on CP after the with spmd.no_typecheck() block.

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.

it would not propagate correctly because it gets hard coded to be V on CP after the with spmd.no_typecheck() block.

sorry I'm very confused. Which one is correct, why would we set the other thing wrong? And why we don't fix that problem, but instead pursuing this PR?

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.

If the user decided to not use CP in the attention for the encoder but use CP in the attention for the decoder, then the sharding configuration for encoder attention could use R on CP.
Then, inside the encoder attention, q would come in as R on CP, and out should be also R on CP.
So using spmd.assert_type(out, spmd.V, spmd.PartitionSpec("dp", "tp", "cp", None)) declares a wrong type for out in that use case.
Without this change, we would need to call inner_attention with no_typecheck in the forward and assert the correct types.
With this change, we can just set ShardingConfig on inner_attention.

fegin pushed a commit that referenced this pull request Jul 21, 2026
In `VarlenAtttention`, remove hard coded `spmd_types` of `varlen_attn`
output.
Similar to #3924 (see
[comment](#3924 (review))).

Tested by running `llama3_debugmodel_varlen_attn` and
`gpt_oss_debugmodel` with `--parallelism.spmd_backend spmd_types ` and
`--debug.spmd_typechecking`.
saforem2 pushed a commit to saforem2/torchtitan that referenced this pull request Jul 21, 2026
In `VarlenAtttention`, remove hard coded `spmd_types` of `varlen_attn`
output.
Similar to pytorch#3924 (see
[comment](pytorch#3924 (review))).

Tested by running `llama3_debugmodel_varlen_attn` and
`gpt_oss_debugmodel` with `--parallelism.spmd_backend spmd_types ` and
`--debug.spmd_typechecking`.
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.

4 participants