"""Triton grouped GEMM + fused SwiGLU up-projection for top-K MoE FFN. Performs: h_e = silu(x_e @ W_gate[e]) * (x_e @ W_up[e]) where x_e is the slice of permuted hidden states routed to expert e. """ from __future__ import annotations import torch import torch.nn as nn import triton import triton.language as tl @triton.jit def _swiglu_kernel( x_ptr, w_gate_ptr, w_up_ptr, out_ptr, offsets_ptr, H: tl.constexpr, I: tl.constexpr, stride_xm: tl.constexpr, stride_wm0: tl.constexpr, stride_wm1: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, ): """One CUDA block = one (expert, m-tile, n-tile).""" pid_e = tl.program_id(0) pid_m = tl.program_id(1) pid_n = tl.program_id(2) start = tl.load(offsets_ptr + pid_e) end = tl.load(offsets_ptr + pid_e + 1) M_e = end - start m0 = pid_m * BLOCK_M n0 = pid_n * BLOCK_N if m0 >= M_e: return # Tile bounds (relative to this expert's slice) rm = m0 + tl.arange(0, BLOCK_M) rn = n0 + tl.arange(0, BLOCK_N) mask_m = rm < M_e mask_n = rn < I # Output tile accumulator acc_gate = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) acc_up = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) # Pointers relative to this expert's slice x_e_ptr = x_ptr + start * stride_xm out_e_ptr = out_ptr + start * I # Weight base for this expert w_gate_e = w_gate_ptr + pid_e * stride_wm0 w_up_e = w_up_ptr + pid_e * stride_wm0 for k0 in range(0, H, BLOCK_K): rk = k0 + tl.arange(0, BLOCK_K) mask_k = rk < H # Load X tile: (BLOCK_M, BLOCK_K) x_offs = rm[:, None] * stride_xm + rk[None, :] x = tl.load(x_e_ptr + x_offs, mask=mask_m[:, None] & mask_k[None, :], other=0.0).to(tl.bfloat16) # Load gate weight tile: (BLOCK_K, BLOCK_N) w_gate_offs = rk[:, None] * stride_wm1 + rn[None, :] w_gate = tl.load(w_gate_e + w_gate_offs, mask=mask_k[:, None] & mask_n[None, :], other=0.0).to(tl.bfloat16) # Load up weight tile w_up = tl.load(w_up_e + w_gate_offs, mask=mask_k[:, None] & mask_n[None, :], other=0.0).to(tl.bfloat16) acc_gate = tl.dot(x, w_gate, acc_gate) acc_up = tl.dot(x, w_up, acc_up) gate = acc_gate.to(tl.bfloat16) up = acc_up.to(tl.bfloat16) # SwiGLU epilogue silu = gate * tl.sigmoid(gate.to(tl.float32)).to(tl.bfloat16) out = silu * up # Store output tile out_e_ptr = out_ptr + start * I out_offs = rm[:, None] * I + rn[None, :] tl.store(out_e_ptr + out_offs, out, mask=mask_m[:, None] & mask_n[None, :]) # Autotune over a small set of shapes that should perform well on Blackwell/Hopper. @triton.autotune( configs=[ triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "BLOCK_K": 64, "GROUP_SIZE_M": 1}, num_stages=3, num_warps=4), triton.Config({"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 64, "GROUP_SIZE_M": 1}, num_stages=3, num_warps=4), triton.Config({"BLOCK_M": 128, "BLOCK_N": 64, "BLOCK_K": 64, "GROUP_SIZE_M": 1}, num_stages=3, num_warps=4), triton.Config({"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 64, "GROUP_SIZE_M": 1}, num_stages=3, num_warps=4), triton.Config({"BLOCK_M": 64, "BLOCK_N": 256, "BLOCK_K": 64, "GROUP_SIZE_M": 1}, num_stages=3, num_warps=8), triton.Config({"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 64, "GROUP_SIZE_M": 1}, num_stages=2, num_warps=8), triton.Config({"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 64, "GROUP_SIZE_M": 1}, num_stages=2, num_warps=8), triton.Config({"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 128, "GROUP_SIZE_M": 1}, num_stages=2, num_warps=4), ], key=["H", "I"], ) @triton.jit def _swiglu_kernel_autotune( x_ptr, w_gate_ptr, w_up_ptr, out_ptr, offsets_ptr, H: tl.constexpr, I: tl.constexpr, stride_xm: tl.constexpr, stride_wm0: tl.constexpr, stride_wm1: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, GROUP_SIZE_M: tl.constexpr, ): _swiglu_kernel( x_ptr, w_gate_ptr, w_up_ptr, out_ptr, offsets_ptr, H, I, stride_xm, stride_wm0, stride_wm1, BLOCK_M, BLOCK_N, BLOCK_K, ) class Model(nn.Module): """Up-projection of a top-K MoE FFN with fused SwiGLU (Triton grouped GEMM).""" def __init__(self, T_total: int, H: int, I: int, E: int, K: int): # noqa: E741 super().__init__() self.T_total = T_total self.H = H self.I = I self.E = E self.K = K self.W_gate = nn.Parameter(torch.empty(E, H, I, dtype=torch.bfloat16)) self.W_up = nn.Parameter(torch.empty(E, H, I, dtype=torch.bfloat16)) nn.init.normal_(self.W_gate, std=0.02) nn.init.normal_(self.W_up, std=0.02) def forward( self, hidden_states: torch.Tensor, # (T_perm, H) bf16 expert_offsets: torch.Tensor, # (E+1,) int32 ) -> torch.Tensor: T_perm, H = hidden_states.shape I = self.I E = self.E out = torch.empty(T_perm, I, dtype=torch.bfloat16, device=hidden_states.device) # Offsets may be on CPU; move to GPU for the kernel if expert_offsets.device.type != "cuda": expert_offsets = expert_offsets.cuda() # Compute max tokens per expert for grid sizing counts = expert_offsets[1:] - expert_offsets[:-1] max_m = int(counts.max().item()) # Use autotuned kernel grid = lambda META: (E, triton.cdiv(max_m, META["BLOCK_M"]), triton.cdiv(I, META["BLOCK_N"])) _swiglu_kernel_autotune[grid]( hidden_states, self.W_gate, self.W_up, out, expert_offsets, H=H, I=I, stride_xm=hidden_states.stride(0), stride_wm0=self.W_gate.stride(0), stride_wm1=self.W_gate.stride(1), ) return out # Module-level shape shims (rewritten by check.py / benchmark.py) T_total = 32768 H = 4096 I = 1536 # noqa: E741 E = 128 K = 8 def _build_routing(T_total: int, E: int, K: int, device: str = "cpu") -> torch.Tensor: T_perm = T_total * K base = T_perm // E rem = T_perm - base * E counts = torch.full((E,), base, dtype=torch.int32, device=device) counts[:rem] += 1 offsets = torch.zeros(E + 1, dtype=torch.int32, device=device) offsets[1:] = torch.cumsum(counts, dim=0) return offsets def get_inputs(): T_perm = T_total * K hidden_states = torch.randn(T_perm, H, dtype=torch.bfloat16) * 0.1 expert_offsets = _build_routing(T_total, E, K) return [hidden_states, expert_offsets] def get_init_inputs(): return [T_total, H, I, E, K]