"""Grouped GEMM + fused SwiGLU up-projection for top-K MoE FFN (H100 / SM90). Implements variable-length grouped GEMM via block scheduling and fuses SiLU(gate) * up in the GEMM epilogue so hidden states are read once. """ from __future__ import annotations import torch import torch.nn as nn import triton import triton.language as tl BLOCK_M = 128 @triton.autotune( configs=[ triton.Config({"BLOCK_N": 128, "BLOCK_K": 64}, num_stages=3, num_warps=8), triton.Config({"BLOCK_N": 256, "BLOCK_K": 64}, num_stages=3, num_warps=8), triton.Config({"BLOCK_N": 128, "BLOCK_K": 128}, num_stages=3, num_warps=8), triton.Config({"BLOCK_N": 64, "BLOCK_K": 128}, num_stages=4, num_warps=8), triton.Config({"BLOCK_N": 256, "BLOCK_K": 32}, num_stages=4, num_warps=8), triton.Config({"BLOCK_N": 128, "BLOCK_K": 32}, num_stages=5, num_warps=8), triton.Config({"BLOCK_N": 64, "BLOCK_K": 64}, num_stages=4, num_warps=4), ], key=["N", "K"], ) @triton.jit def _fused_grouped_gemm_swiglu_kernel( A, B_gate, B_up, C, ExpertOffsets, BlockToExpert, BlockToM, N, K, num_blocks, stride_a_t, stride_a_k, stride_bg_n, stride_bg_k, stride_bu_n, stride_bu_k, stride_c_t, stride_c_n, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, BLOCK_M: tl.constexpr = BLOCK_M, ): pid = tl.program_id(0) pid_n = tl.program_id(1) if pid >= num_blocks: return expert_id = tl.load(BlockToExpert + pid) m_start = tl.load(BlockToM + pid) expert_token_start = tl.load(ExpertOffsets + expert_id) global_m_start = expert_token_start + m_start offs_m = tl.arange(0, BLOCK_M) offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) offs_k = tl.arange(0, BLOCK_K) a_ptrs = A + (global_m_start + offs_m[:, None]) * stride_a_t + offs_k[None, :] * stride_a_k bg_ptrs = B_gate + (expert_id * N + offs_n[None, :]) * stride_bg_n + offs_k[:, None] * stride_bg_k bu_ptrs = B_up + (expert_id * N + offs_n[None, :]) * stride_bu_n + offs_k[:, None] * stride_bu_k expert_token_end = tl.load(ExpertOffsets + expert_id + 1) expert_num_tokens = expert_token_end - expert_token_start valid_m = m_start + offs_m < expert_num_tokens acc_gate = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) acc_up = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) for k_start in range(0, K, BLOCK_K): k_offs = k_start + offs_k a_mask = valid_m[:, None] & (k_offs[None, :] < K) a = tl.load(a_ptrs, mask=a_mask, other=0.0) b_mask = (offs_n[None, :] < N) & (k_offs[:, None] < K) b_gate = tl.load(bg_ptrs, mask=b_mask, other=0.0) b_up = tl.load(bu_ptrs, mask=b_mask, other=0.0) acc_gate += tl.dot(a, b_gate, out_dtype=tl.float32) acc_up += tl.dot(a, b_up, out_dtype=tl.float32) a_ptrs += BLOCK_K * stride_a_k bg_ptrs += BLOCK_K * stride_bg_k bu_ptrs += BLOCK_K * stride_bu_k silu_gate = acc_gate * tl.sigmoid(acc_gate) result = silu_gate * acc_up c_ptrs = C + (global_m_start + offs_m[:, None]) * stride_c_t + offs_n[None, :] * stride_c_n c_mask = valid_m[:, None] & (offs_n[None, :] < N) tl.store(c_ptrs, result.to(tl.bfloat16), mask=c_mask) def _build_block_schedule( expert_offsets: torch.Tensor, num_experts: int, block_m: int = BLOCK_M, ) -> tuple[torch.Tensor, torch.Tensor, int]: offsets_cpu = expert_offsets.cpu() expert_ids: list[int] = [] m_offsets: list[int] = [] for e in range(num_experts): start = int(offsets_cpu[e].item()) end = int(offsets_cpu[e + 1].item()) num_tokens_e = end - start if num_tokens_e == 0: continue num_blocks_e = (num_tokens_e + block_m - 1) // block_m for b in range(num_blocks_e): expert_ids.append(e) m_offsets.append(b * block_m) device = expert_offsets.device if not expert_ids: return ( torch.zeros(1, dtype=torch.int64, device=device), torch.zeros(1, dtype=torch.int64, device=device), 0, ) block_to_expert = torch.tensor(expert_ids, dtype=torch.int64, device=device) block_to_m = torch.tensor(m_offsets, dtype=torch.int64, device=device) return block_to_expert, block_to_m, len(expert_ids) _schedule_cache: dict[tuple[int, ...], tuple[torch.Tensor, torch.Tensor, int]] = {} def _get_block_schedule(expert_offsets: torch.Tensor, num_experts: int) -> tuple[torch.Tensor, torch.Tensor, int]: key = (num_experts, expert_offsets.data_ptr(), int(expert_offsets.sum().item())) cached = _schedule_cache.get(key) if cached is not None: return cached schedule = _build_block_schedule(expert_offsets, num_experts, BLOCK_M) _schedule_cache[key] = schedule return schedule def fused_grouped_gemm_swiglu( hidden_states: torch.Tensor, w_gate_flat: torch.Tensor, w_up_flat: torch.Tensor, expert_offsets: torch.Tensor, num_experts: int, out_dim: int, hidden_dim: int, ) -> torch.Tensor: """Compute silu(x @ W_gate) * (x @ W_up) with grouped GEMM over experts.""" total_tokens = hidden_states.shape[0] output = torch.empty(total_tokens, out_dim, device=hidden_states.device, dtype=hidden_states.dtype) if total_tokens == 0: return output block_to_expert, block_to_m, num_blocks = _get_block_schedule(expert_offsets, num_experts) if num_blocks == 0: return output def grid(meta): return (num_blocks, triton.cdiv(out_dim, meta["BLOCK_N"])) _fused_grouped_gemm_swiglu_kernel[grid]( hidden_states, w_gate_flat, w_up_flat, output, expert_offsets, block_to_expert, block_to_m, out_dim, hidden_dim, num_blocks, hidden_states.stride(0), hidden_states.stride(1), w_gate_flat.stride(0), w_gate_flat.stride(1), w_up_flat.stride(0), w_up_flat.stride(1), output.stride(0), output.stride(1), ) return output class Model(nn.Module): """Up-projection of a top-K MoE FFN with fused grouped GEMM + SwiGLU.""" 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) self._wg_flat: torch.Tensor | None = None self._wu_flat: torch.Tensor | None = None self._weight_key: tuple[int, int] | None = None def _flat_weights(self) -> tuple[torch.Tensor, torch.Tensor]: key = (self.W_gate.data_ptr(), self.W_up.data_ptr()) if self._weight_key != key: self._wg_flat = self.W_gate.transpose(1, 2).reshape(self.E * self.I, self.H).contiguous() self._wu_flat = self.W_up.transpose(1, 2).reshape(self.E * self.I, self.H).contiguous() self._weight_key = key assert self._wg_flat is not None and self._wu_flat is not None return self._wg_flat, self._wu_flat def forward( self, hidden_states: torch.Tensor, expert_offsets: torch.Tensor, ) -> torch.Tensor: wg_flat, wu_flat = self._flat_weights() return fused_grouped_gemm_swiglu( hidden_states.contiguous(), wg_flat, wu_flat, expert_offsets, self.E, self.I, self.H, ) # 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: 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]