Repository navigation
Make core MoE collectives explicit - #4878
Conversation
[ghstack-poisoned]
For review, refer to the MoE sharding diagram: https://github.com/pytorch/torchtitan/blob/main/assets/images/moe_sharding.png Goals of this PR: - Make all core MoE collectives explicit. The common MoE sharding config no longer relies on automatic src -> dst redistribution. - Place collectives in the appropriate rematerialization regions so saving a region saves both its compute and communication. Main changes Shared experts: - Add SharedExpertRowParallelLinear. With sequence parallelism, it explicitly reduce-scatters its Partial output to Shard(0). Without sequence parallelism, it keeps the output Partial so the routed and shared branches can be added before one final all-reduce, as shown in the diagram above. - Use this class for shared-expert w2. The existing w2 remat region therefore covers both the projection and its reduce-scatter. - Remove the shared-expert src -> dst output redistribution. - Preserve quantization and LoRA replacement support, and prevent async TP from replacing this specialized linear. MoE TP/EP transitions: - Explicitly shard the routed branch across TP when entering EP. Without SP, x uses Invariant -> Shard(0); with SP, x is already sharded. The replicated padding mask is explicitly sharded alongside the routed tokens. - Without SP, explicitly zero-fill the routed Shard(0) output into a Partial tensor, add it to the shared-expert Partial output, and perform one final Partial -> Invariant all-reduce. - With SP, keep both branch outputs Shard(0); the shared-expert w2 owns its Partial -> Shard(0) reduce-scatter, so no final MoE reduction is needed. - Remove the remaining automatic router, routed-expert, MoE input/output, and padding-mask redistributions. Rematerialization: - Add first-class w13 and w2 regions around the routed grouped linears. - Put the final TP all-reduce in its own tp_output_reduction region because it occurs after routed/shared branch combination. - Document the regions that should be saved together to avoid replaying expensive MoE compute and communication. ghstack-source-id: 503aba6 Pull-Request: #4878
For review, see the MoE sharding diagram: https://github.com/pytorch/torchtitan/blob/main/assets/images/moe_sharding.png Goals: - Make all core MoE collectives explicit; remove automatic src -> dst redistribution. - Place collectives in the appropriate remat regions. Main changes: - Add SharedExpertRowParallelLinear for shared-expert w2. It explicitly reduce-scatters to Shard(0) with SP, or keeps Partial without SP so the shared and routed outputs can be combined before one all-reduce. The existing w2 region now covers both compute and communication. - Explicitly handle the TP -> EP input transition for routed activations and padding masks. - Explicitly convert the routed output from Shard(0) -> Partial and perform the final Partial -> Invariant all-reduce when SP is disabled. - Remove the remaining src -> dst MoE sharding boundaries and add regions for routed w13, routed w2, and the final TP reduction. ghstack-source-id: 503aba6 Pull-Request: #4878
For review, see the MoE sharding diagram: https://github.com/pytorch/torchtitan/blob/main/assets/images/moe_sharding.png Goals: - Make all core MoE collectives explicit; remove automatic src -> dst redistribution. - Place collectives in the appropriate remat regions. Main changes: - Add SharedExpertRowParallelLinear for shared-expert w2. It explicitly reduce-scatters to Shard(0) with SP, or keeps Partial without SP so the shared and routed outputs can be combined before one all-reduce. The existing w2 region now covers both compute and communication. - Explicitly handle the TP -> EP input transition for routed activations and padding masks. - Explicitly convert the routed output from Shard(0) -> Partial and perform the final Partial -> Invariant all-reduce when SP is disabled. - Remove the remaining src -> dst MoE sharding boundaries and add regions for routed w13 and w2. - Keep the final all-reduce in a standalone remat region because routed combine and branch addition prevent colocating it with either w2 computation. ghstack-source-id: 70fca70 Pull-Request: #4878
[ghstack-poisoned]
For review, see the MoE sharding diagram: https://github.com/pytorch/torchtitan/blob/main/assets/images/moe_sharding.png Goals: - Make all core MoE collectives explicit; remove automatic src -> dst redistribution. - Place collectives in the appropriate remat regions. Main changes: - Add SharedExpertRowParallelLinear for shared-expert w2. It explicitly reduce-scatters to Shard(0) with SP, or keeps Partial without SP so the shared and routed outputs can be combined before one all-reduce. The existing w2 region now covers both compute and communication. - Explicitly handle the TP -> EP input transition for routed activations and padding masks. - Explicitly convert the routed output from Shard(0) -> Partial and perform the final Partial -> Invariant all-reduce when SP is disabled. - Remove the remaining src -> dst MoE sharding boundaries and add regions for routed w13 and w2. - Keep the final all-reduce in a standalone remat region because routed combine and branch addition prevent colocating it with either w2 computation. ghstack-source-id: fde2fd0 Pull-Request: #4878
| ( | ||
| routed_x_TD, | ||
| routed_padding_mask_T, | ||
| ) = self._shard_routed_branch_inputs_across_tp(x_TD, padding_mask_T) |
There was a problem hiding this comment.
Personally I feel the code is more readable if we put the if conditions (TP degree > 1? SP enabled?) here. Main reason is that the function name is suggesting we definitely will shard things, which is not true. Alternative is to introduce _maybe_xxx as prefix, but I feel the if-else is not too bad if inlined here.
Similar for the S->P conversion and all-reduce.
There was a problem hiding this comment.
I like the _maybe_xxx idea.
Inlining would duplicate code across the models. Also the conditions differ: with SP x is already sharded, but the replicated padding mask still needs R->S(0)
| return super().forward(input) | ||
|
|
||
|
|
||
| class SharedExpertRowParallelLinear(Linear): |
There was a problem hiding this comment.
Compared with introducing another Linear subclass, I wonder if we could just
- put if-else to module construction in model_registry
- condition on if SP is on / off -- if on, use Col / Row linear; if off, use Linear.
This way transforms like async TP would apply out-of-box.
What do you think?
There was a problem hiding this comment.
I thought about that earlier but decided to go for code reading simplicity.
Asking codex, I got to know that SP is not available during model_registry, so this might not be easily doable.
On the review comment: conceptually, RowParallelLinear with SP and Linear without SP would work. However, model_registry does not know the runtime SP setting. SP becomes available in
update_from_config, after transforms such as async TP have already run. Therefore this would not make async TP work automatically without restructuring transform ordering or
threading parallelism into model construction.
There was a problem hiding this comment.
SP is not available during
model_registry
We can easily add it to -- a single SP boolean is consumed by both model_registry and ParallelismConfig.
- I think this is fine because TP is already native to model code.
- I believe this class doesn't work with async TP? https://github.com/pytorch/torchtitan/blob/main/torchtitan/config/transform/async_tensor_parallel.py#L61 The async TP transform seems having another issue that every col/row subclass will be converted to async_col / async_row, losing its original class behavior (today we won't hit). Given this caveat, I would recommend we don't proliferate this Linear subclass.
For review, see the MoE sharding diagram: https://github.com/pytorch/torchtitan/blob/main/assets/images/moe_sharding.png Goals: - Make all core MoE collectives explicit; remove automatic src -> dst redistribution. - Place collectives in the appropriate remat regions. Main changes: - Add SharedExpertRowParallelLinear for shared-expert w2. It explicitly reduce-scatters to Shard(0) with SP, or keeps Partial without SP so the shared and routed outputs can be combined before one all-reduce. The existing w2 region now covers both compute and communication. - Explicitly handle the TP -> EP input transition for routed activations, padding masks, and DeepSeek V4 hash-router token IDs. - Explicitly convert the routed output from Shard(0) -> Partial and perform the final Partial -> Invariant all-reduce when SP is disabled. - Remove the remaining src -> dst MoE sharding boundaries and add regions for routed w13 and w2. - Keep the final all-reduce in a standalone remat region because routed combine and branch addition prevent colocating it with either w2 computation. ghstack-source-id: 1815be4 Pull-Request: #4878
| recompute=self.remat_should_recompute("w13"), | ||
| )(routed_input_RD.bfloat16(), offsets_E) | ||
| gate_RF, up_RF = gate_up_R2F.unbind(dim=-2) | ||
| remat.recompute_needs_tensor(gate_RF, up_RF) |
There was a problem hiding this comment.
What's the reason to tag the unbinded two tensors, not the gate_up_R2F? The code gate_RF, up_RF = gate_up_R2F.unbind(dim=-2) will be recomputed anyway if RegionalAC is on?
There was a problem hiding this comment.
This is wrong. Thanks for catching. It should be recompute_needs_tensor(gate_up_R2F)
ANd yes, the unbind op will be always recomputed.
| either case and is explicitly sharded here to follow the routed tokens. | ||
| """ | ||
| if spmd_sparse_mesh() is None: | ||
| return x_TD, padding_mask_T |
There was a problem hiding this comment.
do you think we could / should assert TP is None on dense mesh?
There was a problem hiding this comment.
We should .. EP >= TP. So yes, we should.
| if padding_mask_T is not None: | ||
| padding_mask_T = spmd.redistribute( | ||
| padding_mask_T, | ||
| tp_group, | ||
| src=spmd.R, | ||
| dst=spmd.S(0), | ||
| backward_options={"op_dtype": padding_mask_T.dtype}, | ||
| ) |
There was a problem hiding this comment.
indentation?
| if padding_mask_T is not None: | |
| padding_mask_T = spmd.redistribute( | |
| padding_mask_T, | |
| tp_group, | |
| src=spmd.R, | |
| dst=spmd.S(0), | |
| backward_options={"op_dtype": padding_mask_T.dtype}, | |
| ) | |
| if padding_mask_T is not None: | |
| padding_mask_T = spmd.redistribute( | |
| padding_mask_T, | |
| tp_group, | |
| src=spmd.R, | |
| dst=spmd.S(0), | |
| backward_options={"op_dtype": padding_mask_T.dtype}, | |
| ) |
There was a problem hiding this comment.
The padding mask is replicated even when SP has already sharded x_TD.
| local_mtp_input_valid_mask_T = self._maybe_shard_mtp_valid_mask_across_tp( | ||
| mtp_input_valid_mask | ||
| ) | ||
| prev_embed = prev_embed * local_mtp_input_valid_mask_T.unsqueeze(-1).to( |
There was a problem hiding this comment.
the code looks a bit puzzling
- is the change because you move module boundary redistribute to model code?
- it only shards valid mask but not prev_embedding and then do bitwise multiplication? maybe the previous code is already having such behaviors..
There was a problem hiding this comment.
- yes, we are removing all src->dst for MoEs, even for models
- the padding mask is replicate even if SP is enabled, thats why we have to specifically redistribute it.
| return super().forward(input) | ||
|
|
||
|
|
||
| class SharedExpertRowParallelLinear(Linear): |
There was a problem hiding this comment.
SP is not available during
model_registry
We can easily add it to -- a single SP boolean is consumed by both model_registry and ParallelismConfig.
- I think this is fine because TP is already native to model code.
- I believe this class doesn't work with async TP? https://github.com/pytorch/torchtitan/blob/main/torchtitan/config/transform/async_tensor_parallel.py#L61 The async TP transform seems having another issue that every col/row subclass will be converted to async_col / async_row, losing its original class behavior (today we won't hit). Given this caveat, I would recommend we don't proliferate this Linear subclass.
[ghstack-poisoned]
|
Warning: Unknown label
Please add the new label to .github/pytorch-probot.yml |
For review, see the MoE sharding diagram: https://github.com/pytorch/torchtitan/blob/main/assets/images/moe_sharding.png Goals: - Make all core MoE collectives explicit; remove automatic src -> dst redistribution. - Place collectives in the appropriate remat regions. Main changes: - Add SharedExpertRowParallelLinear for shared-expert w2. It explicitly reduce-scatters to Shard(0) with SP, or keeps Partial without SP so the shared and routed outputs can be combined before one all-reduce. The existing w2 region now covers both compute and communication. - Explicitly handle the TP -> EP input transition for routed activations, padding masks, and DeepSeek V4 hash-router token IDs. - Explicitly convert the routed output from Shard(0) -> Partial and perform the final Partial -> Invariant all-reduce when SP is disabled. - Remove the remaining src -> dst MoE sharding boundaries and add regions for routed w13 and w2. - Keep the final all-reduce in a standalone remat region because routed combine and branch addition prevent colocating it with either w2 computation. ghstack-source-id: 31a5472 Pull-Request: pytorch/torchtitan#4878
…anges Summary: Recent TorchTitan syncs changed several APIs that `experiments/fb/flex_shard` depends on, so `flex_shard_tests` now fails at import time (`unittest` `loadTestsFromName` ImportError). This diff moves the fb FlexShard code to the new APIs, fixes the EP>1 DistMuon break from #4419, and ports the Qwen3 recipe. - pytorch/torchtitan#4904 (optimizer config refactor): `build_dist_muon(...)` is replaced by the `DistMuon(...)` class, which takes the same arguments. `comm_free_adapter.build_local_dist_muon` now constructs `DistMuon` directly. - pytorch/torchtitan#4660 (`components.optimizer` -> `components.optim`, `Trainer.Config.optim`): - Imports now come from `torchtitan.components.optim`. - DSV3 Muon configs set `config.optim.optimizer`. - `FlexShardDistMuonOptimizers` accepts the new `enable_cuda_graph` kwarg. It raises if the flag is set, the same way upstream `OptimizersContainer` rejects optimizers that can't be captured. - `_log_optimizer` now takes a pattern string. - pytorch/torchtitan#4617: `ParallelismConfig` now lives in `torchtitan.config.parallelism`. - pytorch/torchtitan#4905: - `ParallelDims` is now `ParallelismContext`, and the `parallel_dims=` kwarg is now `parallelism_context=`. - `get_spmd_context(...)` is replaced by `parallelism_context.activate_spmd()`. - The `efsdp` mesh axis is now `edp_shard`. This also covers the `partition_rank_axis_name` passed to the DistMuon bucket planner. - Tests build the context with `ParallelismContext.from_config(config, DistributedTopology(world_size=...))`. - pytorch/torchtitan#4840: `BlockShard(block_size=R)` is now `BlockShard(block_sizes=(R,))`. - pytorch/torchtitan#4878: the DSV3 `model_registry` now requires `enable_sp`. The FlexShard wrapper passes `enable_sp=False`. FlexShard rejects TP, and `False` keeps the shared-expert `w2` as a plain `Linear`, as it was before #4878. - pytorch/torchtitan#4419 (EP without DTensor): `Module._parallelize` now leaves EP-sharded routed experts as plain local `nn.Parameter` shards. It records their layouts in each module's `_sharding_config` instead of returning DTensors. With EP>1, DistMuon failed with "Partitioned block parameters must be DTensors", and `dtensor_to_global_layout` no longer found anything to declare. - flex_shard `dist_muon/placement.py` and `storage_layout.py` now read the FlexShard `GlobalLayout` contract (`get_global_layout`) instead of DTensor placements. `get_dim0_block_partitions` no longer takes `partition_axis_name`. - The new `experiments/fb/flex_shard/spmd_layouts.py` `declare_spmd_global_layouts(model, mesh)` collects `_sharding_config.state_shardings` and declares them through `spmd_types_to_global_layout`. The DSV3 recipes and tests call it where they used to call `dtensor_to_global_layout`. - EP>1 configs now need `training.disable_cuda_graphs`: upstream config validation rejects CUDA graphs with the all-to-all token dispatcher. `flex_shard_deepseek_v3_debug_muon` sets EP=2 after construction, so it skipped that check and would fail when launched from the CLI. It now disables CUDA graphs, as upstream EP configs do. - Qwen3 recipe port. It was broken before these syncs, by `protocols.model_spec`, `FusedQKVLinear`, `components.metrics`, `tools.logging`, `default_adamw` and `set_spmd_backend`. - It follows the DSV3 pattern: `FlexShardQwen3Model(Qwen3Model)` with `Config.muon_pattern`, and `parallelize()` runs `parallelize_qwen3_muon` under `activate_spmd()`. - Configs are rebuilt on the current `Trainer.Config` fields with the same hyperparameters. - Q/K/V BlockShard plans use the fused `QKVLinear.wqkv`: one `head_dim`-row matrix per Q/K/V head. - `parallelize_qwen3_muon` uses `dp_shard`, always calls `_parallelize` (as DSV3 does), and declares the EP layouts. - DSV3 `test_debug_muon_train_step` now disables autograd multithreading, as upstream `init_distributed` does. The SPMD mesh is thread-local, and FSDPTest skips `init_distributed`. So selective-AC recompute ran on an autograd device thread with no mesh set, the MoE token dispatch skipped EP there, and backward failed in `torch._grouped_mm` with "matrix batch sizes have to match". The upstream Trainer is not affected: the DSV3 debug model with EP=2 + SAC trains normally. The `comm_free_adapter` change is the same as the one in D122391176, the auto-generated Test Blame fix. This diff also covers the other breakages in fb/flex_shard. The DistMuon tests (DSV3 `test_shard0_owned_mixed` and `test_debug_muon_train_step`, and Qwen3 `test_debug_muon_train_step`) now get past every API break. They still fail on the fused `w13` weights, which the next diff (D122443668) fixes. Reviewed By: weifengpy Differential Revision: D122692766 Pull Request resolved: #50
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: - Add VocabParallelEmbedding(Embedding). The masked vocab-shard lookup runs in an explicit spmd.local_map region that returns TP-Partial; the module then reduces it in the remat region `<fqn>.tp_reduce`: P -> S(0) (reduce-scatter) with SP, P -> I (all-reduce) without. - `replicate_output=True` selects P -> R instead, for multimodal models whose vision scatter needs the full sequence on every TP rank (qwen3_5 family, kimi_k3, and kimi_k2_7 under SP). - The base Embedding keeps returning TP-Partial. The Transformers modeling backend experiment converts nn.Embedding to it in place and still owns its own reduction; it is migrated separately. 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._final_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, multimodal_token_embedding_sharding_config, and pre_lm_head_norm_sharding_config now only declare the boundary layouts (asserted under typechecking) and no longer request a redistribution. BC: custom models that build Embedding.Config with token_embedding_sharding_config must switch to VocabParallelEmbedding.Config, and custom forwards that call the root norm must call _final_norm_and_gather (or add maybe_gather_tp_input) instead. Bug fix (Muse Spark): on main, Muse Spark's token embedding receives no gradient under TP. The implicit boundary redistribution runs with async_op=True (#5398) and returns an AsyncCollectiveTensor; it flows straight into the compiled `muse_spark_rmsnorm` region, and torch.compile returns an output with requires_grad=False, silently cutting the graph. The explicit reduction here is synchronous like RowParallelLinear's, so the embedding trains again. Verified with seed 42: at TP2+EP2 every step-1 parameter gradient is bitwise identical to main except tok_embeddings.embedding.weight (None on main, 0.0590 here; 0.0564 at TP1). The async/compile interaction itself is an upstream issue; this change only stops exercising it at these boundaries. 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). Muse Spark differs only as described above. qwen3_5, kimi_k2_7, kimi_k3, and Muse Glimmer multimodal could not be compared on the test machine (base-tree env/recipe failures or nondeterministic kernels).
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 the new multimodal.residual_to_replicated_layout, 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. 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 (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._final_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 and pre_lm_head_norm_sharding_config now only declare the boundary layouts (asserted under typechecking) and no longer request a redistribution. BC: Embedding is renamed to VocabParallelEmbedding; custom forwards that call the root norm before lm_head must call _final_norm_and_gather (or add maybe_gather_tp_input) instead. Bug fix (Muse Spark): on main, Muse Spark's token embedding receives no gradient under TP. The implicit boundary redistribution runs with async_op=True (#5398) and returns an AsyncCollectiveTensor; it flows straight into the compiled `muse_spark_rmsnorm` region, and torch.compile returns an output with requires_grad=False, silently cutting the graph. The explicit reduction here is synchronous like RowParallelLinear's, so the embedding trains again. Verified with seed 42: at TP2+EP2 every step-1 parameter gradient is bitwise identical to main except tok_embeddings.embedding.weight (None on main, 0.0590 here; 0.0564 at TP1). The async/compile interaction itself is an upstream issue; this change only stops exercising it at these boundaries. 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.
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 the new multimodal.residual_to_replicated_layout, 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. 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 (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 and pre_lm_head_norm_sharding_config now only declare the boundary layouts (asserted under typechecking) and no longer request a redistribution. BC: Embedding is renamed to VocabParallelEmbedding; 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. Bug fix (Muse Spark): on main, Muse Spark's token embedding receives no gradient under TP. The implicit boundary redistribution runs with async_op=True (#5398) and returns an AsyncCollectiveTensor; it flows straight into the compiled `muse_spark_rmsnorm` region, and torch.compile returns an output with requires_grad=False, silently cutting the graph. The explicit reduction here is synchronous like RowParallelLinear's, so the embedding trains again. Verified with seed 42: at TP2+EP2 every step-1 parameter gradient is bitwise identical to main except tok_embeddings.embedding.weight (None on main, 0.0590 here; 0.0564 at TP1). The async/compile interaction itself is an upstream issue; this change only stops exercising it at these boundaries. 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.
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 the new multimodal.residual_to_replicated_layout, 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. 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 (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 and pre_lm_head_norm_sharding_config now only declare the boundary layouts (asserted under typechecking) and no longer request a redistribution. BC: Embedding is renamed to VocabParallelEmbedding; 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. Bug fix (Muse Spark): on main, Muse Spark's token embedding receives no gradient under TP. The implicit boundary redistribution runs with async_op=True (#5398) and returns an AsyncCollectiveTensor; it flows straight into the compiled `muse_spark_rmsnorm` region, and torch.compile returns an output with requires_grad=False, silently cutting the graph. The explicit reduction here is synchronous like RowParallelLinear's, so the embedding trains again. Verified with seed 42: at TP2+EP2 every step-1 parameter gradient is bitwise identical to main except tok_embeddings.embedding.weight (None on main, 0.0590 here; 0.0564 at TP1). The async/compile interaction itself is an upstream issue; this change only stops exercising it at these boundaries. 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.
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. 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, 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.
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 decision comes from the build-time config, like layer 0's input layout, because the RL generator drops vision_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, 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.
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. 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, 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. Text-only RL: the vLLM generator used to build a multimodal flavor and then set vision_encoder = None, so the model no longer matched its config (layer 0 still expected the post-scatter layout). Text RL recipes now use text-only flavors instead (Qwen3.5 debugmodel_text / 9B_text, Kimi K3 debugmodel_text, the multimodal flavor with has_vision_encoder=False), and the generator raises on a config with a vision encoder. Qwen35StateDictAdapter reads the HF prefix (model.language_model.* vs model.*) from the checkpoint index, so a text-only flavor still loads a multimodal Qwen3.5 checkpoint. 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.
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. - 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.
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. - 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.
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. - 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.
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. - 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.
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. - 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.
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. - 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.
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. - 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.
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. - 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.
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.
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.
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.
…5802) Stacked on #6035. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why TP collectives are moving out of `ShardingConfig` src -> dst pairs, where `Module` inserts them implicitly, and into explicit `spmd.redistribute` calls in model code. `RowParallelLinear` / `ColumnParallelLinear` and the MoE (#4878) already work this way. The token embedding's reduction and the gather before `lm_head` are the last decoder collectives still inserted implicitly. Terms: the *residual layout* (`residual_activation_placement`, already on main) is the TP layout of the `(tokens, hidden)` stream between blocks: `S(0)` with sequence parallelism, `I` (Invariant) without. **Example (TP=2, SP on).** ``` tokens -> embedding (vocab-sharded weight, each rank's lookup is TP-Partial) main: config out_src=P, out_dst=S(0) -> Module inserts reduce-scatter now: VocabParallelEmbedding.forward: spmd.redistribute(P -> S(0)) -> [multimodal only] vision scatter needs the full sequence on every rank main: a second embedding config with out_dst=R -> all-reduce instead now: maybe_gather_tp_input(S(0) -> R) right before the scatter -> blocks (residual layout S(0)) -> final norm main: config out_dst=R -> Module inserts all-gather now: Decoder._pre_lm_head_norm_and_gather: maybe_gather_tp_input(S(0) -> R) -> lm_head (vocab-sharded, needs R) ``` ## What changed **Embedding** - `Embedding` is renamed to `VocabParallelEmbedding` (the TODO on main). It is now the only token embedding class, so no embedding can return an unreduced TP partial. - Under TP, the masked vocab-shard lookup runs in a `spmd.local_map` region: TP-replicated token ids in, TP-partial embeddings out. The module then reduces to the residual layout: P -> S(0) (reduce-scatter) with SP, P -> I (all-reduce) without. Without TP it is a plain lookup. - On main the lookup was already a local region: `local_spmd=True` made `Module` wrap the whole forward in `local_map`. The region is explicit now because the reduction runs in `forward`, on typed tensors, outside it. - The embedding always emits the residual layout. Multimodal models gather explicitly before the vision scatter, under the same conditions that used to select a replicated embedding: - Qwen3.5 family and Kimi K3: when they have a vision encoder. - Kimi K2.5: when it has one and SP is on. The condition is just `self.vision_encoder is not None`, which is reliable because #6035 stops the RL generator from deleting the encoder after build. `multimodal_token_embedding_sharding_config` is removed. - The Transformers modeling backend keeps its `(batch, sequence)` layout and its own reduction, through a lookup-only subclass in `module_conversion.py`. **Final norm** - `lm_head` is vocab-sharded, so it needs the full hidden states on every rank. - New `Decoder._pre_lm_head_norm_and_gather`: root norm, then `maybe_gather_tp_input`. With SP that is S(0) -> R (all-gather); without, it is I -> R (forward no-op, backward all-reduce). - It gathers after the norm, so under SP the norm only touches the local sequence shard. - It gathers once, rather than inside `lm_head`, which `ChunkedLossWrapper` calls once per chunk. Moving the gather into `lm_head` (with the chunked loss chunking the local shard) is a follow-up, because it changes the loss summation order. - Called by `Decoder` and every model with its own forward: deepseek_v3 MTP, deepseek_v4, kimi_k2_7, kimi_k3, muse_glimmer, muse_spark, qwen3_5. The MTP block gathers its `mtp_norm` output the same way. **Sharding configs** - `token_embedding_sharding_config` now only declares (and, under typechecking, asserts) boundary layouts. - `pre_lm_head_norm_sharding_config` was identical to `norm_sharding_config` and is removed. **Mechanical, skimmable:** - the `Embedding` -> `VocabParallelEmbedding` rename across flavors; - the one-line `_pre_lm_head_norm_and_gather` call in each model forward. ## Alternatives considered - **Keep a `replicate_output` flag on the embedding:** it restated the layout the flavor already chose through the sharding config, twice per flavor (13 sites). Gathering at the scatter keeps the layout decision next to its only consumer. Under SP it is RS + AG instead of one AR (same bytes, one extra latency, once per step). - **Derive the reduction target from the sharding config:** the config would again choose which collective runs, the pattern this stack removes. - **Keep `local_spmd=True` and drop the explicit `local_map`:** the flag wraps the whole forward, so the reduction would have to be a raw collective with a hand-written backward, or go back to the implicit boundary collective. - **Gather inside `lm_head`:** see Final norm above. Follow-up PR. ## User-facing changes | Before | After | | --- | --- | | `Embedding.Config(...)` | `VocabParallelEmbedding.Config(...)` | | `multimodal_token_embedding_sharding_config()` | `token_embedding_sharding_config(enable_sp=...)`; the model gathers before the vision scatter | | `pre_lm_head_norm_sharding_config(...)` | `norm_sharding_config(...)` | | Custom forward calls `self.norm(h)` before `lm_head` | Call `self._pre_lm_head_norm_and_gather(h)` | ## Numerics Bitwise-identical loss and grad_norm over 10 steps vs. main `9f70e5597` (seed 42, deterministic, `scripts/loss_compare.py --assert-equal`): | Config | Result | | --- | --- | | llama3 TP2+SP / TP2 no SP / TP2+CP2 | identical | | llama3 TP4+SP / TP4 no SP | identical | | qwen3 TP2+SP | identical | | deepseek_v3 MTP TP2+EP2, SP / no SP | identical | | deepseek_v3 MTP TP4, SP / no SP | identical | | gpt_oss TP2+EP2 | identical | | deepseek_v4 FSDP | identical | | Transformers backend dense / MoE, TP2 | identical | | qwen3_5 video TP2+SP | identical | | muse_spark TP2+EP2 | see below | The multimodal models that used the replicated embedding were also checked with a full-model fwd + bwd at TP2 and fixed inputs. Output and every parameter gradient on both ranks were compared against main, which is itself deterministic across two runs: | Model | SP | Result | | --- | --- | --- | | qwen3_5 debugmodel (with vision encoder) | on / off | identical / identical | | kimi_k2_7 debugmodel (with vision encoder), TP2 and TP4 | on / off | identical / identical | Kimi K3 couldn't run on the test machine (KDA kernel library mismatch). It takes the same code path as qwen3_5. **Muse Spark:** on main, `tok_embeddings.embedding.weight.grad` is `None` under TP. With this PR it gets a gradient (0.0590 vs. 0.0564 at TP1), and every other parameter gradient is bitwise identical to main. Why main loses it isn't root caused yet: a minimal async-collective + torch.compile repro doesn't reproduce it. Tracked in #5915. ## Testing - `test_vocab_parallel_embedding_parity` (`test_embedding.py`) builds `VocabParallelEmbedding` end to end under strict typechecking. That also checks the new `local_map` types. It covers SP on and off, and vocab sizes that do and don't divide TP. It catches a wrong reduction (bitwise vs. DTensor's embedding and the unsharded one) and wrong weight gradients. - `test_fsdp_embedding.py` (4 GPUs) uses the real class and `token_embedding_sharding_config`; passes. - CPU unit tests (models, config): same 40 failures and 5 collection errors as the base commit on the dev machine (missing packages), none new. ## Known issues / follow-ups - Gather inside `lm_head` instead of after the final norm (follow-up, needs a loss comparison). - Qwen3.5's forward asserts TP-Replicate embeddings under `debug.spmd_typechecking`, which is wrong for text-only models under TP. This already affects Qwen3.8 on main. - Stack: next is #5803 (vision encoder TP collectives). #5806 restores the residual layout explicitly after the vision scatter. The top PR, #5807, removes `in_dst_shardings` / `out_dst_shardings`, so `ShardingConfig` can no longer insert a collective.
Stack from ghstack (oldest at bottom):
For review, see the MoE sharding diagram:
https://github.com/pytorch/torchtitan/blob/main/assets/images/moe_sharding.png
Goals:
Main changes: