Repository navigation
[PyTorch] Allow num_out_tokens == 0 in the mask-map MoE permute - #3958
Draft
algebra-MCX wants to merge 3 commits into
Draft
algebra-MCX wants to merge 3 commits into
algebra-MCX wants to merge 3 commits into
Conversation
A non-empty input whose mask routing map routes no token (for example an expert-parallel rank whose local experts were not selected) legitimately has zero permuted rows. moe_permute rejected this with "requires num_out_tokens > 0", and once that guard is relaxed, moe_unpermute returned a [0, hidden] tensor instead of zeros of restore_shape, and its backward returned a gradient shaped like the unpermuted output for the empty permuted input. - Accept num_out_tokens >= 0 in the mask-map permute (eager and fake); negative values are still rejected. With the capacity semantics of the Triton row map, 0 drops every routed entry. - Return zeros of [num_tokens, hidden_size] from the mask-map unpermute forward when the permuted input is empty but num_tokens > 0, matching its fake implementation. - Return an empty [0, hidden_size] input gradient from the unpermute backward on the empty-input path. - Add tests for an all-false routing map and for zero capacity across moe_permute, moe_permute_with_probs and moe_permute_and_pad_with_probs, eager and torch.compile, forward and backward. Reported downstream as NVIDIA/Megatron-LM#8690. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Chenxi Ma <114001934+algebra-MCX@users.noreply.github.com>
Run the existing FP8 mask-map permute check with an all-false routing map for every supported recipe (delayed, current scaling, block scaling and MXFP8) and both FP8 formats. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Chenxi Ma <114001934+algebra-MCX@users.noreply.github.com>
Test the zero-output case through the existing mask-map, alongside-probs and padding helpers, which compare forward and backward (including the probs gradient) against the PyTorch reference, instead of a separate hand-written test. The alongside-probs helper showed that moe_permute_with_probs returned no probs gradient when num_out_tokens == 0: the backward decided whether to compute it from the size of the permuted-probs gradient, which is empty in that case. Decide from ctx.needs_probs_grad instead, matching the empty-input path, which returns a zero probs gradient. Also drop the num_tokens == 0 special case in the mask-map unpermute forward: zeros of [num_tokens, hidden_size] cover it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Chenxi Ma <114001934+algebra-MCX@users.noreply.github.com>
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
moe_permute(..., map_type="mask")andmoe_permute_with_probsreject a non-empty input whose routing map routes no token:Zero permuted rows is a legitimate state. With dropless top-k routing and expert parallelism, a rank's local experts can simply not be selected for a microbatch. Following the hint in the message still gives 0, because
routing_map.sum()is 0. Megatron-LM hits this inMoEAllGatherTokenDispatcherwithmoe_permute_fusion=True: the zero-token rank raises, and its peers block in the combine reduce-scatter (NVIDIA/Megatron-LM#8690).The
> 0guard was added in #2876 to reject the former-1default. Since #3347 the Triton row map treatsnum_out_tokensas a capacity and drops entries at or past it, sonum_out_tokens == 0is well defined: every routed entry is dropped and the output has no rows. This PR accepts it and keeps rejecting negative values.Relaxing the guard exposes a second bug on the combine side. The mask-map unpermute forward returned
inp.clone()for an empty permuted input, so it produced[0, hidden]instead of zeros ofrestore_shape, which disagrees with its own fake implementation ([num_tokens, hidden]). Its backward then returned the[num_tokens, hidden]incoming gradient as the gradient of the[0, hidden]input.A third issue is in the permute backward. It decided whether to compute the probs gradient from the size of the permuted-probs gradient, which is also empty when
num_out_tokens == 0, somoe_permute_with_probsreturned no gradient forprobsthat require one. The empty-input path of the same function returns a zero probs gradient.Related downstream issue: NVIDIA/Megatron-LM#8690
Type of change
Changes
num_out_tokens >= 0instead of> 0. Negative values (for example a-1"infer" sentinel) are still rejected. Docstrings ofmoe_permuteandmoe_permute_with_probsnow say that 0 gives an empty output.[num_tokens, hidden_size], matching the fake implementation.[0, hidden_size]gradient for the empty input.ctx.needs_probs_grad, instead of when it is non-empty. With probs that do not require a gradient, the kernel no longer computes one that was then discarded.tests/pytorch/test_permutation.py:test_permutation_mask_map_zero_out_tokens: a non-empty input with an all-false routing map (num_out_tokens=0) through the existing_test_permutation_mask_map(with merging probs),_test_permutation_mask_map_alongside_probsand_test_permutation_and_padding_mask_maphelpers, which compare forward and backward, including the probs gradient, against the PyTorch reference, in eager andtorch.compile.test_permutation_mask_map_fp8_zero_out_tokens: the existing FP8 mask-map permute check (_test_permutation_mask_map_fp8, bit-exact data and scales against the PyTorch reference) withnum_out_tokens=0, for the delayed, current-scaling, block-scaling and MXFP8 recipes and both FP8 formats.test_permutation_mask_map_rejects_negative_out_tokens.The index-map path and the JAX
token_dispatchguard are unchanged. JAX has the same> 0check; I have not changed or tested it here.Testing
Environment: NVIDIA B200 (sm_100), container
nvcr.io/nvidia/pytorch:26.11-py3(torch 2.15.0a0, CUDA 13.5, Triton 3.9.0). The container ships TE 2.21.0+7457e47d. The change is Python-only, so I tested by overlaying the four Python permutation sources (pytorch/permutation.py,pytorch/triton/permutation.py,common/triton/permutation.py,pytorch/device.py) from this branch onto the installed package. That is not a source build of this branch.mainsources (no fix): all 14 zero-token cases fail on thenum_out_tokens > 0assertion, eagerly or through the fake implementation undertorch.compile.[0, 128]vs(64, 128)) and, in the alongside-probs helper, on the missing probs gradient. That is how the second and third issues above were found.tests/pytorch/test_permutation.py -k "not benchmark": 301 passed, 121 skipped, 0 failed.num_tokens == 0and the probs-gradient condition, which the allgather dispatcher (no probs through the fused permute) does not reach.MoELayerwith the allgather dispatcher, EP=2 on 2x B200, router forced so that EP rank 1 receives 0 tokens,moe_permute_fusion=True, with TE grouped-GEMM experts and with sequential experts, forward and backward. Before: rank 1 raises the assertion above. After: both ranks complete, and the output matches a reference computed from rank 0's experts (max abs error 0.0).moe_permute_fusion=True. Before: ranks 2 and 3 raise the assertion above. After: all four ranks complete, and the output, the input gradient and every parameter gradient are bitwise equal to the unfused reference.black24.4.2 with the repository arguments reports both files unchanged.pylint4.1.3 withpylintrcontransformer_engine/pytorch/permutation.pyrates it 10.00/10, as onmain.Not covered yet: Hopper, the
qa/L0_*launchers, and context parallelism in the downstream check.Checklist:
🤖 Generated with Claude Code