Skip to content

[MoE][1/n] Introduce token dispatcher and replace token reorderer - #2842

Merged
acisseJZhong merged 76 commits into
mainfrom
gh/acisseJZhong/6/head
Apr 17, 2026
Merged

acisseJZhong merged 76 commits into
mainfrom
gh/acisseJZhong/6/head

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Apr 4, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

TODO tracking here #2956

Summary

Introduce a token dispatcher abstraction (token_dispatcher.py) that encapsulates the full token routing lifecycle — dispatch (reorder + optional EP all-to-all) and combine (reverse dispatch + shared_experts overlap + score application + scatter_add).

Dispatcher hierarchy:

  • LocalTokenDispatcher — EP=1, local token reordering only. Base class for all dispatchers.
  • AllToAllTokenDispatcher — EP>1, adds NCCL all-to-all dispatch/combine. Calls super().combine() for shared score+scatter_add logic. Supports sequence parallel via sp_size config.
  • TorchAOTokenDispatcher — EP>1, extends AllToAllTokenDispatcher with permute_and_pad for FP8/MXFP8 quantized grouped GEMMs.
  • DeepEPTokenDispatcher — EP>1, uses DeepEP/HybridEP library kernels instead of standard all-to-all.

Key changes:

  • GroupedExperts.forward() now owns the full dispatch → expert compute → combine pipeline, accepting shared_experts to overlap with async combine communication.
  • MoE.forward() simplified to: router → self.experts(x, top_scores, indices, shared_experts=self.shared_experts) → reshape.
  • DeepEPMoE no longer overrides forward() — the dispatcher handles both NCCL and DeepEP paths.
  • Removed TokenReorderer (folded into dispatchers) and moe_deepep.py (folded into dispatchers + simplified DeepEPMoE).
  • ReordererSequenceParallel input/output hooks replaced by sp_size config on AllToAllTokenDispatcher — sequence parallel token splitting now happens inside the dispatcher's dispatch() and combine().
  • ExpertParallel / ExpertTensorParallel now only handle weight sharding + setting ep_group on the dispatcher.
  • Removed score_before_experts from MoE.Config (now lives on the dispatcher).

Motivation

Previously, token routing was split across three places:

  1. TokenReorderer — reorder tokens from token-index to expert-index order
  2. MoE.forward() — score application, shared_experts, scatter_add
  3. ExpertParallel input/output hooks — all-to-all dispatch/combine (EP>1 only)

This made it hard to reason about the async overlap pattern (shared_experts should run while combine communication is in flight), and DeepEPMoE had to duplicate most of MoE.forward().

Now, the dispatcher encapsulates the full lifecycle. Benefits:

  • Async overlap is explicit: combine() starts async communication, runs shared_experts, then forces sync via scatter_add or sync_combine().
  • Single place to swap dispatch/combine implementations (NCCL, DeepEP, HybridEP, TorchAO).
  • AllToAllTokenDispatcher.combine() reuses LocalTokenDispatcher.combine() via super(), eliminating code duplication.
  • DeepEPMoE.forward() is no longer needed — the base MoE.forward() works for all paths.
  • Sequence parallel logic consolidated into AllToAllTokenDispatcher — no more ReordererSequenceParallel class with distribute_module input/output hooks. The dispatcher splits tokens in dispatch() and combine() when sp_size > 1.
  • Enables local_map usage: single wrapper around GroupedExperts (which contains the dispatcher).

Test Plan

Losses matched under EP=1, EP>1, --parallelism.expert_parallel_comm_backend=deepep, and torchao cases.

NCCL_NVLS_ENABLE=0 NGPU=8 ./run_train.sh     --module llama4     --config llama4_debugmodel     --parallelism.pipeline_parallel_degree 1     --parallelism.data_parallel_shard_degree 4     --parallelism.tensor_parallel_degree 2     --parallelism.expert_parallel_degree 2     --parallelism.expert_tensor_parallel_degree 2      --metrics.enable_wandb --training.steps 100
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 2 --parallelism.expert_tensor_parallel_degree 1" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 1 --parallelism.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint

cc @fegin for parallelism refactor, @elfiegg @shuhuayu for removing DeepEP MoE.

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 4, 2026
ghstack-source-id: 8b847d1
Pull Request resolved: #2842
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Apr 4, 2026
@acisseJZhong
acisseJZhong marked this pull request as draft April 4, 2026 00:33
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 4, 2026
ghstack-source-id: a358818
Pull Request resolved: #2842
acisseJZhong added a commit that referenced this pull request Apr 6, 2026
ghstack-source-id: cac7fa6
Pull Request resolved: #2842
acisseJZhong added a commit that referenced this pull request Apr 6, 2026
ghstack-source-id: 6c6e1ef
Pull Request resolved: #2842
acisseJZhong added a commit that referenced this pull request Apr 7, 2026
ghstack-source-id: d3737c4
Pull Request resolved: #2842
## Summary
                                                                 
- Introduce LocalTokenDispatcher (EP=1) and TokenDispatcher (EP>1) in a new `token_dispatcher.py` that unify token reordering, scoring, all-to-all dispatch/combine, and scatter-add output combining.                                   
- Move dispatch/combine logic out of ExpertParallel hooks into the dispatchers, which live inside GroupedExperts; ExpertParallel and ExpertTensorParallel now only handle weight sharding. Remove TokenReorderer and the manual unsort/score/scatter logic from MoE.forward().                                     
                                                               
## Motivation        

**Previously,** token routing was split across three places:
1. (Required, both EP=1 and EP>1) TokenReorderer — turn tokens from token index oriented to expert index oriented
2. MoE.forward() — gathered tokens, applied scores, called experts, scattered outputs back
3. (Optional; only for EP>1) ExpertParallel input/output hooks — all-to-all dispatch/combine                             
                                                                 
Model and EP code are strictly decoupled. The [Expert Parallel](https://github.com/pytorch/torchtitan/blob/8e17400d396618785dab25f096510b4553c3a80d/torchtitan/distributed/expert_parallel.py#L74) class handles dispatch/combine logic when EP>1, while the Token Reorderer handles permuting tokens  from token index oriented to expert index oriented for both EP=1 and EP>1. 

**Now,** we encapsulates the token dispatch and token combine, together with reorder logic inside a single token dispatcher module, which lives inside the GroupedExperts module. And we use different token dispatcher for EP=1, EP>1. **The benefits are** 
- We no longer have both token reorderer and token dispatch/combine in ExpertParallel. We encapsulate this dispatching logic. 
- We can swap different token dispatchers for different dispatch/combine implementations. For example, we could use have different token dispatchers to uses naive A2A, A2A dedup when topk>1, or DeepEP.  
- This also enables the ease of local_map usage: we use a single local map wrapping GroupedExperts(which contains token dispatcher).

[ghstack-poisoned]
## Summary
                                                                 
- Introduce LocalTokenDispatcher (EP=1) and TokenDispatcher (EP>1) in a new `token_dispatcher.py` that unify token reordering, scoring, all-to-all dispatch/combine, and scatter-add output combining.                                   
- Move dispatch/combine logic out of ExpertParallel hooks into the dispatchers, which live inside GroupedExperts; ExpertParallel and ExpertTensorParallel now only handle weight sharding. Remove TokenReorderer and the manual unsort/score/scatter logic from MoE.forward().                                     
                                                               
## Motivation        

**Previously,** token routing was split across three places:
1. (Required, both EP=1 and EP>1) TokenReorderer — turn tokens from token index oriented to expert index oriented
2. MoE.forward() — gathered tokens, applied scores, called experts, scattered outputs back
3. (Optional; only for EP>1) ExpertParallel input/output hooks — all-to-all dispatch/combine                             
                                                                 
Model and EP code are strictly decoupled. The [Expert Parallel](https://github.com/pytorch/torchtitan/blob/8e17400d396618785dab25f096510b4553c3a80d/torchtitan/distributed/expert_parallel.py#L74) class handles dispatch/combine logic when EP>1, while the Token Reorderer handles permuting tokens  from token index oriented to expert index oriented for both EP=1 and EP>1. 

**Now,** we encapsulates the token dispatch and token combine, together with reorder logic inside a single token dispatcher module, which lives inside the GroupedExperts module. And we use different token dispatcher for EP=1, EP>1. **The benefits are** 
- We no longer have both token reorderer and token dispatch/combine in ExpertParallel. We encapsulate this dispatching logic. 
- We can swap different token dispatchers for different dispatch/combine implementations. For example, we could use have different token dispatchers to uses naive A2A, A2A dedup when topk>1, or DeepEP.  
- This also enables the ease of local_map usage: we use a single local map wrapping GroupedExperts(which contains token dispatcher).

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 7, 2026
ghstack-source-id: 7c43c37
Pull Request resolved: #2842
## Summary
                                                                 
- Introduce LocalTokenDispatcher (EP=1) and TokenDispatcher (EP>1) in a new `token_dispatcher.py` that unify token reordering, scoring, all-to-all dispatch/combine, and scatter-add output combining.                                   
- Move dispatch/combine logic out of ExpertParallel hooks into the dispatchers, which live inside GroupedExperts; ExpertParallel and ExpertTensorParallel now only handle weight sharding. Remove TokenReorderer and the manual unsort/score/scatter logic from MoE.forward().                                     
                                                               
## Motivation        

**Previously,** token routing was split across three places:
1. (Required, both EP=1 and EP>1) TokenReorderer — turn tokens from token index oriented to expert index oriented
2. MoE.forward() — gathered tokens, applied scores, called experts, scattered outputs back
3. (Optional; only for EP>1) ExpertParallel input/output hooks — all-to-all dispatch/combine                             
                                                                 
Model and EP code are strictly decoupled. The [Expert Parallel](https://github.com/pytorch/torchtitan/blob/8e17400d396618785dab25f096510b4553c3a80d/torchtitan/distributed/expert_parallel.py#L74) class handles dispatch/combine logic when EP>1, while the Token Reorderer handles permuting tokens  from token index oriented to expert index oriented for both EP=1 and EP>1. 

**Now,** we encapsulates the token dispatch and token combine, together with reorder logic inside a single token dispatcher module, which lives inside the GroupedExperts module. And we use different token dispatcher for EP=1, EP>1. **The benefits are** 
- We no longer have both token reorderer and token dispatch/combine in ExpertParallel. We encapsulate this dispatching logic. 
- We can swap different token dispatchers for different dispatch/combine implementations. For example, we could use have different token dispatchers to uses naive A2A, A2A dedup when topk>1, or DeepEP.  
- This also enables the ease of local_map usage: we use a single local map wrapping GroupedExperts(which contains token dispatcher).

[ghstack-poisoned]
## Summary
                                                                 
- Introduce LocalTokenDispatcher (EP=1) and TokenDispatcher (EP>1) in a new `token_dispatcher.py` that unify token reordering, scoring, all-to-all dispatch/combine, and scatter-add output combining.                                   
- Move dispatch/combine logic out of ExpertParallel hooks into the dispatchers, which live inside GroupedExperts; ExpertParallel and ExpertTensorParallel now only handle weight sharding. Remove TokenReorderer and the manual unsort/score/scatter logic from MoE.forward().                                     
                                                               
## Motivation        

**Previously,** token routing was split across three places:
1. (Required, both EP=1 and EP>1) TokenReorderer — turn tokens from token index oriented to expert index oriented
2. MoE.forward() — gathered tokens, applied scores, called experts, scattered outputs back
3. (Optional; only for EP>1) ExpertParallel input/output hooks — all-to-all dispatch/combine                             
                                                                 
Model and EP code are strictly decoupled. The [Expert Parallel](https://github.com/pytorch/torchtitan/blob/8e17400d396618785dab25f096510b4553c3a80d/torchtitan/distributed/expert_parallel.py#L74) class handles dispatch/combine logic when EP>1, while the Token Reorderer handles permuting tokens  from token index oriented to expert index oriented for both EP=1 and EP>1. 

**Now,** we encapsulates the token dispatch and token combine, together with reorder logic inside a single token dispatcher module, which lives inside the GroupedExperts module. And we use different token dispatcher for EP=1, EP>1. **The benefits are** 
- We no longer have both token reorderer and token dispatch/combine in ExpertParallel. We encapsulate this dispatching logic. 
- We can swap different token dispatchers for different dispatch/combine implementations. For example, we could use have different token dispatchers to uses naive A2A, A2A dedup when topk>1, or DeepEP.  
- This also enables the ease of local_map usage: we use a single local map wrapping GroupedExperts(which contains token dispatcher).

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 7, 2026
ghstack-source-id: 9a2a520
Pull Request resolved: #2842
## Summary
                                                                 
- Introduce LocalTokenDispatcher (EP=1) and TokenDispatcher (EP>1) in a new `token_dispatcher.py` that unify token reordering, scoring, all-to-all dispatch/combine, and scatter-add output combining.                                   
- Move dispatch/combine logic out of ExpertParallel hooks into the dispatchers, which live inside GroupedExperts; ExpertParallel and ExpertTensorParallel now only handle weight sharding. Remove TokenReorderer and the manual unsort/score/scatter logic from MoE.forward().                                     
                                                               
## Motivation        

**Previously,** token routing was split across three places:
1. (Required, both EP=1 and EP>1) TokenReorderer — turn tokens from token index oriented to expert index oriented
2. MoE.forward() — gathered tokens, applied scores, called experts, scattered outputs back
3. (Optional; only for EP>1) ExpertParallel input/output hooks — all-to-all dispatch/combine                             
                                                                 
Model and EP code are strictly decoupled. The [Expert Parallel](https://github.com/pytorch/torchtitan/blob/8e17400d396618785dab25f096510b4553c3a80d/torchtitan/distributed/expert_parallel.py#L74) class handles dispatch/combine logic when EP>1, while the Token Reorderer handles permuting tokens  from token index oriented to expert index oriented for both EP=1 and EP>1. 

**Now,** we encapsulates the token dispatch and token combine, together with reorder logic inside a single token dispatcher module, which lives inside the GroupedExperts module. And we use different token dispatcher for EP=1, EP>1. **The benefits are** 
- We no longer have both token reorderer and token dispatch/combine in ExpertParallel. We encapsulate this dispatching logic. 
- We can swap different token dispatchers for different dispatch/combine implementations. For example, we could use have different token dispatchers to uses naive A2A, A2A dedup when topk>1, or DeepEP.  
- This also enables the ease of local_map usage: we use a single local map wrapping GroupedExperts(which contains token dispatcher).

[ghstack-poisoned]
## Summary
                                                                 
- Introduce LocalTokenDispatcher (EP=1) and TokenDispatcher (EP>1) in a new `token_dispatcher.py` that unify token reordering, scoring, all-to-all dispatch/combine, and scatter-add output combining.                                   
- Move dispatch/combine logic out of ExpertParallel hooks into the dispatchers, which live inside GroupedExperts; ExpertParallel and ExpertTensorParallel now only handle weight sharding. Remove TokenReorderer and the manual unsort/score/scatter logic from MoE.forward().                                     
                                                               
## Motivation        

**Previously,** token routing was split across three places:
1. (Required, both EP=1 and EP>1) TokenReorderer — turn tokens from token index oriented to expert index oriented
2. MoE.forward() — gathered tokens, applied scores, called experts, scattered outputs back
3. (Optional; only for EP>1) ExpertParallel input/output hooks — all-to-all dispatch/combine                             
                                                                 
Model and EP code are strictly decoupled. The [Expert Parallel](https://github.com/pytorch/torchtitan/blob/8e17400d396618785dab25f096510b4553c3a80d/torchtitan/distributed/expert_parallel.py#L74) class handles dispatch/combine logic when EP>1, while the Token Reorderer handles permuting tokens  from token index oriented to expert index oriented for both EP=1 and EP>1. 

**Now,** we encapsulates the token dispatch and token combine, together with reorder logic inside a single token dispatcher module, which lives inside the GroupedExperts module. And we use different token dispatcher for EP=1, EP>1. **The benefits are** 
- We no longer have both token reorderer and token dispatch/combine in ExpertParallel. We encapsulate this dispatching logic. 
- We can swap different token dispatchers for different dispatch/combine implementations. For example, we could use have different token dispatchers to uses naive A2A, A2A dedup when topk>1, or DeepEP.  
- This also enables the ease of local_map usage: we use a single local map wrapping GroupedExperts(which contains token dispatcher).

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 7, 2026
ghstack-source-id: b957acd
Pull Request resolved: #2842
@acisseJZhong
acisseJZhong marked this pull request as ready for review April 7, 2026 02:57

ep_size = self.ep_size

# TODO: Extract this local reordering block (histc, argsort, score

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.

I thought you said EP dispatcher doesn't necessarily need to have the same reorder steps.
Is it still needed for nccl AllToAll dispatcher, or are you going to change the implementation later?

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 think before this PR, the torch.hist + torch.argsort(aka routing map generation) logic exists both in token reorderer

num_tokens_per_expert = torch.histc(
anddd moe forward
num_tokens_per_expert = torch.histc(
so it's duplicated.

After this PR, it only exists once in the dispatcher. The todo is more about refactoring this part to be a helper function(and maybe mimic six's routing map generation logic, but don't have to) instead of duplicating code.

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.

I see. Sounds good.

…replace token reorderer"


TODO tracking here #2956
## Summary

Introduce a token dispatcher abstraction (`token_dispatcher.py`) that encapsulates the full token routing lifecycle — dispatch (reorder + optional EP all-to-all) and combine (reverse dispatch + shared_experts overlap + score application + scatter_add).

**Dispatcher hierarchy:**
- `LocalTokenDispatcher` — EP=1, local token reordering only. Base class for all dispatchers.
- `AllToAllTokenDispatcher` — EP>1, adds NCCL all-to-all dispatch/combine. Calls `super().combine()` for shared score+scatter_add logic. Supports sequence parallel via `sp_size` config.
- `TorchAOTokenDispatcher` — EP>1, extends AllToAllTokenDispatcher with `permute_and_pad` for FP8/MXFP8 quantized grouped GEMMs.
- `DeepEPTokenDispatcher` — EP>1, uses DeepEP/HybridEP library kernels instead of standard all-to-all.

**Key changes:**
- `GroupedExperts.forward()` now owns the full dispatch → expert compute → combine pipeline, accepting `shared_experts` to overlap with async combine communication.
- `MoE.forward()` simplified to: router → `self.experts(x, top_scores, indices, shared_experts=self.shared_experts)` → reshape.
- `DeepEPMoE` no longer overrides `forward()` — the dispatcher handles both NCCL and DeepEP paths.
- Removed `TokenReorderer` (folded into dispatchers) and `moe_deepep.py` (folded into dispatchers + simplified `DeepEPMoE`).
- `ReordererSequenceParallel` input/output hooks replaced by `sp_size` config on `AllToAllTokenDispatcher` — sequence parallel token splitting now happens inside the dispatcher's `dispatch()` and `combine()`.
- `ExpertParallel` / `ExpertTensorParallel` now only handle weight sharding + setting `ep_group` on the dispatcher.
- Removed `score_before_experts` from `MoE.Config` (now lives on the dispatcher).

## Motivation

**Previously,** token routing was split across three places:
1. `TokenReorderer` — reorder tokens from token-index to expert-index order
2. `MoE.forward()` — score application, shared_experts, scatter_add
3. `ExpertParallel` input/output hooks — all-to-all dispatch/combine (EP>1 only)

This made it hard to reason about the async overlap pattern (shared_experts should run while combine communication is in flight), and `DeepEPMoE` had to duplicate most of `MoE.forward()`.

**Now,** the dispatcher encapsulates the full lifecycle. Benefits:
- Async overlap is explicit: `combine()` starts async communication, runs `shared_experts`, then forces sync via scatter_add or `sync_combine()`.
- Single place to swap dispatch/combine implementations (NCCL, DeepEP, HybridEP, TorchAO).
- `AllToAllTokenDispatcher.combine()` reuses `LocalTokenDispatcher.combine()` via `super()`, eliminating code duplication.
- `DeepEPMoE.forward()` is no longer needed — the base `MoE.forward()` works for all paths.
- Sequence parallel logic consolidated into `AllToAllTokenDispatcher` — no more `ReordererSequenceParallel` class with `distribute_module` input/output hooks. The dispatcher splits tokens in `dispatch()` and `combine()` when `sp_size > 1`.
- Enables `local_map` usage: single wrapper around `GroupedExperts` (which contains the dispatcher).

## Test Plan
Losses matched under EP=1, EP>1, `--parallelism.expert_parallel_comm_backend=deepep`, and torchao cases.
```
NCCL_NVLS_ENABLE=0 NGPU=8 ./run_train.sh     --module llama4     --config llama4_debugmodel     --parallelism.pipeline_parallel_degree 1     --parallelism.data_parallel_shard_degree 4     --parallelism.tensor_parallel_degree 2     --parallelism.expert_parallel_degree 2     --parallelism.expert_tensor_parallel_degree 2      --metrics.enable_wandb --training.steps 100
```

```
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 2 --parallelism.expert_tensor_parallel_degree 1" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 1 --parallelism.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

cc fegin for parallelism refactor, elfiegg shuhuayu for removing DeepEP MoE.

[ghstack-poisoned]
…orderer"


TODO tracking here #2956
## Summary

Introduce a token dispatcher abstraction (`token_dispatcher.py`) that encapsulates the full token routing lifecycle — dispatch (reorder + optional EP all-to-all) and combine (reverse dispatch + shared_experts overlap + score application + scatter_add).

**Dispatcher hierarchy:**
- `LocalTokenDispatcher` — EP=1, local token reordering only. Base class for all dispatchers.
- `AllToAllTokenDispatcher` — EP>1, adds NCCL all-to-all dispatch/combine. Calls `super().combine()` for shared score+scatter_add logic. Supports sequence parallel via `sp_size` config.
- `TorchAOTokenDispatcher` — EP>1, extends AllToAllTokenDispatcher with `permute_and_pad` for FP8/MXFP8 quantized grouped GEMMs.
- `DeepEPTokenDispatcher` — EP>1, uses DeepEP/HybridEP library kernels instead of standard all-to-all.

**Key changes:**
- `GroupedExperts.forward()` now owns the full dispatch → expert compute → combine pipeline, accepting `shared_experts` to overlap with async combine communication.
- `MoE.forward()` simplified to: router → `self.experts(x, top_scores, indices, shared_experts=self.shared_experts)` → reshape.
- `DeepEPMoE` no longer overrides `forward()` — the dispatcher handles both NCCL and DeepEP paths.
- Removed `TokenReorderer` (folded into dispatchers) and `moe_deepep.py` (folded into dispatchers + simplified `DeepEPMoE`).
- `ReordererSequenceParallel` input/output hooks replaced by `sp_size` config on `AllToAllTokenDispatcher` — sequence parallel token splitting now happens inside the dispatcher's `dispatch()` and `combine()`.
- `ExpertParallel` / `ExpertTensorParallel` now only handle weight sharding + setting `ep_group` on the dispatcher.
- Removed `score_before_experts` from `MoE.Config` (now lives on the dispatcher).

## Motivation

**Previously,** token routing was split across three places:
1. `TokenReorderer` — reorder tokens from token-index to expert-index order
2. `MoE.forward()` — score application, shared_experts, scatter_add
3. `ExpertParallel` input/output hooks — all-to-all dispatch/combine (EP>1 only)

This made it hard to reason about the async overlap pattern (shared_experts should run while combine communication is in flight), and `DeepEPMoE` had to duplicate most of `MoE.forward()`.

**Now,** the dispatcher encapsulates the full lifecycle. Benefits:
- Async overlap is explicit: `combine()` starts async communication, runs `shared_experts`, then forces sync via scatter_add or `sync_combine()`.
- Single place to swap dispatch/combine implementations (NCCL, DeepEP, HybridEP, TorchAO).
- `AllToAllTokenDispatcher.combine()` reuses `LocalTokenDispatcher.combine()` via `super()`, eliminating code duplication.
- `DeepEPMoE.forward()` is no longer needed — the base `MoE.forward()` works for all paths.
- Sequence parallel logic consolidated into `AllToAllTokenDispatcher` — no more `ReordererSequenceParallel` class with `distribute_module` input/output hooks. The dispatcher splits tokens in `dispatch()` and `combine()` when `sp_size > 1`.
- Enables `local_map` usage: single wrapper around `GroupedExperts` (which contains the dispatcher).

## Test Plan
Losses matched under EP=1, EP>1, `--parallelism.expert_parallel_comm_backend=deepep`, and torchao cases.
```
NCCL_NVLS_ENABLE=0 NGPU=8 ./run_train.sh     --module llama4     --config llama4_debugmodel     --parallelism.pipeline_parallel_degree 1     --parallelism.data_parallel_shard_degree 4     --parallelism.tensor_parallel_degree 2     --parallelism.expert_parallel_degree 2     --parallelism.expert_tensor_parallel_degree 2      --metrics.enable_wandb --training.steps 100
```

```
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 2 --parallelism.expert_tensor_parallel_degree 1" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 1 --parallelism.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

cc fegin for parallelism refactor, elfiegg shuhuayu for removing DeepEP MoE.

[ghstack-poisoned]
…replace token reorderer"


TODO tracking here #2956
## Summary

Introduce a token dispatcher abstraction (`token_dispatcher.py`) that encapsulates the full token routing lifecycle — dispatch (reorder + optional EP all-to-all) and combine (reverse dispatch + shared_experts overlap + score application + scatter_add).

**Dispatcher hierarchy:**
- `LocalTokenDispatcher` — EP=1, local token reordering only. Base class for all dispatchers.
- `AllToAllTokenDispatcher` — EP>1, adds NCCL all-to-all dispatch/combine. Calls `super().combine()` for shared score+scatter_add logic. Supports sequence parallel via `sp_size` config.
- `TorchAOTokenDispatcher` — EP>1, extends AllToAllTokenDispatcher with `permute_and_pad` for FP8/MXFP8 quantized grouped GEMMs.
- `DeepEPTokenDispatcher` — EP>1, uses DeepEP/HybridEP library kernels instead of standard all-to-all.

**Key changes:**
- `GroupedExperts.forward()` now owns the full dispatch → expert compute → combine pipeline, accepting `shared_experts` to overlap with async combine communication.
- `MoE.forward()` simplified to: router → `self.experts(x, top_scores, indices, shared_experts=self.shared_experts)` → reshape.
- `DeepEPMoE` no longer overrides `forward()` — the dispatcher handles both NCCL and DeepEP paths.
- Removed `TokenReorderer` (folded into dispatchers) and `moe_deepep.py` (folded into dispatchers + simplified `DeepEPMoE`).
- `ReordererSequenceParallel` input/output hooks replaced by `sp_size` config on `AllToAllTokenDispatcher` — sequence parallel token splitting now happens inside the dispatcher's `dispatch()` and `combine()`.
- `ExpertParallel` / `ExpertTensorParallel` now only handle weight sharding + setting `ep_group` on the dispatcher.
- Removed `score_before_experts` from `MoE.Config` (now lives on the dispatcher).

## Motivation

**Previously,** token routing was split across three places:
1. `TokenReorderer` — reorder tokens from token-index to expert-index order
2. `MoE.forward()` — score application, shared_experts, scatter_add
3. `ExpertParallel` input/output hooks — all-to-all dispatch/combine (EP>1 only)

This made it hard to reason about the async overlap pattern (shared_experts should run while combine communication is in flight), and `DeepEPMoE` had to duplicate most of `MoE.forward()`.

**Now,** the dispatcher encapsulates the full lifecycle. Benefits:
- Async overlap is explicit: `combine()` starts async communication, runs `shared_experts`, then forces sync via scatter_add or `sync_combine()`.
- Single place to swap dispatch/combine implementations (NCCL, DeepEP, HybridEP, TorchAO).
- `AllToAllTokenDispatcher.combine()` reuses `LocalTokenDispatcher.combine()` via `super()`, eliminating code duplication.
- `DeepEPMoE.forward()` is no longer needed — the base `MoE.forward()` works for all paths.
- Sequence parallel logic consolidated into `AllToAllTokenDispatcher` — no more `ReordererSequenceParallel` class with `distribute_module` input/output hooks. The dispatcher splits tokens in `dispatch()` and `combine()` when `sp_size > 1`.
- Enables `local_map` usage: single wrapper around `GroupedExperts` (which contains the dispatcher).

## Test Plan
Losses matched under EP=1, EP>1, `--parallelism.expert_parallel_comm_backend=deepep`, and torchao cases.
```
NCCL_NVLS_ENABLE=0 NGPU=8 ./run_train.sh     --module llama4     --config llama4_debugmodel     --parallelism.pipeline_parallel_degree 1     --parallelism.data_parallel_shard_degree 4     --parallelism.tensor_parallel_degree 2     --parallelism.expert_parallel_degree 2     --parallelism.expert_tensor_parallel_degree 2      --metrics.enable_wandb --training.steps 100
```

```
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 2 --parallelism.expert_tensor_parallel_degree 1" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 1 --parallelism.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

cc fegin for parallelism refactor, elfiegg shuhuayu for removing DeepEP MoE.

[ghstack-poisoned]
…orderer"


TODO tracking here #2956
## Summary

Introduce a token dispatcher abstraction (`token_dispatcher.py`) that encapsulates the full token routing lifecycle — dispatch (reorder + optional EP all-to-all) and combine (reverse dispatch + shared_experts overlap + score application + scatter_add).

**Dispatcher hierarchy:**
- `LocalTokenDispatcher` — EP=1, local token reordering only. Base class for all dispatchers.
- `AllToAllTokenDispatcher` — EP>1, adds NCCL all-to-all dispatch/combine. Calls `super().combine()` for shared score+scatter_add logic. Supports sequence parallel via `sp_size` config.
- `TorchAOTokenDispatcher` — EP>1, extends AllToAllTokenDispatcher with `permute_and_pad` for FP8/MXFP8 quantized grouped GEMMs.
- `DeepEPTokenDispatcher` — EP>1, uses DeepEP/HybridEP library kernels instead of standard all-to-all.

**Key changes:**
- `GroupedExperts.forward()` now owns the full dispatch → expert compute → combine pipeline, accepting `shared_experts` to overlap with async combine communication.
- `MoE.forward()` simplified to: router → `self.experts(x, top_scores, indices, shared_experts=self.shared_experts)` → reshape.
- `DeepEPMoE` no longer overrides `forward()` — the dispatcher handles both NCCL and DeepEP paths.
- Removed `TokenReorderer` (folded into dispatchers) and `moe_deepep.py` (folded into dispatchers + simplified `DeepEPMoE`).
- `ReordererSequenceParallel` input/output hooks replaced by `sp_size` config on `AllToAllTokenDispatcher` — sequence parallel token splitting now happens inside the dispatcher's `dispatch()` and `combine()`.
- `ExpertParallel` / `ExpertTensorParallel` now only handle weight sharding + setting `ep_group` on the dispatcher.
- Removed `score_before_experts` from `MoE.Config` (now lives on the dispatcher).

## Motivation

**Previously,** token routing was split across three places:
1. `TokenReorderer` — reorder tokens from token-index to expert-index order
2. `MoE.forward()` — score application, shared_experts, scatter_add
3. `ExpertParallel` input/output hooks — all-to-all dispatch/combine (EP>1 only)

This made it hard to reason about the async overlap pattern (shared_experts should run while combine communication is in flight), and `DeepEPMoE` had to duplicate most of `MoE.forward()`.

**Now,** the dispatcher encapsulates the full lifecycle. Benefits:
- Async overlap is explicit: `combine()` starts async communication, runs `shared_experts`, then forces sync via scatter_add or `sync_combine()`.
- Single place to swap dispatch/combine implementations (NCCL, DeepEP, HybridEP, TorchAO).
- `AllToAllTokenDispatcher.combine()` reuses `LocalTokenDispatcher.combine()` via `super()`, eliminating code duplication.
- `DeepEPMoE.forward()` is no longer needed — the base `MoE.forward()` works for all paths.
- Sequence parallel logic consolidated into `AllToAllTokenDispatcher` — no more `ReordererSequenceParallel` class with `distribute_module` input/output hooks. The dispatcher splits tokens in `dispatch()` and `combine()` when `sp_size > 1`.
- Enables `local_map` usage: single wrapper around `GroupedExperts` (which contains the dispatcher).

## Test Plan
Losses matched under EP=1, EP>1, `--parallelism.expert_parallel_comm_backend=deepep`, and torchao cases.
```
NCCL_NVLS_ENABLE=0 NGPU=8 ./run_train.sh     --module llama4     --config llama4_debugmodel     --parallelism.pipeline_parallel_degree 1     --parallelism.data_parallel_shard_degree 4     --parallelism.tensor_parallel_degree 2     --parallelism.expert_parallel_degree 2     --parallelism.expert_tensor_parallel_degree 2      --metrics.enable_wandb --training.steps 100
```

```
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 2 --parallelism.expert_tensor_parallel_degree 1" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 1 --parallelism.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

cc fegin for parallelism refactor, elfiegg shuhuayu for removing DeepEP MoE.

[ghstack-poisoned]
…replace token reorderer"


TODO tracking here #2956
## Summary

Introduce a token dispatcher abstraction (`token_dispatcher.py`) that encapsulates the full token routing lifecycle — dispatch (reorder + optional EP all-to-all) and combine (reverse dispatch + shared_experts overlap + score application + scatter_add).

**Dispatcher hierarchy:**
- `LocalTokenDispatcher` — EP=1, local token reordering only. Base class for all dispatchers.
- `AllToAllTokenDispatcher` — EP>1, adds NCCL all-to-all dispatch/combine. Calls `super().combine()` for shared score+scatter_add logic. Supports sequence parallel via `sp_size` config.
- `TorchAOTokenDispatcher` — EP>1, extends AllToAllTokenDispatcher with `permute_and_pad` for FP8/MXFP8 quantized grouped GEMMs.
- `DeepEPTokenDispatcher` — EP>1, uses DeepEP/HybridEP library kernels instead of standard all-to-all.

**Key changes:**
- `GroupedExperts.forward()` now owns the full dispatch → expert compute → combine pipeline, accepting `shared_experts` to overlap with async combine communication.
- `MoE.forward()` simplified to: router → `self.experts(x, top_scores, indices, shared_experts=self.shared_experts)` → reshape.
- `DeepEPMoE` no longer overrides `forward()` — the dispatcher handles both NCCL and DeepEP paths.
- Removed `TokenReorderer` (folded into dispatchers) and `moe_deepep.py` (folded into dispatchers + simplified `DeepEPMoE`).
- `ReordererSequenceParallel` input/output hooks replaced by `sp_size` config on `AllToAllTokenDispatcher` — sequence parallel token splitting now happens inside the dispatcher's `dispatch()` and `combine()`.
- `ExpertParallel` / `ExpertTensorParallel` now only handle weight sharding + setting `ep_group` on the dispatcher.
- Removed `score_before_experts` from `MoE.Config` (now lives on the dispatcher).

## Motivation

**Previously,** token routing was split across three places:
1. `TokenReorderer` — reorder tokens from token-index to expert-index order
2. `MoE.forward()` — score application, shared_experts, scatter_add
3. `ExpertParallel` input/output hooks — all-to-all dispatch/combine (EP>1 only)

This made it hard to reason about the async overlap pattern (shared_experts should run while combine communication is in flight), and `DeepEPMoE` had to duplicate most of `MoE.forward()`.

**Now,** the dispatcher encapsulates the full lifecycle. Benefits:
- Async overlap is explicit: `combine()` starts async communication, runs `shared_experts`, then forces sync via scatter_add or `sync_combine()`.
- Single place to swap dispatch/combine implementations (NCCL, DeepEP, HybridEP, TorchAO).
- `AllToAllTokenDispatcher.combine()` reuses `LocalTokenDispatcher.combine()` via `super()`, eliminating code duplication.
- `DeepEPMoE.forward()` is no longer needed — the base `MoE.forward()` works for all paths.
- Sequence parallel logic consolidated into `AllToAllTokenDispatcher` — no more `ReordererSequenceParallel` class with `distribute_module` input/output hooks. The dispatcher splits tokens in `dispatch()` and `combine()` when `sp_size > 1`.
- Enables `local_map` usage: single wrapper around `GroupedExperts` (which contains the dispatcher).

## Test Plan
Losses matched under EP=1, EP>1, `--parallelism.expert_parallel_comm_backend=deepep`, and torchao cases.
```
NCCL_NVLS_ENABLE=0 NGPU=8 ./run_train.sh     --module llama4     --config llama4_debugmodel     --parallelism.pipeline_parallel_degree 1     --parallelism.data_parallel_shard_degree 4     --parallelism.tensor_parallel_degree 2     --parallelism.expert_parallel_degree 2     --parallelism.expert_tensor_parallel_degree 2      --metrics.enable_wandb --training.steps 100
```

```
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 2 --parallelism.expert_tensor_parallel_degree 1" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 1 --parallelism.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

cc fegin for parallelism refactor, elfiegg shuhuayu for removing DeepEP MoE.

[ghstack-poisoned]
…orderer"


TODO tracking here #2956
## Summary

Introduce a token dispatcher abstraction (`token_dispatcher.py`) that encapsulates the full token routing lifecycle — dispatch (reorder + optional EP all-to-all) and combine (reverse dispatch + shared_experts overlap + score application + scatter_add).

**Dispatcher hierarchy:**
- `LocalTokenDispatcher` — EP=1, local token reordering only. Base class for all dispatchers.
- `AllToAllTokenDispatcher` — EP>1, adds NCCL all-to-all dispatch/combine. Calls `super().combine()` for shared score+scatter_add logic. Supports sequence parallel via `sp_size` config.
- `TorchAOTokenDispatcher` — EP>1, extends AllToAllTokenDispatcher with `permute_and_pad` for FP8/MXFP8 quantized grouped GEMMs.
- `DeepEPTokenDispatcher` — EP>1, uses DeepEP/HybridEP library kernels instead of standard all-to-all.

**Key changes:**
- `GroupedExperts.forward()` now owns the full dispatch → expert compute → combine pipeline, accepting `shared_experts` to overlap with async combine communication.
- `MoE.forward()` simplified to: router → `self.experts(x, top_scores, indices, shared_experts=self.shared_experts)` → reshape.
- `DeepEPMoE` no longer overrides `forward()` — the dispatcher handles both NCCL and DeepEP paths.
- Removed `TokenReorderer` (folded into dispatchers) and `moe_deepep.py` (folded into dispatchers + simplified `DeepEPMoE`).
- `ReordererSequenceParallel` input/output hooks replaced by `sp_size` config on `AllToAllTokenDispatcher` — sequence parallel token splitting now happens inside the dispatcher's `dispatch()` and `combine()`.
- `ExpertParallel` / `ExpertTensorParallel` now only handle weight sharding + setting `ep_group` on the dispatcher.
- Removed `score_before_experts` from `MoE.Config` (now lives on the dispatcher).

## Motivation

**Previously,** token routing was split across three places:
1. `TokenReorderer` — reorder tokens from token-index to expert-index order
2. `MoE.forward()` — score application, shared_experts, scatter_add
3. `ExpertParallel` input/output hooks — all-to-all dispatch/combine (EP>1 only)

This made it hard to reason about the async overlap pattern (shared_experts should run while combine communication is in flight), and `DeepEPMoE` had to duplicate most of `MoE.forward()`.

**Now,** the dispatcher encapsulates the full lifecycle. Benefits:
- Async overlap is explicit: `combine()` starts async communication, runs `shared_experts`, then forces sync via scatter_add or `sync_combine()`.
- Single place to swap dispatch/combine implementations (NCCL, DeepEP, HybridEP, TorchAO).
- `AllToAllTokenDispatcher.combine()` reuses `LocalTokenDispatcher.combine()` via `super()`, eliminating code duplication.
- `DeepEPMoE.forward()` is no longer needed — the base `MoE.forward()` works for all paths.
- Sequence parallel logic consolidated into `AllToAllTokenDispatcher` — no more `ReordererSequenceParallel` class with `distribute_module` input/output hooks. The dispatcher splits tokens in `dispatch()` and `combine()` when `sp_size > 1`.
- Enables `local_map` usage: single wrapper around `GroupedExperts` (which contains the dispatcher).

## Test Plan
Losses matched under EP=1, EP>1, `--parallelism.expert_parallel_comm_backend=deepep`, and torchao cases.
```
NCCL_NVLS_ENABLE=0 NGPU=8 ./run_train.sh     --module llama4     --config llama4_debugmodel     --parallelism.pipeline_parallel_degree 1     --parallelism.data_parallel_shard_degree 4     --parallelism.tensor_parallel_degree 2     --parallelism.expert_parallel_degree 2     --parallelism.expert_tensor_parallel_degree 2      --metrics.enable_wandb --training.steps 100
```

```
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 2 --parallelism.expert_tensor_parallel_degree 1" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 1 --parallelism.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

cc fegin for parallelism refactor, elfiegg shuhuayu for removing DeepEP MoE.

[ghstack-poisoned]
return top_scores, selected_experts_indices

def _prepare_output_fn(self, mod, outputs, device_mesh):
# shape (batch_size * seq_len * top_k // ep_degree)

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.

@tianyu-l double check, this comment should be tp_degree right?

I updated the logic here since your last review

, let me know if it makes sense to you.

@fegin fegin 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.

LGTM, all my comments can be addressed in a later PR.

Comment on lines 101 to 104
from torchtitan.models.common.token_dispatcher import (
AllToAllTokenDispatcher,
DeepEPTokenDispatcher,
)

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.

nit: since multiple function use this import, should we move it to module-level import? Claude likes to put the import into local sometimes. But since there multiple usages, I'm wondering if this is a good strategy.

Comment on lines +148 to +153
) -> (
LocalTokenDispatcher.Config
| AllToAllTokenDispatcher.Config
| TorchAOTokenDispatcher.Config
| DeepEPTokenDispatcher.Config
):

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.

nit: lol, this is a bit verbose. Should we have a type alias defined in somewhere?

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.

Just use the base class?

Comment thread torchtitan/models/common/moe.py Outdated
c. combine — starts async EP communication (NCCL all-to-all or DeepEP combine),
runs shared_experts in parallel with the async communication,
then forces sync (scatter_add for NCCL AllToAll, sync_combine for DeepEP)
and produces final output

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.

Maybe add description saying that step a and step c are handled by TokenDispatcher. Also async EP communication is optional (if LocalTokenDispatcher is used).

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.

thanks, modified the comments. Async EP communication is not needed when EP=1.

Also serves as the base class for EP dispatchers (AllToAllTokenDispatcher,
DeepEPTokenDispatcher) which override dispatch() and combine().

Not an nn.Module — dispatchers have no learnable parameters or buffers.

@fegin fegin Apr 17, 2026 •

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.

We may have to make it as a Module because we want to use LocalMap sharding configuration. We can discuss this later.

Please ignore my comment, I confused myself.

self.ep_size = config.ep_size
self.sp_size = config.sp_size
# Set at runtime by ExpertParallel / ExpertTensorParallel._partition_fn()
self.ep_group: dist.ProcessGroup

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.

Probably make it optional and actually check that it is not None before using it. It is safer and matches the reason why we introduce pyrefly.

# Set at runtime by ExpertParallel / ExpertTensorParallel._partition_fn()
self.ep_group: dist.ProcessGroup
# Set at runtime by apply_moe_ep_tp from tp_mesh.get_local_rank()
self.sp_rank: int = 0

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.

Set as -1 and check before using it?

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.

yeah sounds good, better to set default to sth not valid, to make sure it's being properly set when used.

…replace token reorderer"


TODO tracking here #2956
## Summary

Introduce a token dispatcher abstraction (`token_dispatcher.py`) that encapsulates the full token routing lifecycle — dispatch (reorder + optional EP all-to-all) and combine (reverse dispatch + shared_experts overlap + score application + scatter_add).

**Dispatcher hierarchy:**
- `LocalTokenDispatcher` — EP=1, local token reordering only. Base class for all dispatchers.
- `AllToAllTokenDispatcher` — EP>1, adds NCCL all-to-all dispatch/combine. Calls `super().combine()` for shared score+scatter_add logic. Supports sequence parallel via `sp_size` config.
- `TorchAOTokenDispatcher` — EP>1, extends AllToAllTokenDispatcher with `permute_and_pad` for FP8/MXFP8 quantized grouped GEMMs.
- `DeepEPTokenDispatcher` — EP>1, uses DeepEP/HybridEP library kernels instead of standard all-to-all.

**Key changes:**
- `GroupedExperts.forward()` now owns the full dispatch → expert compute → combine pipeline, accepting `shared_experts` to overlap with async combine communication.
- `MoE.forward()` simplified to: router → `self.experts(x, top_scores, indices, shared_experts=self.shared_experts)` → reshape.
- `DeepEPMoE` no longer overrides `forward()` — the dispatcher handles both NCCL and DeepEP paths.
- Removed `TokenReorderer` (folded into dispatchers) and `moe_deepep.py` (folded into dispatchers + simplified `DeepEPMoE`).
- `ReordererSequenceParallel` input/output hooks replaced by `sp_size` config on `AllToAllTokenDispatcher` — sequence parallel token splitting now happens inside the dispatcher's `dispatch()` and `combine()`.
- `ExpertParallel` / `ExpertTensorParallel` now only handle weight sharding + setting `ep_group` on the dispatcher.
- Removed `score_before_experts` from `MoE.Config` (now lives on the dispatcher).

## Motivation

**Previously,** token routing was split across three places:
1. `TokenReorderer` — reorder tokens from token-index to expert-index order
2. `MoE.forward()` — score application, shared_experts, scatter_add
3. `ExpertParallel` input/output hooks — all-to-all dispatch/combine (EP>1 only)

This made it hard to reason about the async overlap pattern (shared_experts should run while combine communication is in flight), and `DeepEPMoE` had to duplicate most of `MoE.forward()`.

**Now,** the dispatcher encapsulates the full lifecycle. Benefits:
- Async overlap is explicit: `combine()` starts async communication, runs `shared_experts`, then forces sync via scatter_add or `sync_combine()`.
- Single place to swap dispatch/combine implementations (NCCL, DeepEP, HybridEP, TorchAO).
- `AllToAllTokenDispatcher.combine()` reuses `LocalTokenDispatcher.combine()` via `super()`, eliminating code duplication.
- `DeepEPMoE.forward()` is no longer needed — the base `MoE.forward()` works for all paths.
- Sequence parallel logic consolidated into `AllToAllTokenDispatcher` — no more `ReordererSequenceParallel` class with `distribute_module` input/output hooks. The dispatcher splits tokens in `dispatch()` and `combine()` when `sp_size > 1`.
- Enables `local_map` usage: single wrapper around `GroupedExperts` (which contains the dispatcher).

## Test Plan
Losses matched under EP=1, EP>1, `--parallelism.expert_parallel_comm_backend=deepep`, and torchao cases.
```
NCCL_NVLS_ENABLE=0 NGPU=8 ./run_train.sh     --module llama4     --config llama4_debugmodel     --parallelism.pipeline_parallel_degree 1     --parallelism.data_parallel_shard_degree 4     --parallelism.tensor_parallel_degree 2     --parallelism.expert_parallel_degree 2     --parallelism.expert_tensor_parallel_degree 2      --metrics.enable_wandb --training.steps 100
```

```
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 2 --parallelism.expert_tensor_parallel_degree 1" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 1 --parallelism.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

cc fegin for parallelism refactor, elfiegg shuhuayu for removing DeepEP MoE.

[ghstack-poisoned]
…orderer"


TODO tracking here #2956
## Summary

Introduce a token dispatcher abstraction (`token_dispatcher.py`) that encapsulates the full token routing lifecycle — dispatch (reorder + optional EP all-to-all) and combine (reverse dispatch + shared_experts overlap + score application + scatter_add).

**Dispatcher hierarchy:**
- `LocalTokenDispatcher` — EP=1, local token reordering only. Base class for all dispatchers.
- `AllToAllTokenDispatcher` — EP>1, adds NCCL all-to-all dispatch/combine. Calls `super().combine()` for shared score+scatter_add logic. Supports sequence parallel via `sp_size` config.
- `TorchAOTokenDispatcher` — EP>1, extends AllToAllTokenDispatcher with `permute_and_pad` for FP8/MXFP8 quantized grouped GEMMs.
- `DeepEPTokenDispatcher` — EP>1, uses DeepEP/HybridEP library kernels instead of standard all-to-all.

**Key changes:**
- `GroupedExperts.forward()` now owns the full dispatch → expert compute → combine pipeline, accepting `shared_experts` to overlap with async combine communication.
- `MoE.forward()` simplified to: router → `self.experts(x, top_scores, indices, shared_experts=self.shared_experts)` → reshape.
- `DeepEPMoE` no longer overrides `forward()` — the dispatcher handles both NCCL and DeepEP paths.
- Removed `TokenReorderer` (folded into dispatchers) and `moe_deepep.py` (folded into dispatchers + simplified `DeepEPMoE`).
- `ReordererSequenceParallel` input/output hooks replaced by `sp_size` config on `AllToAllTokenDispatcher` — sequence parallel token splitting now happens inside the dispatcher's `dispatch()` and `combine()`.
- `ExpertParallel` / `ExpertTensorParallel` now only handle weight sharding + setting `ep_group` on the dispatcher.
- Removed `score_before_experts` from `MoE.Config` (now lives on the dispatcher).

## Motivation

**Previously,** token routing was split across three places:
1. `TokenReorderer` — reorder tokens from token-index to expert-index order
2. `MoE.forward()` — score application, shared_experts, scatter_add
3. `ExpertParallel` input/output hooks — all-to-all dispatch/combine (EP>1 only)

This made it hard to reason about the async overlap pattern (shared_experts should run while combine communication is in flight), and `DeepEPMoE` had to duplicate most of `MoE.forward()`.

**Now,** the dispatcher encapsulates the full lifecycle. Benefits:
- Async overlap is explicit: `combine()` starts async communication, runs `shared_experts`, then forces sync via scatter_add or `sync_combine()`.
- Single place to swap dispatch/combine implementations (NCCL, DeepEP, HybridEP, TorchAO).
- `AllToAllTokenDispatcher.combine()` reuses `LocalTokenDispatcher.combine()` via `super()`, eliminating code duplication.
- `DeepEPMoE.forward()` is no longer needed — the base `MoE.forward()` works for all paths.
- Sequence parallel logic consolidated into `AllToAllTokenDispatcher` — no more `ReordererSequenceParallel` class with `distribute_module` input/output hooks. The dispatcher splits tokens in `dispatch()` and `combine()` when `sp_size > 1`.
- Enables `local_map` usage: single wrapper around `GroupedExperts` (which contains the dispatcher).

## Test Plan
Losses matched under EP=1, EP>1, `--parallelism.expert_parallel_comm_backend=deepep`, and torchao cases.
```
NCCL_NVLS_ENABLE=0 NGPU=8 ./run_train.sh     --module llama4     --config llama4_debugmodel     --parallelism.pipeline_parallel_degree 1     --parallelism.data_parallel_shard_degree 4     --parallelism.tensor_parallel_degree 2     --parallelism.expert_parallel_degree 2     --parallelism.expert_tensor_parallel_degree 2      --metrics.enable_wandb --training.steps 100
```

```
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 2 --parallelism.expert_tensor_parallel_degree 1" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 1 --parallelism.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

cc fegin for parallelism refactor, elfiegg shuhuayu for removing DeepEP MoE.

[ghstack-poisoned]
…replace token reorderer"


TODO tracking here #2956
## Summary

Introduce a token dispatcher abstraction (`token_dispatcher.py`) that encapsulates the full token routing lifecycle — dispatch (reorder + optional EP all-to-all) and combine (reverse dispatch + shared_experts overlap + score application + scatter_add).

**Dispatcher hierarchy:**
- `LocalTokenDispatcher` — EP=1, local token reordering only. Base class for all dispatchers.
- `AllToAllTokenDispatcher` — EP>1, adds NCCL all-to-all dispatch/combine. Calls `super().combine()` for shared score+scatter_add logic. Supports sequence parallel via `sp_size` config.
- `TorchAOTokenDispatcher` — EP>1, extends AllToAllTokenDispatcher with `permute_and_pad` for FP8/MXFP8 quantized grouped GEMMs.
- `DeepEPTokenDispatcher` — EP>1, uses DeepEP/HybridEP library kernels instead of standard all-to-all.

**Key changes:**
- `GroupedExperts.forward()` now owns the full dispatch → expert compute → combine pipeline, accepting `shared_experts` to overlap with async combine communication.
- `MoE.forward()` simplified to: router → `self.experts(x, top_scores, indices, shared_experts=self.shared_experts)` → reshape.
- `DeepEPMoE` no longer overrides `forward()` — the dispatcher handles both NCCL and DeepEP paths.
- Removed `TokenReorderer` (folded into dispatchers) and `moe_deepep.py` (folded into dispatchers + simplified `DeepEPMoE`).
- `ReordererSequenceParallel` input/output hooks replaced by `sp_size` config on `AllToAllTokenDispatcher` — sequence parallel token splitting now happens inside the dispatcher's `dispatch()` and `combine()`.
- `ExpertParallel` / `ExpertTensorParallel` now only handle weight sharding + setting `ep_group` on the dispatcher.
- Removed `score_before_experts` from `MoE.Config` (now lives on the dispatcher).

## Motivation

**Previously,** token routing was split across three places:
1. `TokenReorderer` — reorder tokens from token-index to expert-index order
2. `MoE.forward()` — score application, shared_experts, scatter_add
3. `ExpertParallel` input/output hooks — all-to-all dispatch/combine (EP>1 only)

This made it hard to reason about the async overlap pattern (shared_experts should run while combine communication is in flight), and `DeepEPMoE` had to duplicate most of `MoE.forward()`.

**Now,** the dispatcher encapsulates the full lifecycle. Benefits:
- Async overlap is explicit: `combine()` starts async communication, runs `shared_experts`, then forces sync via scatter_add or `sync_combine()`.
- Single place to swap dispatch/combine implementations (NCCL, DeepEP, HybridEP, TorchAO).
- `AllToAllTokenDispatcher.combine()` reuses `LocalTokenDispatcher.combine()` via `super()`, eliminating code duplication.
- `DeepEPMoE.forward()` is no longer needed — the base `MoE.forward()` works for all paths.
- Sequence parallel logic consolidated into `AllToAllTokenDispatcher` — no more `ReordererSequenceParallel` class with `distribute_module` input/output hooks. The dispatcher splits tokens in `dispatch()` and `combine()` when `sp_size > 1`.
- Enables `local_map` usage: single wrapper around `GroupedExperts` (which contains the dispatcher).

## Test Plan
Losses matched under EP=1, EP>1, `--parallelism.expert_parallel_comm_backend=deepep`, and torchao cases.
```
NCCL_NVLS_ENABLE=0 NGPU=8 ./run_train.sh     --module llama4     --config llama4_debugmodel     --parallelism.pipeline_parallel_degree 1     --parallelism.data_parallel_shard_degree 4     --parallelism.tensor_parallel_degree 2     --parallelism.expert_parallel_degree 2     --parallelism.expert_tensor_parallel_degree 2      --metrics.enable_wandb --training.steps 100
```

```
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 2 --parallelism.expert_tensor_parallel_degree 1" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 1 --parallelism.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

cc fegin for parallelism refactor, elfiegg shuhuayu for removing DeepEP MoE.

[ghstack-poisoned]
…orderer"


TODO tracking here #2956
## Summary

Introduce a token dispatcher abstraction (`token_dispatcher.py`) that encapsulates the full token routing lifecycle — dispatch (reorder + optional EP all-to-all) and combine (reverse dispatch + shared_experts overlap + score application + scatter_add).

**Dispatcher hierarchy:**
- `LocalTokenDispatcher` — EP=1, local token reordering only. Base class for all dispatchers.
- `AllToAllTokenDispatcher` — EP>1, adds NCCL all-to-all dispatch/combine. Calls `super().combine()` for shared score+scatter_add logic. Supports sequence parallel via `sp_size` config.
- `TorchAOTokenDispatcher` — EP>1, extends AllToAllTokenDispatcher with `permute_and_pad` for FP8/MXFP8 quantized grouped GEMMs.
- `DeepEPTokenDispatcher` — EP>1, uses DeepEP/HybridEP library kernels instead of standard all-to-all.

**Key changes:**
- `GroupedExperts.forward()` now owns the full dispatch → expert compute → combine pipeline, accepting `shared_experts` to overlap with async combine communication.
- `MoE.forward()` simplified to: router → `self.experts(x, top_scores, indices, shared_experts=self.shared_experts)` → reshape.
- `DeepEPMoE` no longer overrides `forward()` — the dispatcher handles both NCCL and DeepEP paths.
- Removed `TokenReorderer` (folded into dispatchers) and `moe_deepep.py` (folded into dispatchers + simplified `DeepEPMoE`).
- `ReordererSequenceParallel` input/output hooks replaced by `sp_size` config on `AllToAllTokenDispatcher` — sequence parallel token splitting now happens inside the dispatcher's `dispatch()` and `combine()`.
- `ExpertParallel` / `ExpertTensorParallel` now only handle weight sharding + setting `ep_group` on the dispatcher.
- Removed `score_before_experts` from `MoE.Config` (now lives on the dispatcher).

## Motivation

**Previously,** token routing was split across three places:
1. `TokenReorderer` — reorder tokens from token-index to expert-index order
2. `MoE.forward()` — score application, shared_experts, scatter_add
3. `ExpertParallel` input/output hooks — all-to-all dispatch/combine (EP>1 only)

This made it hard to reason about the async overlap pattern (shared_experts should run while combine communication is in flight), and `DeepEPMoE` had to duplicate most of `MoE.forward()`.

**Now,** the dispatcher encapsulates the full lifecycle. Benefits:
- Async overlap is explicit: `combine()` starts async communication, runs `shared_experts`, then forces sync via scatter_add or `sync_combine()`.
- Single place to swap dispatch/combine implementations (NCCL, DeepEP, HybridEP, TorchAO).
- `AllToAllTokenDispatcher.combine()` reuses `LocalTokenDispatcher.combine()` via `super()`, eliminating code duplication.
- `DeepEPMoE.forward()` is no longer needed — the base `MoE.forward()` works for all paths.
- Sequence parallel logic consolidated into `AllToAllTokenDispatcher` — no more `ReordererSequenceParallel` class with `distribute_module` input/output hooks. The dispatcher splits tokens in `dispatch()` and `combine()` when `sp_size > 1`.
- Enables `local_map` usage: single wrapper around `GroupedExperts` (which contains the dispatcher).

## Test Plan
Losses matched under EP=1, EP>1, `--parallelism.expert_parallel_comm_backend=deepep`, and torchao cases.
```
NCCL_NVLS_ENABLE=0 NGPU=8 ./run_train.sh     --module llama4     --config llama4_debugmodel     --parallelism.pipeline_parallel_degree 1     --parallelism.data_parallel_shard_degree 4     --parallelism.tensor_parallel_degree 2     --parallelism.expert_parallel_degree 2     --parallelism.expert_tensor_parallel_degree 2      --metrics.enable_wandb --training.steps 100
```

```
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 2 --parallelism.expert_tensor_parallel_degree 1" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 1 --parallelism.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

cc fegin for parallelism refactor, elfiegg shuhuayu for removing DeepEP MoE.

[ghstack-poisoned]
@acisseJZhong
acisseJZhong changed the base branch from gh/acisseJZhong/6/base to main April 17, 2026 23:12
@acisseJZhong
acisseJZhong merged commit 09ea7d8 into main Apr 17, 2026
11 of 15 checks passed
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Apr 18, 2026
Replay upstream changes from PRs pytorch#2878 (fused QKV) and pytorch#2842/pytorch#2960
(attention backend abstraction) onto the ezpz agpt experiment:

- Replace inner_attention/mask_type params with attn_backend string
  and fuse_qkv bool in _build_agpt_layers and _build_agpt_config
- Add _ezpz_get_attention_config() that overrides the sdpa case with
  XPU-aware EzpzScaledDotProductAttention, delegates others to upstream
- Remove deepcopy-based _apply_flex_attn/_apply_varlen_attn overlays;
  configs now specify attn_backend directly
- Add FusedQKVLinear detection and branching TP plan in parallelize.py
- Pass fuse_qkv through to make_gqa_config()
- Preserve all XPU customizations (SDPA workaround, Megatron init,
  capture_scalar_outputs fix)
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Apr 18, 2026
Replay upstream changes from PRs pytorch#2842 (token dispatcher) and pytorch#2960
(EP config refactor) onto the ezpz MoE experiment:

- Replace inner_attention/mask_type with attn_backend string in
  _make_moe_attn_config and _build_moe_layers
- Update make_moe_config calls: remove score_before_experts (moved to
  token dispatcher)
- Update make_experts_config calls: add top_k and score_before_experts
  params (now passed through to token dispatcher config)
- Remove DeepEPExpertParallel and ReordererSequenceParallel imports
  (removed upstream; token dispatching now handled internally)
- Preserve XPU SDPA variant (_10b_2b_sdpa) and _default_inner_attention
mreso added a commit to mreso/torchtitan that referenced this pull request Apr 21, 2026
Two post-merge fixups so the experiment runs again:
- parallelize.py: BaseExpertParallel was removed in pytorch#2842 (token dispatcher
  refactor). Replace with ParallelStyle directly — HFExpertParallel
  implements its own _partition_fn/_token_dispatch/_token_combine/_apply
  and doesn't follow the new token_dispatcher API.
- config_registry.py: rename two stale ProfilingConfig(...) call sites to
  Profiler.Config(...) (the other two were renamed by auto-merge; these
  belong to MoE configs added on the branch and were missed).
mreso added a commit to mreso/torchtitan that referenced this pull request Apr 22, 2026
Mirrors the ExpertParallel/dispatcher split in main (PR pytorch#2842):
HFExpertParallel becomes a thin ParallelStyle that shards expert
weights and sets ep_group on a dispatcher attached to the experts
module. All all-to-all dispatch/combine logic moves to a new
HFTokenDispatcher that subclasses LocalTokenDispatcher and overrides
dispatch/combine with # pyrefly: ignore [bad-override] (same pattern
as DeepEPTokenDispatcher).

The dispatcher is attached to the experts module in apply_moe_ep_tp
just before parallelize_module — native models do the equivalent in
GroupedExperts.__init__, but we can't modify HF's experts module.

Verified bit-exact loss/grad_norm with --debug.seed=42 --debug.deterministic
on EP=2 and TP=2+EP=2 MoE configs.
acisseJZhong added a commit that referenced this pull request Apr 29, 2026
Stacked on #3125

## Summary

Removes expert tensor parallelism (ETP). With the trend toward fine-grained experts, sharding already-skinny expert weights with TP is impractical — the shapes become too small for efficient GEMMs. Additionally, when ETP>1 all TP ranks within the same EP group perform redundant all-to-all communication, wasting bandwidth (see [discussion](#2842 (comment))). 

This removes the `ExpertTensorParallel` classes, the `etp` mesh axis, the `expert_tensor_parallel_degree` / `expert_parallel_comm_backend` config fields, and all ETP references across models and experiments.

## Test plan
- [ ] `pre-commit run --all-files` passes
- [ ] Existing EP integration tests pass (ETP=1 was the common config, which is now the only path)

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 29, 2026
Stacked on #3125

## Summary

Removes expert tensor parallelism (ETP). With the trend toward fine-grained experts, sharding already-skinny expert weights with TP is impractical — the shapes become too small for efficient GEMMs. Additionally, when ETP>1 all TP ranks within the same EP group perform redundant all-to-all communication, wasting bandwidth (see [discussion](#2842 (comment))). 

This removes the `ExpertTensorParallel` classes, the `etp` mesh axis, the `expert_tensor_parallel_degree` / `expert_parallel_comm_backend` config fields, and all ETP references across models and experiments.

## Test plan
- [ ] `pre-commit run --all-files` passes
- [ ] Existing EP integration tests pass (ETP=1 was the common config, which is now the only path)

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 30, 2026
Stacked on #3125

## Summary

Removes expert tensor parallelism (ETP). With the trend toward fine-grained experts, sharding already-skinny expert weights with TP is impractical — the shapes become too small for efficient GEMMs. Additionally, when ETP>1 all TP ranks within the same EP group perform redundant all-to-all communication, wasting bandwidth (see [discussion](#2842 (comment))). 

This removes the `ExpertTensorParallel` classes, the `etp` mesh axis, the `expert_tensor_parallel_degree` / `expert_parallel_comm_backend` config fields, and all ETP references across models and experiments.

## Test plan
- [ ] `pre-commit run --all-files` passes
```
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 2" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 1 --parallelism.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 30, 2026
Stacked on #3125

## Summary

Removes expert tensor parallelism (ETP). With the trend toward fine-grained experts, sharding already-skinny expert weights with TP is impractical — the shapes become too small for efficient GEMMs. Additionally, when ETP>1 all TP ranks within the same EP group perform redundant all-to-all communication, wasting bandwidth (see [discussion](#2842 (comment))). 

This removes the `ExpertTensorParallel` classes, the `etp` mesh axis, the `expert_tensor_parallel_degree` / `expert_parallel_comm_backend` config fields, and all ETP references across models and experiments.

## Test plan
- [ ] `pre-commit run --all-files` passes
```
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 2" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 1 --parallelism.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 30, 2026
Stacked on #3125

## Summary

Removes expert tensor parallelism (ETP). With the trend toward fine-grained experts, sharding already-skinny expert weights with TP is impractical — the shapes become too small for efficient GEMMs. Additionally, when ETP>1 all TP ranks within the same EP group perform redundant all-to-all communication, wasting bandwidth (see [discussion](#2842 (comment))). 

This removes the `ExpertTensorParallel` classes, the `etp` mesh axis, the `expert_tensor_parallel_degree` / `expert_parallel_comm_backend` config fields, and all ETP references across models and experiments.

## Test plan
- [ ] `pre-commit run --all-files` passes
```
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 2" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 1 --parallelism.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 30, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack) (oldest at
bottom):
* __->__ #3167

Stacked on #3125

## Summary

Removes expert tensor parallelism (ETP). With the trend toward
fine-grained experts, sharding already-skinny expert weights with TP is
impractical — the shapes become too small for efficient GEMMs.
Additionally, when ETP>1 all TP ranks within the same EP group perform
redundant all-to-all communication, wasting bandwidth (see
[discussion](#2842 (comment))).

This removes the `ExpertTensorParallel` classes, the `etp` mesh axis,
the `expert_tensor_parallel_degree` / `expert_parallel_comm_backend`
config fields, and all ETP references across models and experiments.

## Test plan
- [ ] `pre-commit run --all-files` passes
```
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 2" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 1 --parallelism.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```
saforem2 pushed a commit to saforem2/torchtitan that referenced this pull request Apr 30, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack) (oldest at
bottom):
* __->__ pytorch#3167

Stacked on pytorch#3125

## Summary

Removes expert tensor parallelism (ETP). With the trend toward
fine-grained experts, sharding already-skinny expert weights with TP is
impractical — the shapes become too small for efficient GEMMs.
Additionally, when ETP>1 all TP ranks within the same EP group perform
redundant all-to-all communication, wasting bandwidth (see
[discussion](pytorch#2842 (comment))).

This removes the `ExpertTensorParallel` classes, the `etp` mesh axis,
the `expert_tensor_parallel_degree` / `expert_parallel_comm_backend`
config fields, and all ETP references across models and experiments.

## Test plan
- [ ] `pre-commit run --all-files` passes
```
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 2" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 1 --parallelism.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```
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.

4 participants