[GH-ISSUE #38] Using -1 in m_indices to skip experts doesn't seem to work in m_grouped_gemm_fp8_fp8_bf16_nt_contiguous #27

Closed
opened 2026-10-26 21:10:50 +00:00 by bsakaguchi · 1 comment
Owner

Originally created by @bnellnm on GitHub (Mar 4, 2025).
Original GitHub issue: https://github.com/deepseek-ai/DeepGEMM/issues/38

According to the documentation of m_grouped_gemm_fp8_fp8_bf16_nt_contiguous: "-1 in this tensor indicates no RHS matrix selected, the kernel will skip the computation for that aligned block.", but when I try using this feature I end up with crashes or wrong answers. See attached script derived from test_core.py

import random
import torch
from typing import Tuple

import deep_gemm
from deep_gemm import calc_diff, ceil_div, get_col_major_tma_aligned_tensor


def per_token_cast_to_fp8(x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
    assert x.dim() == 2 and x.size(1) % 128 == 0
    m, n = x.shape
    x_view = x.view(m, -1, 128)
    x_amax = x_view.abs().float().amax(dim=2).view(m, -1).clamp(1e-4)
    return (x_view * (448.0 / x_amax.unsqueeze(2))).to(torch.float8_e4m3fn).view(m, n), (x_amax / 448.0).view(m, -1)


def per_block_cast_to_fp8(x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
    assert x.dim() == 2
    m, n = x.shape
    x_padded = torch.zeros((ceil_div(m, 128) * 128, ceil_div(n, 128) * 128), dtype=x.dtype, device=x.device)
    x_padded[:m, :n] = x
    x_view = x_padded.view(-1, 128, x_padded.size(1) // 128, 128)
    x_amax = x_view.abs().float().amax(dim=(1, 3), keepdim=True).clamp(1e-4)
    x_scaled = (x_view * (448.0 / x_amax)).to(torch.float8_e4m3fn)
    return x_scaled.view_as(x_padded)[:m, :n].contiguous(), (x_amax / 448.0).view(x_view.size(0), x_view.size(2))


def construct_grouped(num_groups: int, m: int, k: int, n: int, is_masked: bool) -> \
        Tuple[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor, torch.Tensor], torch.Tensor, torch.Tensor]:
    x = torch.randn((num_groups, m, k), device='cuda', dtype=torch.bfloat16)
    y = torch.randn((num_groups, n, k), device='cuda', dtype=torch.bfloat16)
    out = torch.empty((num_groups, m, n), device='cuda', dtype=torch.bfloat16)
    ref_out = torch.einsum('gmk,gnk->gmn', x, y)

    assert m % 4 == 0, f'TMA alignment error: {m}'
    x_fp8 = (torch.empty_like(x, dtype=torch.float8_e4m3fn),
             torch.empty((num_groups, m, k // 128), device='cuda', dtype=torch.float))
    y_fp8 = (torch.empty_like(y, dtype=torch.float8_e4m3fn),
             torch.empty((num_groups, (n + 127) // 128, k // 128), device='cuda', dtype=torch.float))
    for i in range(num_groups):
	x_fp8[0][i], x_fp8[1][i] = per_token_cast_to_fp8(x[i])
	y_fp8[0][i], y_fp8[1][i] = per_block_cast_to_fp8(y[i])

    # For non-masked input, we must merge the group and M dims                                                               
    if not is_masked:
	x_fp8 = (x_fp8[0].view(-1, k), per_token_cast_to_fp8(x.view(-1, k))[1])
	out, ref_out = out.view(-1, n), ref_out.view(-1, n)

    # Transpose earlier so that the testing will not trigger transposing kernels                                             
    x_fp8 = (x_fp8[0], get_col_major_tma_aligned_tensor(x_fp8[1]))
    return x_fp8, y_fp8, out, ref_out


def test_m_grouped_gemm_contiguous() -> None:
    print('Testing grouped contiguous GEMM:')

    num_groups, m, k, n = (4, 8192, 7168, 4096)
    x_fp8, y_fp8, out, ref_out = construct_grouped(num_groups, m, k, n, is_masked=False)
    m_indices = torch.arange(0, num_groups, device='cuda', dtype=torch.int)
    print("Try to skip the first block.")
    m_indices[m_indices == 0] = -1
    m_indices = m_indices.unsqueeze(-1).expand(num_groups, m).contiguous().view(-1)
    print(m_indices)
    deep_gemm.m_grouped_gemm_fp8_fp8_bf16_nt_contiguous(x_fp8, y_fp8, out, m_indices)
    diff = calc_diff(out, ref_out)
    assert diff < 0.001, f'm={m * num_groups}, {k=}, {n=}, {diff:.5f}'


if __name__ == '__main__':
    torch.backends.cuda.matmul.allow_tf32 = True
    torch.backends.cudnn.allow_tf32 = True
    torch.manual_seed(0)
    random.seed(0)

    print('Library path:')
    print(f' > {deep_gemm.__path__}\n')

    test_m_grouped_gemm_contiguous()
> python3 test_bug.py
Testing grouped contiguous GEMM:
Try to skip the first block.
tensor([-1, -1, -1,  ...,  3,  3,  3], device='cuda:0', dtype=torch.int32)
Traceback (most recent call last):
  File "/home/bnell/DeepGEMM/tests/test_bug.py", line 82, in <module>
    test_m_grouped_gemm_contiguous()
  File "/home/bnell/DeepGEMM/tests/test_bug.py", line 67, in test_m_grouped_gemm_contiguous
    diff = calc_diff(out, ref_out)
  File "/home/bnell/DeepGEMM/deep_gemm/utils.py", line 142, in calc_diff
    denominator = (x * x + y * y).sum()
RuntimeError: CUDA error: an illegal memory access was encountered
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be in\
correct.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1
Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.
Originally created by @bnellnm on GitHub (Mar 4, 2025). Original GitHub issue: https://github.com/deepseek-ai/DeepGEMM/issues/38 According to the documentation of `m_grouped_gemm_fp8_fp8_bf16_nt_contiguous`: "`-1` in this tensor indicates no RHS matrix selected, the kernel will skip the computation for that aligned block.", but when I try using this feature I end up with crashes or wrong answers. See attached script derived from `test_core.py` ``` import random import torch from typing import Tuple import deep_gemm from deep_gemm import calc_diff, ceil_div, get_col_major_tma_aligned_tensor def per_token_cast_to_fp8(x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: assert x.dim() == 2 and x.size(1) % 128 == 0 m, n = x.shape x_view = x.view(m, -1, 128) x_amax = x_view.abs().float().amax(dim=2).view(m, -1).clamp(1e-4) return (x_view * (448.0 / x_amax.unsqueeze(2))).to(torch.float8_e4m3fn).view(m, n), (x_amax / 448.0).view(m, -1) def per_block_cast_to_fp8(x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: assert x.dim() == 2 m, n = x.shape x_padded = torch.zeros((ceil_div(m, 128) * 128, ceil_div(n, 128) * 128), dtype=x.dtype, device=x.device) x_padded[:m, :n] = x x_view = x_padded.view(-1, 128, x_padded.size(1) // 128, 128) x_amax = x_view.abs().float().amax(dim=(1, 3), keepdim=True).clamp(1e-4) x_scaled = (x_view * (448.0 / x_amax)).to(torch.float8_e4m3fn) return x_scaled.view_as(x_padded)[:m, :n].contiguous(), (x_amax / 448.0).view(x_view.size(0), x_view.size(2)) def construct_grouped(num_groups: int, m: int, k: int, n: int, is_masked: bool) -> \ Tuple[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor, torch.Tensor], torch.Tensor, torch.Tensor]: x = torch.randn((num_groups, m, k), device='cuda', dtype=torch.bfloat16) y = torch.randn((num_groups, n, k), device='cuda', dtype=torch.bfloat16) out = torch.empty((num_groups, m, n), device='cuda', dtype=torch.bfloat16) ref_out = torch.einsum('gmk,gnk->gmn', x, y) assert m % 4 == 0, f'TMA alignment error: {m}' x_fp8 = (torch.empty_like(x, dtype=torch.float8_e4m3fn), torch.empty((num_groups, m, k // 128), device='cuda', dtype=torch.float)) y_fp8 = (torch.empty_like(y, dtype=torch.float8_e4m3fn), torch.empty((num_groups, (n + 127) // 128, k // 128), device='cuda', dtype=torch.float)) for i in range(num_groups): x_fp8[0][i], x_fp8[1][i] = per_token_cast_to_fp8(x[i]) y_fp8[0][i], y_fp8[1][i] = per_block_cast_to_fp8(y[i]) # For non-masked input, we must merge the group and M dims if not is_masked: x_fp8 = (x_fp8[0].view(-1, k), per_token_cast_to_fp8(x.view(-1, k))[1]) out, ref_out = out.view(-1, n), ref_out.view(-1, n) # Transpose earlier so that the testing will not trigger transposing kernels x_fp8 = (x_fp8[0], get_col_major_tma_aligned_tensor(x_fp8[1])) return x_fp8, y_fp8, out, ref_out def test_m_grouped_gemm_contiguous() -> None: print('Testing grouped contiguous GEMM:') num_groups, m, k, n = (4, 8192, 7168, 4096) x_fp8, y_fp8, out, ref_out = construct_grouped(num_groups, m, k, n, is_masked=False) m_indices = torch.arange(0, num_groups, device='cuda', dtype=torch.int) print("Try to skip the first block.") m_indices[m_indices == 0] = -1 m_indices = m_indices.unsqueeze(-1).expand(num_groups, m).contiguous().view(-1) print(m_indices) deep_gemm.m_grouped_gemm_fp8_fp8_bf16_nt_contiguous(x_fp8, y_fp8, out, m_indices) diff = calc_diff(out, ref_out) assert diff < 0.001, f'm={m * num_groups}, {k=}, {n=}, {diff:.5f}' if __name__ == '__main__': torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True torch.manual_seed(0) random.seed(0) print('Library path:') print(f' > {deep_gemm.__path__}\n') test_m_grouped_gemm_contiguous() ``` ``` > python3 test_bug.py Testing grouped contiguous GEMM: Try to skip the first block. tensor([-1, -1, -1, ..., 3, 3, 3], device='cuda:0', dtype=torch.int32) Traceback (most recent call last): File "/home/bnell/DeepGEMM/tests/test_bug.py", line 82, in <module> test_m_grouped_gemm_contiguous() File "/home/bnell/DeepGEMM/tests/test_bug.py", line 67, in test_m_grouped_gemm_contiguous diff = calc_diff(out, ref_out) File "/home/bnell/DeepGEMM/deep_gemm/utils.py", line 142, in calc_diff denominator = (x * x + y * y).sum() RuntimeError: CUDA error: an illegal memory access was encountered CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be in\ correct. For debugging consider passing CUDA_LAUNCH_BLOCKING=1 Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions. ```
Author
Owner

@soundOfDestiny commented on GitHub (Mar 4, 2025):

The documentation was incorrect and it has been fixed in latest main yesterday.

<!-- gh-comment-id:2699176162 --> @soundOfDestiny commented on GitHub (Mar 4, 2025): The documentation was incorrect and it has been fixed in latest main yesterday.
Sign in to join this conversation.
No labels
pull-request
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
deepseek-ai/DeepGEMM#27
No description provided.