"""Grouped GEMM + fused SwiGLU up-projection for top-K MoE, hand-written in Triton. Design (persistent grouped-GEMM scheduler, à la CUTLASS grouped GEMM / the Triton grouped-mm kernel PyTorch Inductor emits for `torch._grouped_mm`): - One kernel launch. Grid = NUM_SMS persistent programs. - Each program walks the E experts in order, maintaining a running count of tiles already dispatched (`iterated_tiles`). For each expert it computes how many (BLOCK_M x BLOCK_N) tiles that expert owns and consumes the ones that land on its strided tile-id sequence (tidx, tidx+NUM_SMS, ...). Because H and I are static (compile-time) but per-expert row counts are data-dependent, this scan is the only way to map a flat tile id to (expert, row offset) without a host<->device sync. - Gate and up projections share the same A (hidden_states) tile load per K-step -- that's the fusion win over two independent grouped GEMMs -- and SiLU(gate) * up is computed in registers before a single masked store, so the (T_perm, I) gate/up intermediates are never materialized. - A/W tiles are loaded via TMA tensor descriptors (safe even for the ragged last tile of an expert: any spillover rows just compute garbage that gets masked out at the store). The output store uses plain masked tl.store since TMA stores can't be partially masked and a ragged tile must never clobber the next expert's rows. """ from __future__ import annotations import torch import torch.nn as nn import triton import triton.language as tl OP_TYPE = "grouped_gemm_swiglu" SUPPORTED_PRECISIONS = ["bf16"] HARDWARE_REQUIRED = ["RTX_PRO_6000", "H100", "B200"] def _alloc_fn(size: int, alignment: int, stream): return torch.empty(size, dtype=torch.int8, device="cuda") if torch.cuda.is_available(): triton.set_allocator(_alloc_fn) _NUM_SMS = torch.cuda.get_device_properties(0).multi_processor_count else: _NUM_SMS = 132 def _configs(): # The epilogue keeps TWO (BLOCK_M, BLOCK_N) fp32 accumulators live across # the whole K reduction (gate + up), so register pressure is ~2x a plain # matmul's for the same tile -- and shared memory holds one A tile plus # TWO B tiles (gate + up) per pipeline stage. Both blow the occupancy # budget much faster than usual, so bias the search toward more warps # per tile (halves accumulator regs/thread for the same tile) rather # than just bigger tiles. specs = [ (128, 64, 64, 3, 8), (128, 64, 32, 3, 8), (128, 64, 64, 2, 8), (256, 64, 64, 2, 8), (128, 128, 64, 2, 8), (128, 128, 32, 3, 8), (64, 64, 64, 4, 4), (64, 128, 32, 3, 4), (128, 32, 64, 3, 8), (256, 32, 64, 3, 8), (128, 64, 64, 3, 4), (64, 64, 32, 3, 8), (128, 128, 64, 2, 16), (128, 64, 32, 2, 16), ] return [ triton.Config({"BLOCK_M": bm, "BLOCK_N": bn, "BLOCK_K": bk}, num_stages=ns, num_warps=nw) for bm, bn, bk, ns, nw in specs ] @triton.autotune(configs=_configs(), key=["H", "I", "E"]) @triton.jit def _grouped_swiglu_kernel( x_ptr, wg_ptr, wu_ptr, out_ptr, offsets_ptr, T_perm, H: tl.constexpr, I: tl.constexpr, E: tl.constexpr, # noqa: E741 stride_xm, stride_we, stride_wh, stride_om, NUM_SMS: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, ): NUM_N_TILES: tl.constexpr = tl.cdiv(I, BLOCK_N) NUM_K_TILES: tl.constexpr = tl.cdiv(H, BLOCK_K) x_desc = tl.make_tensor_descriptor( x_ptr, shape=[T_perm, H], strides=[stride_xm, 1], block_shape=[BLOCK_M, BLOCK_K] ) wg_desc = tl.make_tensor_descriptor( wg_ptr, shape=[E, H, I], strides=[stride_we, stride_wh, 1], block_shape=[1, BLOCK_K, BLOCK_N], ) wu_desc = tl.make_tensor_descriptor( wu_ptr, shape=[E, H, I], strides=[stride_we, stride_wh, 1], block_shape=[1, BLOCK_K, BLOCK_N], ) pid = tl.program_id(0) tidx = pid iterated_tiles = 0 m_end = 0 for e in tl.range(E): m_start = m_end m_end = tl.load(offsets_ptr + e + 1) m_size = m_end - m_start num_m_tiles = tl.cdiv(m_size, BLOCK_M) num_tiles = num_m_tiles * NUM_N_TILES while tidx >= iterated_tiles and tidx < iterated_tiles + num_tiles: gidx = tidx - iterated_tiles tile_m = gidx % num_m_tiles tile_n = gidx // num_m_tiles row0 = m_start + tile_m * BLOCK_M col0 = tile_n * BLOCK_N acc_g = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) acc_u = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) for k in range(NUM_K_TILES): a = x_desc.load([row0, k * BLOCK_K]) bg = wg_desc.load([e, k * BLOCK_K, col0]).reshape(BLOCK_K, BLOCK_N) bu = wu_desc.load([e, k * BLOCK_K, col0]).reshape(BLOCK_K, BLOCK_N) acc_g = tl.dot(a, bg, acc_g) acc_u = tl.dot(a, bu, acc_u) silu = acc_g * tl.sigmoid(acc_g) result = (silu * acc_u).to(out_ptr.dtype.element_ty) offs_m = row0 + tl.arange(0, BLOCK_M) offs_n = col0 + tl.arange(0, BLOCK_N) out_ptrs = out_ptr + offs_m[:, None] * stride_om + offs_n[None, :] mask = (offs_m[:, None] < m_end) & (offs_n[None, :] < I) tl.store(out_ptrs, result, mask=mask) tidx += NUM_SMS iterated_tiles += num_tiles def grouped_swiglu( hidden_states: torch.Tensor, expert_offsets: torch.Tensor, W_gate: torch.Tensor, W_up: torch.Tensor, ) -> torch.Tensor: T_perm, H = hidden_states.shape E, H2, I = W_gate.shape assert H == H2 out = torch.empty((T_perm, I), dtype=torch.bfloat16, device=hidden_states.device) grid = (_NUM_SMS,) _grouped_swiglu_kernel[grid]( hidden_states, W_gate, W_up, out, expert_offsets, T_perm, H, I, E, hidden_states.stride(0), W_gate.stride(0), W_gate.stride(1), out.stride(0), NUM_SMS=_NUM_SMS, ) return out class Model(nn.Module): """Up-projection of a top-K MoE FFN with fused SwiGLU. Inputs at call time: hidden_states: (T_perm, H) bf16, already permuted to expert order expert_offsets: (E+1,) int32, prefix sums of token counts per expert so expert e owns rows [offsets[e]:offsets[e+1]] T_perm = T_total * K (each token visits K experts) Output: gated_up: (T_perm, I) bf16 """ 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: return grouped_swiglu(hidden_states, expert_offsets, self.W_gate, self.W_up) # Module-level shape shims rewritten by check.py / benchmark.py per shape. 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: """Round-robin-ish routing metadata: balanced offsets summing to T_total*K.""" 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]