"""MoE up-projection: variable-length grouped GEMM + fused SwiGLU on B200 (SM100). Kernel (CUDA C++/CUTLASS 3.x, built from ./csrc + ./cutlass headers): - stock Blackwell ptr-array warp-specialized mainloop from cutlass/gemm/collective builders: tcgen05 2-SM MMA, 256x256x64 MMA tile, cluster (2,1,1), TMA A/B with per-group device tensormap updates (cutlass::arch::Sm100, KernelPtrArrayTmaWarpSpecialized2SmSm100); - custom fused epilogue (csrc/moe_swiglu_epilogue.hpp, generated from the stock array TMA epilogue by gen_epilogue.py): weights are pre-interleaved so each 256-wide MMA tile is [128 gate cols | 128 up cols] of the same output columns; the epilogue loads both TMEM subtiles, computes silu(g) * u in fp32 registers, and TMA-stores the half-width bf16 tile. The producer C-load pipeline is disabled (no C operand) — its full-width subtile cadence would deadlock against the half-width store loop; - per-group problem shapes / A,B,D pointers / strides are built on device from expert_offsets by a tiny prep kernel (no host sync); zero-token experts and non-tile-multiple sizes handled by the group scheduler + TMA bounds. Weights are re-packed once (cached, keyed on parameter data_ptr/version) into the 128-column-block interleaved layout W[e, h, 256*b + j] = W_gate[e, h, 128*b + j] (0 <= j < 128) W[e, h, 256*b + 128 + j] = W_up[e, h, 128*b + j]. Falls back to a Triton persistent grouped-GEMM kernel (solution_il.py) if the extension cannot be built or fails at runtime. Measured (B200, median of 20 L2-flushed iters, cold clocks): shape0 (T=32768,H=4096,I=1536,E=128,K=8): ~4.0 ms (~1650 real TFLOPS, 73% peak) shape1 (T=4096, H=2048,I=1024,E=64, K=4): ~0.134 ms shape2 (T=16384,H=2048,I=4096,E=64, K=8): ~2.73 ms (~1610 real TFLOPS, 72% peak) """ from __future__ import annotations import os import sys from pathlib import Path import torch import torch.nn as nn _HERE = Path(__file__).resolve().parent sys.path.insert(0, str(_HERE)) _ext = None _ext_err = None # (H, I, E) -> (raster, swizzle, config_id); config_id: 0=cluster(2,1), 1=(4,1), 2=(2,2) CONFIGS = { (4096, 1536, 128): (0, 1, 0), (2048, 1024, 64): (0, 1, 0), (2048, 4096, 64): (0, 1, 0), } DEFAULT_CONFIG = (0, 1, 0) def _get_ext(): global _ext, _ext_err if _ext is not None or _ext_err is not None: return _ext try: os.environ["TORCH_EXTENSIONS_DIR"] = str(_HERE / "torch_ext_cache") from torch.utils.cpp_extension import load _ext = load( name="moe_gg_fused", sources=[str(_HERE / "csrc" / "moe_gg_binding.cpp"), str(_HERE / "csrc" / "moe_gg.cu")], extra_include_paths=[str(_HERE / "cutlass" / "include"), str(_HERE / "cutlass" / "tools" / "util" / "include")], extra_cuda_cflags=[ "-O3", "-std=c++17", "-DNDEBUG", "-DMOE_FUSED=1", "--expt-relaxed-constexpr", "-gencode=arch=compute_100a,code=sm_100a", "--threads=8", ], extra_cflags=["-O2", "-std=c++17"], verbose=os.environ.get("MOE_GG_VERBOSE", "0") == "1", ) except Exception as e: # noqa: BLE001 _ext_err = e _ext = None return _ext class Model(nn.Module): """Same interface as reference.Model.""" 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._w_cache = None self._buf_cache = None self._sm_count = None self._fallback = None self._use_ext = None self._ext_verified = False self.cfg = list(CONFIGS.get((H, I, E), DEFAULT_CONFIG)) def _resolve_backend(self): if self._use_ext is None: ok = self.I % 128 == 0 and self.H % 64 == 0 and _get_ext() is not None self._use_ext = bool(ok) if not self._use_ext: self._use_fallback() return self._use_ext def _w_cat(self): wg, wu = self.W_gate, self.W_up key = (wg.data_ptr(), wg._version, wu.data_ptr(), wu._version) if self._w_cache is not None and self._w_cache[0] == key: return self._w_cache[1] HB = 128 E, H, I = self.E, self.H, self.I # noqa: E741 Wg = wg.detach().reshape(E, H, I // HB, HB) Wu = wu.detach().reshape(E, H, I // HB, HB) W = torch.stack([Wg, Wu], dim=3).reshape(E, H, 2 * I).contiguous() self._w_cache = (key, W) return W def _ext_buffers(self, ext, device): if self._buf_cache is None: if self._sm_count is None: self._sm_count = torch.cuda.get_device_properties(device).multi_processor_count ga = torch.empty(ext.group_args_bytes(self.E), dtype=torch.uint8, device=device) ws_bytes = ext.workspace_bytes(self.E, self._sm_count) ws = torch.empty(max(int(ws_bytes), 16), dtype=torch.uint8, device=device) self._buf_cache = (ga, ws) return self._buf_cache def _use_fallback(self): import solution_il fb = solution_il.Model(self.T_total, self.H, self.I, self.E, self.K) fb.W_gate = self.W_gate fb.W_up = self.W_up self._fallback = fb.to(self.W_gate.device) self._use_ext = False def forward( self, hidden_states: torch.Tensor, # (T_perm, H) bf16 expert_offsets: torch.Tensor, # (E+1,) int32 ) -> torch.Tensor: if not self._resolve_backend(): return self._fallback(hidden_states, expert_offsets) if not self._ext_verified: try: out = self._forward_ext(hidden_states, expert_offsets) torch.cuda.synchronize() self._ext_verified = True return out except Exception: self._use_fallback() return self._fallback(hidden_states, expert_offsets) return self._forward_ext(hidden_states, expert_offsets) def _forward_ext(self, hidden_states, expert_offsets): ext = _get_ext() T_perm, H = hidden_states.shape if expert_offsets.dtype != torch.int32: expert_offsets = expert_offsets.to(torch.int32) if not expert_offsets.is_contiguous(): expert_offsets = expert_offsets.contiguous() if not hidden_states.is_contiguous(): hidden_states = hidden_states.contiguous() W = self._w_cat() out = torch.empty(T_perm, self.I, dtype=torch.bfloat16, device=hidden_states.device) ga, ws = self._ext_buffers(ext, hidden_states.device) ext.run(hidden_states, W, out, expert_offsets, ga, ws, self.E, H, 2 * self.I, self.I, self._sm_count, *self.cfg) 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: 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] # ================================================================== # WARNING: solution loads sidecar 'moe_gg_binding.cpp' but it was not found in the run archive. # ================================================================== # ================================================================== # WARNING: solution loads sidecar 'moe_gg.cu' but it was not found in the run archive. # ================================================================== # ================================================================== # ===== sidecar: solution_il.py (7829 bytes, loaded by solution.py) ===== # ================================================================== """Interleaved-weight variant: single accumulator, gate/up in adjacent N columns. W_cat (E, H, 2I) with W_cat[..., 2j] = W_gate[..., j], W_cat[..., 2j+1] = W_up[..., j] (one-time cached transform). The grouped GEMM runs with N = 2I; the epilogue splits adjacent column pairs (reshape + tl.split), computes silu(g)*u, and stores the (BM, BN//2) output tile at column n0//2. """ from __future__ import annotations import torch import torch.nn as nn import triton import triton.language as tl def _tma_alloc(size: int, alignment: int, stream): return torch.empty(size, device="cuda", dtype=torch.int8) triton.set_allocator(_tma_alloc) # (H, I, E) -> kernel config (swept on B200). _CFG = dict(BM=128, BN=256, BK=64, GROUP_M=4, WS=False, SUBTILE=True, FLATTEN=True, num_warps=8, num_stages=4) CONFIGS = { (4096, 1536, 128): dict(_CFG), (2048, 1024, 64): dict(_CFG), (2048, 4096, 64): dict(_CFG), } DEFAULT_CONFIG = dict(_CFG) @triton.jit def _silu_pair(acc, BM: tl.constexpr, BN: tl.constexpr): # acc (BM, BN) with interleaved (gate, up) column pairs -> (BM, BN//2) pairs = tl.reshape(acc, (BM, BN // 2, 2)) g, u = tl.split(pairs) return g * tl.sigmoid(g) * u @triton.jit def _moe_swiglu_il_kernel( x_ptr, w_ptr, out_ptr, sched_ptr, ntiles_ptr, T_perm, H, I2, I, E, T_MAX, NUM_SMS: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, WS: tl.constexpr, SUBTILE: tl.constexpr, FLATTEN: tl.constexpr, ): pid = tl.program_id(0) x_desc = tl.make_tensor_descriptor( x_ptr, shape=[T_perm, H], strides=[H, 1], block_shape=[BM, BK]) w_desc = tl.make_tensor_descriptor( w_ptr, shape=[E, H, I2], strides=[H * I2, I2, 1], block_shape=[1, BK, BN]) k_tiles = H // BK ntiles = tl.load(ntiles_ptr) tile_c = pid - NUM_SMS for t in tl.range(pid, ntiles, NUM_SMS, flatten=FLATTEN, warp_specialize=WS): e = tl.load(sched_ptr + t) row0 = tl.load(sched_ptr + T_MAX + t) n0 = tl.load(sched_ptr + 3 * T_MAX + t) acc = tl.zeros((BM, BN), dtype=tl.float32) for ki in range(k_tiles): k = ki * BK a = x_desc.load([row0, k]) b = w_desc.load([e, k, n0]).reshape(BK, BN) acc = tl.dot(a, b, acc) # epilogue: independent dataflow (re-load schedule with its own counter) tile_c += NUM_SMS row0_c = tl.load(sched_ptr + T_MAX + tile_c) hi_c = tl.load(sched_ptr + 2 * T_MAX + tile_c) n0_c = tl.load(sched_ptr + 3 * T_MAX + tile_c) rows = row0_c + tl.arange(0, BM) mask = (rows < hi_c)[:, None] orows = out_ptr + rows.to(tl.int64)[:, None] * I no2 = n0_c // 2 if SUBTILE: a0 = tl.permute(tl.reshape(acc, (BM, 2, BN // 2)), (0, 2, 1)) accl, accr = tl.split(a0) h0 = _silu_pair(accl, BM, BN // 2).to(tl.bfloat16) cols0 = no2 + tl.arange(0, BN // 4) tl.store(orows + cols0[None, :], h0, mask=mask) h1 = _silu_pair(accr, BM, BN // 2).to(tl.bfloat16) tl.store(orows + (cols0 + BN // 4)[None, :], h1, mask=mask) else: h = _silu_pair(acc, BM, BN).to(tl.bfloat16) cols = no2 + tl.arange(0, BN // 2) tl.store(orows + cols[None, :], h, mask=mask) class Model(nn.Module): """Same interface as reference.Model.""" 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._num_sms = None self._sched_cache = None self._w_cache = None # (gate_ptr, gate_ver, up_ptr, up_ver, W_cat) self.cfg = dict(CONFIGS.get((H, I, E), DEFAULT_CONFIG)) def _w_cat(self): wg, wu = self.W_gate, self.W_up key = (wg.data_ptr(), wg._version, wu.data_ptr(), wu._version) if self._w_cache is not None and self._w_cache[0] == key: return self._w_cache[1] W = torch.stack([wg.detach(), wu.detach()], dim=-1).reshape( self.E, self.H, 2 * self.I).contiguous() self._w_cache = (key, W) return W def _build_schedule(self, offs: torch.Tensor, T_perm: int): cfg = self.cfg BM, BN, GROUP_M = cfg["BM"], cfg["BN"], cfg["GROUP_M"] E = self.E dev = offs.device num_n = 2 * self.I // BN counts = offs[1:] - offs[:-1] tiles_m = (counts + (BM - 1)) // BM tp = torch.zeros(E + 1, dtype=torch.int32, device=dev) torch.cumsum(tiles_m, 0, out=tp[1:]) tpn = tp * num_n R_max = T_perm // BM + E T_MAX = R_max * num_n t_ids = torch.arange(T_MAX, dtype=torch.int32, device=dev) e_of = torch.clamp(torch.searchsorted(tpn, t_ids, right=True) - 1, 0, E - 1) l = t_ids - tpn[e_of] num_m_e = tiles_m[e_of] nig = GROUP_M * num_n gid = l // nig first_m = gid * GROUP_M gsz = torch.clamp(num_m_e - first_m, 1, GROUP_M) m = first_m + (l % gsz) n = (l % nig) // gsz row0 = offs[e_of] + m * BM hi = offs[e_of + 1] sched = torch.stack([ e_of.to(torch.int32), row0.to(torch.int32), hi.to(torch.int32), (n * BN).to(torch.int32)]).contiguous() ntiles = tpn[-1:].contiguous() return sched, ntiles, T_MAX 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 out = torch.empty(T_perm, self.I, dtype=torch.bfloat16, device=hidden_states.device) W = self._w_cat() c = self._sched_cache if (c is None or c[0] is not expert_offsets or c[1] != expert_offsets._version): sched, ntiles, T_MAX = self._build_schedule(expert_offsets, T_perm) self._sched_cache = (expert_offsets, expert_offsets._version, sched, ntiles, T_MAX) else: sched, ntiles, T_MAX = c[2], c[3], c[4] if self._num_sms is None: self._num_sms = torch.cuda.get_device_properties( hidden_states.device).multi_processor_count cfg = self.cfg grid = (self._num_sms,) _moe_swiglu_il_kernel[grid]( hidden_states, W, out, sched, ntiles, T_perm, H, 2 * self.I, self.I, self.E, T_MAX, NUM_SMS=self._num_sms, BM=cfg["BM"], BN=cfg["BN"], BK=cfg["BK"], WS=cfg["WS"], SUBTILE=cfg["SUBTILE"], FLATTEN=cfg.get("FLATTEN", True), num_warps=cfg["num_warps"], num_stages=cfg["num_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: 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]