Skip to content

[PyTorch] Allow num_out_tokens == 0 in the mask-map MoE permute - #3958

Draft
algebra-MCX wants to merge 3 commits into
NVIDIA:mainfrom
algebra-MCX:fix-mask-permute-zero-out-tokens
Draft

algebra-MCX wants to merge 3 commits into
NVIDIA:mainfrom
algebra-MCX:fix-mask-permute-zero-out-tokens

Conversation

@algebra-MCX

@algebra-MCX algebra-MCX commented Nov 27, 2026 •

Copy link
Copy Markdown

Description

moe_permute(..., map_type="mask") and moe_permute_with_probs reject a non-empty input whose routing map routes no token:

AssertionError: moe_permute (mask map) requires num_out_tokens > 0, got 0.
Use int(routing_map.sum()) or num_tokens * top_k.

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 in MoEAllGatherTokenDispatcher with moe_permute_fusion=True: the zero-token rank raises, and its peers block in the combine reduce-scatter (NVIDIA/Megatron-LM#8690).

The > 0 guard was added in #2876 to reject the former -1 default. Since #3347 the Triton row map treats num_out_tokens as a capacity and drops entries at or past it, so num_out_tokens == 0 is 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 of restore_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, so moe_permute_with_probs returned no gradient for probs that 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

  • Documentation change (change only to the documentation, either a fix or a new content)
  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Infra/Build change
  • Code refactoring

Changes

  • Mask-map permute (eager and fake): require num_out_tokens >= 0 instead of > 0. Negative values (for example a -1 "infer" sentinel) are still rejected. Docstrings of moe_permute and moe_permute_with_probs now say that 0 gives an empty output.
  • Mask-map unpermute forward: for an empty permuted input, return zeros of [num_tokens, hidden_size], matching the fake implementation.
  • Mask-map unpermute backward, empty-input path: return a [0, hidden_size] gradient for the empty input.
  • Mask-map permute backward: pass the permuted-probs gradient to the kernel when 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 in 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_probs and _test_permutation_and_padding_mask_map helpers, which compare forward and backward, including the probs gradient, against the PyTorch reference, in eager and torch.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) with num_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_dispatch guard are unchanged. JAX has the same > 0 check; 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.

  • New tests on main sources (no fix): all 14 zero-token cases fail on the num_out_tokens > 0 assertion, eagerly or through the fake implementation under torch.compile.
  • With only the guard relaxed, they fail on the unpermute shape ([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.
  • With this PR: tests/pytorch/test_permutation.py -k "not benchmark": 301 passed, 121 skipped, 0 failed.
  • The two downstream checks below ran on the first two commits. The last commit changes only the unpermute empty-input branch for num_tokens == 0 and the probs-gradient condition, which the allgather dispatcher (no probs through the fused permute) does not reach.
  • Downstream check: a Megatron-LM MoELayer with 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).
  • Downstream check with tensor and sequence parallelism: the allgather dispatcher with TP=2, sequence parallelism, EP=2 (expert TP = TP) and TE grouped-GEMM experts on 4x B200, router forced so that both GPUs of EP rank 1 receive 0 tokens. The same layer runs forward and backward on the same input with the unfused permute (the reference) and then with 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.
  • black 24.4.2 with the repository arguments reports both files unchanged. pylint 4.1.3 with pylintrc on transformer_engine/pytorch/permutation.py rates it 10.00/10, as on main.

Not covered yet: Hopper, the qa/L0_* launchers, and context parallelism in the downstream check.

Checklist:

  • I have read and followed the contributing guidelines
  • The functionality is complete
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

🤖 Generated with Claude Code

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>
@github-actions github-actions Bot added the community-contribution PRs from external contributor outside the core maintainers, representing community-driven work. label Nov 27, 2026
algebra-MCX and others added 2 commits November 27, 2026 11:50
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

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution PRs from external contributor outside the core maintainers, representing community-driven work.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant