""" Triton Megakernel: fused GEMM1 + SwiGLU + GEMM2 for T<=15. Single Triton kernel replacing 3 separate launches. Uses tl.dot for tensor cores, native FP8, and tl.max for SwiGLU scaling. No TMA, no CuTe DSL, no TMEM — just proven Triton patterns. Grid: (N_TILES, E_LOCAL) where N_TILES = max(N1/128, H/128) = 56 Each program handles one output tile for one expert across all 3 phases: Phase 1: GEMM1 (bidy < 32 N-tiles) Phase 2: SwiGLU (bidy < 16 I-blocks) Phase 3: GEMM2 (all 56 H-tiles) Phase transitions via atomic per-expert completion counters. """ import torch import triton import triton.language as tl @triton.jit def _pdl_launch_dependents(): tl.inline_asm_elementwise( "griddepcontrol.launch_dependents; mov.u32 $0, 0;", "=r", [], dtype=tl.int32, is_pure=False, pack=1) @triton.jit def _pdl_wait(): tl.inline_asm_elementwise( "griddepcontrol.wait; mov.u32 $0, 0;", "=r", [], dtype=tl.int32, is_pure=False, pack=1) @triton.jit def _globaltimer(): return tl.inline_asm_elementwise( "mov.u64 $0, %globaltimer;", "=l", [], dtype=tl.int64, is_pure=False, pack=1) @triton.autotune( configs=[ triton.Config({}, num_warps=2, num_stages=1), triton.Config({}, num_warps=2, num_stages=2), triton.Config({}, num_warps=2, num_stages=3), triton.Config({}, num_warps=4, num_stages=1), triton.Config({}, num_warps=4, num_stages=2), triton.Config({}, num_warps=4, num_stages=3), triton.Config({}, num_warps=8, num_stages=1), triton.Config({}, num_warps=8, num_stages=2), ], key=[], ) @triton.jit def triton_megakernel( # Inputs (sorted layout from routing) hidden_states_ptr, a_scale_ptr, # GEMM1 weights W1_ptr, W1_scale_ptr, stride_w1_e, stride_w1s_e, # GEMM2 weights W2_ptr, W2_scale_ptr, stride_w2_e, stride_w2s_e, # Routing expert_offsets_ptr, sorted_token_ids_ptr, # Intermediates (pre-allocated) G1_ptr, # [total_routed, N=4096] fp16 — GEMM1 output swiglu_fp16_ptr, # [total_routed, I=2048] fp16 — SwiGLU output swiglu_scale_ptr, # [total_routed, NUM_I_BLOCKS=16] fp32 — SwiGLU per-block scale gemm2_out_ptr, # [total_routed, H=7168] fp32 — GEMM2 output (weighted) gathered_weights_ptr, # [total_routed] fp32 — routing weights # Phase barriers gemm1_done_ptr, # [E_LOCAL] int32 — per-expert GEMM1 tiles completed swiglu_done_ptr, # [E_LOCAL] int32 — per-expert SwiGLU tiles completed # Dimensions stride_as, # A_scale stride (= T for [K_BLOCKS, T] layout) H: tl.constexpr, # 7168 N: tl.constexpr, # 4096 I_dim: tl.constexpr, # 2048 BK: tl.constexpr, # 128 BN: tl.constexpr, # 128 BM: tl.constexpr, # block M for GEMM tiles NUM_KB_H: tl.constexpr, # H/BK = 56 NUM_KB_I: tl.constexpr, # I/BK = 16 NUM_NB: tl.constexpr, # N/BN = 32 NUM_HB: tl.constexpr, # H/BN = 56 NUM_IB: tl.constexpr, # I/BN = 16 GRID_X: tl.constexpr = 56, # grid dim 0 (for GEMM2 stride) E_LOCAL: tl.constexpr = 32, # number of local experts (for expert_map sentinel check) trace_ptr=None, # [E_LOCAL, 6] int64 — globaltimer trace (optional) TRACE: tl.constexpr = False, expert_map_ptr=None, # [8] int32 — compact active expert IDs (optional) USE_EXPERT_MAP: tl.constexpr = False, gemm1_accum_ptr=None, # [SPLIT_K * max_routed, N] fp32 — split-K partition buffer SPLIT_K: tl.constexpr = 1, ACCUM_SPLIT_STRIDE: tl.constexpr = 0, # max_routed * N (stride between partitions) ): """Fused GEMM1 + SwiGLU + GEMM2 megakernel. Grid: (max(NUM_NB, NUM_HB), E_LOCAL) = (56, 32) Each program handles one N/H-tile for one expert. Phase transitions via atomic counters (FlashMoE style). """ tile_id = tl.program_id(0) _pdl_wait() # Resolve expert_id: compact map (T=1) or direct grid index if USE_EXPERT_MAP: expert_id = tl.load(expert_map_ptr + tl.program_id(1)) # Sentinel: slots beyond active experts map to E_LOCAL (invalid) if expert_id >= E_LOCAL: _pdl_launch_dependents() return else: expert_id = tl.program_id(1) # Expert boundaries start = tl.load(expert_offsets_ptr + expert_id).to(tl.int64) end = tl.load(expert_offsets_ptr + expert_id + 1).to(tl.int64) num_tokens = end - start # Early exit for inactive experts (0 tokens) if num_tokens == 0: _pdl_launch_dependents() return # Trace: record start time (tile_id=0 only) if TRACE: if tile_id == 0: tl.store(trace_ptr + expert_id * 6 + 0, _globaltimer()) # ══════════════════════════════════════════════════════ # Phase 1: GEMM1 — [num_tok, H] × [N, H]^T → [num_tok, N] # SPLIT_K=1: tiles 0..31 (NUM_NB), full K, store FP16 to G1 # SPLIT_K>1: tiles 0..NUM_NB*SPLIT_K-1, partial K, store FP32 to partition # ══════════════════════════════════════════════════════ if tile_id < NUM_NB * SPLIT_K: n_tile = tile_id % NUM_NB k_split = tile_id // NUM_NB # 0 when SPLIT_K=1 n_offset = n_tile * BN offs_n = n_offset + tl.arange(0, BN) w1_base = W1_ptr + expert_id * stride_w1_e w1s_base = W1_scale_ptr + expert_id * stride_w1s_e offs_m = tl.arange(0, BM) # Loop over token groups pid_m = 0 while pid_m * BM < num_tokens: row_mask = (pid_m * BM + offs_m) < num_tokens tok_ids = tl.load( sorted_token_ids_ptr + start + pid_m * BM + offs_m, mask=row_mask, other=0) acc = tl.zeros((BM, BN), dtype=tl.float32) for kb_local in range(0, NUM_KB_H // SPLIT_K, 2): kb = k_split * (NUM_KB_H // SPLIT_K) + kb_local # K-block 1 offs_k1 = kb * BK + tl.arange(0, BK) a1 = tl.load( hidden_states_ptr + tok_ids[:, None] * H + offs_k1[None, :], mask=row_mask[:, None], other=0.0) a_s1 = tl.load( a_scale_ptr + kb * stride_as + tok_ids, mask=row_mask, other=0.0).to(tl.float32) w1 = tl.load( w1_base + offs_n[None, :] * H + offs_k1[:, None]) w_s1 = tl.load(w1s_base + n_tile * NUM_KB_H + kb).to(tl.float32) acc += tl.dot(a1, w1) * (a_s1[:, None] * w_s1) # K-block 2 kb2 = kb + 1 offs_k2 = kb2 * BK + tl.arange(0, BK) a2 = tl.load( hidden_states_ptr + tok_ids[:, None] * H + offs_k2[None, :], mask=row_mask[:, None], other=0.0) a_s2 = tl.load( a_scale_ptr + kb2 * stride_as + tok_ids, mask=row_mask, other=0.0).to(tl.float32) w2 = tl.load( w1_base + offs_n[None, :] * H + offs_k2[:, None]) w_s2 = tl.load(w1s_base + n_tile * NUM_KB_H + kb2).to(tl.float32) acc += tl.dot(a2, w2) * (a_s2[:, None] * w_s2) global_row = start + pid_m * BM if SPLIT_K > 1: # Store partial to this split's partition (no atomics) tl.store( gemm1_accum_ptr + k_split * ACCUM_SPLIT_STRIDE + (global_row + offs_m[:, None]) * N + offs_n[None, :], acc, mask=row_mask[:, None]) else: # Store GEMM1 output as FP16 tl.store( G1_ptr + (global_row + offs_m[:, None]) * N + offs_n[None, :], acc.to(tl.float16), mask=row_mask[:, None]) pid_m += 1 # Signal GEMM1 tile done for this expert tl.atomic_add(gemm1_done_ptr + expert_id, 1) # Trace: after GEMM1 if TRACE: if tile_id == 0: tl.store(trace_ptr + expert_id * 6 + 1, _globaltimer()) # ══════════════════════════════════════════════════════ # Phase 2: SwiGLU — [num_tok, N=4096] → [num_tok, I=2048] fp16 + scale # Only tiles 0..15 (I/128 = 16 tiles) # ══════════════════════════════════════════════════════ if tile_id < NUM_IB: # Wait for ALL GEMM1 tiles of this expert to complete. # Pairwise signaling (per-N-tile counters) was tested but regressed T=80 by 30% # due to 32x more atomics and zeroing overhead. Single counter is better. while tl.atomic_add(gemm1_done_ptr + expert_id, 0) < NUM_NB * SPLIT_K: pass # Trace: after barrier1 wait if TRACE: if tile_id == 0: tl.store(trace_ptr + expert_id * 6 + 2, _globaltimer()) k_offset = tile_id * BK offs_k = k_offset + tl.arange(0, BK) offs_m_sw = tl.arange(0, BM) pid_m = 0 while pid_m * BM < num_tokens: row_mask = (pid_m * BM + offs_m_sw) < num_tokens global_row = start + pid_m * BM if SPLIT_K > 1: # Sum SPLIT_K partials for gate and up (reduction at read time) x1 = tl.zeros((BM, BK), dtype=tl.float32) x2 = tl.zeros((BM, BK), dtype=tl.float32) for ks in range(SPLIT_K): x1 += tl.load( gemm1_accum_ptr + ks * ACCUM_SPLIT_STRIDE + (global_row + offs_m_sw[:, None]) * N + offs_k[None, :], mask=row_mask[:, None], other=0.0) x2 += tl.load( gemm1_accum_ptr + ks * ACCUM_SPLIT_STRIDE + (global_row + offs_m_sw[:, None]) * N + I_dim + offs_k[None, :], mask=row_mask[:, None], other=0.0) else: # Load gate and up from G1 (FP16) x1 = tl.load( G1_ptr + (global_row + offs_m_sw[:, None]) * N + offs_k[None, :], mask=row_mask[:, None], other=0.0).to(tl.float32) x2 = tl.load( G1_ptr + (global_row + offs_m_sw[:, None]) * N + I_dim + offs_k[None, :], mask=row_mask[:, None], other=0.0).to(tl.float32) # SwiGLU: silu(x2) * x1 silu_x2 = x2 * tl.sigmoid(x2) c_tile = silu_x2 * x1 # Per-row per-block scaling to FP16 range max_val = tl.max(tl.abs(c_tile), axis=1) scale = max_val / 448.0 # FP8 E4M3 max = 448 scale = tl.where(scale > 0, scale, 1.0) c_fp8 = (c_tile / scale[:, None]).to(tl.float8e4nv) tl.store( swiglu_fp16_ptr + (global_row + offs_m_sw[:, None]) * I_dim + offs_k[None, :], c_fp8, mask=row_mask[:, None]) tl.store( swiglu_scale_ptr + (global_row + offs_m_sw) * NUM_IB + tile_id, scale, mask=row_mask) pid_m += 1 # Signal SwiGLU tile done tl.atomic_add(swiglu_done_ptr + expert_id, 1) # Trace: after SwiGLU if TRACE: if tile_id == 0: tl.store(trace_ptr + expert_id * 6 + 3, _globaltimer()) # ══════════════════════════════════════════════════════ # Phase 3: GEMM2 — [num_tok, I] × [H, I]^T → [num_tok, H] # All 56 tiles (H/128) # ══════════════════════════════════════════════════════ # Wait for ALL SwiGLU tiles of this expert while tl.atomic_add(swiglu_done_ptr + expert_id, 0) < NUM_IB: pass # Trace: after barrier2 wait if TRACE: if tile_id == 0: tl.store(trace_ptr + expert_id * 6 + 4, _globaltimer()) w2_base = W2_ptr + expert_id * stride_w2_e w2s_base = W2_scale_ptr + expert_id * stride_w2s_e offs_m_g2 = tl.arange(0, BM) # Loop over H-blocks: stride by grid size (GRID_X programs share the H-blocks) h_block = tile_id while h_block < NUM_HB: n_offset_g2 = h_block * BN offs_n_g2 = n_offset_g2 + tl.arange(0, BN) pid_m = 0 while pid_m * BM < num_tokens: row_mask = (pid_m * BM + offs_m_g2) < num_tokens global_row = start + pid_m * BM rw = tl.load(gathered_weights_ptr + global_row + offs_m_g2, mask=row_mask, other=0.0).to(tl.float32) acc = tl.zeros((BM, BN), dtype=tl.float32) for kb in range(NUM_KB_I): k_offset = kb * BK offs_k = k_offset + tl.arange(0, BK) a = tl.load( swiglu_fp16_ptr + (global_row + offs_m_g2[:, None]) * I_dim + offs_k[None, :], mask=row_mask[:, None], other=0.0) a_s = tl.load( swiglu_scale_ptr + (global_row + offs_m_g2) * NUM_IB + kb, mask=row_mask, other=0.0).to(tl.float32) w = tl.load( w2_base + offs_n_g2[None, :] * I_dim + offs_k[:, None]) # FP8 — native dot (no .to(tl.float16)) w_s = tl.load(w2s_base + h_block * NUM_KB_I + kb).to(tl.float32) dot_result = tl.dot(a, w) acc += dot_result * (a_s[:, None] * w_s) acc = acc * rw[:, None] tl.store( gemm2_out_ptr + (global_row + offs_m_g2[:, None]) * H + offs_n_g2[None, :], acc.to(tl.bfloat16), mask=row_mask[:, None]) pid_m += 1 h_block += GRID_X # stride by actual grid X size # Trace: after GEMM2 if TRACE: if tile_id == 0: tl.store(trace_ptr + expert_id * 6 + 5, _globaltimer()) _pdl_launch_dependents() @triton.autotune( configs=[ triton.Config({}, num_warps=2, num_stages=1), triton.Config({}, num_warps=2, num_stages=2), triton.Config({}, num_warps=2, num_stages=3), triton.Config({}, num_warps=4, num_stages=1), triton.Config({}, num_warps=4, num_stages=2), triton.Config({}, num_warps=4, num_stages=3), triton.Config({}, num_warps=8, num_stages=1), triton.Config({}, num_warps=8, num_stages=2), ], key=[], ) @triton.jit def triton_megakernel_t1( # Routing inputs (replaces mega_routing_scatter_kernel) logits_ptr, bias_ptr, scale_factor, local_expert_offset, # Outputs for downstream gather_reduce gather_idx_ptr, gather_count_ptr, # Inputs (sorted layout: position == pid_y for T=1) hidden_states_ptr, a_scale_ptr, # GEMM1 weights W1_ptr, W1_scale_ptr, stride_w1_e, stride_w1s_e, # GEMM2 weights W2_ptr, W2_scale_ptr, stride_w2_e, stride_w2s_e, # Intermediates (pre-allocated) G1_ptr, # [max_routed, N=4096] fp16 swiglu_fp16_ptr, # [max_routed, I=2048] fp16 swiglu_scale_ptr, # [max_routed, NUM_IB=16] fp32 gemm2_out_ptr, # [max_routed, H=7168] bf16 # Phase barriers (zeroed by CTA(0,0) at start; release via zero_done_ptr) gemm1_done_ptr, # [E_LOCAL] int32 — reset to 0 each call by CTA(0,0) swiglu_done_ptr, # [E_LOCAL] int32 — reset to 0 each call by CTA(0,0) zero_done_ptr, # [1] int32 — CTA(0,0) writes call_id after zeroing; others wait this_call_id, # monotonic per-call int (1, 2, 3, ...) # Dimensions stride_as, H: tl.constexpr, N: tl.constexpr, I_dim: tl.constexpr, BK: tl.constexpr, BN: tl.constexpr, BM: tl.constexpr, NUM_KB_H: tl.constexpr, NUM_KB_I: tl.constexpr, NUM_NB: tl.constexpr, NUM_HB: tl.constexpr, NUM_IB: tl.constexpr, GRID_X: tl.constexpr, E_LOCAL: tl.constexpr, gemm1_accum_ptr, SPLIT_K: tl.constexpr, ACCUM_SPLIT_STRIDE: tl.constexpr, ): """T=1-specialized fused megakernel: inline routing + GEMM1 + SwiGLU + GEMM2. Each CTA replicates the routing computation in registers (no cross-CTA sync for routing data). pid_y selects the pid_y-th active local expert sorted by local_id. CTA(0,0) writes gather_idx/gather_count for downstream gather_reduce. """ tile_id = tl.program_id(0) pid_y = tl.program_id(1) _pdl_wait() # ────────────────────────────────────────────── # Init: CTA(0,0) zeros mk_*_done; others wait via zero_done flag. # Acq/rel semantics on the atomic ensures the zeros are visible to # other CTAs once they observe zero_done >= this_call_id. # ────────────────────────────────────────────── if tile_id == 0: if pid_y == 0: e_offs = tl.arange(0, 32) e_mask = e_offs < E_LOCAL zeros32 = tl.zeros((32,), dtype=tl.int32) tl.store(gemm1_done_ptr + e_offs, zeros32, mask=e_mask) tl.store(swiglu_done_ptr + e_offs, zeros32, mask=e_mask) tl.atomic_xchg(zero_done_ptr, this_call_id) # ────────────────────────────────────────────── # Inline routing (T=1) — replicated per CTA # Done in parallel with the init wait; cheap math hides under spin. # ────────────────────────────────────────────── NEG_INF = float('-inf') offs_g = tl.arange(0, 256) bias = tl.load(bias_ptr + offs_g).to(tl.float32) group_id = offs_g >> 5 # 0..7 logits = tl.load(logits_ptr + offs_g).to(tl.float32) s = 1.0 / (1.0 + tl.exp(-logits)) s_wb = s + bias # Top-2-per-group score (DeepSeek group-of-experts gating) g_score = tl.zeros([256], dtype=tl.float32) for g in tl.static_range(8): in_g = (group_id == g) vals = tl.where(in_g, s_wb, NEG_INF) m1 = tl.max(vals) vals2 = tl.where(vals >= m1, NEG_INF, vals) m2 = tl.max(vals2) score = m1 + tl.where(m2 > NEG_INF, m2, 0.0) g_score = tl.where(in_g, score, g_score) # Top-4 groups (with smallest-id tiebreak) g_sel = tl.zeros([256], dtype=tl.float32) for _i in tl.static_range(4): avail = tl.where(g_sel > 0.5, NEG_INF, g_score) mx = tl.max(avail) has_mx = (avail >= mx) & (avail > NEG_INF) min_gid = tl.min(tl.where(has_mx, group_id, 8)) g_sel = tl.where(group_id == min_gid, 1.0, g_sel) # Top-8 selection within eligible groups eligible = tl.where(g_sel > 0.5, s_wb, NEG_INF) weight_sum = tl.zeros([], dtype=tl.float32) is_topk = tl.zeros([256], dtype=tl.int1) topk_w = tl.zeros([256], dtype=tl.float32) for _i in tl.static_range(8): mx = tl.max(eligible) is_mx = (eligible >= mx) & (eligible > NEG_INF) idx = tl.min(tl.where(is_mx, offs_g, 256)) exact = (offs_g == idx) s_val = tl.sum(tl.where(exact, s, 0.0)) weight_sum = weight_sum + s_val is_topk = is_topk | exact topk_w = tl.where(exact, s_val, topk_w) eligible = tl.where(exact, NEG_INF, eligible) inv_sum = scale_factor / (weight_sum + 1e-20) topk_w = topk_w * inv_sum # Filter to local experts; rank by global_id (== local_id ordering) local_id_per_global = offs_g - local_expert_offset is_local = (local_id_per_global >= 0) & (local_id_per_global < E_LOCAL) is_topk_local = is_topk & is_local is_topk_local_i32 = is_topk_local.to(tl.int32) total_local = tl.sum(is_topk_local_i32) # Rank: pid_y == r means I'm the r-th active local (sorted by local_id) ranks = tl.cumsum(is_topk_local_i32, axis=0) - 1 my_pos = (ranks == pid_y) & is_topk_local my_global_id = tl.sum(tl.where(my_pos, offs_g, 0)) my_local_id = my_global_id - local_expert_offset my_weight = tl.sum(tl.where(my_pos, topk_w, 0.0)) # CTA(0,0): write downstream-needed buffers (gather_reduce reads these) if tile_id == 0: if pid_y == 0: tl.store(gather_count_ptr, total_local) k_offs = tl.arange(0, 8) tl.store(gather_idx_ptr + k_offs, k_offs.to(tl.int32), mask=k_offs < total_local) # Inactive slot (pid_y >= total_local): nothing to do if pid_y >= total_local: _pdl_launch_dependents() return # Sync: wait for CTA(0,0)'s zero of mk_*_done to be visible before any # phase reads/writes them. acq/rel on the spin's atomic provides the fence. # Routing computation above hides most of CTA(0,0)'s init latency. while tl.atomic_add(zero_done_ptr, 0) < this_call_id: pass expert_id = my_local_id start = pid_y # T=1: 1 token per active expert; offsets equal rank rw_scalar = my_weight # routing weight for this expert (in register) # ────────────────────────────────────────────── # Phase 1: GEMM1 — [1, H] × [N, H]^T → [1, N] # ────────────────────────────────────────────── if tile_id < NUM_NB * SPLIT_K: n_tile = tile_id % NUM_NB k_split = tile_id // NUM_NB n_offset = n_tile * BN offs_n = n_offset + tl.arange(0, BN) offs_m = tl.arange(0, BM) row_mask = offs_m < 1 # T=1: only row 0 valid w1_base = W1_ptr + expert_id * stride_w1_e w1s_base = W1_scale_ptr + expert_id * stride_w1s_e # tok_id is always 0 for T=1 tok_ids = tl.zeros([BM], dtype=tl.int64) acc = tl.zeros((BM, BN), dtype=tl.float32) for kb_local in range(0, NUM_KB_H // SPLIT_K, 2): kb = k_split * (NUM_KB_H // SPLIT_K) + kb_local offs_k1 = kb * BK + tl.arange(0, BK) a1 = tl.load( hidden_states_ptr + tok_ids[:, None] * H + offs_k1[None, :], mask=row_mask[:, None], other=0.0) a_s1 = tl.load( a_scale_ptr + kb * stride_as + tok_ids, mask=row_mask, other=0.0).to(tl.float32) w1 = tl.load( w1_base + offs_n[None, :] * H + offs_k1[:, None]) w_s1 = tl.load(w1s_base + n_tile * NUM_KB_H + kb).to(tl.float32) acc += tl.dot(a1, w1) * (a_s1[:, None] * w_s1) kb2 = kb + 1 offs_k2 = kb2 * BK + tl.arange(0, BK) a2 = tl.load( hidden_states_ptr + tok_ids[:, None] * H + offs_k2[None, :], mask=row_mask[:, None], other=0.0) a_s2 = tl.load( a_scale_ptr + kb2 * stride_as + tok_ids, mask=row_mask, other=0.0).to(tl.float32) w2 = tl.load( w1_base + offs_n[None, :] * H + offs_k2[:, None]) w_s2 = tl.load(w1s_base + n_tile * NUM_KB_H + kb2).to(tl.float32) acc += tl.dot(a2, w2) * (a_s2[:, None] * w_s2) global_row = start if SPLIT_K > 1: tl.store( gemm1_accum_ptr + k_split * ACCUM_SPLIT_STRIDE + (global_row + offs_m[:, None]) * N + offs_n[None, :], acc, mask=row_mask[:, None]) else: tl.store( G1_ptr + (global_row + offs_m[:, None]) * N + offs_n[None, :], acc.to(tl.float16), mask=row_mask[:, None]) tl.atomic_add(gemm1_done_ptr + expert_id, 1) # ────────────────────────────────────────────── # Phase 2: SwiGLU # ────────────────────────────────────────────── if tile_id < NUM_IB: # Wait until this call's GEMM1 tiles are all done. # Phase 1 CTAs already synced on zero_done before incrementing, # so reaching NUM_NB*SPLIT_K guarantees all Phase 1 work completed. while tl.atomic_add(gemm1_done_ptr + expert_id, 0) < NUM_NB * SPLIT_K: pass k_offset = tile_id * BK offs_k = k_offset + tl.arange(0, BK) offs_m_sw = tl.arange(0, BM) row_mask = offs_m_sw < 1 global_row = start if SPLIT_K > 1: x1 = tl.zeros((BM, BK), dtype=tl.float32) x2 = tl.zeros((BM, BK), dtype=tl.float32) for ks in range(SPLIT_K): x1 += tl.load( gemm1_accum_ptr + ks * ACCUM_SPLIT_STRIDE + (global_row + offs_m_sw[:, None]) * N + offs_k[None, :], mask=row_mask[:, None], other=0.0) x2 += tl.load( gemm1_accum_ptr + ks * ACCUM_SPLIT_STRIDE + (global_row + offs_m_sw[:, None]) * N + I_dim + offs_k[None, :], mask=row_mask[:, None], other=0.0) else: x1 = tl.load( G1_ptr + (global_row + offs_m_sw[:, None]) * N + offs_k[None, :], mask=row_mask[:, None], other=0.0).to(tl.float32) x2 = tl.load( G1_ptr + (global_row + offs_m_sw[:, None]) * N + I_dim + offs_k[None, :], mask=row_mask[:, None], other=0.0).to(tl.float32) silu_x2 = x2 * tl.sigmoid(x2) c_tile = silu_x2 * x1 max_val = tl.max(tl.abs(c_tile), axis=1) scale = max_val / 448.0 scale = tl.where(scale > 0, scale, 1.0) c_fp8 = (c_tile / scale[:, None]).to(tl.float8e4nv) tl.store( swiglu_fp16_ptr + (global_row + offs_m_sw[:, None]) * I_dim + offs_k[None, :], c_fp8, mask=row_mask[:, None]) tl.store( swiglu_scale_ptr + (global_row + offs_m_sw) * NUM_IB + tile_id, scale, mask=row_mask) tl.atomic_add(swiglu_done_ptr + expert_id, 1) # ────────────────────────────────────────────── # Phase 3: GEMM2 — [1, I] × [H, I]^T → [1, H] # ────────────────────────────────────────────── while tl.atomic_add(swiglu_done_ptr + expert_id, 0) < NUM_IB: pass w2_base = W2_ptr + expert_id * stride_w2_e w2s_base = W2_scale_ptr + expert_id * stride_w2s_e offs_m_g2 = tl.arange(0, BM) row_mask = offs_m_g2 < 1 global_row = start h_block = tile_id while h_block < NUM_HB: n_offset_g2 = h_block * BN offs_n_g2 = n_offset_g2 + tl.arange(0, BN) acc = tl.zeros((BM, BN), dtype=tl.float32) for kb in range(NUM_KB_I): k_offset = kb * BK offs_k = k_offset + tl.arange(0, BK) a = tl.load( swiglu_fp16_ptr + (global_row + offs_m_g2[:, None]) * I_dim + offs_k[None, :], mask=row_mask[:, None], other=0.0) a_s = tl.load( swiglu_scale_ptr + (global_row + offs_m_g2) * NUM_IB + kb, mask=row_mask, other=0.0).to(tl.float32) w = tl.load( w2_base + offs_n_g2[None, :] * I_dim + offs_k[:, None]) w_s = tl.load(w2s_base + h_block * NUM_KB_I + kb).to(tl.float32) dot_result = tl.dot(a, w) acc += dot_result * (a_s[:, None] * w_s) # Scalar routing weight (no GMEM load) acc = acc * rw_scalar tl.store( gemm2_out_ptr + (global_row + offs_m_g2[:, None]) * H + offs_n_g2[None, :], acc.to(tl.bfloat16), mask=row_mask[:, None]) h_block += GRID_X _pdl_launch_dependents()