import torch import torch.nn as nn import triton import triton.language as tl @triton.jit def _matmul_kernel( a_ptr, b_ptr, c_ptr, M, N, K, stride_am, stride_ak, stride_bk, stride_bn, stride_cm, stride_cn, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, GROUP_M: tl.constexpr, ): pid = tl.program_id(axis=0) num_pid_m = tl.cdiv(M, BLOCK_M) num_pid_n = tl.cdiv(N, BLOCK_N) num_pid_in_group = GROUP_M * num_pid_n group_id = pid // num_pid_in_group first_pid_m = group_id * GROUP_M group_size_m = min(num_pid_m - first_pid_m, GROUP_M) pid_m = first_pid_m + (pid % group_size_m) pid_n = (pid % num_pid_in_group) // group_size_m offs_am = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) offs_bn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) offs_k = tl.arange(0, BLOCK_K) a_ptrs = a_ptr + (offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak) b_ptrs = b_ptr + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn) acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) for k in range(0, tl.cdiv(K, BLOCK_K)): a = tl.load(a_ptrs, mask=offs_k[None, :] < K - k * BLOCK_K, other=0.0) b = tl.load(b_ptrs, mask=offs_k[:, None] < K - k * BLOCK_K, other=0.0) acc += tl.dot(a, b) a_ptrs += BLOCK_K * stride_ak b_ptrs += BLOCK_K * stride_bk c = acc.to(tl.bfloat16) offs_cm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) offs_cn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) c_ptrs = c_ptr + offs_cm[:, None] * stride_cm + offs_cn[None, :] * stride_cn tl.store(c_ptrs, c, mask=(offs_cm[:, None] < M) & (offs_cn[None, :] < N)) def _matmul(a: torch.Tensor, b: torch.Tensor, block_m: int = 128, block_n: int = 256, block_k: int = 64): """c = a @ b, where a (M,K) bf16, b (K,N) bf16, output (M,N) bf16.""" M, K = a.shape K2, N = b.shape assert K == K2 c = torch.empty((M, N), device=a.device, dtype=torch.bfloat16) grid = lambda META: (triton.cdiv(M, META["BLOCK_M"]) * triton.cdiv(N, META["BLOCK_N"]),) _matmul_kernel[grid]( a, b, c, M, N, K, a.stride(0), a.stride(1), b.stride(0), b.stride(1), c.stride(0), c.stride(1), BLOCK_M=block_m, BLOCK_N=block_n, BLOCK_K=block_k, GROUP_M=8, ) return c class Model(nn.Module): """y = (x @ w.T).to(bf16), x is fp8_e4m3 (M,K), w is fp8_e4m3 (N,K).""" def __init__(self, M: int, N: int, K: int): super().__init__() self.M, self.N, self.K = M, N, K self.weight = nn.Parameter(torch.empty(N, K, dtype=torch.bfloat16)) nn.init.normal_(self.weight, std=0.02) def forward(self, x: torch.Tensor) -> torch.Tensor: a = x.to(torch.bfloat16) b = self.weight.T # Heuristic tile shapes. if self.M <= 64: return _matmul(a, b, block_m=32, block_n=256, block_k=64) elif self.N >= 12288: return _matmul(a, b, block_m=128, block_n=256, block_k=64) else: return _matmul(a, b, block_m=128, block_n=128, block_k=64) M = 4096 N = 4096 K = 4096 def get_inputs(): x = (torch.rand(M, K) * 8 - 4).to(torch.float8_e4m3fn) return [x] def get_init_inputs(): return [M, N, K]