Repository navigation
[Bug] Fix MoE SP token combine indices - #3604
Conversation
|
|
| topk_expert_ids_TK: torch.Tensor, | ||
| num_local_tokens_per_expert_E: torch.Tensor, | ||
| *, | ||
| input_shape_BLD: tuple[int, int, int] | None = None, |
There was a problem hiding this comment.
Do we need to pass the input_shape_BLD into dispatch()? We can directly pass to combine() and change combine()'s function signature. Now we are passing it via dispatch() and store it in dispatch() Metatdata.
I find a orthogonal problem (uneven shard when SP on L dimension #3619) , but ends up using the similar solution with yours.
There was a problem hiding this comment.
Yeah, passing input_shape_BLD through dispatch() and storing it in the dispatch metadata is not strictly necessary; we could pass it directly to combine() and simplify the function signature/metadata flow.
That said, it looks like the previously merged changes may have already addressed this issue, including the uneven shard case when SP is enabled on the L dimension. Do you think there is still any follow-up work needed on my side here, or is the current implementation sufficient?
| num_output_tokens = combined_TD.shape[0] * self.sp_size | ||
| if metadata.input_shape_BLD is not None: | ||
| B, L, _ = metadata.input_shape_BLD | ||
| num_output_tokens = B * L * self.sp_size |
There was a problem hiding this comment.
Seems a bug when with flattening / unflattening introduced in recent refactor. cc @acisseJZhong
Thanks for catching it!
Could you rebase on latest main? We just introduced a field to make it work with uneven sharding.
There was a problem hiding this comment.
Thanks, the latest main works well now.
| """Metadata returned by AllToAllTokenDispatcher.dispatch() for use in combine().""" | ||
|
|
||
| input_shape: tuple # for _unpermute | ||
| input_shape_BLD: tuple[int, int, int] | None # for SP global token indices |
There was a problem hiding this comment.
bad name in two regards:
- almost the same as one line above; does it mean very different things? If so should differentiate in naming
_BLDsuffix means the tensor itself has this shape, according to the convention. Here it's actually a tuple of 3 integers.
There was a problem hiding this comment.
Thanks, after #3619 is merged, is there anything else I still need to do here?
There was a problem hiding this comment.
@Matrix-Z97 thanks for working on this, #3619 is solving a different problem than the one you are reporting, you can rebase onto latest main and reapply your change there? You can use num_local_tokens_after_padding to replace the local_seq_len in _, local_seq_len, _ = input_shape_BLD
There was a problem hiding this comment.
@wwwjn Thanks for the clarification. I rebased the change onto the latest main and reapplied the fix there.
I removed the input_shape_BLD metadata path and replaced the old local_seq_len source with the padding-derived value. One detail is that the MoE-level num_local_tokens_after_padding is the flattened local token count across the batch, so the dispatcher now receives both:
num_local_tokens_after_padding for the combined SP output buffer size
local_seq_len_after_padding = num_local_tokens_after_padding // B as the replacement for the old local_seq_len used by _sp_global_token_indices
This keeps the batch-aware index reconstruction while avoiding input_shape_BLD.
4737d92 to
a2a3b8a
Compare
tianyu-l
left a comment
There was a problem hiding this comment.
The fix looks correct. I would ask one more favor on code organization. Thank you!
| """No-op for the EP=1 dispatcher. Subclasses override.""" | ||
| del ep_mesh, tp_mesh | ||
|
|
||
| def _sp_global_token_indices( |
There was a problem hiding this comment.
LocalTokenDispatcher is only used when EP is off. And "expert sequence parallel" on TP dimension is never used, because during expert TP, the activations have to be Replicated.
See https://github.com/pytorch/torchtitan/blob/main/assets/images/moe_sharding.png for illustration.
My understanding is that you are introducing this function and self.sp_size, self.sp_rank simply because LocalTokenDispatcher is inherited by the several EP token dispatchers to share code.
In stead, I would suggest
- creating a new
BaseEPTokenDispatcher(which subclassesLocalTokenDispatcher) that is inherited by the rest - put the things you introduced here to that class
- share common scaffolding code into that class, e.g.
wire_meshesfunction - raise
NotImplementedErroron functions it doesn't support, e.g.dispatch/combine
WDYT?
tianyu-l
left a comment
There was a problem hiding this comment.
awesome work, thank you very much
one nit comment
| pass | ||
|
|
||
| def __init__(self, config: Config): | ||
| def __init__(self, config: LocalTokenDispatcher.Config): |
There was a problem hiding this comment.
| def __init__(self, config: LocalTokenDispatcher.Config): | |
| def __init__(self, config:Config): |
|
lint error |
|
@Matrix-Z97 The CI failure is unrelated and |
This PR was reopened (likely due to being reverted), so your approval was removed. Please request another review.
wwwjn
left a comment
There was a problem hiding this comment.
Sorry I mis-clicked while I was trying to merge the PR.
The CI error seems unrelated (determinsitic topk error and embedding error), and I do see several MoE model + EP success test case. So I'm going to merge this PR and happy to forward fix if anything is broken
…orch#3604) Replays the equivalent of upstream commit 5ba4399 ([Bug] Fix MoE SP token combine indices, PR pytorch#3604) into this PR14 fork. The buggy per-rank-offset code token_indices_experts_sorted_N = ( metadata.token_indices_experts_sorted_N + x_TD.shape[0] * self.sp_rank ) is mathematically equivalent to `global_idx = local_idx + local_T * sp_rank`, which only works when `B == 1`. For batched inputs, each batch has its own sequence shard, so the offset places tokens at wrong global positions. Fix: - Add `_sp_global_token_indices()` helper on LocalTokenDispatcher that reconstructs global indices with batch-aware sequence offsets: local_pos = local_idx % local_seq_len batch_idx = local_idx // local_seq_len global_idx = batch_idx * (local_seq_len * sp_size) + sp_rank * local_seq_len + local_pos - Add `num_local_tokens_after_padding` + `local_seq_len_after_padding` keyword-only args to all four `combine()` signatures (Local, AllToAll, DeepEP, Hybrid) so the post-PR pytorch#3604 upstream MoE callsite (which now passes them) is signature-compatible. - Replace the per-rank-offset code in AllToAll/DeepEP/Hybrid `combine()` with `self._sp_global_token_indices(...)` calls. Defaults on the new kwargs are `None` for back-compat with the pre-PR-pytorch#3604 callsite; the SP > 1 path asserts `local_seq_len_after_padding` is provided. This is the minimal-diff replay — we keep the existing sibling-class structure rather than introducing upstream's new `BaseEPTokenDispatcher` superclass. Currently latent for ezpz: all ezpz/moe configs run with `sp_size == 1` so the buggy branch was never live for us. Fix lands now to keep parity with upstream and unblock the post-54th-sync merge of `ezpz` into `pr14-fixes` (the upstream MoE callsite now passes `local_seq_len_after_padding=` and `num_local_tokens_after_padding=` to `combine()` — without the new kwargs, dispatch would `TypeError` at runtime).
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0) (oldest at bottom): * #3236 * __->__ #3142 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 - [x] https://github.com/pytorch/pytorch/pull/172792/changes - [x] #3604 ## 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
Summary
Fix incorrect MoE token placement when Tensor Parallelism, Expert Parallelism, and Sequence Parallelism are enabled together.
When SP is enabled, the MoE input
x_BLDis sharded along the sequence dimension. After flattening the local shard, token indices are only local to the current SP shard. The previous combine logic converted local indices to global indices with a simple per-rank offset:This is equivalent to:
This only works when B == 1. For batched inputs, each batch has its own sequence shard, so the simple offset places tokens into the wrong global positions. This can cause noticeable numerical differences when running MoE with TP + EP.
This PR fixes the issue by passing the original local (B, L, D) shape through dispatcher metadata and reconstructing global token indices with batch-aware sequence offsets:
Changes
Validation
Precision validation was performed on a DeepSeek-V3 debug model using 4 H100 GPUs.
Output comparison:
FSDP2 + TP2FSDP2 + TP2 + EP2, without this PRFSDP2 + TP2 + EP2, with this PR