Skip to content

text only rl flavors - #6035

Merged
anijain2305 merged 1 commit into
mainfrom
text-only-rl-flavors
Nov 13, 2026
Merged

anijain2305 merged 1 commit into
mainfrom
text-only-rl-flavors

Conversation

@anijain2305

@anijain2305 anijain2305 commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Add a has_vision_encoder flavor option to build text-only flavors, used by the trainer and the (text-only) generator in RL. Earlier we were deleting the vision_encoder for the generator after the model was built, making the model and config inconsistent.

Why

Text RL recipes build a multimodal Qwen3.5 / Kimi K3 flavor for both the
trainer and the generator. A text-only generator (vLLM without a vision
processor, or SGLang) then deletes the encoder after building the model
(build_inference_model in rl/generator/model.py; originally #4680):

model = model_config.build()
...
if not keep_vision_encoder and getattr(model, "vision_encoder", None) is not None:
    model.vision_encoder = None

After that the generator's model no longer matches its config. Its embedding
and layer 0 are still sharded for a vision scatter that never runs. The trainer
runs the vision encoder on dummy inputs every step, even though RL batches are
text-only. Any code that reads self.vision_encoder to decide a layout sees a
different model in the generator than in the trainer. That is what blocks
#5802, which decides the embedding's TP gather from self.vision_encoder
(review).

Example (alphabet_sort, Qwen3.5-9B, trainer TP2+SP, generator TP2).

before:  trainer   = build("9B")       vision encoder runs on dummy pixels each step
         generator = build("9B"), then vision_encoder = None   (config still multimodal)
after:   trainer   = build("9B")       no vision encoder ("9B_mm" is the multimodal one)
         generator = build("9B")       same model, same config

What changed

Text-only flavors (Muse Spark's naming: plain name = text, _mm = multimodal)

  • Every Qwen3.5 and Kimi K3 flavor name is now text-only: the existing flavor
    function with has_vision_encoder=False. The multimodal version of each is
    <name>_mm (Qwen3.5 debugmodel_mm, debugmodel_moe_mm, 0.8B_mm, 2B_mm,
    4B_mm, 9B_mm, 27B_mm, 35B-A3B_mm, 122B-A10B_mm, 397B-A17B_mm;
    Kimi K3 debugmodel_mm, Kimi-K3_mm). The flavor functions keep
    has_vision_encoder=True as their default, so Qwen3.6, which reuses them,
    is unchanged. No vision encoder,
    and a text decoder layout: the residual-layout token embedding
    (token_embedding_sharding_config) and no post-scatter layer-0 boundary.
    Kimi K3 already chose these from vision_encoder; Qwen3.5 always used the
    multimodal embedding config, so its flavor functions now choose too.
  • Callers that need the vision encoder move to _mm: geometry3k (image
    RL), the Qwen3.5 / Kimi K3 test recipes, the Qwen3.5 vision / M-RoPE /
    vision-bank / adapter tests, the vision FLOPs test, the RL CP-images and
    multimodal-wrapper tests, the DeltaNet GPU tests and the checkpoint-conversion
    scripts. Tests that only exercise the decoder (GDN/KDA, CP, LoRA targets,
    optional imports) keep the plain, now text-only, name.

RL

  • alphabet_sort (9B, 27B), verifiers_terminal_bench (9B, 35B-A3B), the RL
    test recipes (Qwen3.5 / Kimi K3 debug), the generator CUDA-graph test and the
    GDN CUDA-graph test (0.8B) use the text-only flavors.
  • build_inference_model raises a ValueError when a text-only engine
    (keep_vision_encoder=False) gets a config with a vision encoder, instead
    of deleting it. This covers vLLM without a vision processor and SGLang.
  • Image RL (geometry3k, with a vision processor) is unchanged: it keeps the
    multimodal flavor, and the multimodal vLLM wrapper keeps the encoder.

HF checkpoint loading (Qwen35StateDictAdapter)

  • The Qwen3.5 HF checkpoints are multimodal: decoder keys are
    model.language_model.*. The adapter picked that prefix only when the model
    had a vision encoder (otherwise model.*, for text-only checkpoints such as
    Qwen3.8), so the text-only 9B would look for model.layers.* and fail to
    load.
  • It now reads the prefix from model.safetensors.index.json when there is
    one, falling back to the model config without an index. A model without a
    vision encoder still skips the model.visual.* weights. Qwen3.8 checkpoints
    still resolve to model.*.

Alternatives considered

  • Keep the drop and make layout decisions from a build-time flag (what [spmd] Make decoder embedding and final-norm TP collectives explicit #5802
    did first): it hides the mismatch instead of fixing it.
  • Strip vision_encoder from the config in the RL recipe helper: layer 0 and
    the embedding are sharded inside the flavor function, so the config has to
    be built text-only.
  • Add a prefix field to the model config: the prefix describes the checkpoint,
    not the model, and the index already says which layout it is.

User-facing changes

Before After
Qwen3.5 and Kimi K3 flavors include the vision encoder Plain names are text-only; use <name>_mm for the vision encoder
Text-only generator silently drops a vision encoder It raises ValueError: use a text-only flavor, or configure a vision processor

Numerics

Training math is unchanged. On text batches the vision encoder only added
0 * vision_embeds to keep its parameters in the graph. Random-init debug
models can draw different initial weights without the encoder parameters. No
golden loss covers the Qwen3.5 / Kimi K3 RL tests.

Testing

  • New test_qwen35_text_only_flavor_has_no_vision_encoder: the plain flavors
    have no vision encoder and their _mm flavors do, and layer 0 takes the residual layout instead of the
    post-scatter Replicate.
  • New test_text_only_flavor_loads_multimodal_checkpoint: with a multimodal
    index, a text-only flavor maps to model.language_model.* and drops vision
    keys in from_hf. Without an index it maps to model.*.
  • With SP on and off, every Qwen3.5 / Kimi K3 flavor builds, and the
    text-only flavors' embedding output layout equals layer 0's input layout.
  • The affected CPU tests (Qwen3.5, FLOPs, build-config, transformer-block, MoE
    load-balancing, CP validation, TD layout, optional imports, LoRA, CP
    attention) give the same results before and after the rename: 214 passed,
    and the same 25 failures, which come from the dev machine (no FA3).
  • Not run locally (no vllm / torchstore / monarch on the dev machine): the RL
    unit and integration tests. CI covers rl_grpo_qwen3_5_debug_tp2_batch_invariant
    and rl_grpo_kimi_k3_debug_batch_invariant.

Known issues / follow-ups

  • Build text flavors as a Decoder and _mm flavors as a MultimodalModel,
    then decide the generator's vision encoder from the model type instead of
    keep_vision_encoder (review). Needs splitting Qwen35Model and
    KimiK3Model, which also carry text-only behavior.
  • Stack: next is [spmd] Make decoder embedding and final-norm TP collectives explicit #5802 (explicit decoder TP collectives), which relies on this
    to decide the embedding gather from self.vision_encoder.

@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Nov 11, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 11, 2026
@anijain2305
anijain2305 added this pull request to stack #6036 November 11, 2026 20:40
@anijain2305
anijain2305 force-pushed the text-only-rl-flavors branch 2 times, most recently from 2eb1fbf to 2594172 Compare November 12, 2026 00:55
@anijain2305
anijain2305 removed this pull request from stack #6036 November 12, 2026 00:55
@anijain2305
anijain2305 changed the base branch from main to vision-encoders-non-sp November 12, 2026 00:55
@anijain2305
anijain2305 added this pull request to stack #6044 November 12, 2026 00:55
parallelism: InferenceParallelismConfig,
precision: PrecisionConfig,
device: torch.device,
keep_vision_encoder: bool = False,

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.

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.

@anijain2305
I'll submit a PR and rebase onto this one.

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.

Comment thread torchtitan/models/qwen3_5/flavors.py Outdated

MODEL_FLAVORS = {
"debugmodel": (_debugmodel, 4096),
"debugmodel_text": (partial(_debugmodel, has_vision_encoder=False), 4096),

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.

the naming convention has been the other way https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/muse_spark/flavors.py#L1096

but overall if we are not doing it, we should

  • build a Decoder for decoder
  • build a MultimodalModel for _mm variants

@anijain2305
anijain2305 removed this pull request from stack #6044 November 12, 2026 01:40
@anijain2305
anijain2305 added this pull request to stack #6045 November 12, 2026 01:40
Base automatically changed from vision-encoders-non-sp to main November 12, 2026 18:28
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 text-only-rl-flavors branch 2 times, most recently from 307fbf9 to aa1cee9 Compare November 12, 2026 18:34
@anijain2305
anijain2305 requested a review from tianyu-l November 12, 2026 18:36
…on_encoder

The text RL recipes build multimodal Qwen3.5 / Kimi K3 flavors, and a
text-only generator (vLLM without a vision processor, or SGLang) then sets
model.vision_encoder = None after build (build_inference_model). The generator's
model no longer matches its config (layer 0 and the embedding are still
sharded for the vision scatter), and the trainer runs the vision encoder on
dummy inputs every step even though RL batches are text-only.

Instead, build a text-only model for both roles, the same way muse_spark has
debugmodel / debugmodel_mm:
- Add Qwen3.5 debugmodel_text, debugmodel_moe_text, 9B_text and 27B_text, and
  Kimi K3 debugmodel_text: the
  multimodal flavor with has_vision_encoder=False, so no vision encoder and a
  text decoder layout (the residual-layout token embedding, and no
  post-scatter layer-0 boundary).
- Point the text RL recipes (alphabet_sort 9B and 27B,
  verifiers_terminal_bench, the RL test recipes and the generator CUDA-graph
  test) at them. Image RL (geometry3k) keeps the multimodal flavor and a
  vision processor, so its generator keeps the encoder as before.
- build_inference_model raises on a model config with a vision encoder when
  the engine is text-only (keep_vision_encoder=False), instead of dropping
  the encoder.
- Qwen35StateDictAdapter picked the HF decoder prefix from the model config
  (model.language_model.* with a vision encoder, model.* without). The
  Qwen3.5 HF checkpoints are multimodal, so a text-only flavor would look for
  model.layers.* and fail to load them. It now reads the prefix from the
  checkpoint index when there is one, and still skips the vision weights for
  a model without a vision encoder. Text-only checkpoints (Qwen3.8) still
  resolve to model.*.
@anijain2305
anijain2305 merged commit e8d94c2 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