Skip to content

Experimenting MoE new sharding - #3996

Merged
acisseJZhong merged 16 commits into
mainfrom
gh/acisseJZhong/24/head
Aug 11, 2026
Merged

acisseJZhong merged 16 commits into
mainfrom
gh/acisseJZhong/24/head

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • EP on: sequence-sharded layout
  • EP off, experts using pure TP: Partial 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

  • Update standard AllToAll combine to scatter into a local-shard output buffer instead of a full sp_size-expanded buffer.
  • Remove the SP global-index remapping path from EP token dispatchers.
  • Remove local_seq_len_after_padding from the dispatcher combine interface since local-shard combine no longer needs per-rank-to-global SP index mapping.
  • Keep num_local_tokens_after_padding for logical sequence padding, so AllToAll can size the local padded output without materializing pad rows.
  • Make DeepEP combine stay async for all SP sizes; MoE.forward() syncs before the routed output is read.
  • Update MoE sharding annotations so routed and shared expert outputs match before addition:
    • under EP: sequence-sharded
    • without EP: Partial
  • Move shared expert TP redistributions onto the linear layers so w1/w3 expose input all-gather and w2 exposes Partial-to-output-layout reduction.
  • Update the MoE sharding diagram.

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

NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='deepseek_v3' --baseline-config='deepseek_v3_debugmodel' --baseline-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2" --baseline-ngpus=8 --test-module='deepseek_v3' --test-config='deepseek_v3_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2" --test-ngpus=8 --assert-equal --no-seed-checkpoint

loss parity on FSDP4, TP=2, SP off, EP=2, ETP=1: [LOSS_COMPARE] Average difference: 0.000000

NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='deepseek_v3' --baseline-config='deepseek_v3_debugmodel' --baseline-options="--parallelism.spmd_backend spmd_types --parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2 --parallelism.no-enable-sequence-parallel" --baseline-ngpus=8 --test-module='deepseek_v3' --test-config='deepseek_v3_debugmodel' --test-options="--parallelism.spmd_backend spmd_types --parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2 --parallelism.no-enable-sequence-parallel" --test-ngpus=8 --assert-equal --no-seed-checkpoint

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

NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='deepseek_v3' --baseline-config='deepseek_v3_debugmodel' --baseline-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 1" --baseline-ngpus=8 --test-module='deepseek_v3' --test-config='deepseek_v3_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 1" --test-ngpus=8 --assert-equal --no-seed-checkpoint

loss parity on FSDP4, TP=2, SP off, EP=1, ETP=2: [LOSS_COMPARE] Average difference: 0.000000

NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='deepseek_v3' --baseline-config='deepseek_v3_debugmodel' --baseline-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 1 --parallelism.no-enable-sequence-parallel" --baseline-ngpus=8 --test-module='deepseek_v3' --test-config='deepseek_v3_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 1 --parallelism.no-enable-sequence-parallel" --test-ngpus=8 --assert-equal --no-seed-checkpoint

passed spmd type checking:

NCCL_NVLS_ENABLE=0 NGPU=8 MODULE=deepseek_v3 CONFIG=deepseek_v3_debugmodel ./run_train.sh \
  --parallelism.pipeline_parallel_degree 1 \
  --parallelism.data_parallel_shard_degree 4 \
  --parallelism.tensor_parallel_degree 2 \
  --parallelism.expert_parallel_degree 2 \
  --parallelism.spmd_backend spmd_types \
  --debug.spmd_typechecking \
  --training.steps 10 \
  activation-checkpoint:none

Also used a temporary script based on TestBitwiseParityMoEEP to run main
and the current commit with identical checkpoint weights and uneven
prompts, then compared all prefill/decode logprobs and generated
token IDs bit-for-bit.

[ghstack-poisoned]
[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 27, 2026
@acisseJZhong
acisseJZhong marked this pull request as draft July 27, 2026 19:12
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Jul 28, 2026
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Jul 28, 2026
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Jul 28, 2026
@acisseJZhong acisseJZhong changed the title [do not review]experimenting MoE new sharding Experimenting MoE new sharding Jul 28, 2026
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Jul 28, 2026
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Jul 28, 2026
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Jul 28, 2026
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Jul 28, 2026
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Jul 28, 2026
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Jul 31, 2026
@acisseJZhong
acisseJZhong marked this pull request as ready for review July 31, 2026 08:12
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Jul 31, 2026
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Jul 31, 2026

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add a TODO to deprecate this when DTensor backend is deprecated -- for spmd_types, we can directly access this info from global context

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 10, 2026

Copy link
Copy Markdown

Warning: Unknown label ciflow/graph-trainer.
Currently recognized labels are

  • ciflow/8gpu
  • ciflow/h100.8
  • ciflow/rl

Please add the new label to .github/pytorch-probot.yml

[ghstack-poisoned]
[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
@acisseJZhong
acisseJZhong changed the base branch from gh/acisseJZhong/24/base to main August 11, 2026 01:47
@acisseJZhong
acisseJZhong merged commit 45ea2f0 into main Aug 11, 2026
11 checks passed
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.
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/graph-trainer Run GraphTrainer CI ciflow/rl 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.

2 participants