Skip to content

[MoE][2/n]Move EP setup from trainer to config registry and add model_registry params - #2960

Merged
acisseJZhong merged 114 commits into
mainfrom
gh/acisseJZhong/7/head
Apr 18, 2026
Merged

acisseJZhong merged 114 commits into
mainfrom
gh/acisseJZhong/7/head

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Apr 14, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary

Move EP-aware token dispatcher setup from runtime (apply_ep() in Trainer.__post_init__) to config time (model_registry(moe_comm_backend=...)), so config registries build the correct dispatcher upfront.

  • Remove apply_ep() from trainer — Delete the apply_ep() call in Trainer.__post_init__ and the function itself from config_utils.py. Config registries now pass moe_comm_backend directly to model_registry() → make_experts_config() → make_token_dispatcher_config().
  • Simplify make_token_dispatcher_config() — Replace ep_size/sp_size/comm_backend/pad_multiple/hybridep_non_blocking_expert_capacity_factor params with a single moe_comm_backend string ("local", "standard", "torchao", "deepep", "hybridep").
  • Remove ep_size from dispatcher Configs — AllToAllTokenDispatcher, TorchAOTokenDispatcher, and DeepEPTokenDispatcher no longer store ep_size; derived at runtime from ep_group.size(). sp_size and pad_multiple similarly moved to runtime-set attributes.
  • Add get_attention_config() helper — Centralizes attn_backend → (inner_attention, mask_type) mapping, replacing duplicated logic across model families.
  • Add model_registry(moe_comm_backend=...) to all models — llama3, llama4, deepseek_v3, qwen3, qwen3_vl, gpt_oss all accept moe_comm_backend to select the dispatcher at config time.

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[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]
## 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]
## 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]
## 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]
…replace token reorderer"


## Summary
                                                                 
- Introduce LocalTokenDispatcher (EP=1), TokenDispatcher (EP>1), DeepEPTokenDispatcher 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).

## Test
```
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 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2 --parallelism.e
xpert_tensor_parallel_degree 2" --baseline-ngpus=4 --test-module=
'llama4' --test-config='llama4_debugmodel' --test-options="--para
llelism.pipeline_parallel_degree 1 --parallelism.data_parallel_sh
ard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism
.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_de
gree 2" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
…orderer"


## Summary
                                                                 
- Introduce LocalTokenDispatcher (EP=1), TokenDispatcher (EP>1), DeepEPTokenDispatcher 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).

## Test
```
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 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2 --parallelism.e
xpert_tensor_parallel_degree 2" --baseline-ngpus=4 --test-module=
'llama4' --test-config='llama4_debugmodel' --test-options="--para
llelism.pipeline_parallel_degree 1 --parallelism.data_parallel_sh
ard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism
.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_de
gree 2" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
…replace token reorderer"


## Summary
                                                                 
- Introduce LocalTokenDispatcher (EP=1), TokenDispatcher (EP>1), DeepEPTokenDispatcher 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).

## Test
```
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 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2 --parallelism.e
xpert_tensor_parallel_degree 2" --baseline-ngpus=4 --test-module=
'llama4' --test-config='llama4_debugmodel' --test-options="--para
llelism.pipeline_parallel_degree 1 --parallelism.data_parallel_sh
ard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism
.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_de
gree 2" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
…orderer"


## Summary
                                                                 
- Introduce LocalTokenDispatcher (EP=1), TokenDispatcher (EP>1), DeepEPTokenDispatcher 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).

## Test
```
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 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2 --parallelism.e
xpert_tensor_parallel_degree 2" --baseline-ngpus=4 --test-module=
'llama4' --test-config='llama4_debugmodel' --test-options="--para
llelism.pipeline_parallel_degree 1 --parallelism.data_parallel_sh
ard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism
.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_de
gree 2" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
…replace token reorderer"


## Summary
                                                                 
- Introduce LocalTokenDispatcher (EP=1), TokenDispatcher (EP>1), DeepEPTokenDispatcher 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).

## Test
```
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 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2 --parallelism.e
xpert_tensor_parallel_degree 2" --baseline-ngpus=4 --test-module=
'llama4' --test-config='llama4_debugmodel' --test-options="--para
llelism.pipeline_parallel_degree 1 --parallelism.data_parallel_sh
ard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism
.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_de
gree 2" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
…orderer"


## Summary
                                                                 
- Introduce LocalTokenDispatcher (EP=1), TokenDispatcher (EP>1), DeepEPTokenDispatcher 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).

## Test
```
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 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2 --parallelism.e
xpert_tensor_parallel_degree 2" --baseline-ngpus=4 --test-module=
'llama4' --test-config='llama4_debugmodel' --test-options="--para
llelism.pipeline_parallel_degree 1 --parallelism.data_parallel_sh
ard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism
.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_de
gree 2" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
…replace token reorderer"


## Summary
                                                                 
- Introduce LocalTokenDispatcher (EP=1), TokenDispatcher (EP>1), DeepEPTokenDispatcher 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).

## Test
```
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 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2 --parallelism.e
xpert_tensor_parallel_degree 2" --baseline-ngpus=4 --test-module=
'llama4' --test-config='llama4_debugmodel' --test-options="--para
llelism.pipeline_parallel_degree 1 --parallelism.data_parallel_sh
ard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism
.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_de
gree 2" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
…orderer"


## Summary
                                                                 
- Introduce LocalTokenDispatcher (EP=1), TokenDispatcher (EP>1), DeepEPTokenDispatcher 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).

## Test
```
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 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2 --parallelism.e
xpert_tensor_parallel_degree 2" --baseline-ngpus=4 --test-module=
'llama4' --test-config='llama4_debugmodel' --test-options="--para
llelism.pipeline_parallel_degree 1 --parallelism.data_parallel_sh
ard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism
.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_de
gree 2" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
…replace token reorderer"


## Summary
                                                                 
- Introduce LocalTokenDispatcher (EP=1), TokenDispatcher (EP>1), DeepEPTokenDispatcher 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).

## Test
```
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 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2 --parallelism.e
xpert_tensor_parallel_degree 2" --baseline-ngpus=4 --test-module=
'llama4' --test-config='llama4_debugmodel' --test-options="--para
llelism.pipeline_parallel_degree 1 --parallelism.data_parallel_sh
ard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism
.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_de
gree 2" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
…orderer"


## Summary
                                                                 
- Introduce LocalTokenDispatcher (EP=1), TokenDispatcher (EP>1), DeepEPTokenDispatcher 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).

## Test
```
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 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2 --parallelism.e
xpert_tensor_parallel_degree 2" --baseline-ngpus=4 --test-module=
'llama4' --test-config='llama4_debugmodel' --test-options="--para
llelism.pipeline_parallel_degree 1 --parallelism.data_parallel_sh
ard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism
.expert_parallel_degree 2 --parallelism.expert_tensor_parallel_de
gree 2" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
…replace token reorderer"


## Summary
                                                                 
Introduce LocalTokenDispatcher (EP=1), TokenDispatcher (EP>1), DeepEPTokenDispatcher, TorchAoTokenDispatcher 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).

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

[ghstack-poisoned]
…orderer"


## Summary
                                                                 
Introduce LocalTokenDispatcher (EP=1), TokenDispatcher (EP>1), DeepEPTokenDispatcher, TorchAoTokenDispatcher 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).

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

[ghstack-poisoned]
…replace token reorderer"


## Summary
                                                                 
Introduce LocalTokenDispatcher (EP=1), TokenDispatcher (EP>1), DeepEPTokenDispatcher, TorchAoTokenDispatcher 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).

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

[ghstack-poisoned]
…orderer"


## Summary
                                                                 
Introduce LocalTokenDispatcher (EP=1), TokenDispatcher (EP>1), DeepEPTokenDispatcher, TorchAoTokenDispatcher 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).

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

[ghstack-poisoned]
…replace token reorderer"


## Summary
                                                                 
Introduce LocalTokenDispatcher (EP=1), TokenDispatcher (EP>1), DeepEPTokenDispatcher, TorchAoTokenDispatcher 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).

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

[ghstack-poisoned]
…orderer"


## Summary
                                                                 
Introduce LocalTokenDispatcher (EP=1), TokenDispatcher (EP>1), DeepEPTokenDispatcher, TorchAoTokenDispatcher 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).

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

[ghstack-poisoned]
@acisseJZhong
acisseJZhong force-pushed the gh/acisseJZhong/7/head branch 2 times, most recently from 539ef7a to 2940bbf Compare April 17, 2026 23:41
@acisseJZhong
acisseJZhong force-pushed the gh/acisseJZhong/7/head branch from 2940bbf to 4a226aa Compare April 18, 2026 00:30
@acisseJZhong

acisseJZhong commented Apr 18, 2026 •

Copy link
Copy Markdown
Contributor Author

for the graph trainer test: running pytest torchtitan/experiments/graph_trainer/tests/test_bitwise_deterministic.py::TestLlama3BitwiseDeterministic::test_eager_self_deterministic -v before MoE rewrite commit have the same error.

for 8gpu model tests, failing with some cublas error which is likely caused by OOM. I don't think it's related to this PR(my local run is passing on 8 h100 gpus), it's failing on other commits as well. https://github.com/pytorch/torchtitan/actions/workflows/integration_test_8gpu_models.yaml

bypassing the two failed to tests to land.

@acisseJZhong
acisseJZhong merged commit 7cec166 into main Apr 18, 2026
23 of 30 checks passed
@tianyu-l
tianyu-l deleted the gh/acisseJZhong/7/head branch April 18, 2026 05:47
@tianyu-l

Copy link
Copy Markdown
Contributor

@acisseJZhong can we create issues to track CI failure? The model one sounds concerning.

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
acisseJZhong added a commit that referenced this pull request Apr 20, 2026
## Summary

Apply quantization converters on model configs instead of on built models.

Previously, the trainer built the model first, then walked the entire module tree to swap `nn.Linear` with `Float8Linear`. This required a save/restore dance (`capture_module_attrs` / `inject_module_protocol` / `verify_module_protocol`) because `Float8Linear.from_float` creates new module instances, losing `_param_init` and the `Linear`/`Module` protocol.

Now, converters inject a `_convert_fn` into matching configs before `build()`. Each module is converted immediately after construction inside `Module.Config.build()`, which controls the full sequence: create → convert → transfer `_param_init`. Since conversion happens *during* build rather than *after*, the external save/restore is no longer needed — `build()` holds `_param_init` across the conversion inline.

Addresses #2960 (comment) (but not #2981).

**Changes:**
- Add `Configurable.Config.walk()` — generic config tree traversal yielding `(fqn, config)` pairs
- Add `Module.Config._convert_fn` — optional callback applied in `build()` after construction
- Add `ModelConverter.convert_config()` — config-level conversion interface
- `Float8LinearConverter` / `Float8GroupedMMConverter` / `MXFP8Converter`: conversion logic moved from `convert(model)` to `convert_config(model_config)`
- `module_filter_fn` now accepts `Linear.Config` in addition to `nn.Module`
- Trainer calls `convert_config(model_config)` before `build()`, then `convert(model)` for any remaining model-level converters
- `TorchAOTokenDispatcher` selection moved from `make_token_dispatcher_config` to the quantization converters' `convert_config()`, so the model config always uses standard `AllToAllTokenDispatcher` and the converter swaps it when needed

## Test plan
- [ ] `pytest tests/unit_tests/test_model_converter.py` — passes
- [ ] `pytest tests/unit_tests/test_linear.py` — passes
- [ ] Full unit test suite (219 passed, 0 new failures)
- [ ] Verify float8 training produces identical loss with `--debug.seed=42 --debug.deterministic` before vs after

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 20, 2026
## Summary

Apply quantization converters on model configs instead of on built models.

Previously, the trainer built the model first, then walked the entire module tree to swap `nn.Linear` with `Float8Linear`. This required a save/restore dance (`capture_module_attrs` / `inject_module_protocol` / `verify_module_protocol`) because `Float8Linear.from_float` creates new module instances, losing `_param_init` and the `Linear`/`Module` protocol.

Now, converters inject a `_convert_fn` into matching configs before `build()`. Each module is converted immediately after construction inside `Module.Config.build()`, which controls the full sequence: create → convert → transfer `_param_init`. Since conversion happens *during* build rather than *after*, the external save/restore is no longer needed — `build()` holds `_param_init` across the conversion inline.

Addresses #2960 (comment) (but not #2981).

**Changes:**
- Add `Configurable.Config.walk()` — generic config tree traversal yielding `(fqn, config)` pairs
- Add `Module.Config._convert_fn` — optional callback applied in `build()` after construction
- Add `ModelConverter.convert_config()` — config-level conversion interface
- `Float8LinearConverter` / `Float8GroupedMMConverter` / `MXFP8Converter`: conversion logic moved from `convert(model)` to `convert_config(model_config)`
- `module_filter_fn` now accepts `Linear.Config` in addition to `nn.Module`
- Trainer calls `convert_config(model_config)` before `build()`, then `convert(model)` for any remaining model-level converters
- `TorchAOTokenDispatcher` selection moved from `make_token_dispatcher_config` to the quantization converters' `convert_config()`, so the model config always uses standard `AllToAllTokenDispatcher` and the converter swaps it when needed

## Test plan
- [ ] `pytest tests/unit_tests/test_model_converter.py` — passes
- [ ] `pytest tests/unit_tests/test_linear.py` — passes
- [ ] Full unit test suite (219 passed, 0 new failures)
- [ ] Verify float8 training produces identical loss with `--debug.seed=42 --debug.deterministic` before vs after

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 20, 2026
## Summary

Apply quantization converters on model configs instead of on built models.

Previously, the trainer built the model first, then walked the entire module tree to swap `nn.Linear` with `Float8Linear`. This required a save/restore dance (`capture_module_attrs` / `inject_module_protocol` / `verify_module_protocol`) because `Float8Linear.from_float` creates new module instances, losing `_param_init` and the `Linear`/`Module` protocol.

Now, converters inject a `_convert_fn` into matching configs before `build()`. Each module is converted immediately after construction inside `Module.Config.build()`, which controls the full sequence: create → convert → transfer `_param_init`. Since conversion happens *during* build rather than *after*, the external save/restore is no longer needed — `build()` holds `_param_init` across the conversion inline.

Addresses #2960 (comment) (but not #2981).

**Changes:**
- Add `Configurable.Config.walk()` — generic config tree traversal yielding `(fqn, config)` pairs
- Add `Module.Config._convert_fn` — optional callback applied in `build()` after construction
- Add `ModelConverter.convert_config()` — config-level conversion interface
- `Float8LinearConverter` / `Float8GroupedMMConverter` / `MXFP8Converter`: conversion logic moved from `convert(model)` to `convert_config(model_config)`
- `module_filter_fn` now accepts `Linear.Config` in addition to `nn.Module`
- Trainer calls `convert_config(model_config)` before `build()`, then `convert(model)` for any remaining model-level converters
- `TorchAOTokenDispatcher` selection moved from `make_token_dispatcher_config` to the quantization converters' `convert_config()`, so the model config always uses standard `AllToAllTokenDispatcher` and the converter swaps it when needed

## Test plan
- [ ] `pytest tests/unit_tests/test_model_converter.py` — passes
- [ ] `pytest tests/unit_tests/test_linear.py` — passes
- [ ] Full unit test suite (219 passed, 0 new failures)
- [ ] Verify float8 training produces identical loss with `--debug.seed=42 --debug.deterministic` before vs after

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 20, 2026
## Summary

Apply quantization converters on model configs instead of on built models.

Previously, the trainer built the model first, then walked the entire module tree to swap `nn.Linear` with `Float8Linear`. This required a save/restore dance (`capture_module_attrs` / `inject_module_protocol` / `verify_module_protocol`) because `Float8Linear.from_float` creates new module instances, losing `_param_init` and the `Linear`/`Module` protocol.

Now, converters inject a `_convert_fn` into matching configs before `build()`. Each module is converted immediately after construction inside `Module.Config.build()`, which controls the full sequence: create → convert → transfer `_param_init`. Since conversion happens *during* build rather than *after*, the external save/restore is no longer needed — `build()` holds `_param_init` across the conversion inline.

Addresses #2960 (comment) (but not #2981).

**Changes:**
- Add `Configurable.Config.walk()` — generic config tree traversal yielding `(fqn, config)` pairs
- Add `Module.Config._convert_fn` — optional callback applied in `build()` after construction
- Add `ModelConverter.convert_config()` — config-level conversion interface
- `Float8LinearConverter` / `Float8GroupedMMConverter` / `MXFP8Converter`: conversion logic moved from `convert(model)` to `convert_config(model_config)`
- `module_filter_fn` now accepts `Linear.Config` in addition to `nn.Module`
- Trainer calls `convert_config(model_config)` before `build()`, then `convert(model)` for any remaining model-level converters
- `TorchAOTokenDispatcher` selection moved from `make_token_dispatcher_config` to the quantization converters' `convert_config()`, so the model config always uses standard `AllToAllTokenDispatcher` and the converter swaps it when needed

## Test plan
- [ ] `pytest tests/unit_tests/test_model_converter.py` — passes
- [ ] `pytest tests/unit_tests/test_linear.py` — passes
- [ ] Full unit test suite (219 passed, 0 new failures)
- [ ] Verify float8 training produces identical loss with `--debug.seed=42 --debug.deterministic` before vs after

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 21, 2026
…et pad_multiple during config time"

## Summary

Apply quantization converters on model configs instead of on built models.

Previously, the trainer built the model first, then walked the entire module tree to swap `nn.Linear` with `Float8Linear`. This required a save/restore dance (`capture_module_attrs` / `inject_module_protocol` / `verify_module_protocol`) because `Float8Linear.from_float` creates new module instances, losing `_param_init` and the `Linear`/`Module` protocol.

Now, converters inject a `_convert_fn` into matching configs before `build()`. Each module is converted immediately after construction inside `Module.Config.build()`, which controls the full sequence: create → convert → transfer `_param_init`. Since conversion happens *during* build rather than *after*, the external save/restore is no longer needed — `build()` holds `_param_init` across the conversion inline.

Addresses #2960 (comment) (but not #2981).

**Changes:**
- Add `Configurable.Config.walk()` — generic config tree traversal yielding `(fqn, config)` pairs, the config-level equivalent of `swap_linear_layers`
- Add `Module.Config._convert_fn` — optional callback applied in `build()` after construction
- Add `ModelConverter.convert_config()` — config-level conversion interface
- `Float8LinearConverter` / `Float8GroupedMMConverter` / `MXFP8Converter`: conversion logic moved from `convert(model)` to `convert_config(model_config)`
- `module_filter_fn` now accepts `Linear.Config` in addition to `nn.Module`
- Trainer calls `convert_config(model_config)` before `build()`, then `convert(model)` for any remaining model-level converters
- Token dispatcher: converters now swap `AllToAllTokenDispatcher` → `TorchAOTokenDispatcher` and set `pad_multiple` on `DeepEPTokenDispatcher` (hybridep) at config time, with validation that regular deepep does not support `pad_multiple`
- `TorchAOTokenDispatcher.Config` now has `pad_multiple: int` field; `DeepEPTokenDispatcher.Config` has `pad_multiple: int | None = None`

## Test plan
- [x] `pytest tests/unit_tests/test_model_converter.py` — passes
- [x] `pytest tests/unit_tests/test_linear.py` — passes
- [x] Full unit test suite (219 passed, 0 new failures)
- [x] Verify float8 training produces identical loss before vs after:
```
NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama3' --baseline-config='llama3_debugmodel_float8' --baseline-ngpus=8 --test-module='llama3' --test-config='llama3_debugmodel_float8' --test-ngpus=8 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 21, 2026
…during config time"

## Summary

Apply quantization converters on model configs instead of on built models.

Previously, the trainer built the model first, then walked the entire module tree to swap `nn.Linear` with `Float8Linear`. This required a save/restore dance (`capture_module_attrs` / `inject_module_protocol` / `verify_module_protocol`) because `Float8Linear.from_float` creates new module instances, losing `_param_init` and the `Linear`/`Module` protocol.

Now, converters inject a `_convert_fn` into matching configs before `build()`. Each module is converted immediately after construction inside `Module.Config.build()`, which controls the full sequence: create → convert → transfer `_param_init`. Since conversion happens *during* build rather than *after*, the external save/restore is no longer needed — `build()` holds `_param_init` across the conversion inline.

Addresses #2960 (comment) (but not #2981).

**Changes:**
- Add `Configurable.Config.walk()` — generic config tree traversal yielding `(fqn, config)` pairs, the config-level equivalent of `swap_linear_layers`
- Add `Module.Config._convert_fn` — optional callback applied in `build()` after construction
- Add `ModelConverter.convert_config()` — config-level conversion interface
- `Float8LinearConverter` / `Float8GroupedMMConverter` / `MXFP8Converter`: conversion logic moved from `convert(model)` to `convert_config(model_config)`
- `module_filter_fn` now accepts `Linear.Config` in addition to `nn.Module`
- Trainer calls `convert_config(model_config)` before `build()`, then `convert(model)` for any remaining model-level converters
- Token dispatcher: converters now swap `AllToAllTokenDispatcher` → `TorchAOTokenDispatcher` and set `pad_multiple` on `DeepEPTokenDispatcher` (hybridep) at config time, with validation that regular deepep does not support `pad_multiple`
- `TorchAOTokenDispatcher.Config` now has `pad_multiple: int` field; `DeepEPTokenDispatcher.Config` has `pad_multiple: int | None = None`

## Test plan
- [x] `pytest tests/unit_tests/test_model_converter.py` — passes
- [x] `pytest tests/unit_tests/test_linear.py` — passes
- [x] Full unit test suite (219 passed, 0 new failures)
- [x] Verify float8 training produces identical loss before vs after:
```
NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama3' --baseline-config='llama3_debugmodel_float8' --baseline-ngpus=8 --test-module='llama3' --test-config='llama3_debugmodel_float8' --test-ngpus=8 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 21, 2026
…et pad_multiple during config time"

## Summary

Move `pad_multiple` from runtime assignment to config time, and have quantization converters handle `TorchAOTokenDispatcher` selection.

Previously, `pad_multiple` was set at runtime by `apply_moe_ep_tp` in the parallelize code, and `TorchAOTokenDispatcher` was selected at config construction time in `make_token_dispatcher_config`. Now both are handled by the quantization converters in `convert_config()`:

- Converters swap `AllToAllTokenDispatcher.Config` → `TorchAOTokenDispatcher.Config` with the correct `pad_multiple` (16 for FP8, 32 for MXFP8)
- Converters set `pad_multiple` on `DeepEPTokenDispatcher.Config` for hybridep, with validation that regular deepep does not support `pad_multiple`

This removes the need for parallelize code to know about quantization padding requirements.

Addresses #2960 (comment).

**Changes:**
- `TorchAOTokenDispatcher.Config`: add `pad_multiple: int` field, read in `__init__` (resolves the TODO)
- `DeepEPTokenDispatcher.Config`: add `pad_multiple: int | None = None` field, read in `__init__`
- `Float8GroupedMMConverter.convert_config()` / `MXFP8Converter.convert_config()`: swap token dispatcher config and set `pad_multiple`
- Validation: raise `ValueError` if `comm_backend == "deepep"` with quantized grouped GEMMs (deepep does not support `pad_multiple`)

## Test plan
- [ ] `pytest tests/unit_tests/test_model_converter.py`
- [ ] `pytest tests/unit_tests/test_linear.py`
- [ ] Full unit test suite (219 passed, 0 new failures)
- [ ] Verify float8 training produces identical loss before vs after:
```
NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama3' --baseline-config='llama3_debugmodel_float8' --baseline-ngpus=8 --test-module='llama3' --test-config='llama3_debugmodel_float8' --test-ngpus=8 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 21, 2026
…during config time"

## Summary

Move `pad_multiple` from runtime assignment to config time, and have quantization converters handle `TorchAOTokenDispatcher` selection.

Previously, `pad_multiple` was set at runtime by `apply_moe_ep_tp` in the parallelize code, and `TorchAOTokenDispatcher` was selected at config construction time in `make_token_dispatcher_config`. Now both are handled by the quantization converters in `convert_config()`:

- Converters swap `AllToAllTokenDispatcher.Config` → `TorchAOTokenDispatcher.Config` with the correct `pad_multiple` (16 for FP8, 32 for MXFP8)
- Converters set `pad_multiple` on `DeepEPTokenDispatcher.Config` for hybridep, with validation that regular deepep does not support `pad_multiple`

This removes the need for parallelize code to know about quantization padding requirements.

Addresses #2960 (comment).

**Changes:**
- `TorchAOTokenDispatcher.Config`: add `pad_multiple: int` field, read in `__init__` (resolves the TODO)
- `DeepEPTokenDispatcher.Config`: add `pad_multiple: int | None = None` field, read in `__init__`
- `Float8GroupedMMConverter.convert_config()` / `MXFP8Converter.convert_config()`: swap token dispatcher config and set `pad_multiple`
- Validation: raise `ValueError` if `comm_backend == "deepep"` with quantized grouped GEMMs (deepep does not support `pad_multiple`)

## Test plan
- [ ] `pytest tests/unit_tests/test_model_converter.py`
- [ ] `pytest tests/unit_tests/test_linear.py`
- [ ] Full unit test suite (219 passed, 0 new failures)
- [ ] Verify float8 training produces identical loss before vs after:
```
NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama3' --baseline-config='llama3_debugmodel_float8' --baseline-ngpus=8 --test-module='llama3' --test-config='llama3_debugmodel_float8' --test-ngpus=8 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 21, 2026
## Summary

Apply quantization converters on model configs instead of on built models.

Previously, the trainer built the model first, then walked the entire module tree to swap `nn.Linear` with `Float8Linear`. This required a save/restore dance (`capture_module_attrs` / `inject_module_protocol` / `verify_module_protocol`) because `Float8Linear.from_float` creates new module instances, losing `_param_init` and the `Linear`/`Module` protocol.

Now, converters inject a `_convert_fn` into matching configs before `build()`. Each module is converted immediately after construction inside `Module.Config.build()`, which controls the full sequence: create → convert → transfer `_param_init`. Since conversion happens *during* build rather than *after*, the external save/restore is no longer needed — `build()` holds `_param_init` across the conversion inline.

Addresses #2960 (comment) (but not #2981).

**Changes:**
- Add `Configurable.Config.walk()` — generic config tree traversal yielding `(fqn, config)` pairs
- Add `Module.Config._convert_fn` — optional callback applied in `build()` after construction
- Add `ModelConverter.convert_config()` — config-level conversion interface
- `Float8LinearConverter` / `Float8GroupedMMConverter` / `MXFP8Converter`: conversion logic moved from `convert(model)` to `convert_config(model_config)`
- `module_filter_fn` now accepts `Linear.Config` in addition to `nn.Module`
- Trainer calls `convert_config(model_config)` before `build()`, then `convert(model)` for any remaining model-level converters
- `TorchAOTokenDispatcher` selection moved from `make_token_dispatcher_config` to the quantization converters' `convert_config()`, so the model config always uses standard `AllToAllTokenDispatcher` and the converter swaps it when needed

## Test plan
- [ ] `pytest tests/unit_tests/test_model_converter.py` — passes
- [ ] `pytest tests/unit_tests/test_linear.py` — passes
- [ ] Full unit test suite (219 passed, 0 new failures)
- [ ] Verify float8 training produces identical loss before vs after:
```
NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama3' --baseline-config='llama3_debugmodel_float8' --baseline-ngpus=8 --test-module='llama3' --test-config='llama3_debugmodel_float8' --test-ngpus=8 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 21, 2026
## Summary

Apply quantization converters on model configs instead of on built models.

Previously, the trainer built the model first, then walked the entire module tree to swap `nn.Linear` with `Float8Linear`. This required a save/restore dance (`capture_module_attrs` / `inject_module_protocol` / `verify_module_protocol`) because `Float8Linear.from_float` creates new module instances, losing `_param_init` and the `Linear`/`Module` protocol.

Now, converters inject a `_convert_fn` into matching configs before `build()`. Each module is converted immediately after construction inside `Module.Config.build()`, which controls the full sequence: create → convert → transfer `_param_init`. Since conversion happens *during* build rather than *after*, the external save/restore is no longer needed — `build()` holds `_param_init` across the conversion inline.

Addresses #2960 (comment) (but not #2981).

**Changes:**
- Add `Configurable.Config.walk()` — generic config tree traversal yielding `(fqn, config)` pairs
- Add `Module.Config._convert_fn` — optional callback applied in `build()` after construction
- Add `ModelConverter.convert_config()` — config-level conversion interface
- `Float8LinearConverter` / `Float8GroupedMMConverter` / `MXFP8Converter`: conversion logic moved from `convert(model)` to `convert_config(model_config)`
- `module_filter_fn` now accepts `Linear.Config` in addition to `nn.Module`
- Trainer calls `convert_config(model_config)` before `build()`, then `convert(model)` for any remaining model-level converters
- `TorchAOTokenDispatcher` selection moved from `make_token_dispatcher_config` to the quantization converters' `convert_config()`, so the model config always uses standard `AllToAllTokenDispatcher` and the converter swaps it when needed

## Test plan
- [ ] `pytest tests/unit_tests/test_model_converter.py` — passes
- [ ] `pytest tests/unit_tests/test_linear.py` — passes
- [ ] Full unit test suite (219 passed, 0 new failures)
- [ ] Verify float8 training produces identical loss before vs after:
```
NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama3' --baseline-config='llama3_debugmodel_float8' --baseline-ngpus=8 --test-module='llama3' --test-config='llama3_debugmodel_float8' --test-ngpus=8 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 22, 2026
Fixes #2981
Addresses #2960 (comment)

## Summary

Apply quantization at model config construction time by swapping config types, instead of post-build model mutation.

Previously, the trainer built the model, then walked the entire module tree to swap `nn.Linear` with `Float8Linear`, requiring a save/restore dance for `_param_init` and the `Module` protocol. Now, quantization is a config pass in `model_registry()` that replaces `Linear.Config` with `Float8LinearConfig` — a subclass whose `build()` directly produces `Float8Linear`:

```python
# Config pass: swap Linear.Config → Float8LinearConfig in the config tree
model_registry("405B", quantization=QuantizationConfig(
    float8_recipe="rowwise",
    float8_filter_fqns=["output"],
    float8_moe_fqns=["experts"],
))

# Float8LinearConfig.build() → Float8Linear directly, no from_float
```

**Key changes:**
- `Float8LinearConfig(Linear.Config)` — builds `Float8Linear` directly, no `from_float` conversion
- `Configurable.Config.walk()` yields `(fqn, config, parent, attr)` enabling config replacement in the tree
- `QuantizationConfig` dataclass with `apply()` — single entry point for all quantization types
- `convert_to_float8()` — config pass that swaps `Linear.Config` → `Float8LinearConfig`
- `convert_moe_to_float8()` / `convert_moe_to_mxfp8()` — config passes for MoE experts
- `has_quantization()` — type check (`isinstance(c, Float8LinearConfig)`) instead of callback inspection
- Removed: `ModelConverter` protocol, `ModelConvertersContainer`, `Float8LinearConverter`, `Float8GroupedMMConverter`, `MXFP8Converter`, `QuantizationConverter`, `model_converter.py`, `float8.py`, `mx.py`
- Removed: `enable_fsdp_float8_all_gather`, `precompute_float8_dynamic_scale_for_fsdp`, `enable_float8_tensorwise_tp`, `model_converters` from `Trainer.Config` and all parallelize functions

## Test plan
- [ ] Full unit test suite passes (219 passed)
- [ ] Verify float8 training produces identical loss:
```
NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama3' --baseline-config='llama3_debugmodel_float8' --baseline-ngpus=8 --test-module='llama3' --test-config='llama3_debugmodel_float8' --test-ngpus=8 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 22, 2026
Fixes #2981
Addresses #2960 (comment)

## Summary

Apply quantization at model config construction time by swapping config types, instead of post-build model mutation.

Previously, the trainer built the model, then walked the entire module tree to swap `nn.Linear` with `Float8Linear`, requiring a save/restore dance for `_param_init` and the `Module` protocol. Now, quantization is a config pass in `model_registry()` that replaces `Linear.Config` with `Float8LinearConfig` — a subclass whose `build()` directly produces `Float8Linear`:

```python
# Config pass: swap Linear.Config → Float8LinearConfig in the config tree
model_registry("405B", quantization=QuantizationConfig(
    float8_recipe="rowwise",
    float8_filter_fqns=["output"],
    float8_moe_fqns=["experts"],
))

# Float8LinearConfig.build() → Float8Linear directly, no from_float
```

**Key changes:**
- `Float8LinearConfig(Linear.Config)` — builds `Float8Linear` directly, no `from_float` conversion
- `Configurable.Config.walk()` yields `(fqn, config, parent, attr)` enabling config replacement in the tree
- `QuantizationConfig` dataclass with `apply()` — single entry point for all quantization types
- `convert_to_float8()` — config pass that swaps `Linear.Config` → `Float8LinearConfig`
- `convert_moe_to_float8()` / `convert_moe_to_mxfp8()` — config passes for MoE experts
- `has_quantization()` — type check (`isinstance(c, Float8LinearConfig)`) instead of callback inspection
- Removed: `ModelConverter` protocol, `ModelConvertersContainer`, `Float8LinearConverter`, `Float8GroupedMMConverter`, `MXFP8Converter`, `QuantizationConverter`, `model_converter.py`, `float8.py`, `mx.py`
- Removed: `enable_fsdp_float8_all_gather`, `precompute_float8_dynamic_scale_for_fsdp`, `enable_float8_tensorwise_tp`, `model_converters` from `Trainer.Config` and all parallelize functions

## Test plan
- [ ] Full unit test suite passes (219 passed)
- [ ] Verify float8 training produces identical loss:
```
NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama3' --baseline-config='llama3_debugmodel_float8' --baseline-ngpus=8 --test-module='llama3' --test-config='llama3_debugmodel_float8' --test-ngpus=8 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 22, 2026
Fixes #2981
Addresses #2960 (comment)

## Summary

Apply quantization at model config construction time by swapping config types, instead of post-build model mutation.

Previously, the trainer built the model, then walked the entire module tree to swap `nn.Linear` with `Float8Linear`, requiring a save/restore dance for `_param_init` and the `Module` protocol. Now, quantization is a config pass in `model_registry()` that replaces `Linear.Config` with `Float8LinearConfig` — a subclass whose `build()` directly produces `Float8Linear`:

```python
# Config pass: swap Linear.Config → Float8LinearConfig in the config tree
model_registry("405B", quantization=QuantizationConfig(
    float8_recipe="rowwise",
    float8_filter_fqns=["output"],
    float8_moe_fqns=["experts"],
))

# Float8LinearConfig.build() → Float8Linear directly, no from_float
```

**Key changes:**
- `Float8LinearConfig(Linear.Config)` — builds `Float8Linear` directly, no `from_float` conversion
- `Configurable.Config.walk()` yields `(fqn, config, parent, attr)` enabling config replacement in the tree
- `QuantizationConfig` dataclass with `apply()` — single entry point for all quantization types
- `convert_to_float8()` — config pass that swaps `Linear.Config` → `Float8LinearConfig`
- `convert_moe_to_float8()` / `convert_moe_to_mxfp8()` — config passes for MoE experts
- `has_quantization()` — type check (`isinstance(c, Float8LinearConfig)`) instead of callback inspection
- Removed: `ModelConverter` protocol, `ModelConvertersContainer`, `Float8LinearConverter`, `Float8GroupedMMConverter`, `MXFP8Converter`, `QuantizationConverter`, `model_converter.py`, `float8.py`, `mx.py`
- Removed: `enable_fsdp_float8_all_gather`, `precompute_float8_dynamic_scale_for_fsdp`, `enable_float8_tensorwise_tp`, `model_converters` from `Trainer.Config` and all parallelize functions

## Test plan
- [ ] Full unit test suite passes (219 passed)
- [ ] Verify float8 training produces identical loss:
```
NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama3' --baseline-config='llama3_debugmodel_float8' --baseline-ngpus=8 --test-module='llama3' --test-config='llama3_debugmodel_float8' --test-ngpus=8 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 22, 2026
Fixes #2981
Addresses #2960 (comment)

## Summary

Apply quantization at model config construction time by swapping config types, instead of post-build model mutation.

Previously, the trainer built the model, then walked the entire module tree to swap `nn.Linear` with `Float8Linear`, requiring a save/restore dance for `_param_init` and the `Module` protocol. Now, quantization is a config pass in `model_registry()` that replaces `Linear.Config` with `Float8LinearConfig` — a subclass whose `build()` directly produces `Float8Linear`:

```python
# Config pass: swap Linear.Config → Float8LinearConfig in the config tree
model_registry("405B", quantization=QuantizationConfig(
    float8_recipe="rowwise",
    float8_filter_fqns=["output"],
    float8_moe_fqns=["experts"],
))

# Float8LinearConfig.build() → Float8Linear directly, no from_float
```

**Key changes:**
- `Float8LinearConfig(Linear.Config)` — builds `Float8Linear` directly, no `from_float` conversion
- `Configurable.Config.walk()` yields `(fqn, config, parent, attr)` enabling config replacement in the tree
- `QuantizationConfig` dataclass with `apply()` — single entry point for all quantization types
- `convert_to_float8()` — config pass that swaps `Linear.Config` → `Float8LinearConfig`
- `convert_moe_to_float8()` / `convert_moe_to_mxfp8()` — config passes for MoE experts
- `has_quantization()` — type check (`isinstance(c, Float8LinearConfig)`) instead of callback inspection
- Removed: `ModelConverter` protocol, `ModelConvertersContainer`, `Float8LinearConverter`, `Float8GroupedMMConverter`, `MXFP8Converter`, `QuantizationConverter`, `model_converter.py`, `float8.py`, `mx.py`
- Removed: `enable_fsdp_float8_all_gather`, `precompute_float8_dynamic_scale_for_fsdp`, `enable_float8_tensorwise_tp`, `model_converters` from `Trainer.Config` and all parallelize functions

## Test plan
- [ ] Full unit test suite passes (219 passed)
- [ ] Verify float8 training produces identical loss:
```
NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama3' --baseline-config='llama3_debugmodel_float8' --baseline-ngpus=8 --test-module='llama3' --test-config='llama3_debugmodel_float8' --test-ngpus=8 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Apr 22, 2026
Fixes #2981
Addresses #2960 (comment)

## Summary

Apply quantization at model config construction time by swapping config types, instead of post-build model mutation.

Previously, the trainer built the model, then walked the entire module tree to swap `nn.Linear` with `Float8Linear`, requiring a save/restore dance for `_param_init` and the `Module` protocol. Now, quantization is a config pass in `model_registry()` that replaces `Linear.Config` with `Float8LinearConfig` — a subclass whose `build()` directly produces `Float8Linear`:

```python
# Config pass: swap Linear.Config → Float8LinearConfig in the config tree
model_registry("405B", quantization=QuantizationConfig(
    float8_recipe="rowwise",
    float8_filter_fqns=["output"],
    float8_moe_fqns=["experts"],
))

# Float8LinearConfig.build() → Float8Linear directly, no from_float
```

**Key changes:**
- `Float8LinearConfig(Linear.Config)` — builds `Float8Linear` directly, no `from_float` conversion
- `Configurable.Config.walk()` yields `(fqn, config, parent, attr)` enabling config replacement in the tree
- `QuantizationConfig` dataclass with `apply()` — single entry point for all quantization types
- `convert_to_float8()` — config pass that swaps `Linear.Config` → `Float8LinearConfig`
- `convert_moe_to_float8()` / `convert_moe_to_mxfp8()` — config passes for MoE experts
- `has_quantization()` — type check (`isinstance(c, Float8LinearConfig)`) instead of callback inspection
- Removed: `ModelConverter` protocol, `ModelConvertersContainer`, `Float8LinearConverter`, `Float8GroupedMMConverter`, `MXFP8Converter`, `QuantizationConverter`, `model_converter.py`, `float8.py`, `mx.py`
- Removed: `enable_fsdp_float8_all_gather`, `precompute_float8_dynamic_scale_for_fsdp`, `enable_float8_tensorwise_tp`, `model_converters` from `Trainer.Config` and all parallelize functions

## Test plan
- [ ] Full unit test suite passes (219 passed)
- [ ] Verify float8 training produces identical loss:
```
NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama3' --baseline-config='llama3_debugmodel_float8' --baseline-ngpus=8 --test-module='llama3' --test-config='llama3_debugmodel_float8' --test-ngpus=8 --assert-equal --no-seed-checkpoint
```

[ghstack-poisoned]
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.

4 participants