Skip to content

[spmd] Make vision encoder TP and CP collectives explicit - #5803

Merged
anijain2305 merged 1 commit into
explicit-decoder-tp-collectivesfrom
explicit-vision-tp-collectives
Nov 13, 2026
Merged

anijain2305 merged 1 commit into
explicit-decoder-tp-collectivesfrom
explicit-vision-tp-collectives

Conversation

@anijain2305

@anijain2305 anijain2305 commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

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; [spmd] Make multimodal encoder CP output collectives explicit #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.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 4, 2026
@anijain2305
anijain2305 added this pull request to stack #5808 November 4, 2026 06:59
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 4, 2026
@anijain2305
anijain2305 force-pushed the explicit-vision-tp-collectives branch from 7d82bb6 to 33f4e3c Compare November 4, 2026 07:14
@anijain2305
anijain2305 force-pushed the explicit-vision-tp-collectives branch from 33f4e3c to 0ce3205 Compare November 6, 2026 22:44
@anijain2305
anijain2305 force-pushed the explicit-vision-tp-collectives branch from 0ce3205 to f4d98f8 Compare November 6, 2026 23:05
@anijain2305
anijain2305 force-pushed the explicit-vision-tp-collectives branch from f4d98f8 to e6323ed Compare November 6, 2026 23:10
@anijain2305
anijain2305 force-pushed the explicit-vision-tp-collectives branch 2 times, most recently from cc06e3c to 617ffcc Compare November 6, 2026 23:49
@anijain2305

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @anijain2305's task in 3m 26s —— View job


Approve -- see the review (optional suggestions only; a maintainer still needs to review).

@claude claude Bot 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.

Verdict: Approve -- every vision TP boundary keeps the same I -> R conversion in the same backward reduction order, now written in forward. Remaining items are optional. This touches models/common and distributed/, so a maintainer still needs to review.

What this PR does. This continues the explicit-collectives stack (#5802). Each vision-encoder ShardingConfig in_dst/out_dst pair that only changed TP from I to R is removed, and the same conversion now happens in forward:

  • New InvariantColumnParallelLinear for the column-parallel projections.
  • VisionAttention gathers x once, so q/k/v share one backward all-reduce.
  • New maybe_replicate_invariant at the merger and projector outputs, and at the Muse perception banks under SP.

Example. Qwen3.5 vision MLP fc1, TP=2, SP on:

before: fc1 = Linear(sharding: in_src TP=I, in_dst TP=R)
        Module wrapper: redistribute(x, I->R)  # hidden; bwd all-reduce
after:  fc1 = InvariantColumnParallelLinear(sharding: in_src TP=I)
        forward: maybe_gather_tp_input(self, x, src=spmd.I)  # same op, region <fqn>.tp_gather

For the Muse perception norm (out_dst {V, R, R} before, CP via the wrapper plus explicit TP after), spmd_redistribute_per_axis used to run CP then TP in forward, so backward ran TP then CP. The new code runs in the same order, so CP>1 together with TP>1 should also stay bitwise identical.

Should consider

  • torchtitan/config/transform/quantization.py:43 -- NVFP4's build only lets ColumnParallelLinear/RowParallelLinear keep their own collectives. An NVFP4 InvariantColumnParallelLinear (and, already before this PR, InvariantRowParallelLinear) gets decoder in_src/in_dst layouts plus local_spmd. Fix: add both classes to the isinstance tuple at nvfp4/linear.py:382. Unverified.
  • tests/unit_tests/cpu/models/common/test_linear.py:324 -- the new 2-rank test catches only the "missing src=spmd.I" regression. A ~10-line mock subtest next to test_vision_row_parallel_output_is_always_invariant would catch it without spawning a process group.
Details
  • Callsite audit: every remaining vision_colwise_sharding_config() caller with the default input_tp=I is now an InvariantColumnParallelLinear (qwen3_5, kimi_k2_7, kimi_k3, muse_spark NaViT, so Glimmer too). Every q/k/v caller passes input_tp=R behind VisionAttention's gather. Every VisionAttention, vision_merger_sharding_config and moonvit_projector_sharding_config user is updated, so no boundary converts twice or not at all.
  • MXFP8/Float8 quantized subclasses override _linear, not forward, so get_quantized_linear(..., InvariantColumnParallelLinear) keeps the explicit conversion.
  • Muse keeps its SP-only bank replication while Qwen3.5/Kimi always replicate. That matches main and is not introduced here.

Not verified: NVFP4 behavior on vision projections, and multimodal training with real images under TP+CP.

Linear,
ColumnParallelLinear,
RowParallelLinear,
InvariantColumnParallelLinear,

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.

Unverified, needs Blackwell. This now lists InvariantColumnParallelLinear as quantizable, but NVFP4Linear.Config.build (torchtitan/quantization/nvfp4/linear.py:380-382) only lets (ColumnParallelLinear, RowParallelLinear) keep their own collectives. InvariantColumnParallelLinear and InvariantRowParallelLinear subclass Linear, so an NVFP4 vision projection goes down the "plain NVFP4Linear" path instead. That path overwrites in_src/in_dst with the decoder layout (tp=R, cp=S(0)) and sets local_spmd=True.

The vision stream is TP: I, CP: I, and forward now runs I -> R inside that local region, so the declared input type no longer matches the real one. InvariantRowParallelLinear already had this problem before this PR; the PR adds a second class that hits it.

Smallest fix: add both invariant classes to that isinstance tuple. They own their TP collective in forward, same as the generic TP classes. Alternatively, reject vision linears in the NVFP4 converter.

assert redistribute.call_args.kwargs["dst"] == spmd.I


class TestInvariantColumnParallelLinearDistributed(DTensorTestBase):

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.

This 66-line, 2-rank test exists to catch one regression: the layer losing src=spmd.I, i.e. treating the vision input as S(0) under SP. The backward all-reduce it checks numerically is just spmd.redistribute(I -> R), which spmd_types already covers.

The mock-based test_vision_row_parallel_output_is_always_invariant just above catches the same regression for less: patch spmd_dense_sp_enabled to True and assert redistribute.call_args.kwargs["src"] == spmd.I for InvariantColumnParallelLinear, in about 10 lines and with no process-group spawn. Consider folding it in there (e.g. as test_vision_projections_are_always_invariant) and dropping this class.

@anijain2305
anijain2305 force-pushed the explicit-vision-tp-collectives branch from 617ffcc to 6f90957 Compare November 7, 2026 00:05
@anijain2305
anijain2305 marked this pull request as ready for review November 7, 2026 00:10
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 7, 2026
@github-actions
github-actions Bot requested review from andrewor14 and vkuzo November 7, 2026 00:10
@anijain2305 anijain2305 changed the title [spmd] Make vision encoder TP collectives explicit [spmd] Make vision encoder TP and CP collectives explicit Nov 12, 2026
@anijain2305

Copy link
Copy Markdown
Contributor Author

@claude review this PR

@claude

claude Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @anijain2305's task in 4m 33s —— View job


Approve -- please address the items before merging -- see the review (a maintainer still needs to review; @tianyu-l's change request is still open).

@claude claude Bot 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.

Verdict: Approve -- please address the items below before merging. The rewrite keeps every multimodal I -> R conversion in the same forward/backward order and handles all of @tianyu-l's design comments. What's left is a stale description, a redundant test, and one stray line. This touches models/common and distributed/, so a maintainer still needs to review, and @tianyu-l's change request is still open.

What this PR does. It removes the remaining multimodal ShardingConfig src -> dst pairs that converted Invariant -> Replicate, and does those conversions in forward instead:

  • Inside encoders: vision fc1, the Qwen3.5 merger fc1 and the Kimi projector linear_1 become plain ColumnParallelLinear. They are correct because the encoders already run under disable_dense_sp. VisionAttention gathers x once.
  • At the consumer: the encoder now returns TP/CP-I, and the code that merges vision into the text stream converts it with the new maybe_invariant_to_replicate.

Example. Kimi K2.5 at TP2 + CP2:

before: projector out_dst TP I->R          (hidden, inside encoder)
        encoder   out_dst CP I->R          (hidden, encoder boundary)
after:  vision_embeds = self.vision_encoder(...)                 # TP=I, CP=I
        vision_embeds = maybe_invariant_to_replicate(vision_embeds, TP)
        vision_embeds = maybe_invariant_to_replicate(vision_embeds, CP)
        # same order: forward TP then CP, so backward reduces CP then TP

Must fix

  1. The PR description describes the previous design. It lists InvariantColumnParallelLinear, maybe_replicate_invariant, a src= argument on maybe_gather_tp_input, merger/projector-side conversion, a rope-cache conversion, a quantization.py change and TestInvariantColumnParallelLinearDistributed. None of these exist at HEAD. Its numerics table also reports runs of that design, while the commit message says TP2+CP2 and the Qwen3.5 / Kimi K3 / Muse model-level checks were not re-run. The title says "vision", but the audio encoder is also changed. Please replace the body with the commit message's content, and state plainly which checks ran on this version. Also fix the commit message's claim that "no core model issues a collective through ShardingConfig src -> dst redistribution": qwen3_5/sharding.py:52-53 (after_vision_scatter, R -> S(0) under SP) still does.
  2. tests/unit_tests/cpu/models/common/test_linear.py:344 -- the 2-rank test duplicates existing coverage and does not catch the vision-specific regression (inline).

Should consider

  • torchtitan/models/muse_spark/vision_encoder.py:32 -- unrelated blank line (inline).
  • torchtitan/distributed/spmd_types.py:416 -- @tianyu-l asked "why maybe?". The name now matches upstream spmd.invariant_to_replicate, but the prefix is still there. Please answer on that thread. It is a no-op when the axis is absent or has size 1, the same as maybe_gather_tp_input.
Details
  • Maintainer comments at HEAD. The src= override is gone; the encoder uses disable_dense_sp, as suggested. The rope-cache conversion is removed; the config still declares it TP-R. Conversion now happens at the consumer for Qwen3.5 (image and video), Kimi K2.5 and Kimi K3. For Muse, the model-level adapter is the consumer. The maybe_ prefix is still there (see above).
  • Remat. activation_remat.apply hooks only layers.* blocks, and VisionBlock.forward re-enters disable_dense_sp, so block replay keeps src=I. The merger and projector are not replayed as modules, and the region-level tp_gather replay reuses its forward-time arguments.
  • Async TP / quantization. Vision fc1 is now an exact ColumnParallelLinear, so async TP converts it. AsyncColumnParallelLinear.forward falls back when spmd_dense_sp_enabled() is False, so the vision path does a plain I -> R with no fused all-gather. NVFP4 now keeps the module's own collective for vision fc1 (nvfp4/linear.py:382), which resolves the issue the earlier automated review raised.
  • Callsite audit. Every vision_colwise_sharding_config() caller with the default input_tp=I is now a ColumnParallelLinear: qwen3_5, kimi_k2_7, kimi_k3, and the Muse Spark NaViT (which Glimmer reuses). All q/k/v callers pass R behind VisionAttention's gather. No multimodal encoder output config keeps an out_dst, so no boundary converts twice.
  • Muse banks. Under SP, the TP conversion still runs after perception_emb_norm and before * multiplier. That matches the removed perception_*_norm_sharding_config out_dst.
  • RL. Qwen35Model.get_vision_embeds now returns TP-I rather than R to the vLLM wrapper. Forward values are identical, and the masked_scatter_ runs outside activate_spmd().

Not verified: TP2+CP2 numerics and model-level Qwen3.5 / Kimi K3 / Muse numerics for this version (the commit message says these were not re-run).

assert self._row_reduction_dst(linear.build()) == spmd.I


class TestColumnParallelLinearWithDenseSPDisabled(DTensorTestBase):

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.

This 71-line, 2-rank test checks two things that existing tests in this file already cover:

  • test_collective_types_follow_dense_sp_state (line 239): ColumnParallelLinear redistributes with src=spmd.I when spmd_dense_sp_enabled() is False.
  • test_disable_dense_sp_restores_the_registered_setting (line 319): disable_dense_sp() makes spmd_dense_sp_enabled() False even when SP is registered.

What remains is the numerics of spmd.redistribute(I -> R), and that belongs to spmd_types, not this layer. The test also enters disable_dense_sp() itself, so it would not catch the regression that matters for this PR: a vision encoder (or a remat replay of one of its blocks) running without the context manager. Please delete the class along with the set_spmd_meshes import it adds. If you want a guard for the vision path, a mock subtest that runs ColumnParallelLinear through _row_reduction_dst's setup (SP registered, disable_dense_sp() entered) and asserts src == spmd.I is about 10 lines and doesn't spawn a process group.

Comment on lines 31 to +32
from torchtitan.distributed.spmd_types import disable_dense_sp

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.

This file's only change is a blank line between two imports, which is unrelated to the PR. Please drop it.

Suggested change
from torchtitan.distributed.spmd_types import disable_dense_sp
from torchtitan.distributed.spmd_types import disable_dense_sp

@anijain2305
anijain2305 marked this pull request as ready for review November 12, 2026 01:56
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 12, 2026
@github-actions
github-actions Bot requested a review from pianpwk November 12, 2026 01:56
@anijain2305
anijain2305 force-pushed the explicit-vision-tp-collectives branch from 11c9f41 to 9899961 Compare November 12, 2026 02:37
Comment thread torchtitan/models/kimi_k2_7/model.py Outdated
# The encoder output is TP- and CP-invariant; the decoder consumes it in
# TP-sharded computation on CP-sharded tokens, so its gradient is summed
# across both. Converting TP first reduces CP first in backward.
vision_embeds = maybe_invariant_to_replicate(vision_embeds, MeshAxisName.TP)

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.

didn't check details -- do we not need to condition on spmd_dense_sp_enabled this time?

Comment thread torchtitan/distributed/spmd_types.py Outdated
_validate_redistribute_spmd_pair(out_src, out_dst, name="output")


def maybe_invariant_to_replicate(x: torch.Tensor, axis: MeshAxisName) -> torch.Tensor:

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 wouldn't be against

Suggested change
def maybe_invariant_to_replicate(x: torch.Tensor, axis: MeshAxisName) -> torch.Tensor:
def invariant_to_replicate(x: torch.Tensor, axis: MeshAxisName) -> torch.Tensor:

because of the required axis -- to me, if the parallel axis doesn't exist, then off course it'd be no-op. But this is minor and up to you.

group = spmd_mesh_group(axis)
if group is None:
return x
return spmd.invariant_to_replicate(x, group, backward_options={"op_dtype": x.dtype})

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.

would it fail if the group is None? If it's no-op, then we don't need to introduce this wrapper function

anijain2305 added a commit that referenced this pull request Nov 12, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

Introduce a `disable_dense_sp` context manager to explicitly turn off SP
in encoder region. This flag is used by TP-related collectives, and
earlier for encoder we had to use special classes like
InvariantRowParallelLinear to work around this issue. Now, this flag
helps clean up this, and also makes it easy to add explicit collectives
later part of the stack.

## Why
Vision encoders are never sequence-parallel: every TP rank runs the
whole
encoder on the full patch sequence, so their activations stay
TP-Invariant
even when the decoder uses SP. The TP building blocks follow the
decoder's SP
setting (`spmd_dense_sp_enabled()`), so today each encoder-side
difference is
spelled out separately:

- `InvariantRowParallelLinear` is a copy of `RowParallelLinear` whose
only
  change is reducing `P -> I` instead of `P -> S(0) if SP else I`.
- The vision rope cache is declared TP-Invariant, then converted to
Replicate
  at the attention boundary, unlike the decoder's RoPE cache, which is
  Replicate from the start.

Stating "the encoder is a non-SP region" once removes these special
cases.
It also lets the explicit encoder collectives later in this stack
(#5803) use
the standard `ColumnParallelLinear` / `maybe_gather_tp_input` instead of
adding more `Invariant*` variants or a `src=` override.

**Example (TP=2, decoder SP on).**
```
decoder block:   RowParallelLinear    P -> S(0)   (reduce-scatter)
vision encoder:  before: InvariantRowParallelLinear  P -> I   (separate class)
                 after:  RowParallelLinear under disable_dense_sp()  P -> I
```

## What changed
**Non-SP regions**
- New `disable_dense_sp()` context manager
(`torchtitan/distributed/spmd_types.py`):
`spmd_dense_sp_enabled()` is False inside it, and the registered setting
is
  restored on exit.
- The vision encoders' `forward` run under it: `Qwen35VisionEncoder`,
`MoonViTEncoder` (Kimi K2.5 and K3) and `NaViTEncoder` (Muse Spark and
Muse
  Glimmer). Their mergers and projectors run inside the same `forward`.

**Fewer special classes**
- `InvariantRowParallelLinear` is removed. The encoders' attention
`proj`, MLP
`fc2` and merger/projector output use `RowParallelLinear`, which reduces
  `P -> I` there. Same forward, bias handling and remat regions
(`<fqn>.linear`, `<fqn>.tp_reduce`). The quantization converter and
tests
  are updated.
- The vision rope cache (`inv_freq` and the rotary output) is declared
  TP-Replicate at its source, like the decoder's RoPE cache. It has no
gradient, so this only changes its type: the attention boundary no
longer
  converts it, and its `in_dst` entry is gone.

**Async TP**
- `AsyncTensorParallelTransform` converts every `RowParallelLinear` /
  `ColumnParallelLinear` config, which now includes the encoders' row
projections. The async variants always fused a sequence collective. They
now
fall back to the synchronous path when dense SP is disabled, since there
is
nothing to overlap. Without this, async TP would reduce-scatter inside
the
  vision encoder.

**Mechanical, skimmable:** the `InvariantRowParallelLinear` ->
`RowParallelLinear` rename in the Qwen3.5, Kimi K2.5/K3 and Muse Spark
flavors and in the tests.

## Alternatives considered
- **Keep encoder-specific variants (`Invariant*`):** every TP block an
encoder
uses needs a copy, and every transform that matches on class (async TP,
  quantization, LoRA) has to know about each copy.
- **Pass `src=spmd.I` to `maybe_gather_tp_input` at encoder call
sites:** the
  layout is a property of the region, not of each call.
- **Skip encoder linears in `AsyncTensorParallelTransform` by FQN:** the
runtime fallback keys off the same SP state the module already uses, and
  also covers any other non-SP region.

## User-facing changes
| Before | After |
| --- | --- |
| `InvariantRowParallelLinear.Config(...)` |
`RowParallelLinear.Config(...)`, inside a module whose forward runs
under `disable_dense_sp()` |
| Custom vision encoders inherit the decoder's SP setting | Wrap the
encoder forward in `@disable_dense_sp()` if its activations are not
sequence-sharded |

## Numerics
No collective changes: the encoder runs the same ops in the same order.
- `RowParallelLinear` under `disable_dense_sp` takes the same path as
the old
`InvariantRowParallelLinear` (the forwards differ only in the reduction
  target, now `I` in both).
- The rope cache conversion was a type change on a tensor with no
gradient.

End-to-end loss comparison: TODO.

## Testing
- `test_row_parallel_output_is_invariant_with_dense_sp_disabled`: with
decoder
  SP registered, `RowParallelLinear` inside `disable_dense_sp` reduces
  `P -> I`. It catches an encoder row projection that reduce-scatters.
- `test_async_row_parallel_falls_back_with_dense_sp_disabled`: the same
for
`AsyncRowParallelLinear`. It catches async TP fusing a reduce-scatter
inside
  the encoder.
- `TestColumnParallelLinearWithDenseSPDisabled` (2 ranks, strict
typecheck):
`ColumnParallelLinear` on a TP-Invariant input under `disable_dense_sp`,
with decoder SP on and off, matches the unsharded output and gradients.
It
  fails with an `SpmdTypeError` if the context manager is removed.
  `disable_dense_sp` restores the registered setting, also when the body
  raises.
- Existing LoRA (vision adapters under typecheck), NaViT encoder
typecheck,
quantization and transform tests: 157 pass. `test_lora_model_builds` and
`test_nvfp4_hf_export_strips_buffers` fail the same way on main in the
dev
  environment.

## Known issues / follow-ups
- Bottom of the explicit-collectives stack. Next: #6035 (text-only RL
flavors), #5802 (decoder embedding / final norm), #5803 (vision encoder
TP
  collectives, which uses `ColumnParallelLinear` inside these non-SP
  regions).
@anijain2305
anijain2305 force-pushed the explicit-vision-tp-collectives branch from 9899961 to 9d6c41d Compare November 12, 2026 18:28
@anijain2305
anijain2305 force-pushed the explicit-vision-tp-collectives branch from 9d6c41d to 58a19c3 Compare November 12, 2026 18:34
@anijain2305
anijain2305 force-pushed the explicit-vision-tp-collectives branch from 58a19c3 to 5dcf833 Compare November 12, 2026 19:10
@anijain2305
anijain2305 force-pushed the explicit-vision-tp-collectives branch from 5dcf833 to f3b2356 Compare November 12, 2026 23:25
@anijain2305
anijain2305 force-pushed the explicit-vision-tp-collectives branch from f3b2356 to 8010e02 Compare November 13, 2026 00:13
@anijain2305
anijain2305 force-pushed the explicit-vision-tp-collectives branch from 8010e02 to 23663d2 Compare November 13, 2026 03:03
The vision encoders, their outputs and the multimodal perception banks still
relied on ShardingConfig src -> dst redistribution for their TP and CP
boundaries. All of them are Invariant -> Replicate conversions: forward
no-ops whose backward all-reduces the gradient. This moves them into model
code.

Inside the encoders (TP):
- 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.

Encoder outputs (TP and CP): the encoder returns TP- and CP-Invariant output,
and the consumer converts it, since only the consumer knows it needs
Replicate.
- 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.
- Qwen3.5, Kimi K2.5 and Kimi K3 convert with maybe_invariant_to_replicate(TP)
  then (CP) where they merge vision into the text stream
  (_prepare_multimodal_embeds), not in the encoder: the Qwen3.5 merger and
  the Kimi projectors no longer convert, and Qwen3.5's get_vision_embeds
  (also used by the RL vLLM wrapper) returns the encoder output unchanged.
  Converting TP first reduces CP first in backward, the order before this
  stack.
- Muse Spark (vision and audio) and Muse Glimmer (vision) convert CP right
  after calling the encoder, before the adapter / perception norm, where the
  encoder boundary used to convert; they convert the perception banks across
  TP 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.

Sharding configs: vision_colwise_sharding_config,
vision_attention_sharding_config, vision_merger_sharding_config,
moonvit_projector_sharding_config, vision_encoder_sharding_config,
moonvit_encoder_sharding_config, navit_encoder_sharding_config and
audio_encoder_sharding_config only declare boundary layouts 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.

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: earlier versions of these changes were checked bitwise vs. their
parent: the encoder TP collectives at TP2+SP (Qwen3.5, Kimi K2.5, Kimi K3
vision encoder fwd + bwd, output and every parameter gradient on both ranks;
Muse Spark's NaViT within its nondeterministic grid_sample noise, 5e-7), and
the encoder CP outputs at TP2+CP2 (Qwen3.5, Kimi K2.5, Kimi K3 vision
encoders and the Muse Spark audio encoder). The consumer-side version: Kimi
K2.5 full model fwd + bwd at TP2+EP2, SP on and off, is bitwise identical
(output and all 147 gradients, 75 in the vision encoder) to those versions,
and the forward/backward op order matches them for every model. Not re-run:
TP2+CP2 (no CP support in the dev-machine harness) and Qwen3.5 / Kimi K3 /
Muse at the model level (kernels missing on the dev machine).
@anijain2305
anijain2305 force-pushed the explicit-vision-tp-collectives branch from 23663d2 to b862056 Compare November 13, 2026 06:56
@anijain2305
anijain2305 merged commit 79434b4 into main Nov 13, 2026
anijain2305 added a commit that referenced this pull request Nov 13, 2026
…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.
anijain2305 added a commit that referenced this pull request Nov 13, 2026
## 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`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl 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.

2 participants