From 6f95deef5e5cde6bd8b9e3e44a916c266a8f171d Mon Sep 17 00:00:00 2001 From: Chenxi Ma <114001934+algebra-MCX@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:12:09 -0800 Subject: [PATCH 1/3] [PyTorch] Allow num_out_tokens == 0 in the mask-map MoE permute 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 Signed-off-by: Chenxi Ma <114001934+algebra-MCX@users.noreply.github.com> --- tests/pytorch/test_permutation.py | 87 +++++++++++++++++++++++ transformer_engine/pytorch/permutation.py | 30 +++++--- 2 files changed, 107 insertions(+), 10 deletions(-) diff --git a/tests/pytorch/test_permutation.py b/tests/pytorch/test_permutation.py index 53e76ebac17..89dbf3415dc 100644 --- a/tests/pytorch/test_permutation.py +++ b/tests/pytorch/test_permutation.py @@ -1799,6 +1799,93 @@ def test_permutation_mask_map_capacity_drop(torch_dtype, num_tokens): assert_close(unperm, ref_unperm) +@pytest.mark.parametrize("torch_dtype", [torch.float32, torch.bfloat16]) +@pytest.mark.parametrize( + "op, routed", + [ + ("permute", False), + ("permute", True), + ("permute_with_probs", False), + ("permute_with_probs", True), + ("permute_and_pad_with_probs", False), + ], +) +@pytest.mark.parametrize("use_torch_compile", [False, True]) +def test_permutation_mask_map_zero_out_tokens(torch_dtype, op, routed, use_torch_compile): + """Non-empty input with num_out_tokens == 0. + + routed=False: no token is routed to any expert, e.g. an expert-parallel rank whose + local experts were not selected. routed=True: tokens are routed but the capacity is + zero, so every entry is dropped. Both must give an empty permuted buffer, a zero + unpermuted output and zero gradients.""" + if use_torch_compile and op == "permute_and_pad_with_probs": + pytest.skip("moe_permute_and_pad_with_probs reads tokens_per_expert on the host") + num_tokens, num_expert, hidden_size = 64, 8, 128 + torch.manual_seed(1234) + if routed: + routing_map = (torch.rand(num_tokens, num_expert) > 0.5).bool().cuda() + assert int(routing_map.sum()) > 0 + else: + routing_map = torch.zeros(num_tokens, num_expert, dtype=torch.bool, device="cuda") + inp = torch.randn(num_tokens, hidden_size, device="cuda", dtype=torch_dtype) + inp.requires_grad_(True) + probs = torch.rand(num_tokens, num_expert, device="cuda", requires_grad=True) + + def fn(inp, probs): + permuted_probs = None + if op == "permute": + out, row_id_map = te_permute(inp, routing_map, num_out_tokens=0, map_type="mask") + merging_probs = None + elif op == "permute_with_probs": + out, permuted_probs, row_id_map = te_permute_with_probs( + inp, probs, routing_map, num_out_tokens=0 + ) + merging_probs = probs + else: + tokens_per_expert = torch.zeros(num_expert, dtype=torch.int64, device="cuda") + out, permuted_probs, row_id_map, _, padded_tokens_per_expert = ( + te_permute_and_pad_with_probs( + inp, probs, routing_map, tokens_per_expert, align_size=16 + ) + ) + assert int(padded_tokens_per_expert.sum()) == 0 + merging_probs = None + restored = te_unpermute( + out, + row_id_map, + merging_probs=merging_probs, + restore_shape=inp.shape, + map_type="mask", + ) + return out, permuted_probs, restored + + out, permuted_probs, restored = _maybe_compile(fn, use_torch_compile)(inp, probs) + assert out.shape == (0, hidden_size) + if permuted_probs is not None: + assert permuted_probs.shape == (0,) + assert restored.shape == (num_tokens, hidden_size) + torch.testing.assert_close(restored, torch.zeros_like(restored), atol=0, rtol=0) + + loss = (restored.float() * torch.randn_like(restored, dtype=torch.float32)).sum() + if permuted_probs is not None: + loss = loss + permuted_probs.sum() + loss.backward() + torch.testing.assert_close(inp.grad, torch.zeros_like(inp), atol=0, rtol=0) + if op == "permute_with_probs": + # merging_probs feeds the unpermute, so probs must receive a (zero) gradient. + assert probs.grad is not None + if probs.grad is not None: + torch.testing.assert_close(probs.grad, torch.zeros_like(probs), atol=0, rtol=0) + + +def test_permutation_mask_map_rejects_negative_out_tokens(): + """A negative num_out_tokens (such as a -1 'infer' sentinel) is not a valid size.""" + routing_map = torch.ones(4, 2, dtype=torch.bool, device="cuda") + inp = torch.randn(4, 16, device="cuda") + with pytest.raises(AssertionError, match="num_out_tokens >= 0"): + te_permute(inp, routing_map, num_out_tokens=-1, map_type="mask") + + @pytest.mark.parametrize("te_dtype", _te_dtypes) @pytest.mark.parametrize("num_out_tokens", [None]) @pytest.mark.parametrize( diff --git a/transformer_engine/pytorch/permutation.py b/transformer_engine/pytorch/permutation.py index 0eb5ffe88d9..7b5d0cd4144 100644 --- a/transformer_engine/pytorch/permutation.py +++ b/transformer_engine/pytorch/permutation.py @@ -329,8 +329,8 @@ def moe_permute_mask_map_forward( f"Permute not possible: inp.size(0) ({inp.size(0)}) must match " f"routing_map.size(0) ({routing_map.size(0)})." ) - assert num_out_tokens > 0, ( - f"moe_permute (mask map) requires num_out_tokens > 0, got {num_out_tokens}. " + assert num_out_tokens >= 0, ( + f"moe_permute (mask map) requires num_out_tokens >= 0, got {num_out_tokens}. " "Use int(routing_map.sum()) or num_tokens * top_k." ) num_tokens, hidden_size = inp.size() @@ -456,8 +456,8 @@ def _moe_permute_mask_map_forward_fake( # pylint: disable=unused-argument hidden_size = inp.shape[1] num_experts = routing_map.shape[1] if num_tokens > 0: - assert num_out_tokens > 0, ( - f"moe_permute (mask map) requires num_out_tokens > 0, got {num_out_tokens}. " + assert num_out_tokens >= 0, ( + f"moe_permute (mask map) requires num_out_tokens >= 0, got {num_out_tokens}. " "Use int(routing_map.sum()) or num_tokens * top_k." ) out_rows = num_out_tokens @@ -600,7 +600,11 @@ def moe_unpermute_mask_map_forward( ) -> torch.Tensor: """Forward pass for MoE unpermute with mask router map.""" if not inp.numel(): - return inp.clone() + if num_tokens == 0: + return inp.clone() + # No permuted rows (e.g. no token was routed to these experts): every + # token receives nothing, so the output is zero. + return torch.zeros((num_tokens, hidden_size), dtype=inp.dtype, device=inp.device) assert not isinstance( inp, QuantizedTensor ), "The forward of moe_unpermute does not support FP8." @@ -828,11 +832,14 @@ def _moe_unpermute_mask_map_setup_context(ctx, inputs, output): # pylint: disab def _moe_unpermute_mask_map_backward_wrapper(ctx, unpermuted_act_grad): """Backward wrapper calling the appropriate custom backward op.""" if ctx.empty_input: + # The forward input has no rows, so its gradient has none either, even when + # the unpermuted output (and thus unpermuted_act_grad) has num_tokens rows. + act_grad = unpermuted_act_grad.new_zeros((0, ctx.hidden_size)) if ctx.with_probs: _, _, merging_probs, _ = ctx.saved_tensors probs_grad = torch.zeros_like(merging_probs) if ctx.needs_probs_grad else None - return unpermuted_act_grad, None, probs_grad, None, None, None, None - return unpermuted_act_grad, None, None, None, None, None, None + return act_grad, None, probs_grad, None, None, None, None + return act_grad, None, None, None, None, None, None act_grad = None probs_grad = None @@ -913,7 +920,9 @@ def moe_permute( The values in it are the routed expert indices. num_out_tokens : int Number of output tokens (rows in the permuted buffer). - mask map: must be > 0, e.g. int(routing_map.sum()) or num_tokens * top_k. + mask map: must be >= 0, e.g. int(routing_map.sum()) or num_tokens * top_k. + Routed entries beyond the first num_out_tokens rows are dropped, so 0 yields + an empty output, e.g. when routing_map routes no token to any expert. index map: must be >= 0; 0 means infer as num_tokens * top_k. max_token_num : int, default = -1 Workspace sizing hint, only used for map_type='index'. Ignored for 'mask'. @@ -962,8 +971,9 @@ def moe_permute_with_probs( The token to expert mapping tensor of shape [num_tokens, num_experts] and dtype 'int32'. The values in it: 1 means the token is routed to this expert and 0 means not. num_out_tokens : int - Number of output tokens (rows in the permuted buffer). Must be > 0, - e.g. int(routing_map.sum()) or num_tokens * top_k. + Number of output tokens (rows in the permuted buffer). Must be >= 0, + e.g. int(routing_map.sum()) or num_tokens * top_k. Routed entries beyond + the first num_out_tokens rows are dropped, so 0 yields an empty output. """ if isinstance(inp, QuantizedTensor) and torch.compiler.is_compiling(): raise RuntimeError( From b219cbe75886871a36693b7ae8eec7959db77020 Mon Sep 17 00:00:00 2001 From: Chenxi Ma <114001934+algebra-MCX@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:50:07 -0800 Subject: [PATCH 2/3] [PyTorch] Test the quantized mask-map permute with num_out_tokens == 0 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 Signed-off-by: Chenxi Ma <114001934+algebra-MCX@users.noreply.github.com> --- tests/pytorch/test_permutation.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/pytorch/test_permutation.py b/tests/pytorch/test_permutation.py index 89dbf3415dc..03ec256748a 100644 --- a/tests/pytorch/test_permutation.py +++ b/tests/pytorch/test_permutation.py @@ -2078,6 +2078,27 @@ def test_permutation_mask_map_fp8( ) +@pytest.mark.skipif(not fp8_available, reason=reason_for_no_fp8) +@pytest.mark.parametrize("te_dtype", [te.DType.kFloat8E4M3, te.DType.kFloat8E5M2]) +@pytest.mark.parametrize("recipe", fp8_recipes) +def test_permutation_mask_map_fp8_zero_out_tokens(te_dtype, recipe): + """Quantized non-empty input whose routing map routes no token (num_out_tokens == 0).""" + if recipe.mxfp8() and not mxfp8_available: + pytest.skip(reason_for_no_mxfp8) + if recipe.float8_block_scaling() and not fp8_block_scaling_available: + pytest.skip(reason_for_no_fp8_block_scaling) + + _test_permutation_mask_map_fp8( + te_dtype=te_dtype, + num_tokens=256, + num_expert=8, + hidden_size=4096, + topK=2, + num_out_tokens=0, + recipe=recipe, + ) + + @pytest.mark.parametrize("te_dtype", _te_dtypes) @pytest.mark.parametrize("num_tokens", [4096]) @pytest.mark.parametrize("num_expert", [7, 16]) From 9b36c1f6d644e5830ee5a6978724b2495f6c8745 Mon Sep 17 00:00:00 2001 From: Chenxi Ma <114001934+algebra-MCX@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:19:15 -0800 Subject: [PATCH 3/3] [PyTorch] Reuse the permutation test helpers for num_out_tokens == 0 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 Signed-off-by: Chenxi Ma <114001934+algebra-MCX@users.noreply.github.com> --- tests/pytorch/test_permutation.py | 92 ++++------------------- transformer_engine/pytorch/permutation.py | 7 +- 2 files changed, 19 insertions(+), 80 deletions(-) diff --git a/tests/pytorch/test_permutation.py b/tests/pytorch/test_permutation.py index 03ec256748a..b0ce16ba72f 100644 --- a/tests/pytorch/test_permutation.py +++ b/tests/pytorch/test_permutation.py @@ -1799,83 +1799,23 @@ def test_permutation_mask_map_capacity_drop(torch_dtype, num_tokens): assert_close(unperm, ref_unperm) -@pytest.mark.parametrize("torch_dtype", [torch.float32, torch.bfloat16]) -@pytest.mark.parametrize( - "op, routed", - [ - ("permute", False), - ("permute", True), - ("permute_with_probs", False), - ("permute_with_probs", True), - ("permute_and_pad_with_probs", False), - ], -) +@pytest.mark.parametrize("te_dtype", _te_dtypes) @pytest.mark.parametrize("use_torch_compile", [False, True]) -def test_permutation_mask_map_zero_out_tokens(torch_dtype, op, routed, use_torch_compile): - """Non-empty input with num_out_tokens == 0. - - routed=False: no token is routed to any expert, e.g. an expert-parallel rank whose - local experts were not selected. routed=True: tokens are routed but the capacity is - zero, so every entry is dropped. Both must give an empty permuted buffer, a zero - unpermuted output and zero gradients.""" - if use_torch_compile and op == "permute_and_pad_with_probs": - pytest.skip("moe_permute_and_pad_with_probs reads tokens_per_expert on the host") - num_tokens, num_expert, hidden_size = 64, 8, 128 - torch.manual_seed(1234) - if routed: - routing_map = (torch.rand(num_tokens, num_expert) > 0.5).bool().cuda() - assert int(routing_map.sum()) > 0 - else: - routing_map = torch.zeros(num_tokens, num_expert, dtype=torch.bool, device="cuda") - inp = torch.randn(num_tokens, hidden_size, device="cuda", dtype=torch_dtype) - inp.requires_grad_(True) - probs = torch.rand(num_tokens, num_expert, device="cuda", requires_grad=True) - - def fn(inp, probs): - permuted_probs = None - if op == "permute": - out, row_id_map = te_permute(inp, routing_map, num_out_tokens=0, map_type="mask") - merging_probs = None - elif op == "permute_with_probs": - out, permuted_probs, row_id_map = te_permute_with_probs( - inp, probs, routing_map, num_out_tokens=0 - ) - merging_probs = probs - else: - tokens_per_expert = torch.zeros(num_expert, dtype=torch.int64, device="cuda") - out, permuted_probs, row_id_map, _, padded_tokens_per_expert = ( - te_permute_and_pad_with_probs( - inp, probs, routing_map, tokens_per_expert, align_size=16 - ) - ) - assert int(padded_tokens_per_expert.sum()) == 0 - merging_probs = None - restored = te_unpermute( - out, - row_id_map, - merging_probs=merging_probs, - restore_shape=inp.shape, - map_type="mask", - ) - return out, permuted_probs, restored - - out, permuted_probs, restored = _maybe_compile(fn, use_torch_compile)(inp, probs) - assert out.shape == (0, hidden_size) - if permuted_probs is not None: - assert permuted_probs.shape == (0,) - assert restored.shape == (num_tokens, hidden_size) - torch.testing.assert_close(restored, torch.zeros_like(restored), atol=0, rtol=0) - - loss = (restored.float() * torch.randn_like(restored, dtype=torch.float32)).sum() - if permuted_probs is not None: - loss = loss + permuted_probs.sum() - loss.backward() - torch.testing.assert_close(inp.grad, torch.zeros_like(inp), atol=0, rtol=0) - if op == "permute_with_probs": - # merging_probs feeds the unpermute, so probs must receive a (zero) gradient. - assert probs.grad is not None - if probs.grad is not None: - torch.testing.assert_close(probs.grad, torch.zeros_like(probs), atol=0, rtol=0) +def test_permutation_mask_map_zero_out_tokens(te_dtype, use_torch_compile): + """Non-empty input whose routing map routes no token (num_out_tokens == 0), e.g. an + expert-parallel rank whose local experts were not selected.""" + kwargs = dict( + te_dtype=te_dtype, + num_tokens=256, + num_expert=8, + hidden_size=4096, + topK=2, + num_out_tokens=0, + use_torch_compile=use_torch_compile, + ) + _test_permutation_mask_map(with_probs=True, **kwargs) + _test_permutation_mask_map_alongside_probs(tp_size=1, **kwargs) + _test_permutation_and_padding_mask_map(with_merging_probs=True, **kwargs) def test_permutation_mask_map_rejects_negative_out_tokens(): diff --git a/transformer_engine/pytorch/permutation.py b/transformer_engine/pytorch/permutation.py index 7b5d0cd4144..3149f7c90b7 100644 --- a/transformer_engine/pytorch/permutation.py +++ b/transformer_engine/pytorch/permutation.py @@ -560,8 +560,9 @@ def _moe_permute_mask_map_backward_wrapper( row_id_map, pad_offsets = ctx.saved_tensors - # Pass permuted_probs_grad only if it has content - probs_grad_input = grad_permuted_probs if grad_permuted_probs.numel() > 0 else None + # Pass permuted_probs_grad only when probs need a gradient. Its size cannot tell: + # with num_out_tokens == 0 it is empty even though probs need a (zero) gradient. + probs_grad_input = grad_permuted_probs if ctx.needs_probs_grad else None act_grad, probs_grad = torch.ops.te_moe.permute_mask_map_bwd( grad_output, @@ -600,8 +601,6 @@ def moe_unpermute_mask_map_forward( ) -> torch.Tensor: """Forward pass for MoE unpermute with mask router map.""" if not inp.numel(): - if num_tokens == 0: - return inp.clone() # No permuted rows (e.g. no token was routed to these experts): every # token receives nothing, so the output is zero. return torch.zeros((num_tokens, hidden_size), dtype=inp.dtype, device=inp.device)