Repository navigation
[spmd_types] FlexAttention: remove hardcoded spmd_types of FlexAttention._complex_flex_attn output - #3924
Conversation
… 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.
|
|
|
@pianpwk The PR matches what we discussed, but please take a look. We may miss something. |
|
|
||
| import torch | ||
| import torch.nn.functional as F | ||
| from spmd_types.runtime import get_local_type, get_partition_spec |
There was a problem hiding this comment.
nit:
import spmd_types as spmd
from spmd_types.runtime import get_partition_spec
# later call spmd.get_local_type
| 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]) |
There was a problem hiding this comment.
nit: don't need the tuple cast
…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.
|
I made the changes. Thank you! |
| 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``. |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
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)) |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
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`.
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`.
FlexAttention.compiled_flex_attnruns the compiled flex kernel underspmd.no_typecheck()and then re-stamps output's SPMD type.It previously hardcoded
PartitionSpec("dp","tp","cp",None)forout(and"dp","tp","cp"forlse), 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 asq), so derive the output type fromqinstead: copyq's local type + shard-dimPartitionSpecontoout, and the same minus the trailing (unsharded) head-dim entry ontolse.spmd_typeshas a functionassert_type_likethat can copy local types, withoutPartitionSpec.But using that would only preserve correctness when
FlexAttentionis used inside alocal_mapregion, so it is not used here.Edit: spmd_types 0.2.2
assert_type_likedoes havePartitionSpec, but this cannot handle the dimension mismatch forlse.Test plan: existing attention/spmd unit suites pass. Validated e2e under spmd_types + --debug.spmd_typechecking: