Skip to content

[NOT READY FOR REVIEW][Module][MoE] Config-based MoE sharding (qwen3, llama4, gpt_oss, deepseek_v3) - #3160

Closed
fegin wants to merge 21 commits into
gh/fegin/118/basefrom
gh/fegin/118/head
Closed

fegin wants to merge 21 commits into
gh/fegin/118/basefrom
gh/fegin/118/head

Conversation

@fegin

@fegin fegin commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Replace the imperative apply_moe_ep_tp with declarative ShardingConfig on
MoE submodules, mirroring the dense config-based sharding established by
PR1-PR3. Each model's update_from_config now populates sharding plans
on the MoE wrapper, router gate, shared experts, and routed experts;
model.parallelize(parallel_dims) walks the tree and applies them.

Verified bit-identical loss/grad_norm to legacy at step 500 under EP=2
(--debug.seed=42 --debug.deterministic, 4xH100):

  • qwen3: loss 2.02413, grad_norm 0.4862
  • llama4: loss 1.80384, grad_norm 0.1891
  • deepseek_v3: loss 2.02331, grad_norm 0.2702
  • gpt_oss: loss 1.90064, grad_norm 0.2658

Add local_input_grad_placements and local_output_grad_placements
to ShardingConfig, mirroring ColwiseParallelWithGradPlacement (local_input_grad_placements=...) and NoParallel (local_output_grad_placements=...). Plumbed through Module._needed_axes,
_shard_inputs (passes grad_placements to DTensor.from_local),
and _shard_outputs (calls to_local(grad_placements=...) after the
output redistribute, switching the wrapper's effective return type to
local tensor when set).

These fields express what the imperative NoParallel /
ColwiseParallelWithGradPlacement did for the legacy MoE plan; without
them, removing the per-linear annotations would silently over-count
gradients (Partial treated as Replicate downstream).

  • expert_param_placement_sparse(etp_placement) -- {EP: Shard(0), ETP: ...} plus the canonical FSDP storage axes for routed experts
    under EP.
  • expert_param_placement_dense(tp_placement) -- {TP: ...} for
    the EP=1+TP>1 fallback (today's TensorParallel).
  • set_moe_sharding_config(moe_cfg, *, tp_enabled, ep_enabled, etp_enabled, enable_sp, expert_param_layout) -- top-level helper
    that fills sharding configs on the MoE wrapper, router gate, shared
    experts (when present), and routed experts. Branches dense vs sparse
    family for the experts based on ep_enabled.

The wrapper's ShardingConfig combines in_src_shardings /
in_dst_shardings / out_dst_shardings (input AG, output RS) with
LocalMapConfig (dense<->local at the boundary). out_placements
on the LocalMap is Partial -- the body produces a per-rank Partial
sum, and out_dst_shardings reduces Partial -> sp_layout once at the
boundary, mirroring the legacy PrepareModuleInputOutput collective
pattern.

  • AllToAllTokenDispatcher and DeepEPTokenDispatcher now expose
    _wire_meshes(*, ep_mesh, tp_mesh) for the owning Module to install
    meshes at parallelize time.
  • sp_size / sp_rank are read-only @property reads off
    self.tp_mesh (preserving SymInt under CooR precompile).
  • GroupedExperts.parallelize (and GptOssGroupedExperts.parallelize)
    override Module.parallelize to call _wire_meshes after the
    base distribute_tensor pass. Replaces the legacy sideways assignment
    from apply_moe_ep_tp / ExpertParallel._partition_fn.

The manual x.to_local(grad_placements=(Partial(),)) block in
MoE.forward is gone -- the wrapper's LocalMapConfig owns the
boundary. Body operates on plain tensors throughout; child wrappers
(router, experts, shared_experts) re-wrap their inputs via their own
sharding_configs as needed.

  • qwen3 / llama4 / deepseek_v3: share GroupedExperts (w1/w2/w3);
    pass {"w1": Shard(1), "w2": Shard(2), "w3": Shard(1)} as the
    expert_param_layout.
  • gpt_oss: GptOssGroupedExperts has fused mlp1/mlp2 weights+biases;
    pass {"mlp1_weight": Shard(1), "mlp1_bias": Shard(1), "mlp2_weight": Shard(2), "mlp2_bias": Replicate()}. Also fixes
    GptOssMoE.__init__ to forward sharding_config (and
    param_init) when rebuilding GptOssGroupedExperts.Config --
    without this, the rebuild silently dropped the sharding plan and
    torch._grouped_mm failed deep in the kernel.
  • model.parallelize(parallel_dims) is now invoked under
    tp_enabled or ep_enabled (was TP-only). Module.parallelize
    filters disabled axes per-Module so dense Modules no-op cleanly when
    TP=1.
  • apply_moe_ep_tp definition retained in llama4/parallelize.py
    for qwen3_vl (which is not migrated in this PR, deferred). Updated to
    call _wire_meshes instead of writing the now read-only
    sp_size / sp_rank properties. The gpt_oss copy of
    apply_moe_ep_tp and the gpt_oss/expert_parallel.py file are
    deleted -- no remaining callers.

graph_trainer/qwen3 and graph_trainer/deepseek_v3 migrated alongside
their core counterparts (their MoE wiring inherits the core model's
sharding helper via GraphTrainerQwen3Model(Qwen3Model) /
GraphTrainerDeepSeekV3Model(DeepSeekV3Model)).

tests/unit_tests/test_module.py: replaced obsolete
test_unions_across_all_fields (was failing pre-existing on PR6 under
the family-purity contract) with two new tests aligned to the post-PR6
_needed_axes semantics. 30/30 module tests pass.

[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Apr 29, 2026
@fegin fegin changed the title [Module][MoE] Config-based MoE sharding (qwen3, llama4, gpt_oss, deepseek_v3) [NOT READY FOR REVIEW][Module][MoE] Config-based MoE sharding (qwen3, llama4, gpt_oss, deepseek_v3) Apr 29, 2026
fegin added 6 commits April 29, 2026 17:51
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Comment thread tests/unit_tests/test_module.py Resolved
Comment thread torchtitan/models/llama4/parallelize.py Resolved
Comment thread torchtitan/models/llama4/parallelize.py Resolved
Comment thread torchtitan/models/qwen3/parallelize.py Resolved
Comment thread torchtitan/models/qwen3/sharding.py Resolved
fegin added 14 commits May 1, 2026 11:35
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@fegin fegin closed this May 18, 2026
acisseJZhong added a commit that referenced this pull request May 20, 2026
… experts (#3386)

**Copying major part from @fegin's PR
#3160

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

<img width="463" height="665" alt="image"
src="https://github.com/user-attachments/assets/39a2e880-62da-4e20-ab7c-0f36fd0bccc5"
/>


https://excalidraw.com/#json=2abKr0m2s26fc6lyoF9Qq,MqMzUIoXWYJIfckHNOB7Sw

## Summary

Refactor MoE parallelization to establish clean DTensor boundaries:
- **Router**: gate weights Replicate, input all-gathered to Replicate
(via `NoParallel`), compute on DTensor, output converted to local via
`to_local(grad_placements=Partial)`
- **Shared experts**: weights TP-sharded (via
`ColwiseParallel`/`RowwiseParallel`), input all-gathered to Replicate
inside `ColwiseParallel`, compute on DTensor, output local via
`to_local` (Partial placement, `use_local_output=True`)
- **Routed experts**: input converted to local via `to_local` at
`GroupedExperts` boundary, EP-partitioned weights on local tensors,
dispatch/compute/combine all local

Key changes:
- Move `shared_experts` computation from inside
`TokenDispatcher.combine()` to `MoE.forward()`
- Move `to_local` from `MoE.forward()` into `GroupedExperts.forward()`,
with proper `grad_placements` based on placement type (Shard vs
Replicate)
- Replace `ColwiseParallelWithGradPlacement` with standard
`ColwiseParallel` using `input_layouts`
- Remove `shared_experts` parameter from all token dispatchers, replace
with `initial_output` buffer
- For EP+SP, keep `Shard(1)` as desired MoE input layout (avoid
redundant all-gather at MoE boundary); for TP-only, keep `Replicate()`
(required for TP-sharded expert weight reduction)

### Trade-offs
- Removes async overlap between `shared_experts` and the all-to-all
combine. Previously `shared_experts` ran while the combine A2A was in
flight on the NCCL stream. A follow-up can restore overlap using CUDA
streams.

## Test plan
single run
```
NCCL_NVLS_ENABLE=0 NGPU=4 MODULE='llama4' CONFIG='llama4_debugmodel' ./run_train.sh \
    --parallelism.pipeline_parallel_degree 1 \
    --parallelism.data_parallel_shard_degree 2 \
    --parallelism.tensor_parallel_degree 2 \
    --parallelism.expert_parallel_degree 2 \
    --debug.deterministic --debug.seed=42
```
Loss exactly match for dp4tp1ep1. 
```
NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama4' --baseline-config='llama4_debugmodel' --baseline-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 1 --
parallelism.expert_parallel_degree 1 --parallelism.no-ena
ble_sequence_parallel" --baseline-ngpus=4 --test-module='
llama4' --test-config='llama4_debugmodel' --test-options=
"--parallelism.pipeline_parallel_degree 1 --parallelism.d
ata_parallel_shard_degree 4 --parallelism.tensor_parallel
_degree 1 --parallelism.expert_parallel_degree 1 --parall
elism.no-enable_sequence_parallel" --test-ngpus=4 --asser
t-equal --no-seed-checkpoint
```

For other settings, loss is expected to diverge compared to main due to
different reduction pattern, and shared expert computation changes
place.

DP2TP2EP2, dense part default SP2
<img width="1097" height="457" alt="image"
src="https://github.com/user-attachments/assets/942428c4-e08e-4618-8b65-7c14eed39c81"
/>

DP2TP2EP4, dense part SP off
<img width="757" height="357" alt="image"
src="https://github.com/user-attachments/assets/07f6d9da-0b09-460a-b38c-ff64bd498c2e"
/>

tested deepep with both SP on and off
<img width="784" height="314" alt="image"
src="https://github.com/user-attachments/assets/ab304814-54af-4e42-8f9e-f14338b92ed0"
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant