from __future__ import annotations import torch import torch.nn as nn import triton import triton.language as tl @triton.jit def _moe_swiglu_kernel( x_ptr, offsets_ptr, gate_ptr, up_ptr, out_ptr, H: tl.constexpr, I: tl.constexpr, M_PER_EXPERT: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, GROUP_M: tl.constexpr, ): pid = tl.program_id(0) expert = tl.program_id(1) m_tiles = tl.cdiv(M_PER_EXPERT, BLOCK_M) n_tiles = tl.cdiv(I, BLOCK_N) tiles_per_group = GROUP_M * n_tiles group_id = pid // tiles_per_group first_m = group_id * GROUP_M group_m = tl.minimum(m_tiles - first_m, GROUP_M) group_pid = pid - group_id * tiles_per_group tile_m = first_m + (group_pid % group_m) tile_n = group_pid // group_m start = tl.load(offsets_ptr + expert) end = tl.load(offsets_ptr + expert + 1) rows = start + tile_m * BLOCK_M + tl.arange(0, BLOCK_M) cols = tile_n * BLOCK_N + tl.arange(0, BLOCK_N) acc_gate = tl.zeros((BLOCK_M, BLOCK_N), tl.float32) acc_up = tl.zeros((BLOCK_M, BLOCK_N), tl.float32) offs_k = tl.arange(0, BLOCK_K) for k0 in range(0, H, BLOCK_K): k = k0 + offs_k a = tl.load( x_ptr + rows[:, None] * H + k[None, :], mask=(rows[:, None] < end) & (k[None, :] < H), other=0.0, ) wg = tl.load( gate_ptr + expert * H * I + k[:, None] * I + cols[None, :], mask=(k[:, None] < H) & (cols[None, :] < I), other=0.0, ) wu = tl.load( up_ptr + expert * H * I + k[:, None] * I + cols[None, :], mask=(k[:, None] < H) & (cols[None, :] < I), other=0.0, ) acc_gate += tl.dot(a, wg) acc_up += tl.dot(a, wu) sig = 1.0 / (1.0 + tl.exp2(-1.4426950408889634 * acc_gate)) gated = (acc_gate * sig) * acc_up tl.store( out_ptr + rows[:, None] * I + cols[None, :], gated, mask=(rows[:, None] < end) & (cols[None, :] < I), ) @triton.jit def _moe_swiglu_wide_kernel( x_ptr, offsets_ptr, gate_ptr, up_ptr, out_ptr, H: tl.constexpr, I: tl.constexpr, M_PER_EXPERT: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, BLOCK_2N: tl.constexpr, GROUP_M: tl.constexpr, ): pid = tl.program_id(0) expert = tl.program_id(1) m_tiles = tl.cdiv(M_PER_EXPERT, BLOCK_M) n_tiles = tl.cdiv(I, BLOCK_N) tiles_per_group = GROUP_M * n_tiles group_id = pid // tiles_per_group first_m = group_id * GROUP_M group_m = tl.minimum(m_tiles - first_m, GROUP_M) group_pid = pid - group_id * tiles_per_group tile_m = first_m + (group_pid % group_m) tile_n = group_pid // group_m start = tl.load(offsets_ptr + expert) end = tl.load(offsets_ptr + expert + 1) rows = start + tile_m * BLOCK_M + tl.arange(0, BLOCK_M) cols2 = tl.arange(0, BLOCK_2N) is_up = cols2 >= BLOCK_N cols = tile_n * BLOCK_N + (cols2 - tl.where(is_up, BLOCK_N, 0)) acc = tl.zeros((BLOCK_M, BLOCK_2N), tl.float32) offs_k = tl.arange(0, BLOCK_K) for k0 in range(0, H, BLOCK_K): k = k0 + offs_k a = tl.load( x_ptr + rows[:, None] * H + k[None, :], mask=(rows[:, None] < end) & (k[None, :] < H), other=0.0, ) gate_w = gate_ptr + expert * H * I + k[:, None] * I + cols[None, :] up_w = up_ptr + expert * H * I + k[:, None] * I + cols[None, :] b = tl.load( tl.where(is_up[None, :], up_w, gate_w), mask=(k[:, None] < H) & (cols[None, :] < I), other=0.0, ) acc += tl.dot(a, b) acc_pair = tl.reshape(acc, (BLOCK_M, 2, BLOCK_N)) acc_pair = tl.permute(acc_pair, (0, 2, 1)) acc_gate, acc_up = tl.split(acc_pair) out_cols = tile_n * BLOCK_N + tl.arange(0, BLOCK_N) sig = 1.0 / (1.0 + tl.exp2(-1.4426950408889634 * acc_gate)) gated = (acc_gate * sig) * acc_up tl.store( out_ptr + rows[:, None] * I + out_cols[None, :], gated, mask=(rows[:, None] < end) & (out_cols[None, :] < I), ) @triton.jit def _moe_swiglu_pair_kernel( x_ptr, offsets_ptr, pair_ptr, out_ptr, H: tl.constexpr, I: tl.constexpr, M_PER_EXPERT: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, BLOCK_2N: tl.constexpr, GROUP_M: tl.constexpr, ): pid = tl.program_id(0) expert = tl.program_id(1) m_tiles = tl.cdiv(M_PER_EXPERT, BLOCK_M) n_tiles = tl.cdiv(I, BLOCK_N) tiles_per_group = GROUP_M * n_tiles group_id = pid // tiles_per_group first_m = group_id * GROUP_M group_m = tl.minimum(m_tiles - first_m, GROUP_M) group_pid = pid - group_id * tiles_per_group tile_m = first_m + (group_pid % group_m) tile_n = group_pid // group_m start = tl.load(offsets_ptr + expert) end = tl.load(offsets_ptr + expert + 1) rows = start + tile_m * BLOCK_M + tl.arange(0, BLOCK_M) cols2 = tile_n * BLOCK_2N + tl.arange(0, BLOCK_2N) acc = tl.zeros((BLOCK_M, BLOCK_2N), tl.float32) offs_k = tl.arange(0, BLOCK_K) for k0 in range(0, H, BLOCK_K): k = k0 + offs_k a = tl.load( x_ptr + rows[:, None] * H + k[None, :], mask=(rows[:, None] < end) & (k[None, :] < H), other=0.0, ) b = tl.load( pair_ptr + expert * H * I * 2 + k[:, None] * I * 2 + cols2[None, :], mask=(k[:, None] < H) & (cols2[None, :] < I * 2), other=0.0, ) acc += tl.dot(a, b) acc_pair = tl.reshape(acc, (BLOCK_M, BLOCK_N, 2)) acc_gate, acc_up = tl.split(acc_pair) out_cols = tile_n * BLOCK_N + tl.arange(0, BLOCK_N) sig = 1.0 / (1.0 + tl.exp2(-1.4426950408889634 * acc_gate)) gated = (acc_gate * sig) * acc_up tl.store( out_ptr + rows[:, None] * I + out_cols[None, :], gated, mask=(rows[:, None] < end) & (out_cols[None, :] < I), ) class Model(nn.Module): 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)) self.register_buffer("_W_pair", torch.empty(0, dtype=torch.bfloat16), persistent=False) def load_state_dict(self, *args, **kwargs): result = super().load_state_dict(*args, **kwargs) self._pack_weights() return result def _pack_weights(self) -> None: self._W_pair = torch.empty(0, device=self.W_gate.device, dtype=torch.bfloat16) def forward(self, hidden_states: torch.Tensor, expert_offsets: torch.Tensor) -> torch.Tensor: out = torch.empty((hidden_states.shape[0], self.I), device=hidden_states.device, dtype=torch.bfloat16) if self.H == 4096: block_m = 128 block_n = 128 block_k = 64 num_warps = 8 num_stages = 3 use_wide = True group_m = 32 elif self.I >= 4096: block_m = 128 block_n = 128 block_k = 64 num_warps = 8 num_stages = 3 use_wide = True group_m = 16 else: block_m = 128 block_n = 128 block_k = 64 num_warps = 8 num_stages = 3 use_wide = True group_m = 16 m_per_expert = self.T_total * self.K // self.E grid = (triton.cdiv(m_per_expert, block_m) * triton.cdiv(self.I, block_n), self.E) if use_wide and self._W_pair.numel() != 0 and self._W_pair.device == hidden_states.device: _moe_swiglu_pair_kernel[grid]( hidden_states, expert_offsets, self._W_pair, out, self.H, self.I, m_per_expert, BLOCK_M=block_m, BLOCK_N=block_n, BLOCK_K=block_k, BLOCK_2N=block_n * 2, GROUP_M=group_m, num_warps=num_warps, num_stages=num_stages, ) elif use_wide: _moe_swiglu_wide_kernel[grid]( hidden_states, expert_offsets, self.W_gate, self.W_up, out, self.H, self.I, m_per_expert, BLOCK_M=block_m, BLOCK_N=block_n, BLOCK_K=block_k, BLOCK_2N=block_n * 2, GROUP_M=group_m, num_warps=num_warps, num_stages=num_stages, ) else: _moe_swiglu_kernel[grid]( hidden_states, expert_offsets, self.W_gate, self.W_up, out, self.H, self.I, m_per_expert, BLOCK_M=block_m, BLOCK_N=block_n, BLOCK_K=block_k, GROUP_M=group_m, num_warps=num_warps, num_stages=num_stages, ) return out 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]