"""Grouped GEMM + fused SwiGLU for MoE up-projection (SM90 / H100). Design: one Triton kernel computes, per expert e, out[off[e]:off[e+1]] = silu(x_e @ W_gate[e]) * (x_e @ W_up[e]) Each CTA owns one (BM, BN) output tile. The gate and up GEMMs share the A tile loads (loaded once per K-step) and run into two accumulators, so the SwiGLU product is formed in registers and only the final (BM, BN) bf16 tile is written -- no intermediate gate/up round-trip through HBM. The variable-length grouped mapping (which expert a given M-tile belongs to) is derived inside the kernel from expert_offsets with a vectorized cumsum over the E experts, so the host never reads the offsets (zero syncs per call). """ from __future__ import annotations import torch import torch.nn as nn import triton import triton.language as tl @triton.jit def _grouped_gemm_swiglu_kernel( X, WG, WU, O, OFFS, MAX_PID_M, H: tl.constexpr, I: tl.constexpr, E: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, GROUP_M: tl.constexpr, ): pid = tl.program_id(0) num_pid_n = I // BN # ---- L2 swizzle over (m_tile, n_tile) ---------------------------------- 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 = tl.minimum(MAX_PID_M - first_pid_m, GROUP_M) pid_m = first_pid_m + (pid % num_pid_in_group) % group_size_m pid_n = (pid % num_pid_in_group) // group_size_m # ---- map pid_m -> (expert, row range) via in-kernel scan --------------- eidx = tl.arange(0, E) off_lo = tl.load(OFFS + eidx) off_hi = tl.load(OFFS + eidx + 1) mtiles = (off_hi - off_lo + BM - 1) // BM cum = tl.cumsum(mtiles, 0) # inclusive prefix sum total_tiles = tl.max(cum, 0) if pid_m >= total_tiles: return # expert = number of experts whose tile range ends at or before pid_m expert = tl.sum(tl.where(cum <= pid_m, 1, 0), 0) prev_cum = tl.max(tl.where(cum <= pid_m, cum, 0), 0) row_start = tl.sum(tl.where(eidx == expert, off_lo, 0), 0) row_end = tl.sum(tl.where(eidx == expert, off_hi, 0), 0) row0 = row_start + (pid_m - prev_cum) * BM # ---- tile pointers ------------------------------------------------------ rm = tl.arange(0, BM) rn = pid_n * BN + tl.arange(0, BN) rk = tl.arange(0, BK) mask_m = (row0 + rm) < row_end x_ptrs = X + (row0 + rm)[:, None].to(tl.int64) * H + rk[None, :] w_off = expert.to(tl.int64) * H * I + rk[:, None] * I + rn[None, :] wg_ptrs = WG + w_off wu_ptrs = WU + w_off acc_g = tl.zeros((BM, BN), dtype=tl.float32) acc_u = tl.zeros((BM, BN), dtype=tl.float32) for _k in range(0, H, BK): a = tl.load(x_ptrs, mask=mask_m[:, None], other=0.0) bg = tl.load(wg_ptrs) bu = tl.load(wu_ptrs) acc_g = tl.dot(a, bg, acc_g) acc_u = tl.dot(a, bu, acc_u) x_ptrs += BK wg_ptrs += BK * I wu_ptrs += BK * I # ---- fused SwiGLU epilogue --------------------------------------------- out = acc_g * tl.sigmoid(acc_g) * acc_u o_ptrs = O + (row0 + rm)[:, None].to(tl.int64) * I + rn[None, :] tl.store(o_ptrs, out.to(O.dtype.element_ty), mask=mask_m[:, None]) # Per-shape tuned configs: (H, I, E) -> dict(BM, BN, BK, GROUP_M, num_warps, num_stages) _CONFIGS = { (4096, 1536, 128): dict(BM=128, BN=128, BK=32, GROUP_M=8, num_warps=8, num_stages=4), (2048, 1024, 64): dict(BM=128, BN=128, BK=32, GROUP_M=4, num_warps=8, num_stages=6), (2048, 4096, 64): dict(BM=128, BN=128, BK=32, GROUP_M=8, num_warps=8, num_stages=5), } _DEFAULT_CONFIG = dict(BM=128, BN=128, BK=32, GROUP_M=8, num_warps=8, num_stages=4) class Model(nn.Module): """Drop-in replacement for reference.Model with a fused Triton kernel.""" 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 # noqa: E741 E = self.E out = torch.empty(T_perm, I, dtype=torch.bfloat16, device=hidden_states.device) cfg = _CONFIGS.get((H, I, E), _DEFAULT_CONFIG) BM, BN = cfg["BM"], cfg["BN"] max_pid_m = (T_perm + BM - 1) // BM + E # upper bound incl. per-expert tail tiles grid = (max_pid_m * (I // BN),) _grouped_gemm_swiglu_kernel[grid]( hidden_states, self.W_gate, self.W_up, out, expert_offsets, max_pid_m, H=H, I=I, E=E, BM=BM, BN=BN, BK=cfg["BK"], GROUP_M=cfg["GROUP_M"], num_warps=cfg["num_warps"], num_stages=cfg["num_stages"], ) return out # Module-level shape shims (same convention as reference.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]