Repository navigation
Experimenting MoE new sharding - #3996
Merged
Merged
Conversation
[ghstack-poisoned]
acisseJZhong
requested review from
fegin,
tianyu-l,
wconstab and
wwwjn
as code owners
July 27, 2026 19:11
acisseJZhong
marked this pull request as draft
July 27, 2026 19:12
acisseJZhong
marked this pull request as ready for review
July 31, 2026 08:12
tianyu-l
approved these changes
Aug 1, 2026
tianyu-l
left a comment
Contributor
There was a problem hiding this comment.
it'd be good to check the numerics doesn't change (for inference) when input sequence length is not always even
| # --------------------------------------------------------------------- | ||
| return out_BLD | ||
|
|
||
| def parallelize(self, parallel_dims) -> None: |
Contributor
There was a problem hiding this comment.
add a TODO to deprecate this when DTensor backend is deprecated -- for spmd_types, we can directly access this info from global context
This was referenced Aug 1, 2026
This was referenced Aug 5, 2026
|
Warning: Unknown label
Please add the new label to .github/pytorch-probot.yml |
[ghstack-poisoned]
pytorchmergebot
pushed a commit
to pytorch/pytorch
that referenced
this pull request
Aug 10, 2026
## Summary
Add DTensor support for Shard(dim) -> Partial("sum") redistribution
using local zero-fill. This enables the S(1) -> P transition required
by TorchTitan's new MoE sharding
(pytorch/torchtitan#3996).
## Testing
Added forward, backward, uneven-sharding, and graph-planner coverage.
```
python test/distributed/tensor/test_redistribute.py -k shard_to_partial
```
Pull Request resolved: #191828
Approved by: https://github.com/wconstab
saforem2
added a commit
to saforem2/torchtitan
that referenced
this pull request
Aug 11, 2026
…e checked Largest sync in a while (31 files) and the first in a while that needed real replay analysis: 45ea2f0 (pytorch#3996) rewrites models/common/moe_sharding.py (+325/-170) and moe.py, which ezpz/moe imports from. Checked rather than assumed, four ways: - MoE / RoutedExperts / TokenChoiceTopKRouter / GroupedExperts all still exist after the rewrite (AST check, not grep) - pytorch#3996 changed no class or __init__/forward signatures in common/moe.py - our one direct call, set_moe_sharding_config at ezpz/moe/sharding.py:167, matches the current signature exactly (moe_cfg, *, enable_ep, enable_sp, expert_param_layout) - ezpz/moe/*.py and the three rewritten shared modules all parse So: no replay. Also inert for ezpz -- MTP (pytorch#3392) and Muse Glimmer are additive new code we do not import, and nothing touched llama3/. Flagged explicitly: this is a STATIC check only. Sunspot is down (oneCCL allgatherv_ring cluster-wide, PBS returning empty results), so ezpz/moe could not be smoke-tested. Since pytorch#3996 rewrote sharding internals, run a MoE smoke before trusting an EP/SP run on this sync.
This was referenced Aug 11, 2026
wwwjn
added a commit
that referenced
this pull request
Aug 11, 2026
…#4089) ## Summary Enable MinimalAsyncEP to compose with context parallelism, tensor parallelism, and pipeline parallelism. This PR does not add backend-specific CP, TP, or PP dispatch algorithms. The required behavior comes from the common MoE and mesh contracts: - #3996 makes `RoutedExperts` operate on a local sequence shard and return that local layout. - #4080 physically pads the sequence before routing, so every rank dispatches the same number of materialized token rows. - #3970 centralizes lifetime communication-buffer capacity inference for persistent EP backends. - The sparse mesh places PP outside EP, so every pipeline stage owns an independent EP process group. MinimalAsyncEP therefore continues to dispatch the local `x_TD` rows over its EP group and returns a combined tensor with the same local token shape. The common MoE sharding path handles CP and TP, while the pipeline runtime invokes the stage-local MinimalAsyncEP instances. ## Buffer capacity MinimalAsyncEP now uses the shared lifetime capacity derivation: ```python num_token_shards = context_parallel_degree * tensor_parallel_degree if seq_len % num_token_shards != 0: raise ValueError(...) num_max_tokens_per_rank = local_batch_size * seq_len // num_token_shards ``` CP and TP reduce the local token capacity because they shard the sequence dimension before MoE. The shared configuration requires `seq_len` to divide evenly across `CP * TP`; users must pad the configured sequence length when it does not. PP does not enter this calculation because it partitions model layers, not the token axis. This replaces the backend-local `local_batch_size * seq_len` calculation, which overallocated once CP or TP was enabled. The shared setup also fills `hidden_dim`, preserves a user-specified capacity when it is large enough, and rejects an undersized capacity. MinimalAsyncEP keeps only its backend-specific dtype setup. ## Changes - Remove the MinimalAsyncEP configuration restrictions for CP, TP, and PP. - Include MinimalAsyncEP in shared EP buffer-capacity configuration. - Add an H100 integration configuration for `DP-shard=2, CP=2, TP=2, EP=8`. - Keep the test on `spmd_types` until the H100 suite migrates from the default DTensor backend. ## Testing ### Tensor parallelism Four H100s, 10 training steps: ```text DP-shard=2, TP=2, EP=4 spmd_backend=spmd_types compile disabled full activation checkpointing ``` Loss decreased from `8.06603` to `3.86079`; final `grad_norm` was `1.6618`. ### Context parallelism Four H100s, 10 training steps: ```text DP-shard=2, CP=2, EP=4 spmd_backend=spmd_types compile disabled full activation checkpointing ``` Loss decreased from `8.00828` to `3.87139`; final `grad_norm` was `1.5916`. ### Pipeline parallelism Four H100s with PyTorch `2.14.0.dev20260811+cu130`, two optimizer steps: ```text DP-shard=2, PP=2, EP=2 1F1B with 8 microbatches spmd_backend=spmd_types compile disabled full activation checkpointing ``` The run completed MinimalAsyncEP dispatch/combine, pipeline forward/backward, and PP-wide gradient-norm reduction. Loss decreased from `8.32359` to `6.38615`; `grad_norm` changed from `3.6094` to `4.4162`. ### Numerical comparison against AllToAll The standard AllToAll dispatcher and MinimalAsyncEP were run for 10 steps with the same `DP-shard=2, PP=2, EP=2` topology, fused expert kernels, data, seed 42, and deterministic mode. Full-precision TensorBoard metrics show a maximum relative loss difference of `4.55e-4` and a maximum relative grad-norm difference of `2.60e-3`. MinimalAsyncEP is not expected to be bitwise identical to AllToAll: AllToAll rounds each score-weighted expert row to BF16 and then performs deterministic scatter-add in expert order, while MinimalAsyncEP accumulates the top-k rows in FP32 slot order and rounds once. Two diagnostics verify that this difference is numerical rather than token dropping: - A temporary assertion reduced the active receive-row count across every stage-local EP group and required it to equal `EP_size * local_tokens * top_k`. It passed every forward and activation-recompute dispatch across all 10 steps. - Replacing only MinimalAsyncEP's top-k combine arithmetic with the AllToAll arithmetic produced the exact same step-1 loss: `8.1351776123046875` for both backends. Native MinimalAsyncEP produced `8.1351785659790039`. The exact eight-GPU `DP-shard=2, CP=2, TP=2, EP=8` CI configuration was not run locally because the host has seven available H100s. CP and TP were validated independently as listed above. ## Limitations - MinimalAsyncEP requires the `spmd_types` backend. The default DTensor path currently hits the same `Shard(1) -> Partial(sum)` limitation tracked by #4110. - MinimalAsyncEP requires full recomputation: full activation checkpointing for eager training or full memory policy for GraphTrainer.
ankitbhrdwj
pushed a commit
to ankitbhrdwj/pytorch
that referenced
this pull request
Aug 12, 2026
## Summary
Add DTensor support for Shard(dim) -> Partial("sum") redistribution
using local zero-fill. This enables the S(1) -> P transition required
by TorchTitan's new MoE sharding
(pytorch/torchtitan#3996).
## Testing
Added forward, backward, uneven-sharding, and graph-planner coverage.
```
python test/distributed/tensor/test_redistribute.py -k shard_to_partial
```
Pull Request resolved: pytorch#191828
Approved by: https://github.com/wconstab
saforem2
added a commit
to saforem2/torchtitan
that referenced
this pull request
Aug 19, 2026
…ch#3996 stopped passing it Every ezpz MoE config dies at init: TypeError: AllToAllTokenDispatcher.wire_meshes() missing 1 required keyword-only argument: 'tp_mesh' Upstream PR pytorch#3996 ('Experimenting MoE new sharding') changed models/common/moe.py:187 to call wire_meshes(ep_mesh=...) only, dropping tp_mesh. Core's own dispatchers were updated to match; our four ezpz overrides still declared tp_mesh as required keyword-only, so the inherited MoE.parallelize() call raises before step 1. Same class of silent break as pytorch#4045 removing maybe_enable_async_tp. Defaults tp_mesh=None on all four (base, AllToAll, DeepEP, HybridEP). The new caller omits it; anything still passing it keeps working. The default is CORRECT for TP=1 -- sp_size/sp_rank are initialised to 1/0 in __init__, which is exactly the no-SP case. It is NOT correct under TP>1, where combine() would expand to the wrong sequence length. Rather than fail silently, the three dispatchers that consume tp_mesh now warn when it is absent but the mesh topology has a 'tp' axis. The TP check reads the mesh already in hand (ep_mesh's root mesh_dim_names). A first attempt used ParallelDims._current, which does not exist -- with its bare except that helper would have always returned False, i.e. dead code wearing the costume of a guard. Verified by AST: all four now require only ep_mesh. Helper unit-tested on None / no-tp / tp / nested-root / garbage inputs.
saforem2
added a commit
to saforem2/torchtitan
that referenced
this pull request
Aug 19, 2026
…imizer Upstream pytorch#4172 deleted torchtitan/components/lr_scheduler.py. It had become a re-export shim when pytorch#4140 grouped the optimizer components into a package, so LRSchedulersContainer now lives in torchtitan.components.optimizer. Four ezpz registries imported the deleted path: agpt, moe, and the two RL config registries. Without this every one of them fails at import, which is the same failure shape as pytorch#4045 (maybe_enable_async_tp) and pytorch#3996 (wire_meshes tp_mesh) -- upstream removes a path, ezpz overrides still name it. components.optimizer itself survives as a package, so the five other ezpz files importing default_adamw / OptimizersContainer / ParamGroupConfig need no change. Verified: 0 unresolvable torchtitan imports and 0 syntax errors across all ezpz .py files on the merged tree.
3 tasks done
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):
Summary
This updates the MoE EP/SP sharding contract so token dispatchers return the local sequence shard directly instead of constructing a full global-length sparse contribution.
The main change is that routed expert outputs are represented as the MoE local output layout:
Shared experts are updated to produce the same layout as routed experts before the routed + shared add. The outer MoE boundary remains responsible for redistributing the final MoE output to
sp_layout.Changes
sp_size-expanded buffer.local_seq_len_after_paddingfrom the dispatcher combine interface since local-shard combine no longer needs per-rank-to-global SP index mapping.num_local_tokens_after_paddingfor logical sequence padding, so AllToAll can size the local padded output without materializing pad rows.MoE.forward()syncs before the routed output is read.w1/w3expose input all-gather andw2exposes Partial-to-output-layout reduction.Test plan
loss parity on FSDP4, TP=2, SP on, EP=2, ETP=1: AssertionError: 7.949278831481934 != 7.9492878913879395 : Loss mismatch at step 1: baseline=7.949278831481934, test=7.9492878913879395
loss parity on FSDP4, TP=2, SP off, EP=2, ETP=1: [LOSS_COMPARE] Average difference: 0.000000
loss parity on FSDP4, TP=2, SP on, EP=1, ETP=2: AssertionError: 6.0643310546875 != 6.064278602600098 : Loss mismatch at step 2: baseline=6.0643310546875, test=6.064278602600098
loss parity on FSDP4, TP=2, SP off, EP=1, ETP=2: [LOSS_COMPARE] Average difference: 0.000000
passed spmd type checking:
Also used a temporary script based on
TestBitwiseParityMoEEPto run mainand the current commit with identical checkpoint weights and uneven
prompts, then compared all prefill/decode logprobs and generated
token IDs bit-for-bit.