From dcb12daecb392db5037bd795962cc64b6928a7eb Mon Sep 17 00:00:00 2001 From: wanglei875 Date: Sat, 5 Dec 2026 15:43:55 +0800 Subject: [PATCH 1/3] [PyTorch] Ensure contiguous inputs in fused_topk_with_score_function forward Signed-off-by: wanglei875 --- tests/pytorch/test_fused_router.py | 56 ++++++++++++++++++++++++++++ transformer_engine/pytorch/router.py | 22 +++++++++++ 2 files changed, 78 insertions(+) diff --git a/tests/pytorch/test_fused_router.py b/tests/pytorch/test_fused_router.py index e86350f8f1f..614422f0875 100644 --- a/tests/pytorch/test_fused_router.py +++ b/tests/pytorch/test_fused_router.py @@ -2597,6 +2597,62 @@ def test_fused_topk_with_aux_loss_scores_radix_threshold(threshold, expected): assert out.stdout.strip().splitlines()[-1] == expected +@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16]) +@pytest.mark.parametrize("score_function", ["softmax", "sigmoid"]) +def test_topk_non_contiguous_inputs(dtype, score_function): + """Non-contiguous logits and expert_bias views must match contiguous inputs.""" + num_tokens, num_experts, topk = 16, 8, 2 + full_logits = torch.randn( + num_tokens, 2 * num_experts, device="cuda", dtype=dtype, requires_grad=True + ) + logits_nc = full_logits[:, :num_experts] + assert not logits_nc.is_contiguous() + logits_c = logits_nc.detach().clone().contiguous().requires_grad_(True) + + expert_bias_nc = None + expert_bias_c = None + if score_function == "sigmoid": + full_bias = torch.randn(2 * num_experts, device="cuda", dtype=torch.float32) + expert_bias_nc = full_bias[::2] + assert not expert_bias_nc.is_contiguous() + expert_bias_c = expert_bias_nc.contiguous() + + probs_nc, map_nc = fused_topk_with_score_function( + logits_nc, + topk=topk, + use_pre_softmax=False, + num_groups=None, + group_topk=None, + scaling_factor=None, + score_function=score_function, + expert_bias=expert_bias_nc, + ) + probs_c, map_c = fused_topk_with_score_function( + logits_c, + topk=topk, + use_pre_softmax=False, + num_groups=None, + group_topk=None, + scaling_factor=None, + score_function=score_function, + expert_bias=expert_bias_c, + ) + + torch.testing.assert_close(probs_nc, probs_c, atol=0, rtol=0) + torch.testing.assert_close(map_nc, map_c, atol=0, rtol=0) + + grad_out = torch.randn_like(probs_c) + probs_nc.backward(grad_out) + probs_c.backward(grad_out) + torch.testing.assert_close(full_logits.grad[:, :num_experts], logits_c.grad, atol=0, rtol=0) + torch.testing.assert_close( + full_logits.grad[:, num_experts:], + torch.zeros_like(full_logits.grad[:, num_experts:]), + atol=0, + rtol=0, + ) + + def profile_topk_softmax( dtype, num_tokens, diff --git a/transformer_engine/pytorch/router.py b/transformer_engine/pytorch/router.py index 90279878c1f..d313da6f237 100644 --- a/transformer_engine/pytorch/router.py +++ b/transformer_engine/pytorch/router.py @@ -114,6 +114,10 @@ def forward( topk_indices: Optional[torch.Tensor], ): # pylint: disable=missing-function-docstring + if not logits.is_contiguous(): + logits = logits.contiguous() + if expert_bias is not None and not expert_bias.is_contiguous(): + expert_bias = expert_bias.contiguous() probs, routing_output, intermediate_output = tex.fused_topk_with_score_function_fwd( logits, topk, @@ -193,6 +197,12 @@ def forward( histogram_mode: int, ): # pylint: disable=missing-function-docstring + if not logits.is_contiguous(): + logits = logits.contiguous() + if not expert_bias.is_contiguous(): + expert_bias = expert_bias.contiguous() + if not bin_bounds.is_contiguous(): + bin_bounds = bin_bounds.contiguous() ( probs, routing_output, @@ -1113,6 +1123,9 @@ def _topk_map_forward( expert_bias: Optional[torch.Tensor], routing_map_format: int, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + logits = logits.contiguous() + if expert_bias is not None: + expert_bias = expert_bias.contiguous() with torch.cuda.device(logits.device): return tex.fused_topk_with_score_function_fwd( logits, @@ -1169,6 +1182,9 @@ def _topk_indices_forward( routing_map_format: int, topk_indices: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor]: + logits = logits.contiguous() + if expert_bias is not None: + expert_bias = expert_bias.contiguous() with torch.cuda.device(logits.device): probs, _, intermediate_output = tex.fused_topk_with_score_function_fwd( logits, @@ -1261,6 +1277,9 @@ def _qb_map_forward( bin_bounds: torch.Tensor, histogram_mode: int, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + logits = logits.contiguous() + expert_bias = expert_bias.contiguous() + bin_bounds = bin_bounds.contiguous() with torch.cuda.device(logits.device): probs, routing_output, intermediate_output, _, _ = ( tex.fused_topk_with_score_function_qb_fwd( @@ -1311,6 +1330,9 @@ def _qb_indices_forward( bin_bounds: torch.Tensor, histogram_mode: int, ) -> Tuple[torch.Tensor, torch.Tensor]: + logits = logits.contiguous() + expert_bias = expert_bias.contiguous() + bin_bounds = bin_bounds.contiguous() with torch.cuda.device(logits.device): probs, _, intermediate_output, _, _ = tex.fused_topk_with_score_function_qb_fwd( logits, From 5d186a2bbbc5f0f8ce5bda3f38156a7dcd815825 Mon Sep 17 00:00:00 2001 From: wanglei875 Date: Sat, 5 Dec 2026 15:49:00 +0800 Subject: [PATCH 2/3] Return contiguous fake tensors for dense-index router ops and expand tests Signed-off-by: wanglei875 --- tests/pytorch/test_fused_router.py | 124 ++++++++++++++++++++++++--- transformer_engine/pytorch/router.py | 4 +- 2 files changed, 114 insertions(+), 14 deletions(-) diff --git a/tests/pytorch/test_fused_router.py b/tests/pytorch/test_fused_router.py index 614422f0875..539bc86cca3 100644 --- a/tests/pytorch/test_fused_router.py +++ b/tests/pytorch/test_fused_router.py @@ -2597,15 +2597,28 @@ def test_fused_topk_with_aux_loss_scores_radix_threshold(threshold, expected): assert out.stdout.strip().splitlines()[-1] == expected +@pytest.mark.parametrize("execution", ["eager", "compile"]) @pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16]) @pytest.mark.parametrize("score_function", ["softmax", "sigmoid"]) -def test_topk_non_contiguous_inputs(dtype, score_function): +@pytest.mark.parametrize("layout", ["slice", "transpose_dense"]) +def test_topk_non_contiguous_inputs(execution, dtype, score_function, layout): """Non-contiguous logits and expert_bias views must match contiguous inputs.""" num_tokens, num_experts, topk = 16, 8, 2 - full_logits = torch.randn( - num_tokens, 2 * num_experts, device="cuda", dtype=dtype, requires_grad=True - ) - logits_nc = full_logits[:, :num_experts] + if layout == "slice": + base_logits = torch.randn( + num_tokens, 2 * num_experts, device="cuda", dtype=dtype, requires_grad=True + ) + logits_nc = base_logits[:, :num_experts] + topk_indices_nc = None + topk_indices_c = None + else: + base_logits = torch.randn( + num_experts, num_tokens, device="cuda", dtype=dtype, requires_grad=True + ) + logits_nc = base_logits.transpose(0, 1) + topk_indices_nc = torch.empty((num_tokens, topk), device="cuda", dtype=torch.int16) + topk_indices_c = torch.empty((num_tokens, topk), device="cuda", dtype=torch.int16) + assert not logits_nc.is_contiguous() logits_c = logits_nc.detach().clone().contiguous().requires_grad_(True) @@ -2617,7 +2630,8 @@ def test_topk_non_contiguous_inputs(dtype, score_function): assert not expert_bias_nc.is_contiguous() expert_bias_c = expert_bias_nc.contiguous() - probs_nc, map_nc = fused_topk_with_score_function( + router = _router_function(fused_topk_with_score_function, execution) + probs_nc, map_nc = router( logits_nc, topk=topk, use_pre_softmax=False, @@ -2626,6 +2640,7 @@ def test_topk_non_contiguous_inputs(dtype, score_function): scaling_factor=None, score_function=score_function, expert_bias=expert_bias_nc, + topk_indices=topk_indices_nc, ) probs_c, map_c = fused_topk_with_score_function( logits_c, @@ -2636,22 +2651,107 @@ def test_topk_non_contiguous_inputs(dtype, score_function): scaling_factor=None, score_function=score_function, expert_bias=expert_bias_c, + topk_indices=topk_indices_c, ) + assert probs_nc.is_contiguous() torch.testing.assert_close(probs_nc, probs_c, atol=0, rtol=0) torch.testing.assert_close(map_nc, map_c, atol=0, rtol=0) grad_out = torch.randn_like(probs_c) probs_nc.backward(grad_out) probs_c.backward(grad_out) - torch.testing.assert_close(full_logits.grad[:, :num_experts], logits_c.grad, atol=0, rtol=0) - torch.testing.assert_close( - full_logits.grad[:, num_experts:], - torch.zeros_like(full_logits.grad[:, num_experts:]), - atol=0, - rtol=0, + if layout == "slice": + torch.testing.assert_close( + base_logits.grad[:, :num_experts], logits_c.grad, atol=0, rtol=0 + ) + torch.testing.assert_close( + base_logits.grad[:, num_experts:], + torch.zeros_like(base_logits.grad[:, num_experts:]), + atol=0, + rtol=0, + ) + else: + torch.testing.assert_close( + base_logits.grad.transpose(0, 1), logits_c.grad, atol=0, rtol=0 + ) + + +@pytest.mark.parametrize("execution", ["eager", "compile"]) +@pytest.mark.parametrize("use_dense_indices", [False, True]) +def test_qb_topk_non_contiguous_inputs(execution, use_dense_indices): + """Non-contiguous logits, expert_bias, and qb_bin_bounds match contiguous QB inputs.""" + num_tokens, num_experts, topk, num_bins = 16, 8, 2, 16 + base_logits = torch.randn( + num_experts, num_tokens, device="cuda", dtype=torch.float32, requires_grad=True + ) + logits_nc = base_logits.transpose(0, 1) + assert not logits_nc.is_contiguous() + logits_c = logits_nc.detach().clone().contiguous().requires_grad_(True) + + full_bias = torch.randn(2 * num_experts, device="cuda", dtype=torch.float32) + expert_bias_nc = full_bias[::2] + assert not expert_bias_nc.is_contiguous() + expert_bias_c = expert_bias_nc.contiguous() + + full_bounds = torch.tensor([-1.0, 99.0, 1.0, -99.0], device="cuda", dtype=torch.float32) + bin_bounds_nc = full_bounds[::2] + assert not bin_bounds_nc.is_contiguous() + bin_bounds_c = bin_bounds_nc.contiguous() + + histogram_nc = torch.zeros(num_experts, num_bins, dtype=torch.int32, device="cuda") + histogram_c = torch.zeros(num_experts, num_bins, dtype=torch.int32, device="cuda") + topk_indices_nc = ( + torch.empty((num_tokens, topk), device="cuda", dtype=torch.int16) + if use_dense_indices + else None + ) + topk_indices_c = ( + torch.empty((num_tokens, topk), device="cuda", dtype=torch.int16) + if use_dense_indices + else None ) + router = _router_function(fused_topk_with_score_function, execution) + probs_nc, map_nc = router( + logits_nc, + topk=topk, + use_pre_softmax=False, + num_groups=None, + group_topk=None, + scaling_factor=None, + score_function="sigmoid", + expert_bias=expert_bias_nc, + topk_indices=topk_indices_nc, + qb_histogram=histogram_nc, + qb_bin_bounds=bin_bounds_nc, + qb_histogram_mode="two_kernel", + ) + probs_c, map_c = fused_topk_with_score_function( + logits_c, + topk=topk, + use_pre_softmax=False, + num_groups=None, + group_topk=None, + scaling_factor=None, + score_function="sigmoid", + expert_bias=expert_bias_c, + topk_indices=topk_indices_c, + qb_histogram=histogram_c, + qb_bin_bounds=bin_bounds_c, + qb_histogram_mode="two_kernel", + ) + + assert probs_nc.is_contiguous() + torch.testing.assert_close(probs_nc, probs_c, atol=0, rtol=0) + torch.testing.assert_close(map_nc, map_c, atol=0, rtol=0) + torch.testing.assert_close(histogram_nc, histogram_c, atol=0, rtol=0) + + grad_out = torch.randn_like(probs_c) + probs_nc.backward(grad_out) + probs_c.backward(grad_out) + torch.testing.assert_close(base_logits.grad.transpose(0, 1), logits_c.grad, atol=0, rtol=0) + def profile_topk_softmax( dtype, diff --git a/transformer_engine/pytorch/router.py b/transformer_engine/pytorch/router.py index d313da6f237..ecda6d31615 100644 --- a/transformer_engine/pytorch/router.py +++ b/transformer_engine/pytorch/router.py @@ -1216,7 +1216,7 @@ def _topk_indices_forward_fake( ): del topk, use_pre_softmax, num_groups, group_topk, scaling_factor del score_function, expert_bias, routing_map_format, topk_indices - return torch.empty_like(logits), torch.empty_like(logits, dtype=torch.float32) + return logits.new_empty(logits.shape), logits.new_empty(logits.shape, dtype=torch.float32) @torch.library.custom_op("te_moe::router_topk_bwd", mutates_args=()) @@ -1362,7 +1362,7 @@ def _qb_indices_forward_fake( ): del topk, scaling_factor, expert_bias, routing_map_format, topk_indices del histogram, bin_bounds, histogram_mode - return torch.empty_like(logits), torch.empty_like(logits, dtype=torch.float32) + return logits.new_empty(logits.shape), logits.new_empty(logits.shape, dtype=torch.float32) @torch.library.custom_op("te_moe::router_score_fwd", mutates_args=()) From 111918560e8ad6892af776c23ef79229121ebbb3 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sat, 5 Dec 2026 07:50:32 +0000 Subject: [PATCH 3/3] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- tests/pytorch/test_fused_router.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/tests/pytorch/test_fused_router.py b/tests/pytorch/test_fused_router.py index 539bc86cca3..e174125c154 100644 --- a/tests/pytorch/test_fused_router.py +++ b/tests/pytorch/test_fused_router.py @@ -2662,9 +2662,7 @@ def test_topk_non_contiguous_inputs(execution, dtype, score_function, layout): probs_nc.backward(grad_out) probs_c.backward(grad_out) if layout == "slice": - torch.testing.assert_close( - base_logits.grad[:, :num_experts], logits_c.grad, atol=0, rtol=0 - ) + torch.testing.assert_close(base_logits.grad[:, :num_experts], logits_c.grad, atol=0, rtol=0) torch.testing.assert_close( base_logits.grad[:, num_experts:], torch.zeros_like(base_logits.grad[:, num_experts:]), @@ -2672,9 +2670,7 @@ def test_topk_non_contiguous_inputs(execution, dtype, score_function, layout): rtol=0, ) else: - torch.testing.assert_close( - base_logits.grad.transpose(0, 1), logits_c.grad, atol=0, rtol=0 - ) + torch.testing.assert_close(base_logits.grad.transpose(0, 1), logits_c.grad, atol=0, rtol=0) @pytest.mark.parametrize("execution", ["eager", "compile"])