Repository navigation
[spmd] Restore the residual layout explicitly after the multimodal scatter - #5806
Conversation
4479ed1 to
9d5259a
Compare
9d5259a to
002ea18
Compare
002ea18 to
b6f6605
Compare
b6f6605 to
babfb47
Compare
babfb47 to
3d7b4e8
Compare
3d7b4e8 to
d98d3ae
Compare
d98d3ae to
5524196
Compare
5524196 to
a62a934
Compare
a62a934 to
4d2f124
Compare
4d2f124 to
dabe56c
Compare
dabe56c to
8567116
Compare
8567116 to
a5f4cc9
Compare
4b3de15 to
778a00f
Compare
|
@claude review |
|
Claude finished @anijain2305's task in 3m 33s —— View job Approve -- please address the items before merging (fill in the human-written summary, correct the description, and remove dead code and a stale docstring in the Kimi flavors). A maintainer still needs to review. Review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. Moving the post-scatter layout restore out of a special layer-0 ShardingConfig and into explicit model code is the right direction (it is the precondition for #5807), and the change is small and net-negative. A maintainer still needs to review, since this touches models/common/.
What this PR does. Multimodal models gather the token embeddings to TP-Replicate before the vision scatter. Until now, layer 0 had its own ShardingConfig (in_src=R -> in_dst=residual) to convert the stream back implicitly. This PR adds replicate_to_residual(x_TD) in common/multimodal.py, which does R -> S(0) under SP and R -> I otherwise. Each model calls it in forward right after building the embeddings. All the layer-0 special configs and their plumbing are deleted.
Example (Qwen3.5 + vision, TP2 + SP).
before: embed S(0) -> gather -> R -> scatter (R)
-> layer 0 (config in_src=R, in_dst=S(0): implicit slice) -> layers 1..N (S(0))
after: embed S(0) -> gather -> R -> scatter (R)
-> replicate_to_residual: R -> S(0) (explicit slice)
-> layers 0..N (one shared config)
A side benefit: layer 0 now has the same boundary as every other layer, so per-layer compile and remat treat it like the rest. The restore is also keyed on self.vision_encoder at runtime, the same condition as the gather, rather than on a flavor-level flag.
Must fix
- PR description. "Summary (human-written)" is empty. The description also doesn't match the code in two places:
- It names the helper
replicated_to_residual_layout; the code hasreplicate_to_residual. - It says doing the restore "next to the scatter keeps the gather and its inverse in one function". In fact, the gather is in
_prepare_multimodal_embedsand the restore is inforward, and the two share their condition only by duplicating it.
- It names the helper
- Dead code and a stale docstring left behind (outside the diff hunks, so not commented inline):
torchtitan/models/kimi_k2_7/flavors.py:395andtorchtitan/models/kimi_k3/flavors.py:607:multimodal = vision_encoder is not Noneis now unused. Delete both.torchtitan/models/kimi_k3/flavors.py:601-603: the docstring still says "layer 0's input boundary restores the decoder's layout". Change it to say the model's forward restores the layout after the scatter.
Questions
torchtitan/models/kimi_k2_7/model.py:299-- under TP without SP, Kimi K2.5 skips both the gather and the restore. This looks like it may all-reduce the vision gradient twice. It predates this PR, but aligning K2.5 with Qwen3.5 and K3 (gather and restore whenever there is a vision encoder) would remove the SP special case in both places. See the inline comment.
Details
-
Direction: this matches the stack's goal (#5802, then this PR, then #5807): no
ShardingConfigsrc -> dst conversions left in core. I found no other callers of the removedafter_vision_scatter=,first_layer_sharding_config=,sequence_parallel_first_layer_sharding_config,multimodal_first_layer_sharding_config, or the builders'has_vision_encoder=arguments anywhere in the repo, recipes and experiments included. -
Gather/restore pairing:
- Qwen3.5: gathers iff
vision_encoder is not None(model.py:596); restores ifftok_embeddings and vision_encoder. - K3: gathers iff
vision_encoder is not None(model.py:365); restores under the same condition. - K2.5: gathers iff
vision_encoder and dense_sp(model.py:188); restores under the same condition.
Under PP, layer 0 and
tok_embeddingsboth sit on the first stage, so the old flavor-level layer-0 condition and the new runtime condition agree. - Qwen3.5: gathers iff
-
K3 block residual: with no stack passed in, the empty
block_residual_TNDis now derived from the already-restoredh_TD. So its type comes fromunsqueeze/slice of the residual-layout stream, not from the deleted_block_residual_placement. With no stack, this should be equivalent, since layers 1..N already consume what layer 0 emits. -
Memory: under SP with layer-0 remat, layer 0 now saves the
S(0)slice rather than the fullRinput. That is neutral or better.
Not verified: Kimi K3 numerics and type-checking (the author could not run it, and I could not run Python or GPU tests here). The K2.5 no-SP gradient concern is from reading the code only.
| if ( | ||
| self.tok_embeddings is not None | ||
| and self.vision_encoder is not None | ||
| and spmd_dense_sp_enabled() | ||
| ): | ||
| x = replicate_to_residual(x) |
There was a problem hiding this comment.
Question (unverified, and it predates this PR). Without SP, Kimi K2.5 skips both the gather and the restore. That leaves an I stream (the embedding output) with R vision rows scattered into it. The assert just above declares tp: R, but layer 0 expects I.
In backward, layer 0's maybe_gather_tp_input (I -> R) all-reduces the gradient. invariant_to_replicate(vision_embeds, TP) then all-reduces the vision rows' gradient a second time. If that is what happens, vision-encoder gradients come out scaled by the TP degree under TP without SP.
Qwen3.5 and Kimi K3 avoid this by gathering and restoring whenever there is a vision encoder. If K2.5 did the same (drop and spmd_dense_sp_enabled() here and at line 188), all three models would share one condition, and this special case would go away. Is the no-SP path type-checked anywhere in CI?
778a00f to
a9917e4
Compare
|
@claude review |
|
Claude finished @anijain2305's task in 2m 38s —— View job Approve -- please address the items before merging (one stale docstring in |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. All must-fix items from the last review are resolved, and the Kimi K2.5 no-SP gradient bug is now fixed and measured. One stale docstring is left. A maintainer still needs to review, since this touches models/common/.
What this PR does. Multimodal models gather the token embeddings to TP-Replicate before the vision scatter. Before this PR, a special layer-0 ShardingConfig (in_src=R -> in_dst=residual) converted the stream back implicitly. That config is gone. Each model now calls replicate_to_residual(x) in forward right after the scatter. It converts R -> S(0) under SP and R -> I otherwise, and neither direction communicates. Kimi K2.5 now gathers and restores whenever it has a vision encoder, like Qwen3.5 and K3. Without SP it used to scale the vision-encoder gradients by the TP degree.
Example (Kimi K2.5 + vision, TP2, no SP).
before: embed (I) -> scatter R vision rows into I stream -> layer 0 (I)
bwd: layer-0 gather all-reduces + vision invariant_to_replicate all-reduces
-> vision grads x TP degree
after: embed (I) -> gather I->R -> scatter (R) -> replicate_to_residual R->I -> layer 0
bwd: vision rows all-reduced once -> matches TP1
Resolved since the last review:
- The human-written summary is filled in, and the helper name and the alternatives text now match the code.
- The unused
multimodallocals are deleted in the Kimi K2.5 and K3 flavors, and the K3 docstring is updated. - The K2.5 no-SP double reduction is fixed (the author measured vision grads matching TP1).
Must fix
torchtitan/models/kimi_k2_7/sharding.py:13-- the module docstring still says "Under SP, multimodal models gather...". After the K2.5 fix that is wrong (see inline suggestion).
Should consider
tests/unit_tests/cpu/models/qwen3_5/test_qwen3_5.py:295-- delete the test. It now only re-reads its config, and every flavor is already built bytest_qwen35_registry_builds_every_flavor.torchtitan/models/kimi_k2_7/model.py:296-301(andkimi_k3/model.py:454-470) -- thetp: Rassert is unconditional but only holds when the gather ran. Put it under the same condition as the restore. This predates the PR and is unverified.
Details
- Stack direction: this PR is the precondition for #5807. Grepping
in_dst_shardingsusage in the changed models turns up no remaining layer-0 src -> dst pair. - Leftover imports:
replicated_activation_placement(qwen3_5/sharding.py), anddense_activation_placementandresidual_activation_placement(kimi_k3/sharding.py), are all still used elsewhere in their files.ShardingConfigis still used in kimi_k2_7/flavors.py. - K2.5 no-SP comm cost: the fix adds one
(T, D)all-reduce per step in backward, from the embedding gather'sP -> I. That is the cost Qwen3.5 and K3 already pay. A cheaper no-SP alternative would scatter theIvision embeds into theIstream with no gather and no TPinvariant_to_replicate. It would also be special-cased again, though, and one all-reduce per step is small next to the per-layer collectives. Aligning the three models is reasonable. - K3 block residual: it is still derived from
h_TDafter the restore, so it enters layer 0 in the residual layout.
Not verified: Kimi K3 numerics and type checking (CI only); the unconditional-assert failure mode.
| Under SP, multimodal models gather the token embeddings to ``Replicate`` | ||
| before the vision scatter and restore the residual layout after it. |
There was a problem hiding this comment.
This docstring is stale after the K2.5 gradient fix. model.py:189 now gathers whenever there is a vision encoder, not only under SP. As written, it describes the old SP-only behavior that this PR removes.
| Under SP, multimodal models gather the token embeddings to ``Replicate`` | |
| before the vision scatter and restore the residual layout after it. | |
| Multimodal models gather the token embeddings to ``Replicate`` before the | |
| vision scatter and restore the residual layout after it. |
| @@ -293,14 +293,11 @@ def test_qwen35_always_calls_vision_encoder_twice( | |||
| ], | |||
| ) | |||
| def test_qwen35_text_only_flavor_has_no_vision_encoder(flavor: str) -> None: | |||
There was a problem hiding this comment.
Should consider deleting this test. Its one non-trivial check, that layer 0's config differs between the _mm and text flavors, is gone. What is left only re-reads the config it just built: vision_encoder is or isn't None, and the layer counts match. test_qwen35_registry_builds_every_flavor (line 211) already builds every flavor, so deleting this test loses no coverage (.claude/rules/tests.md: don't keep tests that only re-read a config).
a9917e4 to
2045ec0
Compare
…atter Multimodal models gather the token embeddings to TP-Replicate before the vision scatter (maybe_gather_tp_input), so the scatter can write any position. Layer 0 then converted the stream back to the decoder residual layout through a special first-layer ShardingConfig: R -> Shard(0) under SP (a local slice) and R -> Invariant otherwise (a type change). These were the last ShardingConfig src -> dst conversions in core; neither communicates. - Add replicate_to_residual in common/multimodal.py, which undoes the pre-scatter gather. Qwen3.5 (and 3.6/3.8), Kimi K2.5 and Kimi K3 call it right after the scatter, under the same condition as its pre-scatter gather: whenever the stage has the token embeddings and a vision encoder. Kimi K3 converts the stream before deriving the empty block-residual stack from it, so both enter layer 0 in the residual layout as before. - Kimi K2.5 now gathers and restores whenever it has a vision encoder, like Qwen3.5 and Kimi K3. It used to do both only under SP, which left the scattered vision rows TP-Replicate inside an Invariant stream without SP: layer 0's input gather all-reduced their gradient, and the encoder output's invariant_to_replicate all-reduced it again, scaling the vision-encoder gradients by the TP degree (predates this stack). - Remove the layer-0 configs: qwen3_5 transformer_block_sharding_config's after_vision_scatter (and the now-unused has_vision_encoder builder argument), kimi_k2_7 sequence_parallel_first_layer_sharding_config, kimi_k3 multimodal_first_layer_sharding_config, and the first_layer_sharding_config argument of the shared deepseek_v3 layer builder. With this change no core ShardingConfig declares a src -> dst pair that differs on any mesh axis. Numerics (TP2, 2 GPUs, fixed seed and inputs, full debug model fwd + bwd): bitwise-identical output and every parameter gradient on both ranks vs. main for Qwen3.5 and Kimi K2.5 (debug models with a vision encoder), with and without SP. Kimi K3 could not run on the test machine (KDA kernel library version mismatch). Kimi K2.5 with a real image at TP2 without SP: the vision-encoder gradients now match TP1 (they were TP-degree times larger); every other gradient, and all gradients with SP, are bitwise unchanged.
2045ec0 to
788c508
Compare
…5802) Stacked on #6035. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why TP collectives are moving out of `ShardingConfig` src -> dst pairs, where `Module` inserts them implicitly, and into explicit `spmd.redistribute` calls in model code. `RowParallelLinear` / `ColumnParallelLinear` and the MoE (#4878) already work this way. The token embedding's reduction and the gather before `lm_head` are the last decoder collectives still inserted implicitly. Terms: the *residual layout* (`residual_activation_placement`, already on main) is the TP layout of the `(tokens, hidden)` stream between blocks: `S(0)` with sequence parallelism, `I` (Invariant) without. **Example (TP=2, SP on).** ``` tokens -> embedding (vocab-sharded weight, each rank's lookup is TP-Partial) main: config out_src=P, out_dst=S(0) -> Module inserts reduce-scatter now: VocabParallelEmbedding.forward: spmd.redistribute(P -> S(0)) -> [multimodal only] vision scatter needs the full sequence on every rank main: a second embedding config with out_dst=R -> all-reduce instead now: maybe_gather_tp_input(S(0) -> R) right before the scatter -> blocks (residual layout S(0)) -> final norm main: config out_dst=R -> Module inserts all-gather now: Decoder._pre_lm_head_norm_and_gather: maybe_gather_tp_input(S(0) -> R) -> lm_head (vocab-sharded, needs R) ``` ## What changed **Embedding** - `Embedding` is renamed to `VocabParallelEmbedding` (the TODO on main). It is now the only token embedding class, so no embedding can return an unreduced TP partial. - Under TP, the masked vocab-shard lookup runs in a `spmd.local_map` region: TP-replicated token ids in, TP-partial embeddings out. The module then reduces to the residual layout: P -> S(0) (reduce-scatter) with SP, P -> I (all-reduce) without. Without TP it is a plain lookup. - On main the lookup was already a local region: `local_spmd=True` made `Module` wrap the whole forward in `local_map`. The region is explicit now because the reduction runs in `forward`, on typed tensors, outside it. - The embedding always emits the residual layout. Multimodal models gather explicitly before the vision scatter, under the same conditions that used to select a replicated embedding: - Qwen3.5 family and Kimi K3: when they have a vision encoder. - Kimi K2.5: when it has one and SP is on. The condition is just `self.vision_encoder is not None`, which is reliable because #6035 stops the RL generator from deleting the encoder after build. `multimodal_token_embedding_sharding_config` is removed. - The Transformers modeling backend keeps its `(batch, sequence)` layout and its own reduction, through a lookup-only subclass in `module_conversion.py`. **Final norm** - `lm_head` is vocab-sharded, so it needs the full hidden states on every rank. - New `Decoder._pre_lm_head_norm_and_gather`: root norm, then `maybe_gather_tp_input`. With SP that is S(0) -> R (all-gather); without, it is I -> R (forward no-op, backward all-reduce). - It gathers after the norm, so under SP the norm only touches the local sequence shard. - It gathers once, rather than inside `lm_head`, which `ChunkedLossWrapper` calls once per chunk. Moving the gather into `lm_head` (with the chunked loss chunking the local shard) is a follow-up, because it changes the loss summation order. - Called by `Decoder` and every model with its own forward: deepseek_v3 MTP, deepseek_v4, kimi_k2_7, kimi_k3, muse_glimmer, muse_spark, qwen3_5. The MTP block gathers its `mtp_norm` output the same way. **Sharding configs** - `token_embedding_sharding_config` now only declares (and, under typechecking, asserts) boundary layouts. - `pre_lm_head_norm_sharding_config` was identical to `norm_sharding_config` and is removed. **Mechanical, skimmable:** - the `Embedding` -> `VocabParallelEmbedding` rename across flavors; - the one-line `_pre_lm_head_norm_and_gather` call in each model forward. ## Alternatives considered - **Keep a `replicate_output` flag on the embedding:** it restated the layout the flavor already chose through the sharding config, twice per flavor (13 sites). Gathering at the scatter keeps the layout decision next to its only consumer. Under SP it is RS + AG instead of one AR (same bytes, one extra latency, once per step). - **Derive the reduction target from the sharding config:** the config would again choose which collective runs, the pattern this stack removes. - **Keep `local_spmd=True` and drop the explicit `local_map`:** the flag wraps the whole forward, so the reduction would have to be a raw collective with a hand-written backward, or go back to the implicit boundary collective. - **Gather inside `lm_head`:** see Final norm above. Follow-up PR. ## User-facing changes | Before | After | | --- | --- | | `Embedding.Config(...)` | `VocabParallelEmbedding.Config(...)` | | `multimodal_token_embedding_sharding_config()` | `token_embedding_sharding_config(enable_sp=...)`; the model gathers before the vision scatter | | `pre_lm_head_norm_sharding_config(...)` | `norm_sharding_config(...)` | | Custom forward calls `self.norm(h)` before `lm_head` | Call `self._pre_lm_head_norm_and_gather(h)` | ## Numerics Bitwise-identical loss and grad_norm over 10 steps vs. main `9f70e5597` (seed 42, deterministic, `scripts/loss_compare.py --assert-equal`): | Config | Result | | --- | --- | | llama3 TP2+SP / TP2 no SP / TP2+CP2 | identical | | llama3 TP4+SP / TP4 no SP | identical | | qwen3 TP2+SP | identical | | deepseek_v3 MTP TP2+EP2, SP / no SP | identical | | deepseek_v3 MTP TP4, SP / no SP | identical | | gpt_oss TP2+EP2 | identical | | deepseek_v4 FSDP | identical | | Transformers backend dense / MoE, TP2 | identical | | qwen3_5 video TP2+SP | identical | | muse_spark TP2+EP2 | see below | The multimodal models that used the replicated embedding were also checked with a full-model fwd + bwd at TP2 and fixed inputs. Output and every parameter gradient on both ranks were compared against main, which is itself deterministic across two runs: | Model | SP | Result | | --- | --- | --- | | qwen3_5 debugmodel (with vision encoder) | on / off | identical / identical | | kimi_k2_7 debugmodel (with vision encoder), TP2 and TP4 | on / off | identical / identical | Kimi K3 couldn't run on the test machine (KDA kernel library mismatch). It takes the same code path as qwen3_5. **Muse Spark:** on main, `tok_embeddings.embedding.weight.grad` is `None` under TP. With this PR it gets a gradient (0.0590 vs. 0.0564 at TP1), and every other parameter gradient is bitwise identical to main. Why main loses it isn't root caused yet: a minimal async-collective + torch.compile repro doesn't reproduce it. Tracked in #5915. ## Testing - `test_vocab_parallel_embedding_parity` (`test_embedding.py`) builds `VocabParallelEmbedding` end to end under strict typechecking. That also checks the new `local_map` types. It covers SP on and off, and vocab sizes that do and don't divide TP. It catches a wrong reduction (bitwise vs. DTensor's embedding and the unsharded one) and wrong weight gradients. - `test_fsdp_embedding.py` (4 GPUs) uses the real class and `token_embedding_sharding_config`; passes. - CPU unit tests (models, config): same 40 failures and 5 collection errors as the base commit on the dev machine (missing packages), none new. ## Known issues / follow-ups - Gather inside `lm_head` instead of after the final norm (follow-up, needs a loss comparison). - Qwen3.5's forward asserts TP-Replicate embeddings under `debug.spmd_typechecking`, which is wrong for text-only models under TP. This already affects Qwen3.8 on main. - Stack: next is #5803 (vision encoder TP collectives). #5806 restores the residual layout explicitly after the vision scatter. The top PR, #5807, removes `in_dst_shardings` / `out_dst_shardings`, so `ShardingConfig` can no longer insert a collective.
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
this approach, and what you checked yourself. -->
Get rid of implicit redistribution. Yay!!
## Why
`ShardingConfig` could insert collectives implicitly: when a module's
`in_dst_shardings` / `out_dst_shardings` differed from its
`in_src_shardings` /
`out_src_shardings`, the `Module` wrapper redistributed the tensor at
the
boundary (`spmd_redistribute_per_axis`, async). Those collectives were
invisible
in model code, easy to add by accident, and ran with `async_op=True`
(#5915
tracks a gradient bug in that path).
The earlier PRs in this stack moved every such collective into explicit
`spmd.redistribute` calls in module forwards (#5802 decoder embedding
and final
norm, #5803 multimodal encoders, #5805 Transformers backend, #5806 the
post-scatter restore). After them, every remaining `dst` entry equals
its `src`
counterpart, so the boundary redistribution never fires. This PR removes
the
machinery, so a new config can't silently reintroduce an implicit
collective.
**Example (a module boundary).**
```
before: ShardingConfig(in_src_shardings={"x": S(0)}, in_dst_shardings={"x": R})
-> Module wrapper: spmd_redistribute_per_axis(S(0) -> R, async_op=True)
after: ShardingConfig(input_shardings={"x": S(0)}) # asserted only
-> forward: x = spmd.redistribute(x, tp_group, src=S(0), dst=R)
```
## What changed
**Core**
- `ShardingConfig` drops `in_dst_shardings` and `out_dst_shardings`. It
only
declares layouts: parameter/buffer placements and the activation types
at
the boundary.
- With no dst side left, `in_src_shardings` / `out_src_shardings` are
renamed
to `input_shardings` / `output_shardings` (review), at every call site.
- `Module._parallelize` wraps `forward` with boundary checks only
(`_assert_input_types` / `_assert_output_type`, under SPMD type
checking)
and builds local-SPMD regions from `input_shardings` /
`output_shardings`.
- `spmd_redistribute_per_axis`, `spmd_validate_redistributions` and the
async
module-boundary collective path are deleted from
`distributed/spmd_types.py`.
**Configs**
- The redundant `src == dst` entries are removed from the core sharding
helpers (`decoder_sharding.py`, `vision_encoder_sharding.py`), the
Qwen3.5,
Kimi K3, DeepSeek-V4, Muse Spark and Muse Glimmer sharding files, the
Muse
Spark CP-replicate transform, `NVFP4Linear`, and the Transformers
backend's
`hf_sharding.py`.
**Docs**
- MoE `SHARDING.md`, the Transformers backend `add_moe_model` skill and
the
inner-attention docstring described boundary redistribution; they now
describe the explicit collectives. (The MoE collectives were already
explicit in `MoE.forward` on main; the doc was out of date.)
**Mechanical, skimmable:** the field rename across models, configs,
tests and docs; tests drop asserts on the removed fields, and the
tests of the deleted helpers (`test_parallelism_context.py`) are
removed.
## Alternatives considered
- **Keep `dst` fields but assert `dst == src`**: keeps a field whose
only
valid value is a copy of another, and the type still suggests the config
can
move data.
- **Keep the machinery as an opt-in**: a second way to issue collectives
is exactly what the stack removes; out-of-tree code can call
`spmd.redistribute` in its forward.
## User-facing changes
| Before | After |
| --- | --- |
| `ShardingConfig(..., in_dst_shardings=..., out_dst_shardings=...)` |
`TypeError` at construction; declare the layout in `input_shardings` /
`output_shardings` and call `spmd.redistribute` in `forward` for any
layout change |
| `ShardingConfig(in_src_shardings=..., out_src_shardings=...)` |
`ShardingConfig(input_shardings=..., output_shardings=...)` |
| Boundary collectives ran async (`async_op=True`) | No boundary
collectives; the explicit ones in model code are synchronous |
Out-of-tree modules that relied on boundary redistribution must issue
the
collective themselves; a config that still sets the removed fields fails
loudly instead of silently getting a collective.
## Numerics
Seed 42, deterministic, 10 steps; loss and grad_norm bitwise identical
to main
(`scripts/loss_compare.py --assert-equal`):
- llama3: TP2+SP, TP2 without SP, TP2+CP2;
- qwen3: TP2+SP;
- deepseek_v3 with MTP: TP2+EP2, with and without SP;
- gpt_oss: TP2+EP2;
- deepseek_v4: FSDP;
- Transformers backend: dense debug model TP2 (with SP; this backend
always
enables SP with TP), and MoE FSDP+TP+EP+CP (8 GPUs).
Qwen3.5 and Kimi K2.5 (`kimi_k2_7`, `KimiK25Model`; debug models with a
vision encoder), full model
forward + backward at TP2 with SP on and off: output and all gradients
bitwise
identical to the previous commit.
## Testing
- CPU unit tests for the touched modules pass; tests of the deleted
helpers
are removed with them.
## Known issues / follow-ups
- Top of the explicit-collectives stack (#6035, #5802, #5803, #5805,
#5806,
#5807).
- Follow-ups from review: issue the `lm_head` gather from `lm_head`
itself
(TODO in `Decoder._pre_lm_head_norm_and_gather`); build text flavors as
a
`Decoder` and drop `keep_vision_encoder`.
Summary (human-written)
The multimodal model structure is vision encoder -> vision scatter -> decoder.
The input to the vision scatter is TP-replicated, because the scatter needs the full sequence on every rank. The decoder, however, expects the residual layout: S(0) with SP, or I without SP. This PR makes that conversion explicit.
Why
Multimodal models gather the token embeddings to TP-
Replicatebefore thevision scatter (
maybe_gather_tp_input, #5802), so the scatter can write anytoken position. The decoder layers expect the residual layout, so the stream
has to go back:
Replicate -> Shard(0)under sequence parallelism (a localslice) and
Replicate -> Invariantwithout it (a type change).Until now a special layer-0
ShardingConfigdid that conversionimplicitly, through its
in_src -> in_dstpair. These were the lastShardingConfigsrc -> dst conversions in core. #5807 removes implicitredistribution, so the conversion has to be explicit code. Neither conversion
communicates, in forward or backward.
Example (Qwen3.5 with a vision encoder, TP2 + SP).
What changed
Explicit restore (
common/multimodal.py)replicate_to_residual(x_TD):spmd.redistributefromRtoS(0)under dense SP, toIotherwise. A no-op without TP.its pre-scatter gather, so the gather and the restore always pair up:
whenever the stage has the token embeddings and a vision encoder (Qwen3.5,
and Qwen3.6 / 3.8, which share the model; Kimi K2.5; Kimi K3).
from it, so both enter layer 0 in the residual layout, as before.
Kimi K2.5 gradient fix (predates this stack)
scattered vision rows stayed TP-
Replicateinside anInvariantstream:layer 0's input gather all-reduced their gradient, and the encoder output's
invariant_to_replicateall-reduced it again, so vision-encoder gradientswere scaled by the TP degree. It now gathers and restores whenever it has a
vision encoder, like Qwen3.5 and Kimi K3.
Layer-0 configs removed
transformer_block_sharding_config'safter_vision_scatterargument, and the layer builders' now-unused
has_vision_encoderargument(the flavor functions keep theirs, for the vision encoder itself).
sequence_parallel_first_layer_sharding_config.multimodal_first_layer_sharding_configand its block-residualplacement helper.
first_layer_sharding_configargument of the shared layerbuilder, which only Kimi K2.5 used.
After this PR, no core
ShardingConfigdeclares a src -> dst pair thatdiffers on any mesh axis, which is what #5807 relies on.
Mechanical, skimmable: the flavor call sites that passed the removed
arguments, and the Qwen3.5 text-flavor test, which no longer compares layer-0
configs.
Alternatives considered
need code somewhere. Doing it in the model's forward, right after the
scatter, keeps it in model code next to the multimodal input preparation;
the gather and the restore share their condition by repeating it.
arbitrary positions, so each rank would need to know which vision rows land
in its sequence shard. That is a larger change, out of scope here.
User-facing changes
None for users of the built-in models. Out-of-tree flavors that passed
after_vision_scatter=orfirst_layer_sharding_config=must drop theargument and restore the layout in their model's forward.
Numerics
TP2 on 2 GPUs, fixed seed and inputs, full debug model forward + backward:
output and every parameter gradient are bitwise identical to main on both
ranks, for Qwen3.5 and Kimi K2.5 (
kimi_k2_7; debug models with a vision encoder), withand without SP. Kimi K3 could not run on the test machine (KDA kernel library
version mismatch).
Testing
flavor test is removed: with the layer-0 config gone, it only re-read the
config it built.
tp: Rtype assertion after the scatter now runs underthe same condition as the restore (it only holds when the gather ran).
Known issues / follow-ups
in_dst_shardings/out_dst_shardingsfromShardingConfig.