Skip to content

inference moe expert sp padding - #4080

Merged
acisseJZhong merged 14 commits into
mainfrom
gh/acisseJZhong/28/head
Aug 11, 2026
Merged

acisseJZhong merged 14 commits into
mainfrom
gh/acisseJZhong/28/head

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary

this would resolve #3622

Pad MoE inputs to the expert sequence-parallel degree before routing, then
trim the output to its original length. This ensures equal TP shards for
uneven decode batches and removes virtual-padding bookkeeping from token
dispatchers.

Adds a TP=EP=4 vLLM test covering a three-request decode batch and verifying
bitwise decode/prefill parity.

Test Plan

CUDA_VISIBLE_DEVICES=0,1,2,3 torchrun --standalone --nproc-per-node=4     -m pytest -q     torchtitan/experiments/rl/tests/test_generator.py::test_vllm_uneven_decode_tp_padding

[ghstack-poisoned]
[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 7, 2026
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Aug 7, 2026
ghstack-source-id: 7eac073
Pull-Request: #4080
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Aug 7, 2026
ghstack-source-id: ae72c77
Pull-Request: #4080
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Aug 7, 2026
ghstack-source-id: 36cd98b
Pull-Request: #4080
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Aug 7, 2026
ghstack-source-id: 86db615
Pull-Request: #4080
expert_parallel_degree: int = 1
"""Expert parallelism degree for MoE layers. 1 means disabled."""

enable_sequence_parallel: bool = False

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.

The moe part of change looks good to me. But why we would ever enable SP for generator in general? (I know that we are always using expert sp)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

i added this flag just in case we want to turn on SP for inference later. For uneven inference when dense SP on, vllm model runner will pad the global input for us to make sure it's evenly divided. Therefore I need to pass enable_sp in Compilation Config into vllm.

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.

Let's separate it in a different PR if it's needed (with symmetric-memory based AG / RS). Right now it doesn't seem to benefit anyone, so let's split the complexity.

@acisseJZhong acisseJZhong Aug 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

but it we don't do this, if someone run uneven inference when dense SP on, spmd_types will error out. It's not able to turn R -> S(1) due to unevenness. We need to set enable_sp in Compilation Config for vllm model runner to pad.

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.

if someone run uneven inference when dense SP on

why would they

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

you can't control what users would do? why leaving SP + unevenness buggy when we can fix it?

however I admit at this point no user would try this, so doesn't matter.

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Aug 7, 2026
ghstack-source-id: ba3fcbd
Pull-Request: #4080
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Aug 7, 2026
ghstack-source-id: 0fa1079
Pull-Request: #4080
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Aug 7, 2026
ghstack-source-id: ac7da1d
Pull-Request: #4080
Comment thread torchtitan/models/common/moe.py Outdated
# For MoE-internal sequence sharding, physically pad L to a TP multiple
# so each TP rank gets the same local token count and combine output shape.
original_L = x_BLD.shape[1]
if self.input_seq_tp_sharded or self.expert_sequence_parallel_size == 1:

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.

these two are the same thing? True for top 2 figures, and false for the bottom two figures

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.

also I don't think you need explicit if-else when using expert_sequence_parallel_size

@acisseJZhong acisseJZhong Aug 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

no, input_seq_tp_sharded is only the first graph: enable_sp & enable_ep are both true. For the bottom 2 graphs, input is R.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

update: I will delete input_seq_tp_sharded. When dense SP is on, the global input seq is guaranteed to be even as vllm in theory will pad for us https://github.com/vllm-project/vllm/blob/f7ef489e93cf92b8d6ce7403b49f1db867bcc35e/vllm/v1/worker/gpu_model_runner.py#L3570.

However, right now vllm will not pad since we didn't set the compilation config enable_sp correctly, but this is not an issue for us as we hardcode SP off when inference. I will follow up with a PR to patch vllm model runner's pad function to correctly pad when SP on, and also to get rid of the model padding code.

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Aug 8, 2026
ghstack-source-id: 161ad87
Pull-Request: #4080
[ghstack-poisoned]
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Aug 11, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* #4045
* #4067
* #4100
* #4080
* __->__ #3996

## 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]
@acisseJZhong
acisseJZhong changed the base branch from gh/acisseJZhong/28/base to main August 11, 2026 01:49
@acisseJZhong
acisseJZhong merged commit f4f7cf7 into main Aug 11, 2026
14 checks passed
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Aug 11, 2026
wwwjn added a commit that referenced this pull request 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

[RL] MoE EP+TP: a vLLM-decode forward with fewer tokens than the TP degree breaks the sequence-parallel routing path

2 participants