Skip to content

[spmd] Make decoder embedding and final-norm TP collectives explicit - #5802

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

anijain2305 merged 1 commit into
mainfrom
explicit-decoder-tp-collectives

Conversation

@anijain2305

@anijain2305 anijain2305 commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #6035.

Summary (human-written)

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 text only rl flavors #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

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 4, 2026
@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 added this pull request to stack #5808 November 4, 2026 06:59
@anijain2305

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @anijain2305's task in 6m 52s —— View job


Request changes: the PR description is empty, and plain Embedding can now silently return un-reduced embeddings under TP. The full review, with inline comments, is on the PR.

@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: Request changes -- the description is empty, and plain Embedding can now silently return un-reduced embeddings under TP.

What this PR does. It removes the automatic ShardingConfig src -> dst redistributions on the token embedding and the root norm, and runs those collectives explicitly in forward. A new VocabParallelEmbedding subclass reduces its TP-partial lookup itself: reduce-scatter under SP, all-reduce otherwise, and an all-reduce to Replicate when replicate_output is set. A new Decoder._apply_final_norm gathers the norm output to Replicate before lm_head. Every flavor and every Decoder subclass's final-norm call site is updated (I checked all of them, including DSv3 MTP). It continues #4878, alongside #5803 and #5805.

Example (llama3, TP=2 + SP):

main:  tok_embeddings = Embedding + token_embedding_sharding_config
         local_spmd lookup -> P@TP; boundary out_dst reduce-scatters to S(0) (async)
       norm: pre_lm_head_norm_sharding_config out_dst all-gathers S(0) -> R (async)
PR:    tok_embeddings = VocabParallelEmbedding
         local_map lookup -> P; remat.region(spmd.redistribute)(P -> S(0))
       Decoder._apply_final_norm: norm(h) stays S(0) -> maybe_gather_tp_input -> R

It runs the same collectives with the same backward op_dtype, so loss should be bitwise identical. The only difference is that async_op=True is gone, and in both places the consumer uses the result immediately anyway.

Must fix

  1. The PR description is the empty template: no human-written summary, no motivation, no numerics, no testing. Please add the goal (explicit collectives, as in #4878) and a bitwise loss/grad_norm comparison (scripts/loss_compare.py) for TP+SP, TP without SP, one replicate_output flavor (qwen3_5 or kimi_k3 multimodal), and DSv3 with MTP.
  2. torchtitan/models/common/embedding.py:25 -- plain Embedding under TP now returns an un-reduced Partial. Embedding.Config + token_embedding_sharding_config is still type-valid and silently gives wrong embeddings when typechecking is off. Use one class, or raise.
  3. torchtitan/models/common/embedding.py:107 -- the local_map region has no in_types. The old local_spmd boundary declared them.

Should consider

  • torchtitan/models/common/embedding.py:93 -- replicate_output encodes the same layout as the sharding config, with the condition repeated twice at each of 13 call sites. Keep one source of truth.
  • torchtitan/models/common/embedding.py:119 -- the tp_reduce (and norm.tp_gather) remat regions have no effect: only layers.* blocks are checkpointed.
  • tests/unit_tests/cpu/models/common/test_embedding.py:336 -- fold the new test into test_vocab_parallel_embedding_parity (whose comment is now stale), and use set_spmd_meshes instead of patch.object.
Details
  • Call-site audit: every model whose root norm uses pre_lm_head_norm_sharding_config now calls _apply_final_norm: decoder, deepseek_v3 (root and mtp_norm), deepseek_v4, kimi_k2_7, kimi_k3, muse_glimmer, muse_spark, qwen3_5. llama3, qwen3, qwen3_8 and gpt_oss use the base forward. No experiment or recipe uses token_embedding_sharding_config or pre_lm_head_norm_sharding_config. The HF backend has its own sharding (#5805).
  • RL generator: _patch_vllm_all_reduce replaces spmd.redistribute on the module, and VocabParallelEmbedding looks it up at call time. The embedding all-reduce under no-grad therefore still goes through vLLM's custom all-reduce.
  • muse_spark final norm: the gather still runs in final_norm_input_dtype before .to(bfloat16), the same as the old boundary.

Not verified: loss parity on GPU, and the perf effect of dropping async_op=True on the two boundary collectives (expected to be negligible, since the consumer uses the result immediately). A maintainer still needs to review, since this touches models/common.

Comment thread torchtitan/models/common/embedding.py Outdated
Comment on lines +25 to +29
"""Configurable embedding with optional local vocab-parallel execution.

With a TP group, each rank looks up only its vocab shard and returns a
TP-``Partial`` output; the caller owns the reduction.
``VocabParallelEmbedding`` performs it explicitly.

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.

After this PR, plain Embedding under TP returns an un-reduced Partial value, and nothing reduces it. Until now every flavor used Embedding.Config(sharding_config=token_embedding_sharding_config(...)), and Decoder.Config.tok_embeddings is still typed Embedding.Config, so that combination still type-checks. With TP > 1 and spmd typechecking off it silently produces wrong embeddings: each rank keeps only its vocab shard's contribution. On main the same config was correct because the local_spmd boundary did the reduction.

The only remaining TP user of plain Embedding is tests/unit_tests/gpu/distributed/test_fsdp_embedding.py, so the "caller owns the reduction" contract has no production consumer. Smallest fix: use one class. Move the masked lookup and the reduction into a single class (renaming Embedding -> VocabParallelEmbedding, as the removed TODO asked) and update test_fsdp_embedding.py. If you keep both classes, have Embedding.forward raise ValueError when a TP group is active.

Comment thread torchtitan/models/common/embedding.py Outdated
# The masked lookup indexes the vocab shard with bare tensor arithmetic,
# so it runs as a local region whose output is TP-partial.
partial = dense_activation_placement(tp=spmd.P, cp=spmd.S(0))
output = spmd.local_map(out_types=(partial.local_type, partial.partition_spec))(

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 local_map region declares only out_types. .claude/rules/distributed.md requires local_map regions to declare their in_types, and the code this replaces did: local_spmd=True with in_dst_shardings={"input": token_id_placement()}. Without them, typechecking no longer checks that the token ids entering the masked lookup are TP-replicated. Suggested fix:

tokens = token_id_placement()
partial = dense_activation_placement(tp=spmd.P, cp=spmd.S(0))
output = spmd.local_map(
    in_types=((tokens.local_type, tokens.partition_spec),),
    out_types=(partial.local_type, partial.partition_spec),
)(super().forward)(input)

Comment thread torchtitan/models/common/embedding.py Outdated

@dataclass(kw_only=True, slots=True)
class Config(Embedding.Config):
replicate_output: 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.

replicate_output encodes a second time the layout the flavor already chose with the sharding config (multimodal_token_embedding_sharding_config() vs token_embedding_sharding_config()). All 13 call sites repeat the same condition twice (e.g. kimi_k2_7 has multimodal and enable_sp both here and in _token_embedding_sharding). If the two disagree, only spmd typechecking catches it. Under no-SP, R and I have identical forward values but different backward semantics, so with typechecking off the mismatch is silent.

Pick one source of truth. Options: derive dst from the configured output layout; have a single helper build both; or drop the flag, so the embedding always emits the residual layout and the multimodal decoders gather with maybe_gather_tp_input before the vision scatter. The last option means RS + AG instead of one AR: about the same bandwidth, one extra collective latency.

Comment thread torchtitan/models/common/embedding.py Outdated
Comment on lines +119 to +123
return remat.region(
spmd.redistribute,
self.remat_region_name("tp_reduce"),
recompute=self.remat_should_recompute("tp_reduce"),
)(

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 remat region does nothing. Remat only checkpoints and configures layers.* blocks (torchtitan/distributed/activation_remat.py:129-146), so tok_embeddings never runs inside a checkpoint and no save/recompute pattern is ever applied to it. The region and its recompute= flag have no effect, yet the class docstring describes <fqn>.tp_reduce as a remat region, which suggests users can control it through save_regions. Call spmd.redistribute directly and drop the remat wording from the docstring. The same applies to norm.tp_gather from _apply_final_norm; reusing maybe_gather_tp_input there is fine.

Comment on lines +336 to +341
set_current_spmd_mesh(mesh),
patch.object(
embedding_module,
"spmd_dense_sp_enabled",
return_value=enable_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 test mostly duplicates test_vocab_parallel_embedding_parity just above: same 4-rank TP mesh, same vocab sizes, same SP toggle. That test still calls spmd.redistribute by hand, and its comment ("the Module sharding wrapper owns the final P -> S(1)/I redistribution") is now stale. Suggestions:

  1. Fold this into the parity test: build VocabParallelEmbedding there, drop the manual redistribute, and add the replicate_output case and the gradient check. That keeps the DTensor bitwise oracle and the strict typecheck, which this test runs without. With typecheck, the new local_map types also get checked.
  2. Enable SP with set_spmd_meshes(..., dense_sp_enabled=...), as the other TP tests do (e.g. test_tensor_parallel_feed_forward.py), instead of patch.object on the module attribute.

@anijain2305
anijain2305 force-pushed the explicit-decoder-tp-collectives branch 4 times, most recently from f5a19ae to a371b4a Compare November 6, 2026 23:10
@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 5m 26s —— View job


Request changes: the muse_spark gradient fix needs a root cause (the async boundary path it blames is still used elsewhere), the PR needs numerics proof, and two duplicate helpers should go. The full review is on the PR.

@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: Request changes -- the muse_spark gradient fix has no root cause, and the async path it blames still feeds every other module boundary. The PR also needs numerics proof and two duplicates removed.

What this PR does. It renames Embedding to VocabParallelEmbedding and moves the TP reduction of the vocab-sharded lookup from the ShardingConfig boundary into forward: a reduce-scatter under SP, an all-reduce otherwise. The root norm's out_dst all-gather moves into Decoder._pre_lm_head_norm_and_gather, which every Decoder subclass and the DSv3 mtp_norm now call. The multimodal models (qwen3_5, kimi_k3, kimi_k2_7) no longer use a Replicate embedding config. They now gather the embedding output before the vision scatter. The HF backend keeps a subclass whose reduction still happens at the boundary.

Example (qwen3_5 multimodal, TP=4 + SP):

main: lookup -> P; boundary P -> R (all-reduce, async); layer 0 R -> S(0) (slice)
      backward: one all-reduce
PR:   lookup -> P; P -> S(0) (reduce-scatter); S(0) -> R (all-gather); layer 0 R -> S(0)
      backward: all-gather + reduce-scatter

Text-only models run the same collectives as main, but synchronously instead of with async_op=True.

Must fix

  1. PR description. The summary is there now, but there is still no numerics or testing section, and two things need it:
    • The muse_spark fix. "The implicit async collective fed a compiled region that dropped requires_grad" describes a bug in the async boundary path: spmd_redistribute_per_axis(..., async_op=True) at torchtitan/models/base/module.py:619,665, feeding a local_compile region. This PR only takes the embedding off that path. Every other in_dst/out_dst boundary still uses it, including the HF backend embedding (hf_sharding.py:130). Please state the root cause. Then either fix it in the async path, or show that no other boundary feeds a compiled region. If the bug is upstream, add a TODO with an issue link. Also say what would catch it if it came back: the embedding silently got no gradient, and the parity test runs in eager mode.
    • Multimodal + SP comms change. These flavors go from one all-reduce to reduce-scatter + all-gather in both forward and backward, so bitwise parity with main is not guaranteed for TP > 2. Please run scripts/loss_compare.py and report loss and grad_norm for:
      • TP+SP
      • TP without SP
      • a multimodal flavor with SP (qwen3_5 or kimi_k3)
      • DSv3 with MTP
      • muse_spark: show the embedding gradient before and after
  2. torchtitan/models/common/decoder_sharding.py:190 -- pre_lm_head_norm_sharding_config is now identical to norm_sharding_config. Delete it.
  3. torchtitan/models/common/multimodal.py:297 -- residual_to_replicated_layout duplicates maybe_gather_tp_input. Reuse that instead.

Should consider

  • These docstrings still say the embedding is Replicate, or that it is reduced at the module boundary: muse_glimmer/model.py:249-252, kimi_k2_7/sharding.py:13-14,37, kimi_k2_7/flavors.py:153, kimi_k3/sharding.py:123.
  • module_conversion.py:43 -- the experiment calls the private _lookup_vocab_shard from another module.
Details

Status of the earlier review's findings at HEAD:

  • Plain Embedding returning an unreduced Partial: resolved (single class).
  • Missing local_map in_types: resolved.
  • replicate_output duplicating the sharding layout: resolved (dropped).
  • Inert tp_reduce remat region: resolved. norm.tp_gather remains through maybe_gather_tp_input; it is inert but fine.
  • Fold the new test into the parity test and use set_spmd_meshes: resolved.

Layout consistency:

  • kimi_k3 and qwen3_5 gather iff vision_encoder is not None. This matches the layer-0 sharding (multimodal = vision_encoder is not None, after_vision_scatter=has_vision_encoder and layer_id == 0).
  • kimi_k2_7 gathers only with a vision encoder and SP. This matches _first_layer_sharding(multimodal and enable_sp) and keeps main's Invariant embedding under no-SP.
  • Without SP, the gather is I -> R, a forward no-op whose backward all-reduces. That is the same comms as main's P -> R, so these flavors should be bitwise identical without SP.

RL generator: _patch_vllm_all_reduce replaces the spmd.redistribute module attribute, and VocabParallelEmbedding.forward looks it up at call time. The no-grad P -> I embedding reduction therefore still routes to vLLM's custom all-reduce.

Call-site audit: all root-norm call sites (decoder, deepseek_v3 root and mtp_norm, deepseek_v4, kimi_k2_7, kimi_k3, muse_glimmer, muse_spark, qwen3_5) now gather explicitly. No remaining references to Embedding or multimodal_token_embedding_sharding_config in models, experiments, recipes, or tests.

Not verified: loss parity on GPU, and whether any other async boundary in muse_spark (for example the audio encoder boundary at muse_spark/sharding.py:121-133) feeds a compiled region. A maintainer still needs to review, since this touches models/common.

@@ -190,10 +190,9 @@ def norm_sharding_config(*, enable_sp: bool) -> ShardingConfig:
def pre_lm_head_norm_sharding_config(*, enable_sp: bool) -> ShardingConfig:

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.

With out_dst_shardings removed, this function now returns the same config as norm_sharding_config(enable_sp=...) just above: weight placement R if enable_sp else I, and the residual layout in and out. Keeping two names for one config invites them to drift apart. Delete pre_lm_head_norm_sharding_config and use norm_sharding_config at its call sites. The PR already touches most of those flavor files, and the change is mechanical. The "caller gathers before lm_head" note already lives on Decoder._pre_lm_head_norm_and_gather.

Comment thread torchtitan/models/common/multimodal.py Outdated
return inputs_embeds


def residual_to_replicated_layout(x_TD: torch.Tensor) -> 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.

This is maybe_gather_tp_input (torchtitan/models/common/linear/linear.py:267) minus the remat-region wrapper. It does the same TP-group check, the same S(0) if spmd_dense_sp_enabled() else I -> R redistribute, and uses the same op_dtype. This PR already uses maybe_gather_tp_input for the root norm. Call maybe_gather_tp_input(self.tok_embeddings, inputs_embeds) in qwen3_5, kimi_k3 and kimi_k2_7 instead, and delete this helper (about 20 lines). The resulting tok_embeddings.tp_gather region is inert in the same way norm.tp_gather is.

def forward(self, input: torch.Tensor) -> torch.Tensor:
if spmd_mesh_group(MeshAxisName.TP) is None:
return super().forward(input)
return self._lookup_vocab_shard(input)

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.

_lookup_vocab_shard is now a contract between models/common/embedding.py and this experiment, but the leading _ marks it as private to its module (.claude/CLAUDE.md, Naming). Rename it to lookup_vocab_shard; its docstring already describes the TP-partial contract.

Note also that this embedding still reduces through the async out_dst boundary (hf_sharding.py:130). The PR description blames that path for the muse_spark gradient loss (see the review body).

@anijain2305
anijain2305 force-pushed the explicit-decoder-tp-collectives branch from a371b4a to 9ad471b Compare November 6, 2026 23:35
@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 4m 17s —— View job


Request changes: when the RL generator drops the vision encoder, the multimodal embedding gather is skipped, but layer 0 still expects a Replicate input. The full review is on the PR.

@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: Request changes -- the multimodal embedding gather depends on the runtime self.vision_encoder. The RL generator sets it to None, so the embedding output no longer matches the R layout that layer 0 declares. Everything from the previous review is resolved except the pending numerics.

What this PR does. Embedding is renamed to VocabParallelEmbedding, which now reduces its TP-partial lookup in forward (P -> S(0) with SP, P -> I without). The pre-lm_head all-gather moves into Decoder._pre_lm_head_norm_and_gather. Multimodal models now gather the embeddings with maybe_gather_tp_input before the vision scatter, instead of using a Replicate embedding config.

Example (qwen3_5, RL generator, which sets vision_encoder = None after build):

main: embedding P -> R; layer 0 in_src=R -> in_dst residual        consistent
PR:   embedding P -> I (no SP) / S(0) (SP); gather skipped (encoder is None)
      layer 0 still declares in_src=R (has_vision_encoder=True in flavors)
      no SP: typecheck assert fails at the post-embedding tp:R check
      SP:    layer 0 slices the S(0) shard again (R -> S(0)), T/tp^2 tokens per rank

Must fix

  1. torchtitan/models/qwen3_5/model.py:582 -- decide the gather from the config, not from the runtime self.vision_encoder. The same applies to kimi_k3/model.py:360 and kimi_k2_7/model.py:189. Details are in the inline comment. The previous review's layout-consistency note missed this case.

  2. PR description, pending items. These need to be in place before merge:

    • The TP4 multimodal results and the training loss/grad_norm runs (kimi_k2_7, qwen3_5 video at TP4+SP).
    • The muse_spark rerun on 9f70e5597.
    • A link to the issue tracking the missing muse_spark embedding gradient. "A separate issue will track it" has no link yet.

    Not root-causing the muse_spark gradient bug here is acceptable, since #5807 removes the async boundary path. But the issue should exist and be linked, so the bug isn't lost if the stack changes.

Details

Status of the previous review's findings at HEAD:

  • Numerics/testing sections in the description: added (TP4 runs still pending, see must-fix 2).
  • muse_spark root cause: explicitly not claimed; deferred to an issue and to #5805/#5807. The issue link is missing.
  • pre_lm_head_norm_sharding_config: deleted, and all call sites use norm_sharding_config.
  • residual_to_replicated_layout: deleted; uses maybe_gather_tp_input.
  • Stale "Replicate embedding" docstrings: updated.
  • _lookup_vocab_shard: renamed to lookup_vocab_shard.

Gather-condition mismatch:

  • qwen3_5: every flavor passes has_vision_encoder=True (qwen3_5/flavors.py:684 and following), so transformer_block_sharding_config(after_vision_scatter=True) gives layer 0 in_src=R. forward asserts tp: R after _prepare_multimodal_embeds.
  • kimi_k3: multimodal = vision_encoder is not None is decided at config time (kimi_k3/flavors.py:578), and forward asserts tp: R after the embeddings.
  • kimi_k2_7: layer 0 resumes SP iff multimodal and enable_sp, both decided at config time.
  • rl/generator/vllm/model_wrapper.py:499-500 drops the encoder after config.build(), before parallelize. Generator SP is supported: InferenceParallelismConfig.enable_sequence_parallel flows into to_training(), and test_vllm_wrapper.py:127 builds qwen3_5 with TP2+SP.
  • The current qwen3_5 RL recipes run the generator at TP2 without SP and with typechecking off, so RL CI likely still passes. The no-SP case is a latent typecheck failure; the SP case gives wrong shapes.

The rest was checked and has no issue:

  • All root-norm call sites, including DSv3 mtp_norm.
  • Comms for multimodal without SP: P -> I -> R has the same forward and backward comms as main's P -> R.
  • The HF backend _VocabShardEmbedding keeps its boundary reduction, which #5805 covers.
  • vLLM all-reduce routing still sees spmd.redistribute P -> I.

Not verified: GPU numerics, and the generator-SP failure mode, which comes from reading the code and was not run. A maintainer still needs to review, since this touches models/common.

Comment thread torchtitan/models/qwen3_5/model.py Outdated
inputs_embeds = tokens
else:
inputs_embeds = self.tok_embeddings(tokens)
if self.vision_encoder is not None:

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 checks for the gather at runtime with self.vision_encoder, but layer 0's input layout was fixed when the config was built. Every qwen3_5 flavor passes has_vision_encoder=True, so layer 0 always has in_src=R (qwen3_5/sharding.py:48-49). The assert right after the embeddings in forward also requires tp: R.

The RL generator builds the model and then sets self.model.vision_encoder = None (rl/generator/vllm/model_wrapper.py:499-500), so in the generator this gather is skipped:

  • Without SP (the current qwen3_5 RL recipes): the embedding emits I where R is declared. The forward values are the same, but the typecheck assert fails.
  • With generator SP (InferenceParallelismConfig(enable_sequence_parallel=True), a supported config): the embedding reduce-scatters to S(0). Layer 0 then treats that local shard as R and slices it again (R -> S(0)), leaving T/tp^2 tokens per rank.

On main, the embedding was always R, so the bug could not happen. Base the condition on the config instead. For qwen3_5, gather whenever tok_embeddings is present, which matches has_vision_encoder=True and the assert. For kimi_k3 (model.py:360) and kimi_k2_7 (model.py:189), record config.vision_encoder is not None in __init__, the same condition the flavor used to build layer 0.

@anijain2305

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @anijain2305's task in 1m 21s —— View job


Approve: the multimodal embedding gather now follows the build-time config, and the description includes the pending numerics and the #5915 link. The full review is on the PR.

@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 -- the multimodal gather now follows the build-time config, and the description includes the TP4 numerics, the muse_spark rerun, and the #5915 link. A maintainer still needs to review, since this touches models/common.

What changed since the last review. qwen3_5, kimi_k3 and kimi_k2_7 now record config.vision_encoder is not None in __init__ (_built_with_vision_encoder) and gather the embeddings based on that, not on the runtime self.vision_encoder. The RL generator sets vision_encoder = None after build, and the gather still runs, so it matches layer 0's in_src=R and the tp: R assert. New test_vision_scatter_gather_follows_build_config covers the case where the encoder is dropped.

Example (qwen3_5, RL generator, TP2+SP, vision_encoder = None after build):

previous head: embedding P -> S(0); gather skipped; layer 0 treats the S(0) shard as R -> T/tp^2 tokens per rank
this head:     embedding P -> S(0); gather S(0) -> R (built with an encoder); layer 0 R -> S(0)    same as main

Should consider

  • qwen3_5/model.py:561, kimi_k3/model.py:360, kimi_k2_7/model.py:179 -- the three _replicates_embeddings_for_vision copies each check self.tok_embeddings is not None. In qwen3_5 the only caller is already in the tok_embeddings is not None branch. kimi_k3 has just called self.tok_embeddings(tokens). So the check is dead in those two models. You could store the decision once in __init__ (e.g. self._gathers_embeddings_for_vision = config.vision_encoder is not None), adding and spmd_dense_sp_enabled() at the kimi_k2_7 call site, and delete the helper methods. The test would then check the attribute.
Details

Earlier findings, checked at HEAD:

  • The gather condition depended on the runtime vision_encoder (qwen3_5, kimi_k3, kimi_k2_7). Resolved: all three use the build-time flag. kimi_k2_7 still gathers only under SP, which matches _first_layer_sharding(multimodal and enable_sp).
  • Pending items in the description (TP4 multimodal, qwen3_5 training loss, muse_spark rerun on 9f70e5597, an issue link). Resolved. #5915 is open and tracks the muse_spark gradient.
  • Everything from the first two reviews (a single VocabParallelEmbedding class, local_map in_types, no replicate_output, no inert remat region, pre_lm_head_norm_sharding_config deleted, maybe_gather_tp_input reused, lookup_vocab_shard made public, docstrings updated) is still in place.

The Qwen3.8 path (has_vision_encoder=False) gets _built_with_vision_encoder = False, so it never gathers. This matches its layer-0 layout. The tp: R assert in Qwen35Model.forward predates this PR and is unchanged here.

Not verified: GPU numerics (taken from the PR description).

@anijain2305
anijain2305 marked this pull request as ready for review November 7, 2026 00:10
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-decoder-tp-collectives branch from 7ffd0db to 0a451bb Compare November 12, 2026 18:28
@anijain2305
anijain2305 force-pushed the explicit-decoder-tp-collectives branch from 0a451bb to 5e1951d Compare November 12, 2026 18:34
@anijain2305
anijain2305 force-pushed the explicit-decoder-tp-collectives branch from 5e1951d to f1e1e38 Compare November 12, 2026 19:10
@anijain2305
anijain2305 force-pushed the explicit-decoder-tp-collectives branch from f1e1e38 to 668118f Compare November 12, 2026 23:25
@anijain2305
anijain2305 force-pushed the explicit-decoder-tp-collectives branch from 668118f to 85723e2 Compare November 13, 2026 00:12
@anijain2305
anijain2305 force-pushed the explicit-decoder-tp-collectives branch from 85723e2 to c78027c Compare November 13, 2026 03:03
Base automatically changed from text-only-rl-flavors to main November 13, 2026 06:38
anijain2305 added a commit that referenced this pull request Nov 13, 2026
## 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):

```python
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](#5802)).

**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
#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 #5802 (explicit decoder TP collectives), which relies
on this
  to decide the embedding gather from `self.vision_encoder`.
The token embedding output and the final (pre-lm_head) norm output were the
last decoder collectives still inserted implicitly by ShardingConfig
src -> dst redistribution. This moves them into model code, following the
pattern of RowParallelLinear / ColumnParallelLinear and the MoE change (#4878).

Embedding:
- Rename Embedding to VocabParallelEmbedding (the TODO on main) and make it 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), then the
  module reduces to the residual layout: P -> S(0) (reduce-scatter) with SP,
  P -> I (all-reduce) without. Without TP it is a plain lookup.
- The embedding always emits the residual layout. Multimodal models whose
  vision scatter needs the full sequence on every TP rank gather explicitly
  before it with maybe_gather_tp_input, under the same conditions that
  previously selected 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 the runtime vision_encoder, which matches
  the config now that RL builds text-only flavors (previous PR) instead of
  dropping the encoder. multimodal_token_embedding_sharding_config is removed.
- scatter_vision_embeds writes into a copy of the text embeddings. Without SP
  the gather is a no-op I -> R conversion whose output aliases its input, and
  autograd rejects writing into it in place.
- The Transformers modeling backend keeps its (batch, sequence) layout and its
  own reduction through a lookup-only subclass in module_conversion.py, built on
  VocabParallelEmbedding.lookup_vocab_shard.

Final norm:
- lm_head is vocab-sharded (column-parallel), so it needs the full hidden
  states on every TP rank, while the final norm sees them in the residual
  layout. On main, pre_lm_head_norm_sharding_config's out_dst=R hid that
  conversion.
- Add Decoder._pre_lm_head_norm_and_gather: the root norm followed by
  maybe_gather_tp_input, S(0) -> R (all-gather) with SP and I -> R (forward
  no-op, backward all-reduce) without. The gather runs after the norm, so
  under SP the norm only touches the local sequence shard, and it runs
  once, not inside lm_head, which ChunkedLossWrapper calls once per chunk.
- Decoder and every model with its own forward (deepseek_v3 MTP,
  deepseek_v4, kimi_k2_7, kimi_k3, muse_glimmer, muse_spark, qwen3_5) call
  it. The deepseek_v3 MTP block gathers its mtp_norm output the same way.

token_embedding_sharding_config now only declares the boundary layouts
(asserted under typechecking). pre_lm_head_norm_sharding_config became
identical to norm_sharding_config and is removed; the root norms use
norm_sharding_config.

BC: Embedding is renamed to VocabParallelEmbedding;
pre_lm_head_norm_sharding_config is removed (use norm_sharding_config); custom
forwards that call
the root norm before lm_head must call _pre_lm_head_norm_and_gather (or add
maybe_gather_tp_input) instead.

Muse Spark: on main, its token embedding receives no gradient under TP
(tok_embeddings.embedding.weight.grad is None). With this change it does, and
every other parameter gradient is bitwise identical to main. The cause on main
is not root-caused yet (a minimal async-collective + torch.compile repro does
not reproduce it) and is tracked separately.

Numerics: bitwise-identical loss and grad_norm over 10 steps vs. main with
deterministic seed 42 on llama3 (TP2+SP, TP2 no-SP, TP2+CP2), qwen3 (TP2+SP),
deepseek_v3 with MTP (TP2+EP2, SP and no-SP), gpt_oss (TP2+EP2), and
deepseek_v4 (FSDP). Multimodal flavors (Qwen3.5 and Kimi K2.5 debug models,
which build a vision encoder) under TP2 with and without SP: full-model fwd+bwd
output and every parameter gradient bitwise identical to main (main itself
deterministic across two runs). Muse Spark differs only as described above.
@anijain2305
anijain2305 force-pushed the explicit-decoder-tp-collectives branch from c78027c to cf1bab7 Compare November 13, 2026 06:56
@anijain2305
anijain2305 merged commit c783612 into main Nov 13, 2026
anijain2305 added a commit that referenced this pull request Nov 13, 2026
<!--
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.
anijain2305 added a commit that referenced this pull request Nov 13, 2026
…atter (#5806)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

The multimodal model structure is vision encoder -> vision scatter ->
decoder.

The input to the vision scatter is TP-replicated, because the scatter
needs the full sequence on every rank. The decoder, however, expects the
residual layout: S(0) with SP, or I without SP. This PR makes that
conversion explicit.


## Why
Multimodal models gather the token embeddings to TP-`Replicate` before
the
vision scatter (`maybe_gather_tp_input`, #5802), so the scatter can
write any
token position. The decoder layers expect the residual layout, so the
stream
has to go back: `Replicate -> Shard(0)` under sequence parallelism (a
local
slice) and `Replicate -> Invariant` without it (a type change).

Until now a special **layer-0** `ShardingConfig` did that conversion
implicitly, through its `in_src -> in_dst` pair. These were the last
`ShardingConfig` src -> dst conversions in core. #5807 removes implicit
redistribution, so the conversion has to be explicit code. Neither
conversion
communicates, in forward or backward.

**Example (Qwen3.5 with a vision encoder, TP2 + SP).**
```
before: embeddings -> gather S(0)->R -> vision scatter (R)
        -> layer 0 ShardingConfig: in_src=R, in_dst=S(0)   # implicit slice
after:  embeddings -> gather S(0)->R -> vision scatter (R)
        -> replicate_to_residual(x): R->S(0)               # explicit slice
        -> layer 0 (same config as every other layer)
```

## What changed
**Explicit restore** (`common/multimodal.py`)
- New `replicate_to_residual(x_TD)`: `spmd.redistribute` from `R` to
  `S(0)` under dense SP, to `I` otherwise. A no-op without TP.
- Each model calls it right after the scatter, under the same condition
as
  its pre-scatter gather, so the gather and the restore always pair up:
whenever the stage has the token embeddings and a vision encoder
(Qwen3.5,
  and Qwen3.6 / 3.8, which share the model; Kimi K2.5; Kimi K3).
- Kimi K3 restores the stream before deriving the empty block-residual
stack
  from it, so both enter layer 0 in the residual layout, as before.

**Kimi K2.5 gradient fix (predates this stack)**
- Kimi K2.5 used to gather and restore only under SP. Without SP, the
scattered vision rows stayed TP-`Replicate` inside an `Invariant`
stream:
layer 0's input gather all-reduced their gradient, and the encoder
output's
`invariant_to_replicate` all-reduced it again, so vision-encoder
gradients
were scaled by the TP degree. It now gathers and restores whenever it
has a
  vision encoder, like Qwen3.5 and Kimi K3.

**Layer-0 configs removed**
- Qwen3.5: `transformer_block_sharding_config`'s `after_vision_scatter`
argument, and the layer builders' now-unused `has_vision_encoder`
argument
  (the flavor functions keep theirs, for the vision encoder itself).
- Kimi K2.5: `sequence_parallel_first_layer_sharding_config`.
- Kimi K3: `multimodal_first_layer_sharding_config` and its
block-residual
  placement helper.
- DeepSeek-V3: the `first_layer_sharding_config` argument of the shared
layer
  builder, which only Kimi K2.5 used.

After this PR, no core `ShardingConfig` declares a src -> dst pair that
differs on any mesh axis, which is what #5807 relies on.

**Mechanical, skimmable:** the flavor call sites that passed the removed
arguments, and the Qwen3.5 text-flavor test, which no longer compares
layer-0
configs.

## Alternatives considered
- **Keep a layer-0 config and only assert there**: the conversion would
still
  need code somewhere. Doing it in the model's forward, right after the
scatter, keeps it in model code next to the multimodal input
preparation;
  the gather and the restore share their condition by repeating it.
- **Skip the gather and scatter into the sharded stream**: the scatter
writes
arbitrary positions, so each rank would need to know which vision rows
land
  in its sequence shard. That is a larger change, out of scope here.

## User-facing changes
None for users of the built-in models. Out-of-tree flavors that passed
`after_vision_scatter=` or `first_layer_sharding_config=` must drop the
argument and restore the layout in their model's forward.

## Numerics
TP2 on 2 GPUs, fixed seed and inputs, full debug model forward +
backward:
output and every parameter gradient are bitwise identical to main on
both
ranks, for Qwen3.5 and Kimi K2.5 (`kimi_k2_7`; debug models with a
vision encoder), with
and without SP. Kimi K3 could not run on the test machine (KDA kernel
library
version mismatch).

## Testing
- Qwen3.5 CPU tests: with SP on and off, every flavor builds. The
text-only
flavor test is removed: with the layer-0 config gone, it only re-read
the
  config it built.
- Kimi K2.5 / K3: the `tp: R` type assertion after the scatter now runs
under
  the same condition as the restore (it only holds when the gather ran).
- Kimi K3 is covered by CI only.

## Known issues / follow-ups
- Stack: next is #5807, which removes `in_dst_shardings` /
  `out_dst_shardings` from `ShardingConfig`.
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`.
shuhuayu added a commit that referenced this pull request Nov 13, 2026
Main removed implicit ShardingConfig redistribution (#5807) and renamed the
TP token embedding to VocabParallelEmbedding (#5802). Flash-Next now:

- declares input_shardings / output_shardings only;
- restores the residual layout after the vision scatter in forward, as
  Qwen3.5 does, instead of a first-block input conversion;
- gathers the residual stream around PLE in the block, and gathers to
  TP-Replicate after the final mixer for lm_head;
- builds NGramTable directly on nn.Embedding: its forward never used the
  vocab-parallel lookup.

Without TP these calls return their input unchanged.
anshul-si added a commit that referenced this pull request Nov 17, 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. -->

## Why
`Module._spmd_distribute_state` registers a new `nn.Parameter` in every module it distributes. So `_parallelize` unties `tok_embeddings.weight` and `lm_head.weight` in every decoder with `enable_weight_tying=True` (Qwen3 debugmodel/0.6B/1.7B/4B, Llama 3 1B/3B, Qwen3.5 0.8B/2B/4B) before FSDP sees the model. `Decoder.init_states` ties them again, but only after `to_empty()`. FSDP2 therefore gets two parameters for one weight in the group `[tok_embeddings, norm, lm_head]` (three FSDPParams instead of two). Three problems follow:

- **When FSDP pads the tied weight's shard, the embedding trains on a stale copy.** Padding happens when `(vocab / tp) % (dp_shard * cp) != 0`. At lazy init, `FSDPParam.reset_sharded_param` re-reads the module parameters. The embedding's FSDPParam pads a private copy of `lm_head`'s local shard. Then `lm_head`'s FSDPParam pads a second copy and points the parameter at it. The optimizer updates `lm_head`'s copy, but the embedding keeps all-gathering its own, so the embedding rows on every rank with a padded shard never change. This affects:

  | Flavors | Padded at |
  | --- | --- |
  | Qwen3 0.6B/1.7B/4B (vocab 151936) | FSDP degree 6, 12, 24 (any multiple of 3); also TP 8 x FSDP 32 or 64 |
  | Qwen3.5 0.8B/2B/4B (vocab 248320) | FSDP degree 6, 12, 24 (any multiple of 3) |
  | Llama 3 1B/3B (vocab 128256) | TP 8 x FSDP 64, TP 4 x FSDP 128 |

- **Without padding, FSDP2 communicates the tied weight twice.** It all-gathers both copies in every unshard. With `lm_head` in the model forward it also reduce-scatters both. Grouping the three modules was meant to avoid exactly this (see the comment in `apply_fsdp_to_decoder`).
- **Sharders that don't re-read parameters train silently wrong.** A sharder that keeps the parameters it was given at wrap time trains the embedding with a weight the optimizer doesn't hold. FlexShard is one: #5842 rejects tied weights and depends on this fix.

**Example.** Tied Qwen3 debugmodel with vocab 2049, FSDP 2, on GPU. Rank 1 holds 1024 rows, padded to 1025. Per rank, after each optimizer step: does each FSDPParam of the tied group all-gather the live parameter?

```
main     rank 0  VocabParallelEmbedding FSDPParam: yes                 Linear FSDPParam: yes
         rank 1  VocabParallelEmbedding FSDPParam: no, a private copy  Linear FSDPParam: yes
                 (the copy is unchanged after steps 2 and 3: those 1024 embedding rows never train)
this PR  rank 0  VocabParallelEmbedding FSDPParam (shared with lm_head): yes
         rank 1  VocabParallelEmbedding FSDPParam (shared with lm_head): yes
```

Tie state at each lifecycle stage (Qwen3 debugmodel, FSDP 2 or TP 2). Is `tok_embeddings.weight is lm_head.weight` true?

```
          build  _parallelize  fully_shard  to_empty  init_states   tied FSDP group
main      yes    no            no           no        yes           VocabParallelEmbedding.weight, RMSNorm.weight, Linear.weight
this PR   yes    yes           yes          yes       yes           VocabParallelEmbedding.weight (shared with lm_head), RMSNorm.weight
```

## What changed
- New `Decoder._parallelize` (7 lines). It calls `super()._parallelize` and then, if `enable_weight_tying` is set, points `tok_embeddings.weight` at `lm_head.weight` again. Like `__init__`, it then shares the RoPE caches again (`_tie_rope_caches`), for code that runs before `init_states`. On llama3 at `tp=2` (with sequence parallel), `cp=2` and `dp_shard=2`, the caches already stay shared through `_parallelize`, so this changes nothing today.
  - Every in-repo decoder reaches it through `self._parallelize`: `MultimodalModel`, `KimiK3Model`, the GraphTrainer models and the vLLM generator. No decoder overrides `_parallelize`.
- `Decoder.Config.__post_init__` raises `ValueError` if a tied config gives `tok_embeddings` and `lm_head` different weight shardings (`sharding_config.state_shardings["weight"]`).
  - From `_parallelize` on, the embedding uses `lm_head`'s distributed weight, so a mismatch would otherwise be silently wrong.
  - Every in-repo tied flavor declares `dense_param_placement(tp=spmd.S(0))` for both (vocab-sharded on TP, Replicate on DP and CP), so their local shards match under TP.
- `Decoder.init_states` keeps its re-tie (comment-only change).
  - `to_empty()` changes parameters in place and keeps the tie, so FSDP2 no longer needs it.
  - GraphTrainer's SimpleFSDP still does: its `data_parallel` registers new parameters after `_parallelize`, which unties the weights again. Without the re-tie, the embedding would keep the storage that `skip_param_init` never initializes.
  - The `enable_weight_tying` docstring now lists `_parallelize` too.
- Two new tests in `tests/unit_tests/cpu/models/llama3/test_weight_tying.py` (see Testing). The `dataclasses` import moved to the top of that file.

## Alternatives considered
- **Keep parameters shared in `Module._parallelize` / `_spmd_distribute_state`.** The recursion shares no state across modules, so this needs alias bookkeeping at the entry point plus a check that every alias got the same layout: about 20 lines, with one consumer. I built all 59 flavors of the 12 in-repo decoder families on meta. The only shared parameter in any of them is `tok_embeddings.weight` / `lm_head.weight`. The HF-backend experiment unties these before `_parallelize`.
- **Re-tie at the start of `Decoder._apply_fsdp`.** That also runs before `fully_shard` and would work for FSDP2, but only for callers that go through `_apply_fsdp`. Re-tying where `_parallelize` breaks the tie covers every caller, including GraphTrainer and the vLLM generator.
- **Delete the re-tie in `init_states`.** It isn't redundant (SimpleFSDP, above).
- **Re-read parameters in each sharder**, as FSDP2's lazy init does. That patches each sharder separately. In FSDP2 it is exactly what breaks under padding, and FSDP2 would still communicate both copies.

## Numerics
These runs predate the rebase onto `4122eafc0` and were made against main `9f70e5597`. The rebase crosses #5802 (`VocabParallelEmbedding`, the TP gather after the final norm); at `4122eafc0` I reran the new tests, the tied-flavor check and the padded-shard GPU probe (see Testing), not the runs below. GPU runs: seed 42, deterministic, 2x GB200, `scripts/loss_compare.py <main> <this PR> --metrics loss,grad_norm --no-seed-checkpoint`. All use flex attention (FA4 isn't installed locally). CPU runs use gloo, Qwen3 debugmodel and ChunkedLossWrapper, and run 4 steps (adapted from the reviewer's script).

| Config | Loss | Steps | Result |
| --- | --- | --- | --- |
| Llama 3 debugmodel (untied), FSDP 2 | ChunkedLossWrapper | 20 | bitwise equal, `--assert-equal` |
| Qwen3 debugmodel_moe (untied), FSDP 2 | ChunkedLossWrapper | 20 | bitwise equal, `--assert-equal` |
| Qwen3 debugmodel (tied), FSDP 2 | ChunkedLossWrapper (recipe default) | 100 | bitwise equal at every step |
| Llama 3 debugmodel + `enable_weight_tying`, FSDP 2 | ChunkedLossWrapper | 100 | bitwise equal at every step |
| Qwen3 debugmodel (tied), TP 2 | ChunkedLossWrapper | 100 | bitwise equal at every step |
| **Padded:** Qwen3 debugmodel (tied), vocab 2049, FSDP 2 (GPU) | ChunkedLossWrapper | 100 | step 1 equal, differs from step 2; main is wrong (Example) |
| **Padded:** Qwen3 debugmodel (tied), CPU, `dp_shard=3` | ChunkedLossWrapper | 4 | step 0 equal; step 1 7.7073 (main) vs 7.7017 (this PR); main's rank 2 gathers a stale embedding copy |
| Unpadded control: same, CPU, `dp_shard=2` | ChunkedLossWrapper | 4 | bitwise equal |
| The three unpadded tied GPU configs | CrossEntropyLoss (`lm_head` in forward) | 100 | first-step loss equal, then small drift (table below) |

**Padded shards: numerics change because main is wrong.** On main, the embedding's rows on the padded ranks stay at their initial values (Example). This PR trains them. In the GPU vocab-2049 run, the mean absolute loss difference is 6.4e-5, 2.3e-4, 9.5e-4 and 1.0e-3 over steps 1-25, 26-50, 51-75 and 76-100 (max 2.9e-3).

**Unpadded shards with ChunkedLossWrapper (used by every in-repo recipe for a tied flavor): bitwise unchanged.** This holds with the default per-microbatch reduction.
- `lm_head` runs in the loss's own backward passes. `fsdp_partial_backwards` reduce-scatters the tied group after the last of them, before the decoder backward computes the embedding's gradient.
- The decoder backward reduce-scatters the group a second time, and the two results are added in fp32 in the sharded `.grad`.
- This is the same on main, where two FSDPParams point at one sharded parameter, and in this PR, where one FSDPParam is reduced twice. All 66 parameter gradients after the first trainer step are bitwise equal.

**Gradient accumulation with deferred reduction, or HSDP: fp32 rounding-level change.** With gradient accumulation plus `fsdp_defer_gradient_reduction=True`, or with HSDP (whose replica all-reduce `TrainingEngine` defers to the last microbatch), both uses' gradients are summed before a single reduction. The tied gradient then changes at fp32 rounding level. At step 0 on CPU the max difference is 3.4e-8 (FSDP 2, GA 2, deferred) and 3.7e-9 (HSDP 2x2, GA 2). No in-repo tied recipe uses either.

**Unpadded shards with `lm_head` in the forward: the tied gradient changes at bf16 level.**
- Both uses of the weight now run in one backward. FSDP2 delays the unsharded gradient's upcast to `reduce_dtype` (`FSDPParam.defers_grad_upcast`), so autograd adds the embedding's and `lm_head`'s bf16 contributions into one bf16 gradient, which is widened and reduce-scattered once.
- On main, each contribution was widened and reduce-scattered on its own, and the two were added in fp32.
- At step 0 only the tied gradient moves: by at most 4.77e-4 (largest entry 0.187, about half a bf16 unit), in 8.8% of its elements. The first-step loss is bitwise equal.
- Over 100 steps the gap is as large as main's own gap between ChunkedLossWrapper and plain cross entropy, and it doesn't grow. Loss is about 2.75 at step 100.

In the table below, each step-range cell is the mean absolute loss difference over that range. The signed mean is this PR minus main; for the reference row it is CrossEntropyLoss minus ChunkedLossWrapper.

| CrossEntropyLoss run | 1-25 | 26-50 | 51-75 | 76-100 | signed mean, 76-100 | max abs diff |
| --- | --- | --- | --- | --- | --- | --- |
| Qwen3 tied, FSDP 2 | 2.7e-5 | 5.9e-4 | 4.9e-4 | 8.0e-4 | -5.6e-4 | 2.0e-3 |
| Llama 3 tied, FSDP 2 | 5.3e-4 | 4.5e-4 | 2.2e-4 | 2.1e-4 | +1.9e-4 | 2.6e-3 |
| Qwen3 tied, TP 2 | 3.5e-5 | 3.5e-4 | 3.0e-4 | 8.2e-4 | -7.5e-4 | 2.2e-3 |
| Reference: main only, Qwen3 tied FSDP 2, ChunkedLossWrapper vs CrossEntropyLoss | 2.7e-5 | 6.7e-4 | 5.5e-4 | 8.4e-4 | -1.7e-4 | 3.5e-3 |

**Golden losses.** No file in `tests/assets/losses/` trains a tied model except `rl_grpo_cuda.txt`.
- `rl_grpo_cuda.txt` is the RL loss guard: tied Qwen3-0.6B, ChunkedLossWrapper, trainer TP 4, FSDP degree 1, so no padding. It should stay the same, but I couldn't run it (it needs 8 GPUs, vLLM and HF weights).
- The `qwen3` goldens use the untied `debugmodel_moe`. The `llama3` and `sft` goldens use the untied Llama 3 debugmodel.

## Performance
Bytes per rank per step for the tied group: all-gather output and reduce-scatter input. Qwen3 debugmodel (vocab 2048, dim 256), FSDP 2, counted by wrapping FSDP2's collectives inside the trainer.

| Loss | All-gather, main -> this PR | Reduce-scatter, main -> this PR |
| --- | --- | --- |
| ChunkedLossWrapper | 4,195,328 -> 2,098,176 (2 calls) | 4,195,328 -> 4,195,328 (2 calls) |
| CrossEntropyLoss | 2,097,664 -> 1,049,088 (1 call) | 4,195,328 -> 2,098,176 (1 call) |

With ChunkedLossWrapper, reduce-scatter bytes don't change. The group is reduced once after the loss's backward and once after the decoder backward (as the untied `[norm, lm_head]` group is), and the tied weight's gradient is in both reductions either way.

## Testing
- **New tests.** Both fail on main (`4122eafc0`) and pass here.
  - `test_weights_remain_tied_after_parallelize` builds a tied Llama 3 debugmodel on meta, runs `_parallelize` with TP 2 on a fake process group, and asserts `tok_embeddings.weight is lm_head.weight`. It catches any change that unties the weights between `_parallelize` and FSDP.
  - `test_tying_rejects_different_weight_shardings` gives `lm_head` a different weight sharding and expects `ValueError`.
- **All 9 tied flavors** (Llama 3 1B/3B, Qwen3 debugmodel/0.6B/1.7B/4B, Qwen3.5 0.8B/2B/4B), built on meta with a fake process group:
  - With TP 2, each is untied after `_parallelize` on main and tied here (rechecked at `4122eafc0`).
  - At (tp, dp_shard, cp) = (1, 3, 1), (2, 2, 1) and (2, 1, 2), each passes the new layout check and stays tied after `_parallelize`.
- **Padded-shard probes.** These are the GPU run in the Example (rerun at `4122eafc0`, 3 steps: rank 1's embedding FSDPParam is unchanged after steps 2 and 3 on main) and CPU `dp_shard=3`. On main, the padded rank's embedding FSDPParam holds a private, never-updated copy. Here every FSDPParam all-gathers the live parameter.
- **Lifecycle probes** (main vs this PR in one process, FSDP 2 and TP 2): the tie at each stage and the FSDPParam count (Example). GraphTrainer's `apply_simple_fsdp` unties the weights; `init_states` ties them again, and without that re-tie they stay untied.
- **Unit tests** (at `9f70e5597`). `pytest tests/unit_tests/cpu/{models,distributed,config}` plus `tests/unit_tests/cpu/components/test_chunked_loss_fsdp.py`: 850 passed here. On main the first three suites gave 847 passed; the 3 extra here are the two new tests and `test_chunked_loss_fsdp.py`.
  - Both have the same 53 failures and 7 collection errors, all from the local environment: FA4 missing, `transformers` missing, spmd_types 0.2.0 instead of the pinned 0.3.1, and `torch_checkpointing`/`renderers` versions.
- **Lint.** pyrefly 0.45.1 reports the same 12 errors as main. pre-commit passes, except its pyrefly hook, which can't run locally.
- **TP 2 runs** used spmd_types 0.3.1, the pinned version. Main also fails TP 2 locally with 0.2.0.

## Known issues / follow-ups
- **Not run:**
  - TP > 1 together with FSDP > 1 (needs 4+ GPUs; the 8-GPU integration test `qwen3_fsdp+tp+cp_no_sp` trains the tied Qwen3 debugmodel that way).
  - A real-vocabulary padded run, e.g. Qwen3-0.6B at FSDP 6.
  - The RL loss guard.
  - The vLLM generator. It also goes through `parallelize`, and its `_fsdp_load_groups` already maps both tied keys to the shared FSDPParam.
- **Follow-up question:** should SimpleFSDP's `data_parallel` (`torchtitan/experiments/graph_trainer/simple_fsdp.py`) keep shared parameters tied? Then the re-tie in `Decoder.init_states`, and its comment naming an experiment, could go.


ghstack-source-id: 9f70984
Pull-Request: #6144
shuhuayu added a commit that referenced this pull request Nov 17, 2026
Main removed implicit ShardingConfig redistribution (#5807) and renamed the
TP token embedding to VocabParallelEmbedding (#5802). Flash-Next now:

- declares input_shardings / output_shardings only;
- restores the residual layout after the vision scatter in forward, as
  Qwen3.5 does, instead of a first-block input conversion;
- gathers the residual stream around PLE in the block, and gathers to
  TP-Replicate after the final mixer for lm_head;
- builds NGramTable directly on nn.Embedding: its forward never used the
  vocab-parallel lookup.

Without TP these calls return their input unchanged.
anshul-si added a commit that referenced this pull request Nov 18, 2026
…6144)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* __->__ #6144

## 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
`Module._spmd_distribute_state` registers a new `nn.Parameter` in every
module it distributes. So `_parallelize` unties `tok_embeddings.weight`
and `lm_head.weight` in every decoder with `enable_weight_tying=True`
(Qwen3 debugmodel/0.6B/1.7B/4B, Llama 3 1B/3B, Qwen3.5 0.8B/2B/4B)
before FSDP sees the model. `Decoder.init_states` ties them again, but
only after `to_empty()`. FSDP2 therefore gets two parameters for one
weight in the group `[tok_embeddings, norm, lm_head]` (three FSDPParams
instead of two). Three problems follow:

- **When FSDP pads the tied weight's shard, the embedding trains on a
stale copy.** Padding happens when `(vocab / tp) % (dp_shard * cp) !=
0`. At lazy init, `FSDPParam.reset_sharded_param` re-reads the module
parameters. The embedding's FSDPParam pads a private copy of `lm_head`'s
local shard. Then `lm_head`'s FSDPParam pads a second copy and points
the parameter at it. The optimizer updates `lm_head`'s copy, but the
embedding keeps all-gathering its own, so the embedding rows on every
rank with a padded shard never change. This affects:

  | Flavors | Padded at |
  | --- | --- |
| Qwen3 0.6B/1.7B/4B (vocab 151936) | FSDP degree 6, 12, 24 (any
multiple of 3); also TP 8 x FSDP 32 or 64 |
| Qwen3.5 0.8B/2B/4B (vocab 248320) | FSDP degree 6, 12, 24 (any
multiple of 3) |
  | Llama 3 1B/3B (vocab 128256) | TP 8 x FSDP 64, TP 4 x FSDP 128 |

- **Without padding, FSDP2 communicates the tied weight twice.** It
all-gathers both copies in every unshard. With `lm_head` in the model
forward it also reduce-scatters both. Grouping the three modules was
meant to avoid exactly this (see the comment in
`apply_fsdp_to_decoder`).
- **Sharders that don't re-read parameters train silently wrong.** A
sharder that keeps the parameters it was given at wrap time trains the
embedding with a weight the optimizer doesn't hold. FlexShard is one:
#5842 rejects tied weights and depends on this fix.

**Example.** Tied Qwen3 debugmodel with vocab 2049, FSDP 2, on GPU. Rank
1 holds 1024 rows, padded to 1025. Per rank, after each optimizer step:
does each FSDPParam of the tied group all-gather the live parameter?

```
main     rank 0  VocabParallelEmbedding FSDPParam: yes                 Linear FSDPParam: yes
         rank 1  VocabParallelEmbedding FSDPParam: no, a private copy  Linear FSDPParam: yes
                 (the copy is unchanged after steps 2 and 3: those 1024 embedding rows never train)
this PR  rank 0  VocabParallelEmbedding FSDPParam (shared with lm_head): yes
         rank 1  VocabParallelEmbedding FSDPParam (shared with lm_head): yes
```

Tie state at each lifecycle stage (Qwen3 debugmodel, FSDP 2 or TP 2). Is
`tok_embeddings.weight is lm_head.weight` true?

```
          build  _parallelize  fully_shard  to_empty  init_states   tied FSDP group
main      yes    no            no           no        yes           VocabParallelEmbedding.weight, RMSNorm.weight, Linear.weight
this PR   yes    yes           yes          yes       yes           VocabParallelEmbedding.weight (shared with lm_head), RMSNorm.weight
```

## What changed
- New `Decoder._parallelize` (5 lines). It calls `super()._parallelize`
and then, if `enable_weight_tying` is set, points
`tok_embeddings.weight` at `lm_head.weight` again.
- Every in-repo decoder reaches it through `self._parallelize`:
`MultimodalModel`, `KimiK3Model`, the GraphTrainer models and the vLLM
generator. No decoder overrides `_parallelize`.
- `Decoder.Config.__post_init__` raises `ValueError` if a tied config
gives `tok_embeddings` and `lm_head` different weight shardings
(`sharding_config.state_shardings["weight"]`).
- From `_parallelize` on, the embedding uses `lm_head`'s distributed
weight, so a mismatch would otherwise be silently wrong.
- Every in-repo tied flavor declares
`dense_param_placement(tp=spmd.S(0))` for both (vocab-sharded on TP,
Replicate on DP and CP), so their local shards match under TP.
- `Decoder.init_states` keeps its re-tie (comment-only change).
- `to_empty()` changes parameters in place and keeps the tie, so FSDP2
no longer needs it.
- GraphTrainer's SimpleFSDP still does: its `data_parallel` registers
new parameters after `_parallelize`, which unties the weights again.
Without the re-tie, the embedding would keep the storage that
`skip_param_init` never initializes.
  - The `enable_weight_tying` docstring now lists `_parallelize` too.
- Two new tests in
`tests/unit_tests/cpu/models/llama3/test_weight_tying.py` (see Testing).
The `dataclasses` import moved to the top of that file.

## Alternatives considered
- **Keep parameters shared in `Module._parallelize` /
`_spmd_distribute_state`.** The recursion shares no state across
modules, so this needs alias bookkeeping at the entry point plus a check
that every alias got the same layout: about 20 lines, with one consumer.
I built all 59 flavors of the 12 in-repo decoder families on meta. The
only shared parameter in any of them is `tok_embeddings.weight` /
`lm_head.weight`. The HF-backend experiment unties these before
`_parallelize`.
- **Re-tie at the start of `Decoder._apply_fsdp`.** That also runs
before `fully_shard` and would work for FSDP2, but only for callers that
go through `_apply_fsdp`. Re-tying where `_parallelize` breaks the tie
covers every caller, including GraphTrainer and the vLLM generator.
- **Delete the re-tie in `init_states`.** It isn't redundant
(SimpleFSDP, above).
- **Re-read parameters in each sharder**, as FSDP2's lazy init does.
That patches each sharder separately. In FSDP2 it is exactly what breaks
under padding, and FSDP2 would still communicate both copies.

## Numerics
These runs predate the rebase onto `4122eafc0` and were made against
main `9f70e5597`. The rebase crosses #5802 (`VocabParallelEmbedding`,
the TP gather after the final norm); at `4122eafc0` I reran the new
tests, the tied-flavor check and the padded-shard GPU probe (see
Testing), not the runs below. GPU runs: seed 42, deterministic, 2x
GB200, `scripts/loss_compare.py <main> <this PR> --metrics
loss,grad_norm --no-seed-checkpoint`. All use flex attention (FA4 isn't
installed locally). CPU runs use gloo, Qwen3 debugmodel and
ChunkedLossWrapper, and run 4 steps (adapted from the reviewer's
script).

| Config | Loss | Steps | Result |
| --- | --- | --- | --- |
| Llama 3 debugmodel (untied), FSDP 2 | ChunkedLossWrapper | 20 |
bitwise equal, `--assert-equal` |
| Qwen3 debugmodel_moe (untied), FSDP 2 | ChunkedLossWrapper | 20 |
bitwise equal, `--assert-equal` |
| Qwen3 debugmodel (tied), FSDP 2 | ChunkedLossWrapper (recipe default)
| 100 | bitwise equal at every step |
| Llama 3 debugmodel + `enable_weight_tying`, FSDP 2 |
ChunkedLossWrapper | 100 | bitwise equal at every step |
| Qwen3 debugmodel (tied), TP 2 | ChunkedLossWrapper | 100 | bitwise
equal at every step |
| **Padded:** Qwen3 debugmodel (tied), vocab 2049, FSDP 2 (GPU) |
ChunkedLossWrapper | 100 | step 1 equal, differs from step 2; main is
wrong (Example) |
| **Padded:** Qwen3 debugmodel (tied), CPU, `dp_shard=3` |
ChunkedLossWrapper | 4 | step 0 equal; step 1 7.7073 (main) vs 7.7017
(this PR); main's rank 2 gathers a stale embedding copy |
| Unpadded control: same, CPU, `dp_shard=2` | ChunkedLossWrapper | 4 |
bitwise equal |
| The three unpadded tied GPU configs | CrossEntropyLoss (`lm_head` in
forward) | 100 | first-step loss equal, then small drift (table below) |

**Padded shards: numerics change because main is wrong.** On main, the
embedding's rows on the padded ranks stay at their initial values
(Example). This PR trains them. In the GPU vocab-2049 run, the mean
absolute loss difference is 6.4e-5, 2.3e-4, 9.5e-4 and 1.0e-3 over steps
1-25, 26-50, 51-75 and 76-100 (max 2.9e-3).

**Unpadded shards with ChunkedLossWrapper (used by every in-repo recipe
for a tied flavor): bitwise unchanged.** This holds with the default
per-microbatch reduction.
- `lm_head` runs in the loss's own backward passes.
`fsdp_partial_backwards` reduce-scatters the tied group after the last
of them, before the decoder backward computes the embedding's gradient.
- The decoder backward reduce-scatters the group a second time, and the
two results are added in fp32 in the sharded `.grad`.
- This is the same on main, where two FSDPParams point at one sharded
parameter, and in this PR, where one FSDPParam is reduced twice. All 66
parameter gradients after the first trainer step are bitwise equal.

**Gradient accumulation with deferred reduction, or HSDP: fp32
rounding-level change.** With gradient accumulation plus
`fsdp_defer_gradient_reduction=True`, or with HSDP (whose replica
all-reduce `TrainingEngine` defers to the last microbatch), both uses'
gradients are summed before a single reduction. The tied gradient then
changes at fp32 rounding level. At step 0 on CPU the max difference is
3.4e-8 (FSDP 2, GA 2, deferred) and 3.7e-9 (HSDP 2x2, GA 2). No in-repo
tied recipe uses either.

**Unpadded shards with `lm_head` in the forward: the tied gradient
changes at bf16 level.**
- Both uses of the weight now run in one backward. FSDP2 delays the
unsharded gradient's upcast to `reduce_dtype`
(`FSDPParam.defers_grad_upcast`), so autograd adds the embedding's and
`lm_head`'s bf16 contributions into one bf16 gradient, which is widened
and reduce-scattered once.
- On main, each contribution was widened and reduce-scattered on its
own, and the two were added in fp32.
- At step 0 only the tied gradient moves: by at most 4.77e-4 (largest
entry 0.187, about half a bf16 unit), in 8.8% of its elements. The
first-step loss is bitwise equal.
- Over 100 steps the gap is as large as main's own gap between
ChunkedLossWrapper and plain cross entropy, and it doesn't grow. Loss is
about 2.75 at step 100.

In the table below, each step-range cell is the mean absolute loss
difference over that range. The signed mean is this PR minus main; for
the reference row it is CrossEntropyLoss minus ChunkedLossWrapper.

| CrossEntropyLoss run | 1-25 | 26-50 | 51-75 | 76-100 | signed mean,
76-100 | max abs diff |
| --- | --- | --- | --- | --- | --- | --- |
| Qwen3 tied, FSDP 2 | 2.7e-5 | 5.9e-4 | 4.9e-4 | 8.0e-4 | -5.6e-4 |
2.0e-3 |
| Llama 3 tied, FSDP 2 | 5.3e-4 | 4.5e-4 | 2.2e-4 | 2.1e-4 | +1.9e-4 |
2.6e-3 |
| Qwen3 tied, TP 2 | 3.5e-5 | 3.5e-4 | 3.0e-4 | 8.2e-4 | -7.5e-4 |
2.2e-3 |
| Reference: main only, Qwen3 tied FSDP 2, ChunkedLossWrapper vs
CrossEntropyLoss | 2.7e-5 | 6.7e-4 | 5.5e-4 | 8.4e-4 | -1.7e-4 | 3.5e-3
|

**Golden losses.** No file in `tests/assets/losses/` trains a tied model
except `rl_grpo_cuda.txt`.
- `rl_grpo_cuda.txt` is the RL loss guard: tied Qwen3-0.6B,
ChunkedLossWrapper, trainer TP 4, FSDP degree 1, so no padding. It
should stay the same, but I couldn't run it (it needs 8 GPUs, vLLM and
HF weights).
- The `qwen3` goldens use the untied `debugmodel_moe`. The `llama3` and
`sft` goldens use the untied Llama 3 debugmodel.

## Performance
Bytes per rank per step for the tied group: all-gather output and
reduce-scatter input. Qwen3 debugmodel (vocab 2048, dim 256), FSDP 2,
counted by wrapping FSDP2's collectives inside the trainer.

| Loss | All-gather, main -> this PR | Reduce-scatter, main -> this PR |
| --- | --- | --- |
| ChunkedLossWrapper | 4,195,328 -> 2,098,176 (2 calls) | 4,195,328 ->
4,195,328 (2 calls) |
| CrossEntropyLoss | 2,097,664 -> 1,049,088 (1 call) | 4,195,328 ->
2,098,176 (1 call) |

With ChunkedLossWrapper, reduce-scatter bytes don't change. The group is
reduced once after the loss's backward and once after the decoder
backward (as the untied `[norm, lm_head]` group is), and the tied
weight's gradient is in both reductions either way.

## Testing
- **New tests.** Both fail on main (`4122eafc0`) and pass here.
- `test_weights_remain_tied_after_parallelize` builds a tied Llama 3
debugmodel on meta, runs `_parallelize` with TP 2 on a fake process
group, and asserts `tok_embeddings.weight is lm_head.weight`. It catches
any change that unties the weights between `_parallelize` and FSDP.
- `test_tying_rejects_different_weight_shardings` gives `lm_head` a
different weight sharding and expects `ValueError`.
- **All 9 tied flavors** (Llama 3 1B/3B, Qwen3 debugmodel/0.6B/1.7B/4B,
Qwen3.5 0.8B/2B/4B), built on meta with a fake process group:
- With TP 2, each is untied after `_parallelize` on main and tied here
(rechecked at `4122eafc0`).
- At (tp, dp_shard, cp) = (1, 3, 1), (2, 2, 1) and (2, 1, 2), each
passes the new layout check and stays tied after `_parallelize`.
- **Padded-shard probes.** These are the GPU run in the Example (rerun
at `4122eafc0`, 3 steps: rank 1's embedding FSDPParam is unchanged after
steps 2 and 3 on main) and CPU `dp_shard=3`. On main, the padded rank's
embedding FSDPParam holds a private, never-updated copy. Here every
FSDPParam all-gathers the live parameter.
- **Lifecycle probes** (main vs this PR in one process, FSDP 2 and TP
2): the tie at each stage and the FSDPParam count (Example).
GraphTrainer's `apply_simple_fsdp` unties the weights; `init_states`
ties them again, and without that re-tie they stay untied.
- **Unit tests** (at `9f70e5597`). `pytest
tests/unit_tests/cpu/{models,distributed,config}` plus
`tests/unit_tests/cpu/components/test_chunked_loss_fsdp.py`: 850 passed
here. On main the first three suites gave 847 passed; the 3 extra here
are the two new tests and `test_chunked_loss_fsdp.py`.
- Both have the same 53 failures and 7 collection errors, all from the
local environment: FA4 missing, `transformers` missing, spmd_types 0.2.0
instead of the pinned 0.3.1, and `torch_checkpointing`/`renderers`
versions.
- **Lint.** pyrefly 0.45.1 reports the same 12 errors as main.
pre-commit passes, except its pyrefly hook, which can't run locally.
- **TP 2 runs** used spmd_types 0.3.1, the pinned version. Main also
fails TP 2 locally with 0.2.0.

## Known issues / follow-ups
- **Not run:**
- TP > 1 together with FSDP > 1 (needs 4+ GPUs; the 8-GPU integration
test `qwen3_fsdp+tp+cp_no_sp` trains the tied Qwen3 debugmodel that
way).
  - A real-vocabulary padded run, e.g. Qwen3-0.6B at FSDP 6.
  - The RL loss guard.
- The vLLM generator. It also goes through `parallelize`, and its
`_fsdp_load_groups` already maps both tied keys to the shared FSDPParam.
- **Follow-up question:** should SimpleFSDP's `data_parallel`
(`torchtitan/experiments/graph_trainer/simple_fsdp.py`) keep shared
parameters tied? Then the re-tie in `Decoder.init_states`, and its
comment naming an experiment, could go.
tianyu-l added a commit that referenced this pull request Nov 26, 2026
…er override; agent self-review; rl/transport (#6407)

## 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

Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it
approved,
30 then got a formal "request changes" from a maintainer, and about 20
more got
substantive inline asks. In nearly all of them the bot either saw the
problem
and approved anyway, or never asked the questions maintainers ask most
("does
the repo already do this?", "who should own this?"). The opposite
failure, the
bot blocking something a maintainer was fine with, is rare: in the PRs
we
sampled, 2 of its 81 must-fix items were wrong and about a third were
minor
(the empty human-written summary was the biggest source).

**Example** (#6112, controller sizes the rollout worker pool):

```
before: bot approved 10 times; tianyu-l then blocked: "the controller reads
        rollouter.rollouts_per_worker to compute a count it hands back to the
        Rollouter -- violates encapsulation"
after:  same commit, new skill -> Request changes, must-fix #1:
        "controller.py:589 -- wrong owner for the worker count ..."
```

There was also no way for a code owner to overrule the bot except
dismissing
its review in the GitHub UI, and a later `@claude review again` would
block
again.

## What changed

**Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`):
- Verdict rules: Approve only when every remaining item is an edit the
bot
could write itself. Anything the author still owes (a design change, an
unexplained golden change, evidence the PR rests on) is Request changes;
anything only a maintainer can decide is Needs discussion. A hedge like
"a
  maintainer should decide" can't come with Approve.
- Always must-fix: a violated written rule, a silent wrong result, a
second
  definition of an existing concept, a gate finding.
- Design gate: new questions for the existing counterpart, in-repo
ownership,
and the design behind a bug; "ban only what doesn't work on main"; read
the
numbers behind a claim. The overlapping-PR search is mandatory and
reported.
- Re-review covers every commit since the last full review, including
code
taken from the bot's own suggestions. A scoped question gets a
`COMMENT`, not
  a whole-PR verdict.
- The bot fact-checks its own proposed fixes, and cites a source for
claims
  about external tools or marks them unverified (never must-fix).
- An empty "Summary (human-written)" is a one-line "Before merge" note
that
  never affects the verdict.
- Checklist: config ownership direction, general shared wrappers, dead
code the
PR creates, model variants as flavors, a mechanical pass over every new
or
  changed function.

**Code owner override** (`SKILL.md`, `claude-code.yml`,
`CONTRIBUTING.md`): a
code owner comments `@claude override` (optionally `@claude override
2,3:
<reason>`); the bot approves if nothing else is open and doesn't
re-raise the
overridden items. A code owner's GitHub approval or "LGTM" is not an
override,
so a teammate can approve without the bot dropping its findings.
Dismissing the
bot's review still unblocks the PR, but isn't an override: the bot can't
tell
who dismissed it.

**Agent self-review** (`CLAUDE.md`, `pr-description`): an agent
preparing a PR
runs `pr-review` in branch mode first and records unaddressed items in
an
optional "Self-review" section. PRs written without an agent are
unaffected; a
missing section is never a finding.

Where each new rule comes from (maintainer asks the bot missed):

| Change | PRs |
| --- | --- |
| No Approve with open design/evidence items or a "maintainer should
decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 |
| Author waiver can't clear a must-fix | #6201, #6202, #6203 |
| Existing counterpart; one source of truth | #5228, #6169, #5881,
#5823, #5824, #6059, #5812 |
| Responsibility owner; config ownership direction | #6112, #6332,
#5802, #5803, #6325 |
| Fix the design behind the bug; a TODO doesn't justify a workaround |
#5572, #5689, #5657 |
| Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819,
#5543 |
| Re-review covers all new commits; scoped asks don't approve | #5824,
#5842 |
| Mandatory overlap search | #5885, #6248 |
| Ban only what doesn't work on main | #5543 |
| Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868
|

**Rules**: `design.md` gets the one-general-wrapper rule (moved from
`models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the
consumer owning its values; `config.md` gets ownership direction and "a
Config
doesn't read runtime state"; `direction.md` calls all-to-all the MoE
reference
implementation, so a new vendor-specific dispatch path (e.g. #6242)
needs a
reason the existing backends can't serve.

**Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/`
-> d4l3k.

**Mechanical, skim**: `torchtitan/rl/transport/` holds data movement
between RL
actors.
- `rl/model_state_dict_transport.py` ->
`rl/transport/model_state_dict.py`
- `rl/MODEL_STATE_DICT_TRANSPORT.md` ->
`rl/transport/MODEL_STATE_DICT_TRANSPORT.md`
- `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py`
- tests:
`tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py`
->
`tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py`
- imports, READMEs and `scripts/install_rl_env.sh` updated; no code
changes.

## User-facing changes

| Before | After |
| --- | --- |
| Overrule the bot: dismiss its review in the UI, and it blocks again on
the next run | `@claude override [items]: <reason>`; the bot approves
and doesn't re-raise them |
| Empty human-written summary: bot must-fix | One "Before merge" line,
no effect on the verdict |
| `from torchtitan.rl.model_state_dict_transport import ...` | `from
torchtitan.rl.transport.model_state_dict import ...` |
| `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from
torchtitan.rl.transport.rdma_microbatch import ...` |

## Testing

Backtest: the new skill run locally (nothing posted) on each PR at the
commit
and thread state the bot originally saw.

| PR | Bot then | New skill | What the maintainer asked |
| --- | --- | --- | --- |
| #6112 | Approve | Request changes | worker-count ownership (caught) |
| #5837 | Approve | Request changes | apply to `dp_shard` too (caught) |
| #5572 | Approve | Request changes | delete the injection design
(caught) |
| #6201 | Approve after author waived pins | Request changes, waiver
ignored | pins broke GPU tests after merge (caught) |
| #6007 | Approve | Request changes | fold K3.1 into K3 (caught) |
| #5543 | Request changes: "ban it" | Request changes: keep main's path
| don't break gpt-oss + DeepEP (fixed) |
| #6144, #5905 (controls) | Approve | Approve | -- |
| #6137 (control) | Approve | Needs discussion | -- (merge gate on an
upstream API) |

Code owner override, simulated on #6201: override by a code owner lifts
the
named item; `@claude override` from the author changes nothing; a code
owner's
"LGTM" approval followed by "review again" keeps Request changes.

Transport move: 83 RL CPU unit tests pass locally
(`transport/test_model_state_dict.py`, `test_trainer.py`,
`test_engine_loop.py`). `transport/test_rdma_microbatch.py`,
`test_generator.py` and
`test_batcher_actor.py` fail to collect in my env on `origin/main` too
(stale
attention-gym / Monarch), so CI is the check for those.

## Known issues / follow-ups
- Open PRs that edit the moved files rebase cleanly (git follows the
renames),
but new imports of the old module paths will break: #6309 (adds a delta
transport that should live in `rl/transport/`), #6237, #6176, #6177,
#5862,
  and drafts #6127, #6393, #6163, #5764.
- The Actions bot can't read dependency source (e.g. SGLang); follow-up
for the
  workflow.

## Self-review
pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch
mode diffs
against `origin/main` and skips description findings before a
description
exists; the "Config doesn't read runtime state" rule no longer
contradicts
hardware validation; dismissal dropped as an override form (the bot
can't tell
who dismissed); `test_rdma_microbatch.py` added to the transport area.
Not
addressed:
- One concern per PR -- the five changes ship together at the
maintainer's
  request.
- Open PRs touching the moved files -- listed above; the maintainer will
  coordinate.
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