"""Top-K MoE FFN up-projection: grouped GEMM + fused SwiGLU. Per expert e: 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. Implemented as a custom Triton kernel that performs a variable-length grouped GEMM (one GEMM per expert, with the two weight tensors gate/up fused into a single kernel so the A operand is loaded once) and fuses the SwiGLU epilogue. """ from __future__ import annotations import torch import torch.nn as nn import triton import triton.language as tl @triton.jit def _moe_up_swiglu_kernel( x_ptr, wg_ptr, wu_ptr, out_ptr, off_ptr, H, I, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, ): pid_n = tl.program_id(0) pid_m = tl.program_id(1) e = tl.program_id(2) start = tl.load(off_ptr + e) end = tl.load(off_ptr + e + 1) offs_m = start + pid_m * BLOCK_M + tl.arange(0, BLOCK_M) offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) mask_m = offs_m < end mask_n = offs_n < I wg_base = wg_ptr + e * H * I wu_base = wu_ptr + e * H * I 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(0, H, BLOCK_K): offs_k = k + tl.arange(0, BLOCK_K) mask_k = offs_k < H a = tl.load( x_ptr + offs_m[:, None] * H + offs_k[None, :], mask=mask_m[:, None] & mask_k[None, :], other=0.0, ) b_g = tl.load( wg_base + offs_k[:, None] * I + offs_n[None, :], mask=mask_k[:, None] & mask_n[None, :], other=0.0, ) b_u = tl.load( wu_base + offs_k[:, None] * I + offs_n[None, :], mask=mask_k[:, None] & mask_n[None, :], other=0.0, ) acc_g += tl.dot(a, b_g) acc_u += tl.dot(a, b_u) out = acc_g * tl.sigmoid(acc_g) * acc_u out_ptrs = out_ptr + offs_m[:, None] * I + offs_n[None, :] tl.store(out_ptrs, out.to(tl.bfloat16), mask=mask_m[:, None] & mask_n[None, :]) # (BM, BN, BK, num_warps, num_stages) chosen per (H, I) by profiling. _CONFIGS = { # headline: T_total=32768 H=4096 I=1536 E=128 K=8 (4096, 1536): (256, 64, 64, 8, 3), # fast-iteration: T_total=4096 H=2048 I=1024 E=64 K=4 (2048, 1024): (128, 64, 64, 8, 3), # intermediate-heavy: T_total=16384 H=2048 I=4096 E=64 K=8 (2048, 4096): (256, 64, 64, 8, 3), } class Model(nn.Module): """Up-projection of a top-K MoE FFN with fused 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) 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 hidden_states = hidden_states.contiguous() wg = self.W_gate.contiguous() wu = self.W_up.contiguous() expert_offsets = expert_offsets.contiguous() out = torch.empty(T_perm, I, dtype=torch.bfloat16, device=hidden_states.device) BM, BN, BK, warps, stages = _CONFIGS.get((H, I), (128, 64, 64, 8, 3)) # Balanced routing: every expert owns ceil(T_perm / E) rows at most. max_count = (T_perm + E - 1) // E num_n = triton.cdiv(I, BN) num_m = triton.cdiv(max_count, BM) grid = (num_n, num_m, E) _moe_up_swiglu_kernel[grid]( hidden_states, wg, wu, out, expert_offsets, H, I, BLOCK_M=BM, BLOCK_N=BN, BLOCK_K=BK, num_warps=warps, num_stages=stages, ) return out # 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]