Repository navigation
[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
Closed
[NOT READY FOR REVIEW][Module][MoE] Config-based MoE sharding (qwen3, llama4, gpt_oss, deepseek_v3)#3160fegin wants to merge 21 commits into
fegin wants to merge 21 commits into
Conversation
This was referenced Apr 29, 2026
fegin
commented
May 1, 2026
This was referenced May 15, 2026
This was referenced May 17, 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" />
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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):Add
local_input_grad_placementsandlocal_output_grad_placementsto
ShardingConfig, mirroringColwiseParallelWithGradPlacement (local_input_grad_placements=...)andNoParallel (local_output_grad_placements=...). Plumbed throughModule._needed_axes,_shard_inputs(passesgrad_placementstoDTensor.from_local),and
_shard_outputs(callsto_local(grad_placements=...)after theoutput redistribute, switching the wrapper's effective return type to
local tensor when set).
These fields express what the imperative
NoParallel/ColwiseParallelWithGradPlacementdid for the legacy MoE plan; withoutthem, 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 expertsunder EP.
expert_param_placement_dense(tp_placement)--{TP: ...}forthe 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 helperthat 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
ShardingConfigcombinesin_src_shardings/in_dst_shardings/out_dst_shardings(input AG, output RS) withLocalMapConfig(dense<->local at the boundary).out_placementson the LocalMap is
Partial-- the body produces a per-rank Partialsum, and
out_dst_shardingsreduces Partial -> sp_layout once at theboundary, mirroring the legacy
PrepareModuleInputOutputcollectivepattern.
AllToAllTokenDispatcherandDeepEPTokenDispatchernow expose_wire_meshes(*, ep_mesh, tp_mesh)for the owning Module to installmeshes at parallelize time.
sp_size/sp_rankare read-only@propertyreads offself.tp_mesh(preserving SymInt under CooR precompile).GroupedExperts.parallelize(andGptOssGroupedExperts.parallelize)override
Module.parallelizeto call_wire_meshesafter thebase 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 inMoE.forwardis gone -- the wrapper'sLocalMapConfigowns theboundary. Body operates on plain tensors throughout; child wrappers
(router, experts, shared_experts) re-wrap their inputs via their own
sharding_configs as needed.
GroupedExperts(w1/w2/w3);pass
{"w1": Shard(1), "w2": Shard(2), "w3": Shard(1)}as theexpert_param_layout.
GptOssGroupedExpertshas fused mlp1/mlp2 weights+biases;pass
{"mlp1_weight": Shard(1), "mlp1_bias": Shard(1), "mlp2_weight": Shard(2), "mlp2_bias": Replicate()}. Also fixesGptOssMoE.__init__to forwardsharding_config(andparam_init) when rebuildingGptOssGroupedExperts.Config--without this, the rebuild silently dropped the sharding plan and
torch._grouped_mmfailed deep in the kernel.model.parallelize(parallel_dims)is now invoked undertp_enabled or ep_enabled(was TP-only). Module.parallelizefilters disabled axes per-Module so dense Modules no-op cleanly when
TP=1.
apply_moe_ep_tpdefinition retained inllama4/parallelize.pyfor qwen3_vl (which is not migrated in this PR, deferred). Updated to
call
_wire_meshesinstead of writing the now read-onlysp_size/sp_rankproperties. The gpt_oss copy ofapply_moe_ep_tpand thegpt_oss/expert_parallel.pyfile aredeleted -- 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 obsoletetest_unions_across_all_fields(was failing pre-existing on PR6 underthe family-purity contract) with two new tests aligned to the post-PR6
_needed_axessemantics. 30/30 module tests pass.