Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 152 additions & 0 deletions tests/pytorch/test_fused_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -2597,6 +2597,158 @@ 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"])
@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
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)

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()

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=score_function,
expert_bias=expert_bias_nc,
topk_indices=topk_indices_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,
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)
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,
num_tokens,
Expand Down
26 changes: 24 additions & 2 deletions transformer_engine/pytorch/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -1169,6 +1182,9 @@ def _topk_indices_forward(
routing_map_format: int,
topk_indices: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor]:
logits = logits.contiguous()
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
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,
Expand Down Expand Up @@ -1200,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=())
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -1340,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=())
Expand Down