import torch
import triton
import triton.language as tl
@triton.jit
def grouped_matmul_kernel(
# Device pointers to A, B, C matrices
group_a_ptrs_ptr, # (group_size,)
group_b_ptrs_ptr, # (group_size,)
group_c_ptrs_ptr, # (group_size,)
# GEMM sizes: [M, N, K] for each GEMM
group_gemm_sizes_ptr, # (group_size * 3,)
# Leading dimensions: [lda, ldb, ldc] for each GEMM
g_lds_ptr, # (group_size * 3,)
# Number of GEMMs
group_size,
# Number of virtual SMs
NUM_SM: tl.constexpr,
# Tile sizes
BLOCK_SIZE_M: tl.constexpr,
BLOCK_SIZE_N: tl.constexpr,
BLOCK_SIZE_K: tl.constexpr,
):
pid = tl.program_id(0) # virtual SM id
grid = NUM_SM
# Each CTA handles gemms assigned to it based on pid and grid
for gemm_id in range(pid, group_size, grid):
# Load pointers for A, B, C
a_ptr = tl.load(group_a_ptrs_ptr + gemm_id, mask=gemm_id < group_size, other=0)
b_ptr = tl.load(group_b_ptrs_ptr + gemm_id, mask=gemm_id < group_size, other=0)
c_ptr = tl.load(group_c_ptrs_ptr + gemm_id, mask=gemm_id < group_size, other=0)
# Load GEMM sizes: M, N, K
gemm_size = group_gemm_sizes_ptr + gemm_id * 3
M = tl.load(gemm_size + 0, mask=gemm_id < group_size, other=0)
N = tl.load(gemm_size + 1, mask=gemm_id < group_size, other=0)
K = tl.load(gemm_size + 2, mask=gemm_id < group_size, other=0)
# Load leading dimensions: lda, ldb, ldc
lds = g_lds_ptr + gemm_id * 3
lda = tl.load(lds + 0, mask=gemm_id < group_size, other=1)
ldb = tl.load(lds + 1, mask=gemm_id < group_size, other=1)
ldc = tl.load(lds + 2, mask=gemm_id < group_size, other=1)
# Early exit if M or N is zero
should_compute = (M > 0) & (N > 0) & (K > 0)
if not should_compute:
continue
# Cast pointers to float16
a = tl.memory(pointers=a_ptr, dtype=tl.float16)
b = tl.memory(pointers=b_ptr, dtype=tl.float16)
c = tl.memory(pointers=c_ptr, dtype=tl.float16)
# Initialize accumulator
acc = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
# Loop over K dimension
for k in range(0, K, BLOCK_SIZE_K):
# Load A tile
a_tile = tl.load(a_ptr + (k + tl.arange(0, BLOCK_SIZE_K))[:, None] * lda + tl.arange(0, BLOCK_SIZE_M)[None, :],
mask=(k + tl.arange(0, BLOCK_SIZE_K)[:, None] < K) & (tl.arange(0, BLOCK_SIZE_M)[None, :] < M),
other=0.0)
# Load B tile
b_tile = tl.load(b_ptr + (k + tl.arange(0, BLOCK_SIZE_K)) * ldb + tl.arange(0, BLOCK_SIZE_N)[None, :],
mask=(k + tl.arange(0, BLOCK_SIZE_K)[:, None] < K) & (tl.arange(0, BLOCK_SIZE_N)[None, :] < N),
other=0.0)
# Convert to float32 for accumulation
a_tile = a_tile.to(tl.float32)
b_tile = b_tile.to(tl.float32)
# Perform matrix multiplication
acc += tl.dot(a_tile, b_tile)
# Load existing C
c_val = tl.load(c_ptr, dtype=tl.float16)
c_val = c_val.to(tl.float32)
# Update C
c_val += acc
# Store the result back to C
tl.store(c_ptr, c_val.to(tl.float16))
def group_gemm_fn(group_A, group_B, group_C=None,
BLOCK_SIZE_M=128, BLOCK_SIZE_N=128, BLOCK_SIZE_K=128):
group_size = len(group_A)
# Initialize C if not provided
if group_C is None:
group_C = [torch.zeros((A.size(0), B.size(1)), device="cuda", dtype=A.dtype) for A, B in zip(group_A, group_B)]
# Prepare device pointers
group_a_ptrs = torch.tensor([a.data_ptr() for a in group_A], device="cuda", dtype=torch.int64)
group_b_ptrs = torch.tensor([b.data_ptr() for b in group_B], device="cuda", dtype=torch.int64)
group_c_ptrs = torch.tensor([c.data_ptr() for c in group_C], device="cuda", dtype=torch.int64)
# Prepare GEMM sizes and leading dimensions
group_gemm_sizes = torch.tensor([size for gemm in zip(group_A, group_B)
for size in [gemm[0].size(0), gemm[1].size(1), gemm[0].size(1)]],
device="cuda", dtype=torch.int32)
group_lds = torch.tensor([ld for gemm in zip(group_A, group_B, group_C)
for ld in [gemm[0].stride(0), gemm[1].stride(0), gemm[2].stride(0)]],
device="cuda", dtype=torch.int32)
# Define grid
NUM_SM = 8 # Example: Adjust based on your GPU
grid = (NUM_SM,)
# Launch the Triton kernel
grouped_matmul_kernel[grid](
group_a_ptrs,
group_b_ptrs,
group_c_ptrs,
group_gemm_sizes,
group_lds,
group_size,
NUM_SM=NUM_SM,
BLOCK_SIZE_M=BLOCK_SIZE_M,
BLOCK_SIZE_N=BLOCK_SIZE_N,
BLOCK_SIZE_K=BLOCK_SIZE_K,
)
return group_C
# Test Cases
def test_grouped_gemm():
group_m = [1024, 512, 256, 128]
group_n = [1024, 512, 256, 128]
group_k = [1024, 512, 256, 128]
group_A = []
group_B = []
group_C = []
assert len(group_m) == len(group_n)
assert len(group_n) == len(group_k)
group_size = len(group_m)
for i in range(group_size):
M = group_m[i]
N = group_n[i]
K = group_k[i]
dtype = torch.float16
A = torch.rand((M, K), device="cuda", dtype=dtype)
B = torch.rand((K, N), device="cuda", dtype=dtype)
C = torch.zeros((M, N), device="cuda", dtype=dtype)
group_A.append(A)
group_B.append(B)
group_C.append(C)
# Run grouped GEMM
tri_out = group_gemm_fn(group_A, group_B, group_C)
# Reference output
ref_out = [torch.matmul(a, b) for a, b in zip(group_A, group_B)]
# Verification
for i in range(group_size):
assert torch.allclose(tri_out[i], ref_out[i], atol=1e-2, rtol=1e-2), f"GEMM {i} does not match!"
print("All test cases passed!")
# Run the test
test_grouped_gemm()