Skip to content

[rl] Enable TP2EP for unified MoE model in vLLM wrapper - #3142

Merged
wwwjn merged 81 commits into
mainfrom
gh/wwwjn/14/head
Jun 15, 2026
Merged

wwwjn merged 81 commits into
mainfrom
gh/wwwjn/14/head

Conversation

@wwwjn

@wwwjn wwwjn commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Enable Expert Parallelism for MoE models in the vLLM inference path, with TP on dense layers. Includes meta-device init, init_states() fix for RoPE cache, EP mesh creation, enable_sp-based output layout, and MoE debug configs.

Key changes:

  • Meta-device init + to_empty() + init_states() for large MoE models
  • EP mesh: ep = tp_size (TP ranks become EP ranks for experts)
  • Use enable_sp (not inference flag) for output layout and SP splitting
  • enable_sequence_parallel=True, disable_loss_parallel=True for inference
  • Remove stale ModelConvertersContainer references
  • Add MoE debug and 30B-A3B RL configs

Similar as #3057

Dependency

Verification

Qwen3-30B-A3B model on 8 GPU (Trainer TP4 EP4, generator TP4 EP4):

wandb: Detected [openai] in use.
wandb: Use W&B Weave for improved LLM call tracing. Install Weave with `pip install weave` then add `import weave` to the top of your script.
wandb: For more information, check out the docs at: https://weave-docs.wandb.ai
WandB logging enabled
Using renderer qwen3, of type <class 'renderers.configs.Qwen3RendererConfig'>, with args {'enable_thinking': False}
Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
4 generator GPUs + 4 trainer GPUs = 8 total
[actor=<root>] Initializing TorchStoreStrategy with default_transport_type=<TransportType.Unset: 1>
[actor=<root>] Pre-training validation; then 10 steps of RL training
[actor=<root>] ----------
Validation | Step:  0  validation/response_length/mean: 30.10  timing/validate: 29.13
[actor=<root>] Dropping 1 packed rows (9 -> 8) to fit global_batch_size
[actor=<root>] ----------
Train | Step:  1  loss/mean: 0.013  bit_wise/logprob_diff/max: 55.49  reward/_mean: 0.79  rollout_reward/_mean: 0.79  reward/_max: 1.0  rollout_reward/_max: 1.0  reward/zero_std_frac: 0.68  rollout/response_length/max: 42.0  train/grad_norm/mean: 0.46  train/lr: 5.0e-07  perf/tokens_per_second: 141.1  timing/step: 120.0
[actor=<root>] Dropping 1 packed rows (9 -> 8) to fit global_batch_size
[actor=<root>] ----------
Train | Step:  2  loss/mean: 0.0055  bit_wise/logprob_diff/max: 56.85  reward/_mean: 0.70  rollout_reward/_mean: 0.70  reward/_max: 1.0  rollout_reward/_max: 1.0  reward/zero_std_frac: 0.80  rollout/response_length/max: 44.0  train/grad_norm/mean: 0.37  train/lr: 1.0e-06  perf/tokens_per_second: 158.5  timing/step: 110.2
[actor=<root>] Dropping 1 packed rows (9 -> 8) to fit global_batch_size
[actor=<root>] ----------
Train | Step:  3  loss/mean: 0.016  bit_wise/logprob_diff/max: 40.089  reward/_mean: 0.73  rollout_reward/_mean: 0.73  reward/_max: 1.0  rollout_reward/_max: 1.0  reward/zero_std_frac: 0.76  rollout/response_length/max: 47.0  train/grad_norm/mean: 0.45  train/lr: 1.0e-06  perf/tokens_per_second: 156.9  timing/step: 110.0
[actor=<root>] Dropping 1 packed rows (9 -> 8) to fit global_batch_size
[actor=<root>] ----------
Train | Step:  4  loss/mean: 0.011  bit_wise/logprob_diff/max: 40.92  reward/_mean: 0.73  rollout_reward/_mean: 0.73  reward/_max: 1.0  rollout_reward/_max: 1.0  reward/zero_std_frac: 0.72  rollout/response_length/max: 45.0  train/grad_norm/mean: 0.43  train/lr: 1.0e-06  perf/tokens_per_second: 163.3  timing/step: 108.7
[actor=<root>] Dropping 1 packed rows (9 -> 8) to fit global_batch_size
[actor=<root>] ----------
Train | Step:  5  loss/mean: 0.0076  bit_wise/logprob_diff/max: 96.53  reward/_mean: 0.71  rollout_reward/_mean: 0.71  reward/_max: 1.0  rollout_reward/_max: 1.0  reward/zero_std_frac: 0.76  rollout/response_length/max: 42.0  train/grad_norm/mean: 0.36  train/lr: 1.0e-06  perf/tokens_per_second: 165.3  timing/step: 109.2
[actor=<root>] Dropping 1 packed rows (9 -> 8) to fit global_batch_size
[actor=<root>] ----------
Train | Step:  6  loss/mean: 0.011  bit_wise/logprob_diff/max: 48.36  reward/_mean: 0.79  rollout_reward/_mean: 0.79  reward/_max: 1.0  rollout_reward/_max: 1.0  reward/zero_std_frac: 0.84  rollout/response_length/max: 49.0  train/grad_norm/mean: 0.44  train/lr: 1.0e-06  perf/tokens_per_second: 147.1  timing/step: 117.7
[actor=<root>] Dropping 1 packed rows (9 -> 8) to fit global_batch_size
[actor=<root>] ----------
Train | Step:  7  loss/mean: 0.0055  bit_wise/logprob_diff/max: 54.41  reward/_mean: 0.65  rollout_reward/_mean: 0.65  reward/_max: 1.0  rollout_reward/_max: 1.0  reward/zero_std_frac: 0.72  rollout/response_length/max: 43.0  train/grad_norm/mean: 0.12  train/lr: 1.0e-06  perf/tokens_per_second: 158.1  timing/step: 110.1
[actor=<root>] Dropping 1 packed rows (9 -> 8) to fit global_batch_size
[actor=<root>] ----------
Train | Step:  8  loss/mean: 0.0035  bit_wise/logprob_diff/max: 51.040  reward/_mean: 0.66  rollout_reward/_mean: 0.66  reward/_max: 1.0  rollout_reward/_max: 1.0  reward/zero_std_frac: 0.72  rollout/response_length/max: 45.0  train/grad_norm/mean: 0.31  train/lr: 1.0e-06  perf/tokens_per_second: 168.6  timing/step: 101.4
[actor=<root>] Dropping 1 packed rows (9 -> 8) to fit global_batch_size
[actor=<root>] ----------
Train | Step:  9  loss/mean: 0.023  bit_wise/logprob_diff/max: 58.88  reward/_mean: 0.56  rollout_reward/_mean: 0.56  reward/_max: 1.0  rollout_reward/_max: 1.0  reward/zero_std_frac: 0.64  rollout/response_length/max: 46.0  train/grad_norm/mean: 0.73  train/lr: 1.0e-06  perf/tokens_per_second: 175.6  timing/step: 103.8
[actor=<root>] Dropping 2 packed rows (10 -> 8) to fit global_batch_size
[actor=<root>] ----------
Train | Step: 10  loss/mean: 0.020  bit_wise/logprob_diff/max: 50.84  reward/_mean: 0.52  rollout_reward/_mean: 0.52  reward/_max: 1.0  rollout_reward/_max: 1.0  reward/zero_std_frac: 0.64  rollout/response_length/max: 47.0  train/grad_norm/mean: 0.23  train/lr: 1.0e-06  perf/tokens_per_second: 167.2  timing/step: 109.2
[actor=<root>] ----------
Validation | Step: 10  validation/response_length/mean: 31.85  timing/validate: 25.94
[actor=<root>] ============================================================
[actor=<root>] Validation summary (pre / post):
[actor=<root>]   validation_reward/_max:  +1.000  /  +1.000
[actor=<root>]   validation_reward/_mean:  +0.639  /  +0.664
[actor=<root>]   validation_reward/_min:  +0.052  /  +0.056
[actor=<root>]   validation_reward/_std:  +0.406  /  +0.386
[actor=<root>]   validation_reward/_sum:  +12.776  /  +13.289
[actor=<root>]   validation_reward/component/RewardAlphabetSort/mean:  +0.639  /  +0.664
[actor=<root>] ============================================================
[actor=<root>] Closing: tearing down actors and process meshes.

NOTE: this locally run didn't patch #3604, so the trainer are actually producing wrong numerics

Batch-invariant verification

  • To achieve batch invariant in MoE model, we need extra bmm invariant kernel: dense doesn’t meaningfully exercise a 3D batched matmul path in this parity setup, while MoE/EP introduces batched/grouped per-expert shapes and routing-dependent layouts; mm/addmm fixes 2D linear layers, but not 3D aten::bmm/batched matmul reductions.
Validation | Step:  0  validation/response_length/mean: 46.70  timing/validate: 7.059  
[actor=<root>] ----------
Train | Step:  1  loss/mean: 0  bit_wise/logprob_diff/max: 9.5e-07  reward/_mean: 0  rollout_reward/_mean: 0  reward/_max: 0  rollout_reward/_max: 0  reward/zero_std_frac: 1.0  rollout/response_length/max: 50.0  train/grad_norm/mean: 0  train/lr: 0.00040  perf/tokens_per_second: 1253.0  timing/step: 14.12  
[actor=<root>] ----------
Train | Step:  2  loss/mean: 0  bit_wise/logprob_diff/max: 9.5e-07  reward/_mean: 0  rollout_reward/_mean: 0  reward/_max: 0  rollout_reward/_max: 0  reward/zero_std_frac: 1.0  rollout/response_length/max: 50.0  train/grad_norm/mean: 0  train/lr: 0.00080  perf/tokens_per_second: 1542.7  timing/step: 12.10  
[actor=<root>] ----------
Train | Step:  3  loss/mean: 0  bit_wise/logprob_diff/max: 9.5e-07  reward/_mean: 0  rollout_reward/_mean: 0  reward/_max: 0  rollout_reward/_max: 0  reward/zero_std_frac: 1.0  rollout/response_length/max: 50.0  train/grad_norm/mean: 0  train/lr: 0.00080  perf/tokens_per_second: 1667.2  timing/step: 10.78  
[actor=<root>] ----------
Train | Step:  4  loss/mean: 0  bit_wise/logprob_diff/max: 9.5e-07  reward/_mean: 0  rollout_reward/_mean: 0  reward/_max: 0  rollout_reward/_max: 0  reward/zero_std_frac: 1.0  rollout/response_length/max: 50.0  train/grad_norm/mean: 0  train/lr: 0.00080  perf/tokens_per_second: 1641.3  timing/step: 11.034  
[actor=<root>] ----------
Train | Step:  5  loss/mean: 0  bit_wise/logprob_diff/max: 9.5e-07  reward/_mean: 0  rollout_reward/_mean: 0  reward/_max: 0  rollout_reward/_max: 0  reward/zero_std_frac: 1.0  rollout/response_length/max: 50.0  train/grad_norm/mean: 0  train/lr: 0.00080  perf/tokens_per_second: 1641.3  timing/step: 11.0032  
[actor=<root>] ----------
Train | Step:  6  loss/mean: 0  bit_wise/logprob_diff/max: 9.5e-07  reward/_mean: 0  rollout_reward/_mean: 0  reward/_max: 0  rollout_reward/_max: 0  reward/zero_std_frac: 1.0  rollout/response_length/max: 50.0  train/grad_norm/mean: 0  train/lr: 0.00080  perf/tokens_per_second: 1586.3  timing/step: 11.52  
[actor=<root>] ----------
Train | Step:  7  loss/mean: 0  bit_wise/logprob_diff/max: 9.5e-07  reward/_mean: 0  rollout_reward/_mean: 0  reward/_max: 0  rollout_reward/_max: 0  reward/zero_std_frac: 1.0  rollout/response_length/max: 50.0  train/grad_norm/mean: 0  train/lr: 0.00080  perf/tokens_per_second: 1768.6  timing/step: 10.43  
[actor=<root>] ----------
Train | Step:  8  loss/mean: 0  bit_wise/logprob_diff/max: 9.5e-07  reward/_mean: 0  rollout_reward/_mean: 0  reward/_max: 0  rollout_reward/_max: 0  reward/zero_std_frac: 1.0  rollout/response_length/max: 50.0  train/grad_norm/mean: 0  train/lr: 0.00080  perf/tokens_per_second: 1685.5  timing/step: 10.56  
[actor=<root>] ----------
Train | Step:  9  loss/mean: 0  bit_wise/logprob_diff/max: 9.5e-07  reward/_mean: 0  rollout_reward/_mean: 0  reward/_max: 0  rollout_reward/_max: 0  reward/zero_std_frac: 1.0  rollout/response_length/max: 50.0  train/grad_norm/mean: 0  train/lr: 0.00080  perf/tokens_per_second: 1822.5  timing/step: 10.44  
[actor=<root>] ----------
Train | Step: 10  loss/mean: 0  bit_wise/logprob_diff/max: 9.5e-07  reward/_mean: 0  rollout_reward/_mean: 0  reward/_max: 0  rollout_reward/_max: 0  reward/zero_std_frac: 1.0  rollout/response_length/max: 50.0  train/grad_norm/mean: 0  train/lr: 0.00080  perf/tokens_per_second: 1341.5  timing/step: 13.36  

NOTE: the loss is zero is because it's debug MoE model, not meaningful weights loaded so reward is constantly 0

Enable Expert Parallelism for MoE models in the vLLM inference path,
with TP on dense layers. Includes meta-device init, init_states() fix
for RoPE cache, EP mesh creation, enable_sp-based output layout, and
MoE debug configs.

Key changes:
- Meta-device init + to_empty() + init_states() for large MoE models
- EP mesh: ep = tp_size (TP ranks become EP ranks for experts)
- Use enable_sp (not inference flag) for output layout and SP splitting
- enable_sequence_parallel=True, disable_loss_parallel=True for inference
- Remove stale ModelConvertersContainer references
- Add MoE debug and 30B-A3B RL configs

Verified: TP=2, EP+TP=2, EP+TP=4 all produce correct output matching
native vLLM on Qwen3-30B-A3B.

[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Apr 28, 2026
Enable Expert Parallelism for MoE models in the vLLM inference path,
with TP on dense layers. Includes meta-device init, init_states() fix
for RoPE cache, EP mesh creation, enable_sp-based output layout, and
MoE debug configs.

Key changes:
- Meta-device init + to_empty() + init_states() for large MoE models
- EP mesh: ep = tp_size (TP ranks become EP ranks for experts)
- Use enable_sp (not inference flag) for output layout and SP splitting
- enable_sequence_parallel=True, disable_loss_parallel=True for inference
- Remove stale ModelConvertersContainer references
- Add MoE debug and 30B-A3B RL configs

Verified: TP=2, EP+TP=2, EP+TP=4 all produce correct output matching
native vLLM on Qwen3-30B-A3B.


Similar as #3057 

[ghstack-poisoned]
Comment thread torchtitan/experiments/rl/grpo.py Resolved
@wwwjn wwwjn changed the title Enable EP+TP for MoE inference in vLLM wrapper Enable TP2EP for MoE inference in vLLM wrapper Apr 28, 2026
Comment thread torchtitan/models/llama4/parallelize.py Resolved
Comment thread torchtitan/experiments/rl/grpo.py Resolved
Enable Expert Parallelism for MoE models in the vLLM inference path, with TP on dense layers. Includes meta-device init, init_states() fix for RoPE cache, EP mesh creation, enable_sp-based output layout, and MoE debug configs.

Key changes:
- Meta-device init + to_empty() + init_states() for large MoE models
- EP mesh: ep = tp_size (TP ranks become EP ranks for experts)
- Use enable_sp (not inference flag) for output layout and SP splitting
- enable_sequence_parallel=True, disable_loss_parallel=True for inference
- Remove stale ModelConvertersContainer references
- Add MoE debug and 30B-A3B RL configs

Verified: TP=2, EP+TP=2, EP+TP=4 all produce correct output matching native vLLM on Qwen3-30B-A3B.


Similar as #3057 

[ghstack-poisoned]
Comment thread torchtitan/experiments/rl/grpo.py Resolved
Comment thread torchtitan/models/llama4/parallelize.py Resolved
wwwjn added 2 commits April 29, 2026 20:46
…pper"


Enable Expert Parallelism for MoE models in the vLLM inference path, with TP on dense layers. Includes meta-device init, init_states() fix for RoPE cache, EP mesh creation, enable_sp-based output layout, and MoE debug configs.

Key changes:
- Meta-device init + to_empty() + init_states() for large MoE models
- EP mesh: ep = tp_size (TP ranks become EP ranks for experts)
- Use enable_sp (not inference flag) for output layout and SP splitting
- enable_sequence_parallel=True, disable_loss_parallel=True for inference
- Remove stale ModelConvertersContainer references
- Add MoE debug and 30B-A3B RL configs

Verified: TP=2, EP+TP=2, EP+TP=4 all produce correct output matching native vLLM on Qwen3-30B-A3B.


Similar as #3057 

[ghstack-poisoned]
Enable Expert Parallelism for MoE models in the vLLM inference path, with TP on dense layers. Includes meta-device init, init_states() fix for RoPE cache, EP mesh creation, enable_sp-based output layout, and MoE debug configs.

Key changes:
- Meta-device init + to_empty() + init_states() for large MoE models
- EP mesh: ep = tp_size (TP ranks become EP ranks for experts)
- Use enable_sp (not inference flag) for output layout and SP splitting
- enable_sequence_parallel=True, disable_loss_parallel=True for inference
- Remove stale ModelConvertersContainer references
- Add MoE debug and 30B-A3B RL configs

Verified: TP=2, EP+TP=2, EP+TP=4 all produce correct output matching native vLLM on Qwen3-30B-A3B.


Similar as #3057 

[ghstack-poisoned]
@wwwjn wwwjn changed the title Enable TP2EP for MoE inference in vLLM wrapper [rl] Enable TP2EP for MoE inference in vLLM wrapper Apr 30, 2026
wwwjn added 2 commits April 30, 2026 18:44
…M wrapper"


Enable Expert Parallelism for MoE models in the vLLM inference path, with TP on dense layers. Includes meta-device init, init_states() fix for RoPE cache, EP mesh creation, enable_sp-based output layout, and MoE debug configs.

Key changes:
- Meta-device init + to_empty() + init_states() for large MoE models
- EP mesh: ep = tp_size (TP ranks become EP ranks for experts)
- Use enable_sp (not inference flag) for output layout and SP splitting
- enable_sequence_parallel=True, disable_loss_parallel=True for inference
- Remove stale ModelConvertersContainer references
- Add MoE debug and 30B-A3B RL configs

Verified: TP=2, EP+TP=2, EP+TP=4 all produce correct output matching native vLLM on Qwen3-30B-A3B.


Similar as #3057 

[ghstack-poisoned]
Enable Expert Parallelism for MoE models in the vLLM inference path, with TP on dense layers. Includes meta-device init, init_states() fix for RoPE cache, EP mesh creation, enable_sp-based output layout, and MoE debug configs.

Key changes:
- Meta-device init + to_empty() + init_states() for large MoE models
- EP mesh: ep = tp_size (TP ranks become EP ranks for experts)
- Use enable_sp (not inference flag) for output layout and SP splitting
- enable_sequence_parallel=True, disable_loss_parallel=True for inference
- Remove stale ModelConvertersContainer references
- Add MoE debug and 30B-A3B RL configs

Verified: TP=2, EP+TP=2, EP+TP=4 all produce correct output matching native vLLM on Qwen3-30B-A3B.


Similar as #3057 

[ghstack-poisoned]
wwwjn added 4 commits April 30, 2026 20:25
…M wrapper"


Enable Expert Parallelism for MoE models in the vLLM inference path, with TP on dense layers. Includes meta-device init, init_states() fix for RoPE cache, EP mesh creation, enable_sp-based output layout, and MoE debug configs.

Key changes:
- Meta-device init + to_empty() + init_states() for large MoE models
- EP mesh: ep = tp_size (TP ranks become EP ranks for experts)
- Use enable_sp (not inference flag) for output layout and SP splitting
- enable_sequence_parallel=True, disable_loss_parallel=True for inference
- Remove stale ModelConvertersContainer references
- Add MoE debug and 30B-A3B RL configs

Verified: TP=2, EP+TP=2, EP+TP=4 all produce correct output matching native vLLM on Qwen3-30B-A3B.


Similar as #3057 

[ghstack-poisoned]
Enable Expert Parallelism for MoE models in the vLLM inference path, with TP on dense layers. Includes meta-device init, init_states() fix for RoPE cache, EP mesh creation, enable_sp-based output layout, and MoE debug configs.

Key changes:
- Meta-device init + to_empty() + init_states() for large MoE models
- EP mesh: ep = tp_size (TP ranks become EP ranks for experts)
- Use enable_sp (not inference flag) for output layout and SP splitting
- enable_sequence_parallel=True, disable_loss_parallel=True for inference
- Remove stale ModelConvertersContainer references
- Add MoE debug and 30B-A3B RL configs

Verified: TP=2, EP+TP=2, EP+TP=4 all produce correct output matching native vLLM on Qwen3-30B-A3B.


Similar as #3057 

[ghstack-poisoned]
…M wrapper"


Enable Expert Parallelism for MoE models in the vLLM inference path, with TP on dense layers. Includes meta-device init, init_states() fix for RoPE cache, EP mesh creation, enable_sp-based output layout, and MoE debug configs.

Key changes:
- Meta-device init + to_empty() + init_states() for large MoE models
- EP mesh: ep = tp_size (TP ranks become EP ranks for experts)
- Use enable_sp (not inference flag) for output layout and SP splitting
- enable_sequence_parallel=True, disable_loss_parallel=True for inference
- Remove stale ModelConvertersContainer references
- Add MoE debug and 30B-A3B RL configs

Verified: TP=2, EP+TP=2, EP+TP=4 all produce correct output matching native vLLM on Qwen3-30B-A3B.


Similar as #3057 

[ghstack-poisoned]
Enable Expert Parallelism for MoE models in the vLLM inference path, with TP on dense layers. Includes meta-device init, init_states() fix for RoPE cache, EP mesh creation, enable_sp-based output layout, and MoE debug configs.

Key changes:
- Meta-device init + to_empty() + init_states() for large MoE models
- EP mesh: ep = tp_size (TP ranks become EP ranks for experts)
- Use enable_sp (not inference flag) for output layout and SP splitting
- enable_sequence_parallel=True, disable_loss_parallel=True for inference
- Remove stale ModelConvertersContainer references
- Add MoE debug and 30B-A3B RL configs

Verified: TP=2, EP+TP=2, EP+TP=4 all produce correct output matching native vLLM on Qwen3-30B-A3B.


Similar as #3057 

[ghstack-poisoned]
@github-actions github-actions Bot mentioned this pull request May 1, 2026
wwwjn added 2 commits May 1, 2026 14:31
…M wrapper"


Enable Expert Parallelism for MoE models in the vLLM inference path, with TP on dense layers. Includes meta-device init, init_states() fix for RoPE cache, EP mesh creation, enable_sp-based output layout, and MoE debug configs.

Key changes:
- Meta-device init + to_empty() + init_states() for large MoE models
- EP mesh: ep = tp_size (TP ranks become EP ranks for experts)
- Use enable_sp (not inference flag) for output layout and SP splitting
- enable_sequence_parallel=True, disable_loss_parallel=True for inference
- Remove stale ModelConvertersContainer references
- Add MoE debug and 30B-A3B RL configs

Verified: TP=2, EP+TP=2, EP+TP=4 all produce correct output matching native vLLM on Qwen3-30B-A3B.


Similar as #3057 

[ghstack-poisoned]
Enable Expert Parallelism for MoE models in the vLLM inference path, with TP on dense layers. Includes meta-device init, init_states() fix for RoPE cache, EP mesh creation, enable_sp-based output layout, and MoE debug configs.

Key changes:
- Meta-device init + to_empty() + init_states() for large MoE models
- EP mesh: ep = tp_size (TP ranks become EP ranks for experts)
- Use enable_sp (not inference flag) for output layout and SP splitting
- enable_sequence_parallel=True, disable_loss_parallel=True for inference
- Remove stale ModelConvertersContainer references
- Add MoE debug and 30B-A3B RL configs

Verified: TP=2, EP+TP=2, EP+TP=4 all produce correct output matching native vLLM on Qwen3-30B-A3B.


Similar as #3057 

[ghstack-poisoned]
[ghstack-poisoned]
wwwjn added a commit that referenced this pull request Jun 10, 2026
… and fix combine() shape mismatch (#3595)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* #3236
* #3142
* __->__ #3595

## What's the problem
- [Currently] combine() wrongly assume the tokens are evenly sharded on
each rank
https://github.com/pytorch/torchtitan/blob/c0428bb186f5c97e1d1b4ed89febd22916eee302/torchtitan/models/common/token_dispatcher.py#L439-L456
(infer global SPMD in local SPMD region)
- If uneven sharded, out_TD will have different shapes across SP ranks.
- We should directly ban if input number of tokens in input batch can
not be evenly sharded by SP ranks

- [Future] Router will use spmd_types soon, and router is per SP rank.
Per SP rank should have even sharding
- [Future] we want to avoid dispatch/load_balacing the padded token, we
should be able to do that by adding metadata field to record the
actually local tokens for each sp rank

## What does this PR do?

This PR is doing "virtual padding" , and passing metadata around
- Calculate num_local_tokens_after_padding = (T + pad_tokens) // sp_size
in MoE module
- Pass num_local_tokens_after_padding to GroupedExperts module, then to
combine()
- combine() returns a tensor with shape (num_local_tokens_after_padding
* sp_rank, .... )
- slice the combined tensor to (T, ...)  in MoE
wwwjn added 2 commits June 10, 2026 12:46
[ghstack-poisoned]
[ghstack-poisoned]
"<|vision_end|>": 2006,
"<|image_pad|>": 2007,
"<|video_pad|>": 2008
"<|video_pad|>": 2008,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

These special tokens are needed becuase external render (AutoTokenizer in RL) checks these and they are needed by Qwen3 model

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

hf_assets_path="tests/assets/tokenizer"
renderer=RendererConfig(name="qwen3", enable_thinking=False)

[ghstack-poisoned]
completion_message["reasoning_content"] = parsed.reasoning_content
if parsed.tool_calls:
completion_message["tool_calls"] = parsed.tool_calls

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Need to revert

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Changes in this files just adding basic kwargs and make this script runnable with different configs, and align with the generator setup in RL.

# forwards cannot shard across all SP ranks, so pad to ``sp_size`` and
# trim before returning. This is a no-op for training/prefill and EP-off;
# padded tokens only affect the inference-only load-balance counter.
seq_pad = sp_size - L if L < sp_size else 0

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is to solve #3622

TLDR the issue is: when seq_len >= TP_degree, num_local_tokens_per_expert_E = routing_map_BLE.sum(dim=(0, 1)) suppose to be
V (tokens vary across TP ranks) --sum(seq)--> P (partial per-rank count). But when seq_len < TP, it degraded to R --> sum --> R, which can not be converted to P later.

The simple fix there is to pad when seq_len < TP_degree

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

And this path should be only used when inference (however the pretraining might also hit seq_len < SP rank, we can just abandon it) - During inference the token_per_exepert_E would NOT matter much for inference. We need to enforce it's inference only

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Let's add a TODO.

Please wrap the affected region with ------------- so people know this is temporary code which needs to be removed.

wwwjn added 2 commits June 11, 2026 10:40
[ghstack-poisoned]
[ghstack-poisoned]
Comment thread torchtitan/distributed/utils.py Outdated

_upstream_enable()

from vllm.model_executor.layers.batch_invariant import bmm_batch_invariant

@wwwjn wwwjn Jun 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This needs more discussion: We shouldn't put vllm as dependency in core. I will move these part into generator, as it's generator sepecific

Meanwhile I'm asking Claude to check the trace / read the code, where exactly is bmm used in MoE

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Screenshot 2026-06-11 at 4 50 10 PM Only generator model dispatch self.gate() to `bmm`, trainer dispatch it to `mm`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

  1. Does TML package not support batch-invariant bmm?
  2. which exact tensor is not contiguous? I'd like to check if we could just .contiguous() on it before doing linear. I think it's the ``x_BLD` here https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/moe.py#L402. Maybe let's call contiguous on it to avoid further complicating the code, and leave a TODO to investigate if we could refactor later.

@wwwjn wwwjn Jun 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

  1. No, TML's version doesn't include batch-invariant bmm. vllm has batch-invariant bmm implemented.
  2. I'm testing locally if a continous tensor will be dispatched to mm instead of bmm
    Update: with only x_BLD.contiguous() and no bmm override, the drift stayed large (0.016, 2e-05, 0.031, ...),

The Aten dispatch rule for matmul is:

if (dim1==1 && dim2==1) → dot
else if (dim1==2 && dim2==1) → mv
else if (dim1==1 && dim2==2) → mm (unsqueeze)
else if (dim1==2 && dim2==2) → mm // line 2044
else if (should_fold(tensor1, tensor2, has_out)) → mm // line 2046 (fold batch
into rows)
else → bmm // line 2112
(expand+broadcast batch)

Our gate is 3‑D activation @ 2‑D weight (dim1=3, dim2=2), so it lands on the should_fold decision. bmm is taken iff should_fold returns false. What should_fold do is decided at graph_tracing time, and it always returns false no matter we call contiguous or not.

In eager, a contiguous 3-D @ 2-D never produced bmm in eager, DTensor (Shard(1)/Replicate), or backed/unbacked-symbolic tests — they all fold to mm. So the bmm is specifically the traced-inference-graph activation being non-contiguous , which eager .contiguous() doesn't reach.

Another potential solution is fold the 3D activation into 2D (and change sharing config accrodingly)

  B, L, D = x_BLD.shape
  scores_BLE = self.gate(x_BLD.reshape(B * L, D)).view(B, L, -1)

I'm checking if we can implement this cleanly

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this will introduce problem when spmd_types migration happens, so preferring patching vllm bmm for now.

@wwwjn wwwjn changed the title [Not ready][rl] Enable TP2EP for unified MoE model in vLLM wrapper [rl] Enable TP2EP for unified MoE model in vLLM wrapper Jun 11, 2026

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

one comment on the batch-invariant bmm, and some nits

Comment thread torchtitan/distributed/utils.py Outdated

_upstream_enable()

from vllm.model_executor.layers.batch_invariant import bmm_batch_invariant

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

  1. Does TML package not support batch-invariant bmm?
  2. which exact tensor is not contiguous? I'd like to check if we could just .contiguous() on it before doing linear. I think it's the ``x_BLD` here https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/moe.py#L402. Maybe let's call contiguous on it to avoid further complicating the code, and leave a TODO to investigate if we could refactor later.

**self._encode_rollout(rollout),
}
},
# Validation rollouts can contain renderer-owned message objects.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I didn't understand the comment and why we need this. cc @felipemello1

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I hit something (tool calling results) is not serializable error when json dump

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

comment that this is to bypass tool calling results.

# forwards cannot shard across all SP ranks, so pad to ``sp_size`` and
# trim before returning. This is a no-op for training/prefill and EP-off;
# padded tokens only affect the inference-only load-balance counter.
seq_pad = sp_size - L if L < sp_size else 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Let's add a TODO.

Please wrap the affected region with ------------- so people know this is temporary code which needs to be removed.

Comment thread torchtitan/models/common/moe.py Resolved
wwwjn added 3 commits June 12, 2026 14:02
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Comment on lines +118 to +119
expert routing, breaking on-policy logprob parity. Only the generator needs
it (the trainer's gate is ``mm``), so it lives here rather than in core.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What I still don't understand is why trainer gate is folded to mm. In the [eager, compile, cudagraph] x [training, inference] matrix, possibly furthur expanded by TP/EP/SP configs, when do we hit bmm?

#3142 (comment) explained some, but it's not entirely clear.

My point is that

  • if this is e.g. aot_eager compile vs. eager mismatch, then we should ask compile experts to help resolve.
  • basically I would like to learn "Unless xxx is willing to change, we couldn't really solve this problem". The way you describe the issue sounds to me that it's some mismatch, and we can fix it.

I don't mind leaving a TODO for investigation.

@wwwjn
wwwjn changed the base branch from gh/wwwjn/14/base to main June 14, 2026 17:24
wwwjn added 2 commits June 14, 2026 10:34
[ghstack-poisoned]
[ghstack-poisoned]
@wwwjn
wwwjn changed the base branch from main to gh/wwwjn/14/base June 14, 2026 17:34
wwwjn added 2 commits June 14, 2026 11:05
[ghstack-poisoned]
[ghstack-poisoned]
@wwwjn
wwwjn changed the base branch from gh/wwwjn/14/base to main June 15, 2026 00:07
[ghstack-poisoned]
@wwwjn

wwwjn commented Jun 15, 2026

Copy link
Copy Markdown
Contributor Author

Model Test failure is not related

RL test passed: However, for MoE model the loss is 0 (which is expected because we random initialized weights)

@wwwjn
wwwjn merged commit 78fc8ae into main Jun 15, 2026
21 of 24 checks passed
@tianyu-l
tianyu-l deleted the gh/wwwjn/14/head branch June 15, 2026 04:51
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