Repository navigation
[spmd] Make multimodal encoder CP output collectives explicit - #5804
anijain2305 wants to merge 2 commits into
Conversation
7d82bb6 to
33f4e3c
Compare
db61708 to
1137c1f
Compare
33f4e3c to
0ce3205
Compare
1137c1f to
e120b7f
Compare
0ce3205 to
f4d98f8
Compare
e120b7f to
2b78e7b
Compare
f4d98f8 to
e6323ed
Compare
2b78e7b to
cbe5298
Compare
e6323ed to
cc06e3c
Compare
cbe5298 to
30cca14
Compare
cc06e3c to
617ffcc
Compare
30cca14 to
0ccf397
Compare
617ffcc to
6f90957
Compare
0ccf397 to
5fdee84
Compare
|
@claude review |
|
Claude finished @anijain2305's task in 2m 12s —— View job Approve -- please address the items below before merging (the only must-fix is the empty PR description): review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging -- the change is behavior-preserving. It moves the last CP I -> R encoder-output conversion out of ShardingConfig src/dst redistribution and into the encoder forward, and the only open item is the PR description.
What this PR does. Before, four multimodal encoder roots declared out_src=CP:I, out_dst=CP:R, so Module._redistribute_outputs ran an I -> R conversion over CP. That conversion does nothing in forward and all-reduces the gradient in backward. Now each encoder's forward calls maybe_replicate_invariant(x, CP) itself, and its sharding config only declares (and type-asserts) the CP-replicated output. The encoders are Qwen35VisionEncoder, MoonViTEncoder (Kimi K2.5/K3), NaViTEncoder (Muse Spark/Glimmer) and MuseSparkAudioEncoder.
Example. Qwen3.5 vision encoder under TP2+CP2:
before: forward -> self.merger(x) # merger does the TP I->R
_redistribute_outputs: assert CP:I, then spmd.redistribute(CP, I->R, op_dtype=x.dtype)
after: forward -> maybe_replicate_invariant(self.merger(x), CP) # same op, same op_dtype
_redistribute_outputs: assert CP:R, no redistribution
In backward the order is unchanged: the CP all-reduce still runs before the TP all-reduce at the merger/projector. The old forward async_op=True has no effect on an I -> R conversion, because it issues no forward collective. When CP is absent or has size 1, both paths are no-ops: spmd_mesh_group returns None, and the old path skipped size-1 axes.
Must fix
- PR description -- the body is the empty template. The commit message already has the Why / What changed / Numerics content (TP2+CP2 bitwise-identical encoder fwd+bwd; NaViT within
grid_samplenoise). Paste it into the matching sections, and fill in "Summary (human-written)" yourself.
Details
- All callsites covered: Kimi K3 reuses
MoonViTEncoder.forward(it doesn't override it) andmoonvit_encoder_sharding_config. Muse Glimmer builds its encoder throughmuse_spark_navit_configs->navit_encoder_sharding_config. Neither needs its own edit. - The commit message says "no core model issues a collective through ShardingConfig src -> dst". I spot-checked the remaining
out_dst_shardings/in_dst_shardingsentries intorchtitan/models/: lm_head, the routed experts in Muse Sparkflavors.py:473, Muse Spark norms, and Glimmer. All of them have src == dst, so they only assert. The redistribution machinery inModule._redistribute_{inputs,outputs}is still needed byexperiments/transformers_modeling_backend/hf_sharding.py(e.g.P -> I/SProwwise outputs), so it can't be deleted yet. - No new test is needed: this is a refactor with identical ops, and with spmd typechecking on, the existing
out_src_shardingsassertion now checks theCP:Rtype at each encoder boundary.
Not verified: the multi-GPU numerics claim in the commit message (no GPU run).
6f90957 to
79cf16f
Compare
5fdee84 to
24d5d20
Compare
79cf16f to
73fc187
Compare
24d5d20 to
d97e2fc
Compare
73fc187 to
f6e512f
Compare
d97e2fc to
4e240fc
Compare
f6e512f to
28175e9
Compare
4e240fc to
3b1d2fb
Compare
28175e9 to
0c176f4
Compare
3b1d2fb to
881c75a
Compare
The vision encoders and the multimodal perception banks still relied on
ShardingConfig src -> dst redistribution for their TP boundaries. All of them
are TP-Invariant -> Replicate conversions: forward no-ops whose backward
all-reduces the gradient. This moves them into model code.
- The vision MLP fc1, the Qwen3.5 merger fc1 and the Kimi projector linear_1
become ColumnParallelLinear. The encoders run under disable_dense_sp ("Run
vision encoders as non-sequence-parallel regions", earlier in this stack),
so its input conversion is I -> R in `<fqn>.tp_gather`, then `<fqn>.linear`.
- VisionAttention gathers `x` once at its boundary with maybe_gather_tp_input,
the same `attention.tp_gather` pattern the decoder attention modules use,
so q/k/v still share one backward all-reduce.
- Add maybe_invariant_to_replicate(x, axis) to torchtitan/distributed/spmd_types.py:
spmd.invariant_to_replicate over a named mesh axis, skipped when the axis is
not in the mesh. It handles the remaining region-free conversions (encoder
outputs, perception banks); the next commit reuses it on the CP axis.
- The encoder output stays TP-invariant; the consumer decides it needs
Replicate. Qwen3.5, Kimi K2.5 and Kimi K3 convert the encoder output with
maybe_invariant_to_replicate(TP) where the model consumes it, right after
calling the encoder (as Muse already does for its perception banks). The
encoder output still owns the CP boundary here; the next commit moves that
conversion to the consumer as well, after the TP one, so CP is reduced
first in backward as before.
- Muse Glimmer and Muse Spark convert the perception banks (vision, and audio
for Spark) after perception_emb_norm under SP. The SP-only
perception_emb_norm_sharding_config / perception_norm_sharding_config helpers
are removed; the norm now uses the plain CP-replicated config.
- vision_colwise_sharding_config, vision_attention_sharding_config,
vision_merger_sharding_config and moonvit_projector_sharding_config only
declare boundary layouts and no longer request a redistribution.
Tests: TestColumnParallelLinearWithDenseSPDisabled (2 ranks, strict
typecheck): under disable_dense_sp, ColumnParallelLinear on a TP-invariant
input converts I -> R and matches the unsharded output and gradients with
decoder SP on and off; it fails with an SpmdTypeError without the context
manager.
Numerics (TP2+SP, 2 GPUs, fixed seed and inputs, vision encoder fwd + bwd):
bitwise-identical output and every parameter gradient on both ranks vs. the
previous commit for Qwen3.5, Kimi K2.5, and Kimi K3. Muse Spark's NaViT uses
grid_sample, whose backward is nondeterministic on CUDA: excluding its
positional embedding, the Muse Spark visual bank (encoder, adapter, projection,
SP perception-bank conversion) is bitwise identical, and the full NaViT
encoder differs from the previous commit only within its run-to-run noise
(5e-7). End-to-end multimodal training could not be compared on the test
machine (see the previous commit).
After moving to disable_dense_sp and the consumer-side conversion: Kimi K2.5
full model fwd + bwd at TP2+EP2, SP on and off, is bitwise identical (output
and all 147 gradients, 75 of them in the vision encoder) to the earlier
version of this commit above. Qwen3.5, Kimi K3 and Muse were not re-run
(kernels missing on the dev machine); they use the same encoder helpers. With
TP and CP both > 1, this commit alone reduces vision gradients over TP before
CP (previously CP first); the next commit restores the original order.
The vision and audio encoders' root outputs were the last core boundaries redistributed implicitly by ShardingConfig: CP-Invariant -> Replicate, a forward no-op whose backward all-reduces the gradient over CP. As with the TP conversion in the previous commit, the encoder output stays CP-invariant and the consumer converts it, since only the consumer knows it needs Replicate: - Qwen3.5, Kimi K2.5 and Kimi K3 apply maybe_invariant_to_replicate(CP) right after the TP conversion where the model consumes the vision encoder output. Converting TP first reduces CP first in backward, the order before this stack. - Muse Spark (vision and audio) and Muse Glimmer (vision) convert right after calling the encoder, before the adapter / perception norm, where the encoder boundary used to convert. vision_encoder_sharding_config, moonvit_encoder_sharding_config, navit_encoder_sharding_config and audio_encoder_sharding_config now declare the CP-invariant output layout and no longer request a redistribution. audio_encoder_sharding_config also drops its in_dst_shardings, which only repeated in_src_shardings (an identity boundary). With this change no core model issues a collective through ShardingConfig src -> dst redistribution. Numerics: Kimi K2.5 full model fwd + bwd at TP2+EP2, SP on and off, is bitwise identical (output and all 147 gradients) to the previous version of this commit, which converted CP at the end of each encoder and was checked bitwise at TP2+CP2 against its parent. TP2+CP2 was not re-run for this version: the dev-machine harness has no CP support. The forward and backward op order matches that version for every model.
0c176f4 to
7d077fc
Compare
881c75a to
e2623ad
Compare
7d077fc to
11c9f41
Compare
|
Folded into #5803: the encoder CP output conversions now land together with the TP ones (both convert at the consumer). |
<!--
Reviewers need to be convinced, not just informed. Delete sections you
don't need.
Agents: follow .claude/skills/pr-description/SKILL.md. Never fill in the
Summary.
-->
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
this approach, and what you checked yourself. -->
Make the vision encoders' TP and CP conversions explicit
`spmd.redistribute` calls instead of automatic ShardingConfig
redistribution.
Vision encoders do not use SP, they are always TP/CP invariant and every
boundary needs a TP-replicate coversion I->R.
* Column parallel projection - `InvariantColumnParallelLinear` to make
it explicit.
* Vision attention - Gathers once at the boundary.
* Vision outputs - The outputs need a `maybe_replicate_invariant` to go
from vision to encoder boundary.
## Why
On main, every TP boundary in the vision encoders (Qwen3.5, Kimi K2.5,
Kimi K3) and at the Muse perception banks is converted by a
`ShardingConfig` src -> dst pair, which the `Module` wrapper turns into
a hidden collective. All of them are the same conversion, TP-Invariant
-> Replicate: a forward no-op whose backward all-reduces the gradient.
Nothing in `forward` shows that backward all-reduce, yet without it each
rank keeps a partial input gradient for a column-parallel projection.
This continues the explicit-collectives stack (#5802).
**Example: vision MLP `fc1` (column-parallel).**
```
main: fc1 = Linear.Config(sharding_config=vision_colwise_sharding_config())
# config: in_src={"input": I}, in_dst={"input": R}
# -> Module wrapper silently inserts I -> R (bwd all-reduce)
this PR: fc1 = InvariantColumnParallelLinear.Config(sharding_config=vision_colwise_sharding_config())
# forward: super().forward(maybe_gather_tp_input(self, input, src=spmd.I))
# config: in_src={"input": I} only
```
## What changed
**Helpers**
- `maybe_gather_tp_input(module, x, *, src=None)`: new optional `src`.
The default stays the decoder residual layout (S(0) with SP, I without).
Vision passes `src=spmd.I`, because the vision stream is Invariant even
under decoder SP; the default would all-gather an unsharded tensor.
- New `maybe_replicate_invariant(x, axis)` in
`torchtitan/distributed/spmd_types.py`: I -> R on any mesh axis, a no-op
when the axis is absent. Used for free-standing tensors; #5804 reuses it
on the CP axis.
**Vision encoder sites (all I -> R)**
- Column-parallel projections (vision MLP `fc1`, Qwen3.5 merger `fc1`,
Kimi projector `linear_1`): new `InvariantColumnParallelLinear`, the
column counterpart of `InvariantRowParallelLinear`.
- `VisionAttention`: gathers `x` once at its boundary so q/k/v share one
backward all-reduce (the decoder attention pattern); the rope cache
converts alongside it (type only, no gradient).
- Merger / projector outputs (`PatchMerger`, `VisionProjector`,
`KimiK3VisionProjector`): `maybe_replicate_invariant`, since the
features are scattered into the TP-Replicate text stream. The encoder
output still owns the CP boundary, so CP is reduced first in backward.
- Muse Glimmer / Spark perception banks (vision, and audio for Spark),
under decoder SP only: each rank gathers bank rows for its own token
shard, so the bank's gradient is partial per rank.
**Configs**
- `vision_colwise_sharding_config`, `vision_attention_sharding_config`,
`vision_merger_sharding_config` and `moonvit_projector_sharding_config`
only declare boundary layouts.
- Removed the SP-only `perception_emb_norm_sharding_config` (Glimmer)
and `perception_norm_sharding_config` (Spark); the perception norm uses
the plain CP-replicated config.
- Quantization converters may target `InvariantColumnParallelLinear`
(vision `fc1` was quantizable as a plain `Linear`).
**Mechanical, skimmable:** the per-flavor
`_vision_column_parallel_linear` helpers in qwen3_5, kimi_k2_7 and
kimi_k3 flavors, and the import changes.
## Numerics / performance
Same collectives as main (I -> R moves no data in forward), so no
performance change.
| Check | Result |
| --- | --- |
| Vision encoder fwd + bwd, TP2+SP, fixed seed and inputs: Qwen3.5, Kimi
K2.5, Kimi K3 | output and every parameter gradient bitwise identical to
the previous commit, on both ranks |
| Muse Spark visual bank (encoder, adapter, projection, SP bank
conversion) | bitwise identical, excluding NaViT's positional embedding:
its `grid_sample` backward is nondeterministic on CUDA |
| Muse Spark full NaViT encoder | differs only within its own run-to-run
noise (5e-7) |
| Full model fwd + bwd at the top of the stack vs. main `9f70e5597`,
TP2: qwen3_5 and kimi_k2_7, SP on / off | output and every parameter
gradient bitwise identical |
| Training loss and grad_norm vs. main `9f70e5597` (10 steps, seed 42,
deterministic, `scripts/loss_compare.py --assert-equal`) at the top of
the stack: llama3, qwen3, deepseek_v3 MTP, gpt_oss, deepseek_v4,
Transformers backend | identical |
End-to-end multimodal training with real images was not compared on the
test machine; TP4 runs are in progress and will be posted on #5802.
## Testing
- New `TestInvariantColumnParallelLinearDistributed` (`test_linear.py`,
2 ranks, `set_spmd_meshes` with SP on and off, typechecked): the output
matches the unsharded linear's shard, and the input gradient is complete
on every rank, which requires the backward all-reduce. Verified to fail
if the layer drops `src=spmd.I` and treats the vision stream as
sequence-sharded under SP.
- `test_qwen3_5.py`: expects `InvariantColumnParallelLinear` for `fc1`
and `merger.fc1`, with no `in_dst`.
- CPU unit tests (models, config, quantization, distributed, HF
sharding): no new failures vs. main; waiting on CI.
Summary (human-written)
Why
What changed
Numerics / performance
Testing