diff --git "a/kernels/L2/009_decoder_layer_with_residual_connections/src/kernel.cu" "b/kernels/L2/009_decoder_layer_with_residual_connections/src/kernel.cu" new file mode 100644 --- /dev/null +++ "b/kernels/L2/009_decoder_layer_with_residual_connections/src/kernel.cu" @@ -0,0 +1,12404 @@ +// kernel.cu - Fused Qwen3-MoE decoder layer for B200 (sm_100a). +// +// Pipeline: +// 0+1. prep_qkv_kernel : ONE launch: rmsnorm1 rows (x -> fp16 xn) and Wq|Wk|Wv -> fp16 (x 2^4) as extra CTAs +// (row CTAs also write cos/sin as [T/32][32 float4 groups][32 rows] so the QKV epilogue, +// where thread = row, reads them with coalesced 512 B warp loads instead of 32 lines/load) +// convert_w16_kernel : Wo -> fp16 (x 2^4) on the side stream; o_proj / router acquire its device completion +// counter (no event join on the main stream -> the PDL chain stays unbroken) +// 2. tc_gemm : xn @ [Wq;Wk;Wv]^T (tcgen05 kind::f16, TMA-fed, accumulator in TMEM). +// Fused epilogue: bias, per-head +// q/k RMSNorm, RoPE, fp16 conversion (power-of-2 pre-scaled so fp16 keeps an +// 11-bit mantissa without overflow), written in attention layout. +// 3. mask_classify_kernel : classify additive-mask 128x128 tiles (skip / zero / mixed), one 128-bit streaming +// pass on a side stream (event fork/join), overlapped with steps 0-2 +// and writes compact log2e-pre-scaled copies of mixed tiles (coalesced reads in step 4) +// 4. tc_flash_attn_kernel : tcgen05 flash attention (S = QK^T on SS MMAs, O += PV on TS MMAs with P kept in +// TMEM, S/P/O all in TMEM, online softmax with lazy rescale), GQA via +// kv_head = head/8; a work item is a PAIR of q heads of one kv group sharing every K/V tile load; skips fully masked tiles; persistent (grid=#SMs, atomic work counter, LPT order); V consumed as V^T from the QKV epilogue. +// Softmax runs on 2 warpgroups: each query row is split into two 64-column halves. +// 5. tc_gemm : h = resid + attn @ Wo^T + bo (kind::f16; written into the output buffer) +// 6. (fused into 7) : post-attention RMSNorm for the router is applied on the fly inside router_kernel; +// row rstd comes from the sum of squares accumulated by the o_proj epilogue +// 7. router_kernel : fused rmsnorm2 (h -> TF32 hi/lo in smem) + router logits via a 3-product fp16 hi/lo split tcgen05 kind::f16 GEMM (~22-bit, power-of-2 scaled), K split over a thread-block +// cluster with a deterministic DSMEM reduction, fused softmax / top-8 / renorm / histogram +// 8. scatter (scan fused) : sort (token,k) pairs by expert, build per-expert 128-row M tiles, inverse map +// moe_norm_gather : FUSED rmsnorm2 recompute + gather: one block per token reads its h row once, +// normalizes it (TF32 hi, bit-identical to step 6) and writes it with streaming +// stores into its 8 expert-sorted slots of the A operand (xn2 is never re-read) +// (T >= 4096 fp16 path: xn2 written ONCE as fp16 [T,2048]; the fused fp16 MoE kernel +// gathers A rows by token with cp.async into the swizzled smem layout instead) +// 9. tc_gemm : grouped kind::tf32 GEMM directly on the fp32 expert weights (TMA), per expert +// M tile; B tile = 128 gate rows + 128 matching up rows, epilogue act = silu(g)*u +// 9+10 (T < 4096): moe_fused_kernel runs gate/up AND down in ONE persistent kernel with a global work queue +// (gate/up A rows gathered by token from the once-written fp32 xn2 with cp.async) +// (an item covers ALL <= 2 M tiles of an expert 'pair group': each B weight stage +// feeds both tiles' MMAs -> expert weights stream through L2->SM once, not per M tile) +// (down tiles wait on per-M-tile gate/up completion counters); T >= 4096 uses the +// separate fp16 gate/up kernel + the fp16 DOWN instantiation of the same kernel +// (Wd converted in smem once per <=4-M-tile group to bf16, bf16 act (fp32 exponent range: +// silu(g)*u scales quadratically with input magnitude and overflowed fp16), red.v4 epilogue). +// 10. tc_gemm : grouped GEMM act @ Wd^T, scaled by routing weight; epilogue transposes each +// 32x16 slab through smem and scatter-adds with coalesced red.global.add.v4.f32 +// (output = h + moe). +// The tcgen05 GEMM is persistent and warp-specialized (see its section below). +// All kernels are chained with programmatic dependent launch (PDL): each kernel's prologue (mbarrier init, +// TMEM alloc, tensormap prefetch) overlaps the previous kernel's tail; griddepcontrol.wait precedes any +// global-memory access. +#include "kernel.h" +#include "side_steal.cuh" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define HID 2048 +#define NQKV 5120 +#define INTER 768 +#define NEXP 128 +#define TOPK 8 +// T >= this: RoPE tables stored fp16 x 2^-4 by prep_qkv and the QKV GEMM uses the streamed TMEM epilogue (QF) +#define QKV_F16TAB_MIN_T 2048 +#ifndef PREP_VAR_DEFAULT +#define PREP_VAR_DEFAULT -1 +#endif +// T >= this: o_proj runs on e4m3 operands (kind::f8f6f4): attention writes e4m3 attn, convert_w16 writes e4m3 Wo +#ifndef OPROJ_F8_MIN_T +#define OPROJ_F8_MIN_T 2048 +#endif + +// ------------------------------------------------------------------ small helpers +__device__ __forceinline__ float fast_exp2(float x) { + float y; + asm("ex2.approx.ftz.f32 %0, %1;" : "=f"(y) : "f"(x)); + return y; +} +__device__ __forceinline__ uint32_t pack_bf2(float a, float b) { + __nv_bfloat162 h = __floats2bfloat162_rn(a, b); + return *reinterpret_cast(&h); +} +// Explicit packed conversions: ONE cvt.rn.{f16,bf16}x2.f32 (F2FP) per 2 elements; PTX puts the FIRST source in +// the UPPER half, so (b, a) yields low = a, high = b (same layout as __floats2half2_rn(a, b)). +__device__ __forceinline__ uint32_t cvt_h2(uint32_t a, uint32_t b) { + uint32_t d; + asm("cvt.rn.f16x2.f32 %0, %1, %2;" : "=r"(d) : "f"(__uint_as_float(b)), "f"(__uint_as_float(a))); + return d; +} +__device__ __forceinline__ uint32_t cvt_bf2(uint32_t a, uint32_t b) { + uint32_t d; + asm("cvt.rn.bf16x2.f32 %0, %1, %2;" : "=r"(d) : "f"(__uint_as_float(b)), "f"(__uint_as_float(a))); + return d; +} +__device__ __forceinline__ uint32_t smem_u32(const void* p) { return (uint32_t)__cvta_generic_to_shared(p); } +// 4 fp32 -> 4 packed fp8 (byte 0 = a). cvt.rn.satfinite.{e4m3,e5m2}x2.f32 d, x, y puts x in the UPPER byte. +// (also used by the FP8 o_proj path, T >= OPROJ_F8_MIN_T) +__device__ __forceinline__ uint32_t cvt_e4m3x4(float a, float b, float c, float d) { + unsigned short lo, hi; + asm("cvt.rn.satfinite.e4m3x2.f32 %0, %1, %2;" : "=h"(lo) : "f"(b), "f"(a)); + asm("cvt.rn.satfinite.e4m3x2.f32 %0, %1, %2;" : "=h"(hi) : "f"(d), "f"(c)); + return (uint32_t)lo | ((uint32_t)hi << 16); +} +__device__ __forceinline__ uint32_t cvt_e5m2x4(float a, float b, float c, float d) { + unsigned short lo, hi; + asm("cvt.rn.satfinite.e5m2x2.f32 %0, %1, %2;" : "=h"(lo) : "f"(b), "f"(a)); + asm("cvt.rn.satfinite.e5m2x2.f32 %0, %1, %2;" : "=h"(hi) : "f"(d), "f"(c)); + return (uint32_t)lo | ((uint32_t)hi << 16); +} +// same bytes as cvt_e5m2x4, but both packed cvts + the 16-bit pair assembly in ONE asm block (mov.b32 {lo, hi}: +// no zero-extend / shift / or chain, ptxas merges the halves into the F2FP destinations or one PRMT) +__device__ __forceinline__ uint32_t cvt_e5m2x4p(uint32_t a, uint32_t b, uint32_t c, uint32_t d) { + uint32_t r; + asm("{ .reg .b16 lo, hi; cvt.rn.satfinite.e5m2x2.f32 lo, %2, %1; cvt.rn.satfinite.e5m2x2.f32 hi, %4, %3;\n" + " mov.b32 %0, {lo, hi}; }" + : "=r"(r) : "f"(__uint_as_float(a)), "f"(__uint_as_float(b)), "f"(__uint_as_float(c)), "f"(__uint_as_float(d))); + return r; +} +// same bytes as cvt_e4m3x4 (byte 0 = a), both packed cvts + the pair assembly in ONE asm block (mov.b32 {lo, hi}) +__device__ __forceinline__ uint32_t cvt_e4m3x4p(float a, float b, float c, float d) { + uint32_t r; + asm("{ .reg .b16 lo, hi; cvt.rn.satfinite.e4m3x2.f32 lo, %2, %1; cvt.rn.satfinite.e4m3x2.f32 hi, %4, %3;\n" + " mov.b32 %0, {lo, hi}; }" + : "=r"(r) : "f"(a), "f"(b), "f"(c), "f"(d)); + return r; +} +// 4 fp32 (one 16 B raw chunk) -> 4 fp16 as ONE asm block of two packed cvt.rn.f16x2.f32 (low half = first +// element, bit-identical to cvt_h2 / __floats2half2_rn). The x16 variant first scales by 2^4 (mul.rn.f32, identical to +// the C++ x * 16.f product) inside the same block. +__device__ __forceinline__ uint2 cvt_h2x4p(uint4 a) { + uint2 r; + asm("{ cvt.rn.f16x2.f32 %0, %3, %2; cvt.rn.f16x2.f32 %1, %5, %4; }" + : "=r"(r.x), "=r"(r.y) + : "f"(__uint_as_float(a.x)), "f"(__uint_as_float(a.y)), "f"(__uint_as_float(a.z)), "f"(__uint_as_float(a.w))); + return r; +} +__device__ __forceinline__ uint2 cvt_h2x4p16(uint4 a) { + uint2 r; + asm("{ .reg .f32 t0, t1, t2, t3; mul.rn.f32 t0, %2, 0f41800000; mul.rn.f32 t1, %3, 0f41800000;\n" + " mul.rn.f32 t2, %4, 0f41800000; mul.rn.f32 t3, %5, 0f41800000;\n" + " cvt.rn.f16x2.f32 %0, t1, t0; cvt.rn.f16x2.f32 %1, t3, t2; }" + : "=r"(r.x), "=r"(r.y) + : "f"(__uint_as_float(a.x)), "f"(__uint_as_float(a.y)), "f"(__uint_as_float(a.z)), "f"(__uint_as_float(a.w))); + return r; +} +__device__ __forceinline__ void sts128(uint32_t a, uint32_t x, uint32_t y, uint32_t z, uint32_t w) { + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(a), "r"(x), "r"(y), "r"(z), "r"(w) : "memory"); +} +// exact power-of-2 scale s with mx * s < 2^top (1 for mx == 0 / non-finite), exponent clamped to [-60, 60]. +// Used for the attention-output scale (top 7, mx = global max |V| bound) and the Wo row scales (top 8). +__device__ __forceinline__ float f8_scale(float mx, int top) { + if (!(mx > 0.f) || !(mx < INFINITY)) return 1.f; + int e; + e = sidew::frexp_e(mx); + int x = top - e; + x = x < -60 ? -60 : (x > 60 ? 60 : x); + return sidew::pow2i(x); +} +// FP8 QK^T (FA4 path): global power-of-2 e4m3 scale of Q (which = 0) or K (which = 1). After the per-head RMSNorm +// |x_d| <= sqrt(128) max|w| (x_d^2 <= sum x^2), after RoPE |o_d| <= |x1||c| + |x2||s| <= max|x| (max|cos| + max|sin|); +// bound * scale < 2^8 (< 448, e4m3 max). Identical expression in fa4.cu (qk8_scale) so writer and reader agree. +__device__ __forceinline__ float qk8_scale(const unsigned* qkb, int which) { + const float bound = 11.3137085f * __uint_as_float(qkb[2 + which]) * + (__uint_as_float(qkb[0]) + __uint_as_float(qkb[1])); + return f8_scale(bound, 8); +} +__device__ __forceinline__ uint32_t pack_h2(float a, float b) { + __half2 h = __floats2half2_rn(a, b); + return *reinterpret_cast(&h); +} +// fp16 hi / lo split of 4 floats: hi = fp16(a), hs = fp16(hi * shi), ls = fp16((a - hi) * slo) +// (a - hi is exact in fp32; shi / slo are pow2, so hs = hi * shi exactly unless it lands in the fp16 subnormal range) +__device__ __forceinline__ void split3_h4(float4 a, float shi, float slo, uint2& hi, uint2& hs, uint2& ls) { + const float hx = __half2float(__float2half_rn(a.x)), hy = __half2float(__float2half_rn(a.y)); + const float hz = __half2float(__float2half_rn(a.z)), hw = __half2float(__float2half_rn(a.w)); + hi = make_uint2(pack_h2(hx, hy), pack_h2(hz, hw)); + hs = make_uint2(pack_h2(hx * shi, hy * shi), pack_h2(hz * shi, hw * shi)); + ls = make_uint2(pack_h2((a.x - hx) * slo, (a.y - hy) * slo), pack_h2((a.z - hz) * slo, (a.w - hw) * slo)); +} + + +// ------------------------------------------------------------------ Blackwell packed fp32x2 ALU (sm_100: FFMA2/FADD2/FMUL2) +// Each op processes two fp32 lanes held in a 64-bit register pair with ONE issued instruction (per-lane IEEE +// .rn rounding, bit-identical to the scalar ops). Used by the flash-attention softmax, which is issue-bound. +__device__ __forceinline__ float2 ffma2(float2 a, float2 b, float2 c) { + float2 d; + asm("{ .reg .b64 ra, rb, rc, rd; mov.b64 ra, {%2, %3}; mov.b64 rb, {%4, %5}; mov.b64 rc, {%6, %7};\n" + "fma.rn.f32x2 rd, ra, rb, rc; mov.b64 {%0, %1}, rd; }" + : "=f"(d.x), "=f"(d.y) : "f"(a.x), "f"(a.y), "f"(b.x), "f"(b.y), "f"(c.x), "f"(c.y)); + return d; +} +__device__ __forceinline__ float2 fadd2(float2 a, float2 b) { + float2 d; + asm("{ .reg .b64 ra, rb, rd; mov.b64 ra, {%2, %3}; mov.b64 rb, {%4, %5};\n" + "add.rn.f32x2 rd, ra, rb; mov.b64 {%0, %1}, rd; }" + : "=f"(d.x), "=f"(d.y) : "f"(a.x), "f"(a.y), "f"(b.x), "f"(b.y)); + return d; +} +// packed fp32x2 subtract: a - b (bit-identical to fadd2(a, -b), no separate negations) +__device__ __forceinline__ float2 fsub2(float2 a, float2 b) { + float2 d; + asm("{ .reg .b64 ra, rb, rd; mov.b64 ra, {%2, %3}; mov.b64 rb, {%4, %5};\n" + "sub.rn.f32x2 rd, ra, rb; mov.b64 {%0, %1}, rd; }" + : "=f"(d.x), "=f"(d.y) : "f"(a.x), "f"(a.y), "f"(b.x), "f"(b.y)); + return d; +} +__device__ __forceinline__ float2 fmul2(float2 a, float2 b) { + float2 d; + asm("{ .reg .b64 ra, rb, rd; mov.b64 ra, {%2, %3}; mov.b64 rb, {%4, %5};\n" + "mul.rn.f32x2 rd, ra, rb; mov.b64 {%0, %1}, rd; }" + : "=f"(d.x), "=f"(d.y) : "f"(a.x), "f"(a.y), "f"(b.x), "f"(b.y)); + return d; +} +// packed silu(g) * u for two lanes: exp2 / rcp are MUFU (scalar), the surrounding mul / add are FMUL2 / FADD2 +__device__ __forceinline__ float rcp_approx(float x) { + float y; + asm("rcp.approx.ftz.f32 %0, %1;" : "=f"(y) : "f"(x)); + return y; +} +__device__ __forceinline__ float2 silu_mul2(float2 g, float2 u) { + const float2 t = fmul2(g, make_float2(-1.4426950408889634f, -1.4426950408889634f)); + const float2 d = fadd2(make_float2(fast_exp2(t.x), fast_exp2(t.y)), make_float2(1.f, 1.f)); + return fmul2(fmul2(g, make_float2(rcp_approx(d.x), rcp_approx(d.y))), u); +} +// 3-input max (sm_100 PTX max.f32 d, a, b, c): one instruction for two max steps +__device__ __forceinline__ float fmax3(float a, float b, float c) { + float d; + asm("max.f32 %0, %1, %2, %3;" : "=f"(d) : "f"(a), "f"(b), "f"(c)); + return d; +} + +// packed silu(g) * u with ONE MUFU op per element: sigmoid(g) = 0.5 tanh(g / 2) + 0.5 +// (tanh.approx.f32, max rel err ~2^-11) vs ex2 + rcp in silu_mul2. Only where the result is rounded to e5m2 right after. +__device__ __forceinline__ float tanh_approx(float x) { + float y; + asm("tanh.approx.f32 %0, %1;" : "=f"(y) : "f"(x)); + return y; +} +__device__ __forceinline__ float2 silu_mul2_t(float2 g, float2 u) { + const float2 h = fmul2(g, make_float2(0.5f, 0.5f)); + const float2 sg = ffma2(make_float2(tanh_approx(h.x), tanh_approx(h.y)), make_float2(0.5f, 0.5f), make_float2(0.5f, 0.5f)); + return fmul2(fmul2(g, sg), u); +} +// scaled output conversion - 4 (or 2) O values x the folded output scale (1/l [x global fp8 scale]) as packed +// FMUL2 (bit-identical to the scalar products), then one packed cvt per pair. +__device__ __forceinline__ uint32_t e4m3x4_s(const float* p, float2 s2) { + const float2 a = fmul2(make_float2(p[0], p[1]), s2), b = fmul2(make_float2(p[2], p[3]), s2); + return cvt_e4m3x4(a.x, a.y, b.x, b.y); +} +__device__ __forceinline__ uint32_t h2_s(const float* p, float2 s2) { + const float2 a = fmul2(make_float2(p[0], p[1]), s2); + return pack_h2(a.x, a.y); +} +// ------------------------------------------------------------------ early L2 cache-policy helpers (non-MoE kernels) +// keep_pol(): L2 EVICT_LAST policy for data produced by one kernel and consumed by the next (xn, Wqkv16/Wo16, q/k, +// attn, h, xn2); first_pol(): EVICT_FIRST for read-once streams. +__device__ __forceinline__ uint64_t keep_pol() { + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol)); + return pol; +} +__device__ __forceinline__ uint64_t first_pol() { + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + return pol; +} +__device__ __forceinline__ void st_u2_pol(void* addr, uint2 v, uint64_t pol) { + asm volatile("st.global.L2::cache_hint.v2.b32 [%0], {%1, %2}, %3;" ::"l"(addr), "r"(v.x), "r"(v.y), "l"(pol) + : "memory"); +} +__device__ __forceinline__ void st_f4_pol(void* addr, float4 v, uint64_t pol) { + asm volatile("st.global.L2::cache_hint.v4.f32 [%0], {%1, %2, %3, %4}, %5;" ::"l"(addr), "f"(v.x), "f"(v.y), "f"(v.z), + "f"(v.w), "l"(pol) + : "memory"); +} +__device__ __forceinline__ float4 ld_f4_pol(const void* addr, uint64_t pol) { + float4 v; + asm volatile("ld.global.nc.L2::cache_hint.v4.f32 {%0, %1, %2, %3}, [%4], %5;" + : "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w) + : "l"(addr), "l"(pol)); + return v; +} + +// ------------------------------------------------------------------ programmatic dependent launch (PDL) +// pdl_wait() (griddepcontrol.wait) blocks until the previous grid has completed and its memory is visible; +// every kernel calls it BEFORE its first global memory access. +__device__ __forceinline__ void pdl_wait() { asm volatile("griddepcontrol.wait;" ::: "memory"); } +__device__ __forceinline__ void pdl_trigger() { asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); } + +// ------------------------------------------------------------------ chain probe (CHAIN_PROBE builds only) +// thread 0 of every CTA of selected kernels appends {globaltimer, id*4+type | #CTAs<<16} to a device log +// (type 0 = CTA entry, 1 = after griddepcontrol.wait, 2 = CTA end). Compiled out otherwise. +#ifdef CHAIN_PROBE +constexpr unsigned long long CHN_CAP = 1ull << 22; +__device__ unsigned long long g_chn_n; +__device__ ulonglong2* g_chn_log; +__device__ __forceinline__ void chn_rec(int id, int t) { + if (threadIdx.x == 0 && g_chn_log) { + unsigned long long tt; asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(tt) :: "memory"); + const unsigned long long i = atomicAdd(&g_chn_n, 1ull); + if (i < CHN_CAP) g_chn_log[i] = make_ulonglong2(tt, (unsigned long long)(id * 4 + t) | + ((unsigned long long)(gridDim.x * gridDim.y * gridDim.z) << 16)); + } +} +#define CHN(id, t) chn_rec(id, t) +__device__ __forceinline__ void chn_rec_t(int id, int t, int thr) { + if (threadIdx.x == thr && g_chn_log) { + unsigned long long tt; asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(tt) :: "memory"); + const unsigned long long i = atomicAdd(&g_chn_n, 1ull); + if (i < CHN_CAP) g_chn_log[i] = make_ulonglong2(tt, (unsigned long long)(id * 4 + t) | + ((unsigned long long)(gridDim.x * gridDim.y * gridDim.z) << 16)); + } +} +#define CHNT(id, t, thr) chn_rec_t(id, t, thr) +#else +#define CHN(id, t) do { } while (0) +#define CHNT(id, t, thr) do { } while (0) +#endif + +__device__ __forceinline__ void side_signal(unsigned long long* ctr) { + __syncthreads(); + if (threadIdx.x == 0) { asm volatile("red.release.gpu.global.add.u64 [%0], %1;" ::"l"(ctr), "l"((unsigned long long)(1ull)) : "memory"); } +} +__device__ __forceinline__ void side_acquire(const unsigned long long* ctr, unsigned long long target) { + while (true) { + unsigned long long v; + asm volatile("ld.acquire.gpu.global.u64 %0, [%1];" : "=l"(v) : "l"(ctr) : "memory"); + if (v >= target) break; + __nanosleep(32); + } +} + +// ------------------------------------------------------------------ RMSNorm +// One block (256 threads) per 2048-float row; each thread owns 2 float4. +__device__ __forceinline__ float tf32_hi(float x) { + uint32_t r; + asm("cvt.rna.tf32.f32 %0, %1;" : "=r"(r) : "f"(x)); + return __uint_as_float(r); +} +// Shared row-normalization body (used by rmsnorm_kernel and the fused norm+gather so both produce +// bit-identical values): returns w * x * rsqrt(mean(x^2) + eps) for this thread's two float4. +__device__ __forceinline__ void rms_row(const float* __restrict__ x, const float* __restrict__ w, float eps, int row, + int tid, float* red, float4& o0, float4& o1) { + const float4* xr = reinterpret_cast(x + (size_t)row * HID); + float4 v0 = xr[tid], v1 = xr[tid + 256]; + float ss = v0.x * v0.x + v0.y * v0.y + v0.z * v0.z + v0.w * v0.w + v1.x * v1.x + v1.y * v1.y + v1.z * v1.z + + v1.w * v1.w; + for (int o = 16; o; o >>= 1) ss += __shfl_xor_sync(0xffffffff, ss, o); + if ((tid & 31) == 0) red[tid >> 5] = ss; + __syncthreads(); + float tot = 0.f; +#pragma unroll + for (int i = 0; i < 8; i++) tot += red[i]; + float r = rsqrtf(tot / (float)HID + eps); + const float4* wr = reinterpret_cast(w); + float4 w0 = wr[tid], w1 = wr[tid + 256]; + o0 = make_float4(w0.x * (v0.x * r), w0.y * (v0.y * r), w0.z * (v0.z * r), w0.w * (v0.w * r)); + o1 = make_float4(w1.x * (v1.x * r), w1.y * (v1.y * r), w1.z * (v1.z * r), w1.w * (v1.w * r)); +} +// Same normalization but with the row's sum of squares precomputed (accumulated by the o_proj epilogue into +// ssq[row]): no block reduction. Used for the post-attention norm by both the router operand pass and the fused +// norm+gather, so both see the identical rstd. +__device__ __forceinline__ void rms_row_ss(const float* __restrict__ x, const float* __restrict__ w, float ss, + float eps, int row, int tid, float4& o0, float4& o1) { + const float4* xr = reinterpret_cast(x + (size_t)row * HID); + float4 v0 = xr[tid], v1 = xr[tid + 256]; + float r = rsqrtf(ss / (float)HID + eps); + const float4* wr = reinterpret_cast(w); + float4 w0 = wr[tid], w1 = wr[tid + 256]; + o0 = make_float4(w0.x * (v0.x * r), w0.y * (v0.y * r), w0.z * (v0.z * r), w0.w * (v0.w * r)); + o1 = make_float4(w1.x * (v1.x * r), w1.y * (v1.y * r), w1.z * (v1.z * r), w1.w * (v1.w * r)); +} +// MODE 1: fp16 output (A operand of the fp16 QKV GEMM). +// MODE 2: TF32 split of the normalized row: out = hi = rna_tf32(y), out2 = lo = y - hi (router 3xTF32 GEMM). +template +__global__ void __launch_bounds__(256) rmsnorm_kernel(const float* __restrict__ x, const float* __restrict__ w, + float eps, void* __restrict__ out, float* __restrict__ out2, + float* __restrict__ ssq) { + pdl_wait(); + pdl_trigger(); + int row = blockIdx.x, tid = threadIdx.x; + __shared__ float red[8]; + float4 o0, o1; + if (MODE == 1) { + // MODE 1 also zeroes ssq[row], the post-attention sum-of-squares accumulator filled by the o_proj epilogue + if (tid == 0) ssq[row] = 0.f; + rms_row(x, w, eps, row, tid, red, o0, o1); + } else { + rms_row_ss(x, w, ssq[row], eps, row, tid, o0, o1); // stats precomputed by the o_proj epilogue + } + if (MODE == 1) { + uint2* orow = reinterpret_cast(reinterpret_cast<__half*>(out) + (size_t)row * HID); + orow[tid] = make_uint2(pack_h2(o0.x, o0.y), pack_h2(o0.z, o0.w)); + orow[tid + 256] = make_uint2(pack_h2(o1.x, o1.y), pack_h2(o1.z, o1.w)); + } else { + const float4 h0 = make_float4(tf32_hi(o0.x), tf32_hi(o0.y), tf32_hi(o0.z), tf32_hi(o0.w)); + const float4 h1 = make_float4(tf32_hi(o1.x), tf32_hi(o1.y), tf32_hi(o1.z), tf32_hi(o1.w)); + float4* orow = reinterpret_cast(reinterpret_cast(out) + (size_t)row * HID); + float4* lrow = reinterpret_cast(out2 + (size_t)row * HID); + orow[tid] = h0; + orow[tid + 256] = h1; + lrow[tid] = make_float4(o0.x - h0.x, o0.y - h0.y, o0.z - h0.z, o0.w - h0.w); + lrow[tid + 256] = make_float4(o1.x - h1.x, o1.y - h1.y, o1.z - h1.z, o1.w - h1.w); + } +} + +// TF32 hi/lo split of the router weight into zero-padded [256, 2048] buffers (rows >= 128 are zero). +__global__ void __launch_bounds__(256) split_hilo_kernel(const float* __restrict__ src, float* __restrict__ hi, + float* __restrict__ lo, int n_valid4, int n_total4) { + pdl_wait(); + pdl_trigger(); + const int i = blockIdx.x * 256 + threadIdx.x; + if (i >= n_total4) return; + float4 v = make_float4(0.f, 0.f, 0.f, 0.f); + if (i < n_valid4) v = reinterpret_cast(src)[i]; + const float4 h = make_float4(tf32_hi(v.x), tf32_hi(v.y), tf32_hi(v.z), tf32_hi(v.w)); + reinterpret_cast(hi)[i] = h; + reinterpret_cast(lo)[i] = make_float4(v.x - h.x, v.y - h.y, v.z - h.z, v.w - h.w); +} + +// Exact power-of-2 scale s with mx * s < 2^14 (mx = max |value|; s = 1 for mx == 0 / non-finite), exponent clamped to +// [-60, 60] so products of two scales stay normal fp32. +__device__ __forceinline__ float pow2_scale(float mx) { + if (!(mx > 0.f) || !(mx < INFINITY)) return 1.f; + int e; + e = sidew::frexp_e(mx); // mx = f * 2^e, f in [0.5, 1) -> mx < 2^e + int x = 14 - e; + x = x < -60 ? -60 : (x > 60 ? 60 : x); + return sidew::pow2i(x); +} +// fp32 -> fp16 weight conversion with a power-of-2 pre-scale (keeps small weights out of fp16 subnormals). +// Blocks [0, nconv): Wo conversion (1024 float4 per block). Blocks [nconv, nconv + nsplit): router weight TF32 +// hi/lo split (1024 float4 per block) - folded in here so the side stream runs ONE kernel instead of two. +__global__ void __launch_bounds__(256) convert_w16_kernel(const float* __restrict__ src, __half* __restrict__ dst, + size_t n4, float scale, int nconv, + const float* __restrict__ wr, float* __restrict__ wrh, + float* __restrict__ wrl, int nwr4, + unsigned long long* __restrict__ done, int f8, + float* __restrict__ winv, unsigned* __restrict__ cst, + unsigned cep, int ubase) { + const int bx = (int)blockIdx.x + ubase; // unit index (QKV-stolen Wo units are not launched) + CHN(1, 0); + pdl_wait(); + pdl_trigger(); + // 256-bit loads (ld.global.nc.L1::no_allocate.L2::evict_first.v8.f32, sm_100): thread t owns float4 slots + // bx*1024 + 512 h + 2 t + {0, 1} (h = 0, 1) -> 2 x 32 B loads in flight per thread (same 16 KB per CTA); every + // output element is written at the index of its input element, so the converted bytes are identical + const uint64_t rf = first_pol(), kp = keep_pol(); // fp32 Wo read once; fp16 Wo16 consumed by o_proj + auto cidx = [&](int u) -> size_t { return (size_t)bx * 1024 + (size_t)(u >> 1) * 512 + 2 * threadIdx.x + (u & 1); }; + float4 v[4]; + if (bx < nconv) { +#pragma unroll + for (int h = 0; h < 2; h++) { + const size_t i = cidx(2 * h); + if (i + 1 < n4 + 1 && i < n4) { + const float* ap = reinterpret_cast(src) + 4 * i; + asm volatile("ld.global.nc.L1::no_allocate.L2::cache_hint.v8.f32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8], %9;" + : "=f"(v[2 * h].x), "=f"(v[2 * h].y), "=f"(v[2 * h].z), "=f"(v[2 * h].w), + "=f"(v[2 * h + 1].x), "=f"(v[2 * h + 1].y), "=f"(v[2 * h + 1].z), "=f"(v[2 * h + 1].w) + : "l"(ap), "l"(rf)); + } + } + } + { // claim this CTA's unit (o_proj / router warps spinning on the counter may have executed it already) + __shared__ int s_ok; + if (threadIdx.x == 0) s_ok = sidew::claim(cst, bx, cep) ? 1 : 0; + __syncthreads(); + if (!s_ok) { CHN(1, 2); return; } + } + if (bx >= nconv) { + // Router weight fp16 hi/lo split with an exact power-of-2 scale per expert row (block = 2 rows of 2048): + // s_e = 2^(14 - e), max|Wr[e,:]| < 2^e -> |Wr s_e| < 2^14 (fp16-safe), hi = f16(w s_e), lo = f16(w s_e - hi) + // wrh (as fp16) = [256][2048]: rows 0..127 hi, rows 128..255 lo (the N=256 B operand of the router MMA); + // wrl[e] = s_e. hi + lo carries ~22 significant bits (same as the former TF32 hi/lo split). + __shared__ float rmax[2][8]; + const int blk = bx - nconv, base = blk * 1024 + threadIdx.x; + float4 v[4]; + float m[2] = {0.f, 0.f}; +#pragma unroll + for (int u = 0; u < 4; u++) { + v[u] = __ldcs(reinterpret_cast(wr) + base + u * 256); + m[u >> 1] = fmaxf(m[u >> 1], fmaxf(fmaxf(fabsf(v[u].x), fabsf(v[u].y)), fmaxf(fabsf(v[u].z), fabsf(v[u].w)))); + } +#pragma unroll + for (int o = 16; o; o >>= 1) +#pragma unroll + for (int r = 0; r < 2; r++) m[r] = fmaxf(m[r], __shfl_xor_sync(0xffffffff, m[r], o)); + if ((threadIdx.x & 31) == 0) { rmax[0][threadIdx.x >> 5] = m[0]; rmax[1][threadIdx.x >> 5] = m[1]; } + __syncthreads(); + float sc[2]; +#pragma unroll + for (int r = 0; r < 2; r++) { + float mx = 0.f; +#pragma unroll + for (int w8 = 0; w8 < 8; w8++) mx = fmaxf(mx, rmax[r][w8]); + sc[r] = pow2_scale(mx); + } + __half* h16 = reinterpret_cast<__half*>(wrh); +#pragma unroll + for (int u = 0; u < 4; u++) { + const int i = base + u * 256; // float4 index in [128][512] + const float s_ = sc[u >> 1]; + const float x0 = v[u].x * s_, x1 = v[u].y * s_, x2 = v[u].z * s_, x3 = v[u].w * s_; + const __half2 h01 = __floats2half2_rn(x0, x1), h23 = __floats2half2_rn(x2, x3); + const float2 f01 = __half22float2(h01), f23 = __half22float2(h23); + reinterpret_cast(h16)[i] = make_uint2(*reinterpret_cast(&h01), *reinterpret_cast(&h23)); + // the Wr_lo half (rows 128..255) is no longer written - the router MMA reads Wr_hi rows only + (void)f01; (void)f23; + } + if (threadIdx.x == 0) { wrl[2 * blk] = sc[0]; wrl[2 * blk + 1] = sc[1]; } + side_signal(done); // Wr hi/lo + scales written (consumed by router_kernel) + CHN(1, 2); + return; + } + if (f8) { + // fp8 mode: block = Wo row n (4096 floats = output column n of o_proj). Row max -> exact pow2 scale s_n with + // max * s_n < 2^8 (e4m3 max 448), e4m3 bytes Wo[n,k] * s_n into dst (uint8 [2048][4096]), winv[n] = 1 / s_n. + __shared__ float wmx[8]; + float m = 0.f; +#pragma unroll + for (int u = 0; u < 4; u++) + m = fmaxf(m, fmaxf(fmaxf(fabsf(v[u].x), fabsf(v[u].y)), fmaxf(fabsf(v[u].z), fabsf(v[u].w)))); +#pragma unroll + for (int o = 16; o; o >>= 1) m = fmaxf(m, __shfl_xor_sync(0xffffffff, m, o)); + if ((threadIdx.x & 31) == 0) wmx[threadIdx.x >> 5] = m; + __syncthreads(); + float mx = 0.f; +#pragma unroll + for (int w8 = 0; w8 < 8; w8++) mx = fmaxf(mx, wmx[w8]); + const float sc = f8_scale(mx, 8); + uint32_t* d8 = reinterpret_cast(dst); +#pragma unroll + for (int u = 0; u < 4; u++) + d8[cidx(u)] = cvt_e4m3x4(v[u].x * sc, v[u].y * sc, v[u].z * sc, v[u].w * sc); + if (threadIdx.x == 0) winv[bx] = 1.f / sc; + side_signal(done); + CHN(1, 2); + return; + } +#pragma unroll + for (int u = 0; u < 4; u++) { + const size_t i = cidx(u); + if (i < n4) + st_u2_pol(reinterpret_cast(dst) + i, + make_uint2(pack_h2(v[u].x * scale, v[u].y * scale), pack_h2(v[u].z * scale, v[u].w * scale)), kp); + } + side_signal(done); // Wo16 slice written (consumed by o_proj) + CHN(1, 2); +} + +// Fused pre-QKV prep: ONE launch, blockIdx range split; pure DRAM streaming, warp-level reductions only. +// blocks [0, nrb) : rmsnorm1, TWO WARPS PER ROW (4 rows per 256-thread CTA, nrb = ceil(T/4)): warp half h, +// lane l loads float4 256h + l + 32j (j = 0..7) - all 8 x 128-bit loads (32 KB per CTA) +// in flight before the reduction (warp shuffle + smem pair sum) - writes fp16 xn, zeroes +// ssq[row]; half 0 re-lays out cos, half 1 sin +// blocks [nrb, nrb + nconv): Wq|Wk|Wv fp32 -> fp16 (x 2^4) into the concatenated [5120, 2048] destination; +// 2048 float4 per block (8 x 128-bit EVICT_FIRST loads per thread = 32 KB in flight per +// CTA, 64-bit stores). Each source's float4 count is a multiple of 2048, so a block never +// straddles two sources. +constexpr int PREP_CONV4 = 2048; // float4 per conversion block +__device__ __forceinline__ void prep_st16(void* addr, uint4 v, bool hint, uint64_t pol) { + if (hint) + asm volatile("st.global.L2::cache_hint.v4.b32 [%0], {%1, %2, %3, %4}, %5;" ::"l"(addr), "r"(v.x), "r"(v.y), + "r"(v.z), "r"(v.w), "l"(pol) : "memory"); + else + *reinterpret_cast(addr) = v; +} +template +__global__ void __launch_bounds__(256, 4) prep_qkv_kernel(const float* __restrict__ x, const float* __restrict__ w, + float eps, int T, __half* __restrict__ xn, + float* __restrict__ ssq, const float* __restrict__ wq, + const float* __restrict__ wk, const float* __restrict__ wv, + __half* __restrict__ wqkv16, const float* __restrict__ cs, + const float* __restrict__ sn, float* __restrict__ csT, + float* __restrict__ snT, int* __restrict__ zbuf, int nz, + __half* __restrict__ vt, int S, int Spad, + unsigned* __restrict__ qkb, const float* __restrict__ qnw_, + const float* __restrict__ knw_, float* __restrict__ winvq, + float* __restrict__ xinv, __half* __restrict__ xn16s, int wtab, + int x3) { + CHN(2, 0); + // the input loads (x rows, cos/sin, fp32 Wqkv - kernel INPUTS, never written by any kernel of + // this layer) are issued BEFORE griddepcontrol.wait, so the first wave's DRAM reads overlap the previous call's + // MoE tail; every global WRITE (xn, tables, zbuf, Wqkv copy, ssq, qkb) stays after the wait. + // also 897 <= T < 2048 (input loads before the PDL wait; pair-local row reduction below) + const bool early = true; // input loads before the PDL wait for every T (inputs only) + // the FP8 QK bounds (qkb) are never read below T = 2048 (attn_qk_f8 needs T >= 2048), so + // the CTA-wide cos/sin max reduction is skipped and the row sum of squares is combined with a 64-thread named + // barrier per row pair (no __syncthreads on the rows path) + const bool pairred = qkb == nullptr; // no FP8-QK bounds needed (host passes nullptr) -> pair-local row reduction + if (!early) { pdl_wait(); CHN(2, 1); pdl_trigger(); } + const int tid = threadIdx.x; + const int nrb = (T + 3) >> 2; + // grid order = Wqkv conversion blocks FIRST (blockIdx [0, nconv)), RMSNorm row blocks after + // (rb = blockIdx - nconv). The conversion blocks need no griddepcontrol.wait, so dispatched first they stream the + // 42 MB fp32 Wqkv while the predecessor drains / before the row CTAs (which park on the PDL wait) take the slots. + // Same per-block work (row / conversion index mapping unchanged) -> bit-identical outputs. + const int nconv_ = (int)gridDim.x - nrb; + const int rb = (int)blockIdx.x - nconv_; + if (rb >= 0) { + __shared__ float red[8]; + const int warp = tid >> 5, lane = tid & 31, half = warp & 1; + const int row = rb * 4 + (warp >> 1); + __shared__ float4 tab_st[2][4][34]; // RoPE table staging; rows padded 32 -> 34 float4 so the + // transposed re-reads (8 lanes = 4 rows x 2 cols per 16 B phase) hit 8 distinct bank groups (was 4-way conflict) + const bool ok = row < T; + // x half-row: 8 independent 128-bit loads per lane issued back to back (float4 lane + 32 (8 half + j)) + const float4* xr = reinterpret_cast(x + (size_t)(ok ? row : 0) * HID) + half * 256; + float4 v[8]; + if (ok) { +#pragma unroll + for (int j = 0; j < 8; j++) { + if (PVAR & 1) v[j] = ld_f4_pol(xr + lane + 32 * j, first_pol()); + else v[j] = xr[lane + 32 * j]; + } + } + float4 t4 = make_float4(0.f, 0.f, 0.f, 0.f); + if (ok) t4 = reinterpret_cast((half ? sn : cs) + (size_t)row * 128)[lane]; + if (early) { pdl_wait(); CHN(2, 1); pdl_trigger(); } + // RoPE tables re-laid out for the QKV epilogue (thread = row): [row/32][float4 group c4 (0..31)][row%32], + // so a warp's load of one float4 group for its 32 consecutive rows is 512 contiguous bytes (coalesced). + // warp half 0 handles cos, half 1 sin. + float tmx = 0.f; // max |cos| (half 0) / |sin| (half 1) of this lane's 4 table values + if (ok) { + tmx = fmaxf(fmaxf(fabsf(t4.x), fabsf(t4.y)), fmaxf(fabsf(t4.z), fabsf(t4.w))); + // sin first half (d < 64) stored NEGATED: the QKV epilogue's RoPE o1 = x1*c1 + x2*(-s1) is then one packed + // FFMA2 chain (no sign flips); second half (o2 = x2*c2 + x1*s2) stored as is + if (half && lane < 16) t4 = make_float4(-t4.x, -t4.y, -t4.z, -t4.w); + if (T >= QKV_F16TAB_MIN_T) { + // fp16 tables, pre-scaled by 2^-4 (the 2^4 is folded exactly into the QF epilogue's rstd): half the + // bytes / load instructions of fp32 tables. Layout [row/32][16 groups of 8 halves][32 rows] uint4; + // lane writes half of group lane/2. + // staged in smem (q table in.x/.y, k table in.z/.w), written below as coalesced 64 B runs + if (wtab) { + // q / k norm weights folded into the tables: A[j] = w[j] c[j], + // B[j] = w[j ^ 64] s'[j] (s' = sin with the first half negated), one table pair per q / k + // (k tables at + ceil(T/32) * 512 uint4 = second half of the fp32-sized buffers) + const int wl = half ? (lane ^ 16) : lane; + const float4 wq4 = __ldg(reinterpret_cast(qnw_) + wl); + const float4 wk4 = __ldg(reinterpret_cast(knw_) + wl); + tab_st[half][warp >> 1][lane] = make_float4( + __uint_as_float(pack_h2((t4.x * wq4.x) * 0.0625f, (t4.y * wq4.y) * 0.0625f)), + __uint_as_float(pack_h2((t4.z * wq4.z) * 0.0625f, (t4.w * wq4.w) * 0.0625f)), + __uint_as_float(pack_h2((t4.x * wk4.x) * 0.0625f, (t4.y * wk4.y) * 0.0625f)), + __uint_as_float(pack_h2((t4.z * wk4.z) * 0.0625f, (t4.w * wk4.w) * 0.0625f))); + } else + tab_st[half][warp >> 1][lane] = make_float4( + __uint_as_float(pack_h2(t4.x * 0.0625f, t4.y * 0.0625f)), + __uint_as_float(pack_h2(t4.z * 0.0625f, t4.w * 0.0625f)), 0.f, 0.f); + } else { + // staged in smem; written below as 64 B runs (4 consecutive rows x one float4 group) + tab_st[half][warp >> 1][lane] = t4; + } + } + // Fused zero-init (replaces 4 torch::zeros fill launches at the head of the stream), grid-stride over the + // row CTAs (issued while the x loads are in flight): zbuf[0, nz): expert histogram, attention work counter, + // MoE queue / ready counters; V^T padding keys s in [S, Spad) of every (b, kv head, d) row (P is 0 there) + { + const long gi = (long)rb * 256 + tid, gs = (long)nrb * 256; + for (long i = gi; i < nz; i += gs) zbuf[i] = 0; + const int padw = Spad - S; + if (padw > 0) { + // division-free walk (row r, column c) of the flat index i = r * padw + c, i += gs (the former + // 64-bit i / padw per element called the 64-bit division subroutine -> 16 B stack frame) + const int R = (T / S) * 512; + const int gs32 = (int)gs, gi32 = (int)gi; // < 2^31: (T/4 + nconv) CTAs x 256 threads + const int gsr = gs32 / padw, gsc = gs32 - gsr * padw; + int r = gi32 / padw, c = gi32 - r * padw; + while (r < R) { + vt[(size_t)r * Spad + S + c] = __float2half_rn(0.f); + r += gsr; c += gsc; + if (c >= padw) { c -= padw; r++; } + } + } + } + if (T >= QKV_F16TAB_MIN_T) { + // coalesced fp16 RoPE table stores (was: per-lane 8 B stores, 16 partial sectors per warp store): + // fp16 layout [row/32][16 groups][32 rows] uint4 (8 halves); this CTA's 4 rows of one group form a + // 64 B run. Thread t of half h: u = t & 1 (uint2 half of the group), rl = (t >> 1) & 3, g = t >> 3 -> + // a warp store covers 4 x 64 B contiguous runs. Value = lane (2g + u) of row rl. Identical bytes. + __syncthreads(); + const int t = (warp >> 1) * 32 + lane, u = t & 1, rl = (t >> 1) & 3, g = t >> 3; + const int r = rb * 4 + rl; + if (r < T) { + const size_t di = (((size_t)(r >> 5) * 16 + g) * 32 + (r & 31)) * 2 + u; + const float4 sv = tab_st[half][rl][2 * g + u]; + uint2* tb = reinterpret_cast(half ? snT : csT); + tb[di] = make_uint2(__float_as_uint(sv.x), __float_as_uint(sv.y)); + if (wtab) tb[di + (size_t)((T + 31) >> 5) * 1024] = make_uint2(__float_as_uint(sv.z), __float_as_uint(sv.w)); + } + } else { + // coalesced fp32 RoPE table stores: this CTA's 4 rows (4-aligned, same 32-row group) are contiguous + // in the [row/32][group][row%32] layout -> thread (rl = t & 3, group c4 = t >> 2) of half h writes row + // r0 + rl, group c4: a warp store covers 8 x 64 B contiguous runs (was 32 x 16 B). Identical bytes. + __syncthreads(); + const int t = (warp >> 1) * 32 + lane, rl = t & 3, c4 = t >> 2; + const int r = rb * 4 + rl; + if (r < T) { + const size_t di = ((size_t)(r >> 5) * 32 + c4) * 32 + (r & 31); + reinterpret_cast(half ? snT : csT)[di] = tab_st[half][rl][c4]; + } + } + float ss = 0.f; + if (ok) { +#pragma unroll + for (int j = 0; j < 8; j++) ss += v[j].x * v[j].x + v[j].y * v[j].y + v[j].z * v[j].z + v[j].w * v[j].w; + } +#pragma unroll + for (int o = 16; o; o >>= 1) ss += __shfl_xor_sync(0xffffffff, ss, o); + if (lane == 0) red[warp] = ss; + __shared__ unsigned tred[8]; + if (pairred) { + asm volatile("bar.sync %0, 64;" ::"r"(1 + (warp >> 1)) : "memory"); // both warps of the row pair + } else { + { + const unsigned tm = __reduce_max_sync(0xffffffffu, __float_as_uint(tmx)); + if (lane == 0) tred[warp] = tm; + } + __syncthreads(); + if (tid < 2) { // CTA max of cos (tid 0) / sin (tid 1): one conditional global atomicMax per CTA + const unsigned m = max(max(tred[tid], tred[tid + 2]), max(tred[tid + 4], tred[tid + 6])); + atomicMax(qkb + tid, m); // fire-and-forget RED (no blocking volatile pre-read on the rows path) + } + if (rb == 0 && warp >= 6) { // q / k norm weight maxima (warp 6: q, warp 7: k) + const float4 w4 = reinterpret_cast(warp == 6 ? qnw_ : knw_)[lane]; + const float m = fmaxf(fmaxf(fabsf(w4.x), fabsf(w4.y)), fmaxf(fabsf(w4.z), fabsf(w4.w))); + const unsigned mm = __reduce_max_sync(0xffffffffu, __float_as_uint(m)); + if (lane == 0) atomicMax(qkb + 2 + (warp - 6), mm); + } + } + if (!ok) { return; } // warp-uniform + ss = red[warp & ~1] + red[warp | 1]; + if (lane == 0 && half == 0) ssq[row] = 0.f; // post-attention sum-of-squares accumulator (o_proj epilogue) + const float r = rsqrtf(ss / (float)HID + eps); + const float4* wr = reinterpret_cast(w) + half * 256; + uint2* orow = reinterpret_cast(xn + (size_t)row * HID) + half * 256; + const uint64_t kp = keep_pol(); // xn: consumed by the QKV GEMM's TMA loads + if (xinv != nullptr) { + // FP8 QKV: normalized row (same expression as the fp16 path), row max over both half-warps (named + // barrier per row pair; both warps of a pair share ok), exact pow2 scale, e4m3 bytes (4 per float4) + __shared__ unsigned xmx[8]; + float o[8][4]; + float mx = 0.f; +#pragma unroll + for (int j = 0; j < 8; j++) { + const float4 w4 = __ldg(wr + lane + 32 * j); + o[j][0] = w4.x * (v[j].x * r); o[j][1] = w4.y * (v[j].y * r); + o[j][2] = w4.z * (v[j].z * r); o[j][3] = w4.w * (v[j].w * r); + mx = fmaxf(mx, fmaxf(fmaxf(fabsf(o[j][0]), fabsf(o[j][1])), fmaxf(fabsf(o[j][2]), fabsf(o[j][3])))); + } + const unsigned wm = __reduce_max_sync(0xffffffffu, __float_as_uint(mx)); + if (lane == 0) xmx[warp] = wm; + asm volatile("bar.sync %0, 64;" ::"r"(1 + (warp >> 1)) : "memory"); + const float rmx = __uint_as_float(max(xmx[warp & ~1], xmx[warp | 1])); + const float sc = sidew::scale_top(rmx, 8); + if (lane == 0 && half == 0) xinv[row] = 1.f / sc; + uint32_t* orow8 = reinterpret_cast(reinterpret_cast(xn) + (size_t)row * HID) + half * 256; + if (PVAR & 2) { + // word of float4 lane + 32 j; per 4-j block: 4x4 transpose in the 4-lane group, then lane g stores + // words of lanes 4q..4q+3 for j = jb + g at uint32 offset 4q + 32 (jb + g) (16 B aligned) +#pragma unroll + for (int jb = 0; jb < 8; jb += 4) { + uint32_t W[4]; +#pragma unroll + for (int i = 0; i < 4; i++) + W[i] = cvt_e4m3x4(o[jb + i][0] * sc, o[jb + i][1] * sc, o[jb + i][2] * sc, o[jb + i][3] * sc); +#pragma unroll + for (int m = 1; m <= 2; m <<= 1) { + const bool bit = (lane & m) != 0; +#pragma unroll + for (int c0 = 0; c0 < 4; c0++) { + if (c0 & m) continue; + const int c1 = c0 | m; + const uint32_t rcv = __shfl_xor_sync(0xffffffffu, bit ? W[c0] : W[c1], m); + if (bit) W[c0] = rcv; else W[c1] = rcv; + } + } + const int g = lane & 3; + prep_st16(orow8 + (lane & ~3) + 32 * (jb + g), make_uint4(W[0], W[1], W[2], W[3]), false, 0); + } + } else { +#pragma unroll + for (int j = 0; j < 8; j++) + orow8[lane + 32 * j] = cvt_e4m3x4(o[j][0] * sc, o[j][1] * sc, o[j][2] * sc, o[j][3] * sc); + } + if (xn16s != nullptr) { // VS: fp16 copy (same values as the fp16 path) + uint2* orow16 = reinterpret_cast(xn16s + (size_t)row * HID) + half * 256; +#pragma unroll + for (int j = 0; j < 8; j++) + st_u2_pol(orow16 + lane + 32 * j, make_uint2(pack_h2(o[j][0], o[j][1]), pack_h2(o[j][2], o[j][3])), kp); + } + return; + } + if (x3) { + // 3 segments of HID halves per row (row stride QKV_X3_K); same normalized values as the 1-term path + uint2* orow3 = reinterpret_cast(xn + (size_t)row * QKV_X3_K) + half * 256; +#pragma unroll + for (int j = 0; j < 8; j++) { + const float4 w4 = __ldg(wr + lane + 32 * j); + uint2 hi, hs, ls; + split3_h4(make_float4(w4.x * (v[j].x * r), w4.y * (v[j].y * r), w4.z * (v[j].z * r), w4.w * (v[j].w * r)), + 1.f / 256.f, 16.f, hi, hs, ls); + st_u2_pol(orow3 + lane + 32 * j, hi, kp); + st_u2_pol(orow3 + 512 + lane + 32 * j, hs, kp); + st_u2_pol(orow3 + 1024 + lane + 32 * j, ls, kp); + } + return; + } + if (PVAR & 2) { + // lane pair (e, e+1): even lane stores float4s e, e+1 of segment 2m, odd lane those of segment 2m+1 + const bool odd = lane & 1; +#pragma unroll + for (int m = 0; m < 4; m++) { + uint2 hh[2]; +#pragma unroll + for (int t = 0; t < 2; t++) { + const int j = 2 * m + t; + const float4 w4 = __ldg(wr + lane + 32 * j); + hh[t] = make_uint2(pack_h2(w4.x * (v[j].x * r), w4.y * (v[j].y * r)), + pack_h2(w4.z * (v[j].z * r), w4.w * (v[j].w * r))); + } + const uint2 snd = odd ? hh[0] : hh[1]; + uint2 rcv; + rcv.x = __shfl_xor_sync(0xffffffffu, snd.x, 1); + rcv.y = __shfl_xor_sync(0xffffffffu, snd.y, 1); + const uint4 u = odd ? make_uint4(rcv.x, rcv.y, hh[1].x, hh[1].y) : make_uint4(hh[0].x, hh[0].y, rcv.x, rcv.y); + prep_st16(orow + (lane & ~1) + 32 * (2 * m + (odd ? 1 : 0)), u, true, kp); + } + return; + } +#pragma unroll + for (int j = 0; j < 8; j++) { + const float4 w4 = __ldg(wr + lane + 32 * j); // L1/L2-resident, shared by all rows + st_u2_pol(orow + lane + 32 * j, + make_uint2(pack_h2(w4.x * (v[j].x * r), w4.y * (v[j].y * r)), + pack_h2(w4.z * (v[j].z * r), w4.w * (v[j].w * r))), + kp); + } + + return; + } + constexpr size_t NQ4 = (size_t)4096 * HID / 4, NK4 = (size_t)512 * HID / 4; + static_assert(NQ4 % PREP_CONV4 == 0 && NK4 % PREP_CONV4 == 0, "conversion blocks must not straddle sources"); + const size_t g = (size_t)blockIdx.x * PREP_CONV4; // global float4 index in the concatenated destination + const float4* src; + size_t lb; + if (g < NQ4) { src = reinterpret_cast(wq); lb = g; } + else if (g < NQ4 + NK4) { src = reinterpret_cast(wk); lb = g - NQ4; } + else { src = reinterpret_cast(wv); lb = g - NQ4 - NK4; } + const uint64_t rf = first_pol(), kp = keep_pol(); // fp32 Wqkv read once; fp16 copy consumed by the QKV GEMM + float4 v[PREP_CONV4 / 256]; +#pragma unroll + for (int hh = 0; hh < PREP_CONV4 / 512; hh++) { + // 256-bit loads (ld.global.nc.L1::no_allocate.v8.f32, EVICT_FIRST): thread owns float4 slots + // 512 hh + 2 tid + {0, 1} (slot pair u = 2 hh, 2 hh + 1 -> still row hh of the 4-row block); every output is + // written at the index of its input element (pidx), so the converted bytes / row scales are identical + const float* ap = reinterpret_cast(src + lb + 512 * hh + 2 * tid); + asm volatile("ld.global.nc.L1::no_allocate.L2::cache_hint.v8.f32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8], %9;" + : "=f"(v[2 * hh].x), "=f"(v[2 * hh].y), "=f"(v[2 * hh].z), "=f"(v[2 * hh].w), + "=f"(v[2 * hh + 1].x), "=f"(v[2 * hh + 1].y), "=f"(v[2 * hh + 1].z), "=f"(v[2 * hh + 1].w) + : "l"(ap), "l"(rf)); + } + auto pidx = [&](int u) -> int { return 512 * (u >> 1) + 2 * tid + (u & 1); }; + // weight-conversion blocks never wait on the PDL predecessor. Their inputs (fp32 Wq|Wk|Wv) are kernel + // inputs and their outputs (converted Wqkv + winvq) live in a PERSISTENT buffer (main.cpp) that no kernel of the + // previous call still touches once this grid can launch (its only reader, the previous QKV GEMM, and the o_proj L2 + // discard completed before the previous router / MoE passed their PDL waits). So the conversion (loads AND stores) + // runs concurrently with the previous call's MoE tail; the QKV GEMM's griddepcontrol.wait covers prep completion. + if (early) pdl_trigger(); + if (winvq != nullptr && !(xn16s != nullptr && g >= NQ4 + NK4)) { + // FP8 QKV: block = 4 Wqkv rows of 512 float4 (row r <- float4 slots u = 2r, 2r+1 of every thread); per-row + // max -> exact pow2 scale (max * s < 2^8), e4m3 bytes into the [5120][2048] byte destination, winvq = 1 / s + __shared__ float cmx[4][8]; + float mr[4]; +#pragma unroll + for (int r = 0; r < 4; r++) { + const float4 a = v[2 * r], b = v[2 * r + 1]; + mr[r] = fmaxf(fmaxf(fmaxf(fabsf(a.x), fabsf(a.y)), fmaxf(fabsf(a.z), fabsf(a.w))), + fmaxf(fmaxf(fabsf(b.x), fabsf(b.y)), fmaxf(fabsf(b.z), fabsf(b.w)))); +#pragma unroll + for (int o = 16; o; o >>= 1) mr[r] = fmaxf(mr[r], __shfl_xor_sync(0xffffffff, mr[r], o)); + if ((tid & 31) == 0) cmx[r][tid >> 5] = mr[r]; + } + __syncthreads(); + float scr[4]; +#pragma unroll + for (int r = 0; r < 4; r++) { + float mx = 0.f; +#pragma unroll + for (int w8 = 0; w8 < 8; w8++) mx = fmaxf(mx, cmx[r][w8]); + scr[r] = sidew::scale_top(mx, 8); + } + uint32_t* d8 = reinterpret_cast(wqkv16) + g; +#pragma unroll + for (int u = 0; u < PREP_CONV4 / 256; u++) { + const float s_ = scr[u >> 1]; + d8[pidx(u)] = cvt_e4m3x4(v[u].x * s_, v[u].y * s_, v[u].z * s_, v[u].w * s_); + } + if (tid < 4) winvq[g / 512 + tid] = 1.f / scr[tid]; + return; + } + if (x3) { + // float4 f = row f / 512, column group f % 512 -> segments at uint2 offsets 0 / 512 / 1024 of the + // 1536-uint2 (QKV_X3_K halves) destination row: Wh, (W - Wh) 2^8, Wh 2^-4 (W = 2^4 Wqkv) + uint2* d3 = reinterpret_cast(wqkv16); +#pragma unroll + for (int u = 0; u < PREP_CONV4 / 256; u++) { + const size_t f = g + (size_t)pidx(u), o = (f >> 9) * (QKV_X3_K / 4) + (f & 511); + uint2 hi, hs, ls; + split3_h4(make_float4(v[u].x * 16.f, v[u].y * 16.f, v[u].z * 16.f, v[u].w * 16.f), 1.f / 16.f, 256.f, hi, hs, ls); + st_u2_pol(d3 + o, hi, kp); + st_u2_pol(d3 + o + 512, ls, kp); + st_u2_pol(d3 + o + 1024, hs, kp); + } + return; + } + // VS: V rows (g >= NQ4 + NK4) fp16 into the buffer after the e4m3 bytes + uint2* dst = (winvq != nullptr) ? reinterpret_cast(reinterpret_cast(wqkv16) + (size_t)NQKV * HID) + (g - NQ4 - NK4) + : reinterpret_cast(wqkv16) + g; +#pragma unroll + for (int u = 0; u < PREP_CONV4 / 256; u++) + st_u2_pol(dst + pidx(u), + make_uint2(pack_h2(v[u].x * 16.f, v[u].y * 16.f), pack_h2(v[u].z * 16.f, v[u].w * 16.f)), kp); +} + +// ------------------------------------------------------------------ tcgen05 / TMA / mbarrier PTX wrappers +__device__ __forceinline__ void mbar_init(uint32_t a, uint32_t cnt) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(a), "r"(cnt)); +} +__device__ __forceinline__ void mbar_expect_tx(uint32_t a, uint32_t bytes) { + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(a), "r"(bytes) : "memory"); +} +__device__ __forceinline__ void mbar_arrive(uint32_t a) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(a) : "memory"); +} +__device__ __forceinline__ void mbar_wait(uint32_t a, uint32_t parity) { + uint32_t ok = 0; + while (!ok) { + asm volatile( + "{ .reg .pred p; mbarrier.try_wait.parity.shared::cta.b64 p, [%1], %2; selp.u32 %0, 1, 0, p; }" + : "=r"(ok) + : "r"(a), "r"(parity) + : "memory"); + } +} +// mbarrier wait with try_wait's suspend-time hint (thread sleeps in hardware until the phase completes) +__device__ __forceinline__ void mbar_wait_hint(uint32_t a, uint32_t parity) { + uint32_t ok = 0; + while (!ok) { + asm volatile( + "{ .reg .pred p; mbarrier.try_wait.parity.shared::cta.b64 p, [%1], %2, %3; selp.u32 %0, 1, 0, p; }" + : "=r"(ok) + : "r"(a), "r"(parity), "r"(10000000u) + : "memory"); + } +} +// non-blocking: true iff the phase with the given parity has completed +__device__ __forceinline__ bool mbar_test(uint32_t a, uint32_t parity) { + uint32_t ok; + asm volatile( + "{ .reg .pred p; mbarrier.test_wait.parity.shared::cta.b64 p, [%1], %2; selp.u32 %0, 1, 0, p; }" + : "=r"(ok) + : "r"(a), "r"(parity) + : "memory"); + return ok != 0; +} +__device__ __forceinline__ void tma_load_2d(uint32_t dst, const CUtensorMap* map, int x, int y, uint32_t bar) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1, {%2, %3}], [%4];" ::"r"( + dst), + "l"((uint64_t)map), "r"(x), "r"(y), "r"(bar) + : "memory"); +} +// TMA 2D load with an L2 cache-policy hint (policy from createpolicy, e.g. evict_first for read-once streams) +__device__ __forceinline__ void tma_load_2d_hint(uint32_t dst, const CUtensorMap* map, int x, int y, uint32_t bar, + uint64_t pol) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3}], [%4], %5;" ::"r"( + dst), + "l"((uint64_t)map), "r"(x), "r"(y), "r"(bar), "l"(pol) + : "memory"); +} +__device__ __forceinline__ uint64_t l2_policy_evict_first() { + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + return pol; +} +// Vector fire-and-forget fp32 reduction into global memory (sm_90+): 16 B per lane, no return value. +__device__ __forceinline__ void red_add_v4(float* addr, float4 v) { + asm volatile("red.global.add.v4.f32 [%0], {%1, %2, %3, %4};" ::"l"(addr), "f"(v.x), "f"(v.y), "f"(v.z), + "f"(v.w) + : "memory"); +} +// Vector fp32 reduction with an L2 cache-policy hint (e.g. evict_last for the re-hit out rows) +__device__ __forceinline__ void red_add_v4_hint(float* addr, float4 v, uint64_t pol) { + asm volatile("red.global.add.L2::cache_hint.v4.f32 [%0], {%1, %2, %3, %4}, %5;" ::"l"(addr), "f"(v.x), "f"(v.y), + "f"(v.z), "f"(v.w), "l"(pol) + : "memory"); +} +// 16 B global stores with an L2 cache-policy hint +__device__ __forceinline__ void st_v4_hint(float4* addr, float4 v, uint64_t pol) { + asm volatile("st.global.L2::cache_hint.v4.f32 [%0], {%1, %2, %3, %4}, %5;" ::"l"(addr), "f"(v.x), "f"(v.y), "f"(v.z), + "f"(v.w), "l"(pol) + : "memory"); +} +__device__ __forceinline__ void st_u4_hint(uint4* addr, uint4 v, uint64_t pol) { + asm volatile("st.global.L2::cache_hint.v4.b32 [%0], {%1, %2, %3, %4}, %5;" ::"l"(addr), "r"(v.x), "r"(v.y), "r"(v.z), + "r"(v.w), "l"(pol) + : "memory"); +} +__device__ __forceinline__ uint64_t l2_policy_evict_last() { + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol)); + return pol; +} +// elect.sync: true in exactly one (the lowest) active lane of the full warp +__device__ __forceinline__ bool elect_one() { + uint32_t pred; + asm volatile("{ .reg .pred P; elect.sync _|P, 0xffffffff; selp.u32 %0, 1, 0, P; }" : "=r"(pred)); + return pred != 0; +} +__device__ __forceinline__ void tc_fence_before() { asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void tc_fence_after() { asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); } +// K-major operand, 128B swizzle, 8-row core-matrix groups 1024 B apart (SBO), sm100 descriptor version 1. +__device__ __forceinline__ uint64_t make_sdesc(uint32_t addr) { + uint64_t d = 0; + d |= (uint64_t)((addr & 0x3FFFF) >> 4); + d |= (uint64_t)1 << 16; // LBO (ignored for swizzled K-major) + d |= (uint64_t)(1024 >> 4) << 32; // SBO = 1024 B + d |= (uint64_t)1 << 46; // version + d |= (uint64_t)2 << 61; // SWIZZLE_128B + return d; +} + +__device__ __forceinline__ void mma_tf32(uint32_t tmem, uint64_t ad, uint64_t bd, uint32_t idesc, uint32_t acc) { + asm volatile( + "{ .reg .pred p; setp.ne.b32 p, %4, 0; tcgen05.mma.cta_group::1.kind::tf32 [%0], %1, %2, %3, p; }" ::"r"( + tmem), + "l"(ad), "l"(bd), "r"(idesc), "r"(acc)); +} +__device__ __forceinline__ void mma_f16_ss(uint32_t tmem, uint64_t ad, uint64_t bd, uint32_t idesc, uint32_t acc) { + asm volatile( + "{ .reg .pred p; setp.ne.b32 p, %4, 0; tcgen05.mma.cta_group::1.kind::f16 [%0], %1, %2, %3, p; }" ::"r"( + tmem), + "l"(ad), "l"(bd), "r"(idesc), "r"(acc)); +} +// TS variant: A operand read from TMEM (lane = row, each 32-bit column = 2 consecutive fp16 K elements), B from smem. +__device__ __forceinline__ void mma_f16_ts(uint32_t tmem, uint32_t a_tmem, uint64_t bd, uint32_t idesc, uint32_t acc) { + asm volatile( + "{ .reg .pred p; setp.ne.b32 p, %4, 0; tcgen05.mma.cta_group::1.kind::f16 [%0], [%1], %2, %3, p; }" ::"r"( + tmem), + "r"(a_tmem), "l"(bd), "r"(idesc), "r"(acc)); +} +// TS kind::f8f6f4 MMA (A = 8-bit from TMEM, 4 K elements per 32-bit column; B = 8-bit smem descriptor), K = 32 +__device__ __forceinline__ void mma_f8_ts(uint32_t tmem, uint32_t a_tmem, uint64_t bd, uint32_t idesc, uint32_t acc) { + asm volatile( + "{ .reg .pred p; setp.ne.b32 p, %4, 0; tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], [%1], %2, %3, p; }" ::"r"( + tmem), + "r"(a_tmem), "l"(bd), "r"(idesc), "r"(acc)); +} +// K-major operand, 64B swizzle (64 B rows, 8-row groups 512 B apart), sm100 descriptor version 1 +__device__ __forceinline__ uint64_t make_sdesc64(uint32_t addr) { + uint64_t d = 0; + d |= (uint64_t)((addr & 0x3FFFF) >> 4); + d |= (uint64_t)1 << 16; + d |= (uint64_t)(512 >> 4) << 32; + d |= (uint64_t)1 << 46; + d |= (uint64_t)4 << 61; // SWIZZLE_64B + return d; +} +__device__ __forceinline__ void mma_commit(uint32_t bar) { + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(bar) : "memory"); +} +__device__ __forceinline__ void tmem_ld32(uint32_t taddr, float* v) { + uint32_t r[32]; + asm volatile( + "tcgen05.ld.sync.aligned.32x32b.x32.b32 {%0,%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11,%12,%13,%14,%15,%16,%17,%18,%19,%" + "20,%21,%22,%23,%24,%25,%26,%27,%28,%29,%30,%31}, [%32];" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]), "=r"(r[4]), "=r"(r[5]), "=r"(r[6]), "=r"(r[7]), "=r"(r[8]), + "=r"(r[9]), "=r"(r[10]), "=r"(r[11]), "=r"(r[12]), "=r"(r[13]), "=r"(r[14]), "=r"(r[15]), "=r"(r[16]), + "=r"(r[17]), "=r"(r[18]), "=r"(r[19]), "=r"(r[20]), "=r"(r[21]), "=r"(r[22]), "=r"(r[23]), "=r"(r[24]), + "=r"(r[25]), "=r"(r[26]), "=r"(r[27]), "=r"(r[28]), "=r"(r[29]), "=r"(r[30]), "=r"(r[31]) + : "r"(taddr)); + asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); +#pragma unroll + for (int i = 0; i < 32; i++) v[i] = __uint_as_float(r[i]); +} + +// 32-column TMEM store (32 lanes x 32 bit x 32), no wait (caller issues tcgen05.wait::st) +__device__ __forceinline__ void tmem_st32_e(uint32_t taddr, const float* v) { + asm volatile( + "tcgen05.st.sync.aligned.32x32b.x32.b32 [%0], {%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11,%12,%13,%14,%15,%16,%17,%18," + "%19,%20,%21,%22,%23,%24,%25,%26,%27,%28,%29,%30,%31,%32};" ::"r"(taddr), + "f"(v[0]), "f"(v[1]), "f"(v[2]), "f"(v[3]), "f"(v[4]), "f"(v[5]), "f"(v[6]), "f"(v[7]), "f"(v[8]), "f"(v[9]), + "f"(v[10]), "f"(v[11]), "f"(v[12]), "f"(v[13]), "f"(v[14]), "f"(v[15]), "f"(v[16]), "f"(v[17]), "f"(v[18]), + "f"(v[19]), "f"(v[20]), "f"(v[21]), "f"(v[22]), "f"(v[23]), "f"(v[24]), "f"(v[25]), "f"(v[26]), "f"(v[27]), + "f"(v[28]), "f"(v[29]), "f"(v[30]), "f"(v[31]) : "memory"); +} +// two 32-column TMEM loads in flight, one wait +__device__ __forceinline__ void tmem_ld32x2(uint32_t ta, float* va, uint32_t tb, float* vb) { + uint32_t r[32], u[32]; + asm volatile( + "tcgen05.ld.sync.aligned.32x32b.x32.b32 {%0,%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11,%12,%13,%14,%15,%16,%17,%18,%19,%" + "20,%21,%22,%23,%24,%25,%26,%27,%28,%29,%30,%31}, [%32];" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]), "=r"(r[4]), "=r"(r[5]), "=r"(r[6]), "=r"(r[7]), "=r"(r[8]), + "=r"(r[9]), "=r"(r[10]), "=r"(r[11]), "=r"(r[12]), "=r"(r[13]), "=r"(r[14]), "=r"(r[15]), "=r"(r[16]), + "=r"(r[17]), "=r"(r[18]), "=r"(r[19]), "=r"(r[20]), "=r"(r[21]), "=r"(r[22]), "=r"(r[23]), "=r"(r[24]), + "=r"(r[25]), "=r"(r[26]), "=r"(r[27]), "=r"(r[28]), "=r"(r[29]), "=r"(r[30]), "=r"(r[31]) + : "r"(ta)); + asm volatile( + "tcgen05.ld.sync.aligned.32x32b.x32.b32 {%0,%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11,%12,%13,%14,%15,%16,%17,%18,%19,%" + "20,%21,%22,%23,%24,%25,%26,%27,%28,%29,%30,%31}, [%32];" + : "=r"(u[0]), "=r"(u[1]), "=r"(u[2]), "=r"(u[3]), "=r"(u[4]), "=r"(u[5]), "=r"(u[6]), "=r"(u[7]), "=r"(u[8]), + "=r"(u[9]), "=r"(u[10]), "=r"(u[11]), "=r"(u[12]), "=r"(u[13]), "=r"(u[14]), "=r"(u[15]), "=r"(u[16]), + "=r"(u[17]), "=r"(u[18]), "=r"(u[19]), "=r"(u[20]), "=r"(u[21]), "=r"(u[22]), "=r"(u[23]), "=r"(u[24]), + "=r"(u[25]), "=r"(u[26]), "=r"(u[27]), "=r"(u[28]), "=r"(u[29]), "=r"(u[30]), "=r"(u[31]) + : "r"(tb)); + asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); +#pragma unroll + for (int i = 0; i < 32; i++) { va[i] = __uint_as_float(r[i]); vb[i] = __uint_as_float(u[i]); } +} + +// gate/up accumulator pair load. tcgen05.ld.16x32bx2.x16 with immHalfSplitoff 16: +// thread t < 16 reads TMEM lane (base + t) columns [col, col + 16), thread t >= 16 lane (base + t - 16) columns +// [col + 16, col + 32). Issued for the gate lanes (lane base +0) and the up lanes (+16) of two column chunks, one +// wait::ld. va[0..15] = gate, va[16..31] = up of chunk ta; vb likewise for chunk tb. +__device__ __forceinline__ void tmem_ld16x2_gu(uint32_t ta, float* va, uint32_t tb, float* vb) { + uint32_t r[4][16]; + const uint32_t ad[4] = {ta, ta + (16u << 16), tb, tb + (16u << 16)}; +#pragma unroll + for (int k = 0; k < 4; k++) + asm volatile("tcgen05.ld.sync.aligned.16x32bx2.x16.b32 {%0,%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11,%12,%13,%14,%15}, [%16], 16;" + : "=r"(r[k][0]), "=r"(r[k][1]), "=r"(r[k][2]), "=r"(r[k][3]), "=r"(r[k][4]), "=r"(r[k][5]), + "=r"(r[k][6]), "=r"(r[k][7]), "=r"(r[k][8]), "=r"(r[k][9]), "=r"(r[k][10]), "=r"(r[k][11]), + "=r"(r[k][12]), "=r"(r[k][13]), "=r"(r[k][14]), "=r"(r[k][15]) + : "r"(ad[k])); + asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); +#pragma unroll + for (int i = 0; i < 16; i++) { + va[i] = __uint_as_float(r[0][i]); va[16 + i] = __uint_as_float(r[1][i]); + vb[i] = __uint_as_float(r[2][i]); vb[16 + i] = __uint_as_float(r[3][i]); + } +} +// two 8-column TMEM loads (32 lanes x 32 bit x 8) in flight, one wait +__device__ __forceinline__ void tmem_ld8x2(uint32_t ta, float* va, uint32_t tb, float* vb) { + uint32_t r[8], u[8]; + asm volatile("tcgen05.ld.sync.aligned.32x32b.x8.b32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]), "=r"(r[4]), "=r"(r[5]), "=r"(r[6]), "=r"(r[7]) + : "r"(ta)); + asm volatile("tcgen05.ld.sync.aligned.32x32b.x8.b32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];" + : "=r"(u[0]), "=r"(u[1]), "=r"(u[2]), "=r"(u[3]), "=r"(u[4]), "=r"(u[5]), "=r"(u[6]), "=r"(u[7]) + : "r"(tb)); + asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); +#pragma unroll + for (int i = 0; i < 8; i++) { va[i] = __uint_as_float(r[i]); vb[i] = __uint_as_float(u[i]); } +} + +__device__ __forceinline__ void tmem_ld8x4(uint32_t ta, float* va, uint32_t tb, float* vb, uint32_t tc, float* vc, + uint32_t td, float* vd) { + uint32_t r[8], u[8], x[8], y[8]; + asm volatile("tcgen05.ld.sync.aligned.32x32b.x8.b32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]), "=r"(r[4]), "=r"(r[5]), "=r"(r[6]), "=r"(r[7]) : "r"(ta)); + asm volatile("tcgen05.ld.sync.aligned.32x32b.x8.b32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];" + : "=r"(u[0]), "=r"(u[1]), "=r"(u[2]), "=r"(u[3]), "=r"(u[4]), "=r"(u[5]), "=r"(u[6]), "=r"(u[7]) : "r"(tb)); + asm volatile("tcgen05.ld.sync.aligned.32x32b.x8.b32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];" + : "=r"(x[0]), "=r"(x[1]), "=r"(x[2]), "=r"(x[3]), "=r"(x[4]), "=r"(x[5]), "=r"(x[6]), "=r"(x[7]) : "r"(tc)); + asm volatile("tcgen05.ld.sync.aligned.32x32b.x8.b32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];" + : "=r"(y[0]), "=r"(y[1]), "=r"(y[2]), "=r"(y[3]), "=r"(y[4]), "=r"(y[5]), "=r"(y[6]), "=r"(y[7]) : "r"(td)); + asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); +#pragma unroll + for (int i = 0; i < 8; i++) { + va[i] = __uint_as_float(r[i]); vb[i] = __uint_as_float(u[i]); vc[i] = __uint_as_float(x[i]); vd[i] = __uint_as_float(y[i]); + } +} +// 8x8 fp16 transpose inside each 8-lane group (3 xor-shuffle rounds, 2 words per round). Input: this lane's +// 8 values av[0..7] (d = 8k .. 8k+7 of token row lane), scaled x 2^-10 and rounded to fp16. Output: lane t (= lane & 7) +// gets d = 8k + t of the group's 8 tokens (16 B, token order) for one st.v4 into the V^T row. +__device__ __forceinline__ uint4 vt8_transpose(const float* av, int lane) { + const bool bA = lane & 4, bB = lane & 2, bC = lane & 1; + // x 2^-10 as packed FMUL2 + one cvt.rn.f16x2 per pair (bit-identical to the scalar products + pack_h2) + const float2 sc10 = make_float2(0.0009765625f, 0.0009765625f); + const float2 q2_0 = fmul2(make_float2(av[0], av[1]), sc10), q2_1 = fmul2(make_float2(av[2], av[3]), sc10); + const float2 q2_2 = fmul2(make_float2(av[4], av[5]), sc10), q2_3 = fmul2(make_float2(av[6], av[7]), sc10); + const uint32_t w0 = cvt_h2(__float_as_uint(q2_0.x), __float_as_uint(q2_0.y)); + const uint32_t w1 = cvt_h2(__float_as_uint(q2_1.x), __float_as_uint(q2_1.y)); + const uint32_t w2 = cvt_h2(__float_as_uint(q2_2.x), __float_as_uint(q2_2.y)); + const uint32_t w3 = cvt_h2(__float_as_uint(q2_3.x), __float_as_uint(q2_3.y)); + // round A (xor 4): keep the 4-d block (lane & 4), rows s & ~4 / s | 4 + const uint32_t r0 = __shfl_xor_sync(0xffffffffu, bA ? w0 : w2, 4); + const uint32_t r1 = __shfl_xor_sync(0xffffffffu, bA ? w1 : w3, 4); + const uint32_t X0 = bA ? r0 : w0, X1 = bA ? r1 : w1, X2 = bA ? w2 : r0, X3 = bA ? w3 : r1; + // round B (xor 2): keep d pair (lane & 6); Y[j] = row (lane & 1) + 2 j + const uint32_t q0 = __shfl_xor_sync(0xffffffffu, bB ? X0 : X1, 2); + const uint32_t q1 = __shfl_xor_sync(0xffffffffu, bB ? X2 : X3, 2); + const uint32_t Y0 = bB ? q0 : X0, Y1 = bB ? X1 : q0, Y2 = bB ? q1 : X2, Y3 = bB ? X3 : q1; + // round C (xor 1): keep d = t (low half if even lane), exchange the other halves + const uint32_t z0 = __shfl_xor_sync(0xffffffffu, bC ? __byte_perm(Y0, Y1, 0x5410) : __byte_perm(Y0, Y1, 0x7632), 1); + const uint32_t z1 = __shfl_xor_sync(0xffffffffu, bC ? __byte_perm(Y2, Y3, 0x5410) : __byte_perm(Y2, Y3, 0x7632), 1); + uint4 o; + if (bC) { + o.x = __byte_perm(z0, Y0, 0x7610); o.y = __byte_perm(z0, Y1, 0x7632); + o.z = __byte_perm(z1, Y2, 0x7610); o.w = __byte_perm(z1, Y3, 0x7632); + } else { + o.x = __byte_perm(Y0, z0, 0x5410); o.y = __byte_perm(Y1, z0, 0x7610); + o.z = __byte_perm(Y2, z1, 0x5410); o.w = __byte_perm(Y3, z1, 0x7610); + } + return o; +} +// 8-column TMEM store (no wait): 8-register source blocks instead of one 32-register block +__device__ __forceinline__ void tmem_st8_e(uint32_t ta, const float* v) { + asm volatile("tcgen05.st.sync.aligned.32x32b.x8.b32 [%0], {%1,%2,%3,%4,%5,%6,%7,%8};" ::"r"(ta), "f"(v[0]), "f"(v[1]), + "f"(v[2]), "f"(v[3]), "f"(v[4]), "f"(v[5]), "f"(v[6]), "f"(v[7]) : "memory"); +} +// 256-bit read-only global load of 8 consecutive floats (32 B aligned address) into two float4 +__device__ __forceinline__ void ldg_v8f(const float* p, float4& a, float4& b) { + asm volatile("ld.global.nc.v8.f32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];" + : "=f"(a.x), "=f"(a.y), "=f"(a.z), "=f"(a.w), "=f"(b.x), "=f"(b.y), "=f"(b.z), "=f"(b.w) + : "l"(p)); +} +// 4-column TMEM load without wait (destination = one aligned 4-register quad instead of an 8-register block: +// the QF RoPE loop's 8-reg tcgen05.ld destinations forced spills in a fragmented register file) +__device__ __forceinline__ void tmem_ld4_nw(uint32_t ta, float* v) { + uint32_t r0, r1, r2, r3; + asm volatile("tcgen05.ld.sync.aligned.32x32b.x4.b32 {%0,%1,%2,%3}, [%4];" : "=r"(r0), "=r"(r1), "=r"(r2), "=r"(r3) : "r"(ta)); + v[0] = __uint_as_float(r0); v[1] = __uint_as_float(r1); v[2] = __uint_as_float(r2); v[3] = __uint_as_float(r3); +} +__device__ __forceinline__ void tmem_wait_ld() { asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); } +// 8 columns as two x4 loads (no wait) +__device__ __forceinline__ void tmem_ld8q_nw(uint32_t ta, float* v) { tmem_ld4_nw(ta, v); tmem_ld4_nw(ta + 4, v + 4); } +// volatile 64-bit pointer shuffle (two shfl.sync.idx.b32): kept at its use site (no hoisting / CSE) +__device__ __forceinline__ char* shfl_ptr_v(unsigned long long v, int src) { + uint32_t lo = (uint32_t)v, hi = (uint32_t)(v >> 32), rl, rh; + asm volatile("shfl.sync.idx.b32 %0, %1, %2, 0x1f, 0xffffffff;" : "=r"(rl) : "r"(lo), "r"(src)); + asm volatile("shfl.sync.idx.b32 %0, %1, %2, 0x1f, 0xffffffff;" : "=r"(rh) : "r"(hi), "r"(src)); + return reinterpret_cast(((unsigned long long)rh << 32) | rl); +} +#ifndef QKV_QPF_F16 +#define QKV_QPF_F16 3 +#endif +#ifndef QKV_PR2 +#define QKV_PR2 1 +#endif +#ifndef QKV_VT8 +#define QKV_VT8 1 // V^T via 8x8 lane transpose (16 B stores) when S % 8 == 0 +#endif +#ifndef QKV_CST +#define QKV_CST 1 // coalesced q/k stores via 4-lane transpose +#endif +#ifndef QKV_QPF_F8 +#define QKV_QPF_F8 0 // RoPE-table chunks prefetched ahead for e4m3 instantiations (register pressure) +#endif +// 3D TMA load (fused MoE raw weights: box {32 floats, 2 K halves, rows} = 256 contiguous bytes per row) +__device__ __forceinline__ void tma_load_3d_hint(uint32_t dst, const CUtensorMap* map, int x, int y, int z, uint32_t bar, + uint64_t pol) { + asm volatile( + "cp.async.bulk.tensor.3d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3, %4}], [%5], %6;" ::"r"(dst), + "l"((uint64_t)map), "r"(x), "r"(y), "r"(z), "r"(bar), "l"(pol) + : "memory"); +} +// ------------------------------------------------------------------ 2-CTA (cta_group::2) cluster helpers +__device__ __forceinline__ void cl_sync_all() { + asm volatile("barrier.cluster.arrive.release.aligned;\nbarrier.cluster.wait.acquire.aligned;" ::: "memory"); +} +__device__ __forceinline__ uint32_t cl_ctarank() { + uint32_t r; + asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(r)); + return r; +} +// arrive on an mbarrier given by a shared::cluster address (possibly in the peer CTA) +__device__ __forceinline__ void mbar_arrive_cl(uint32_t a) { + asm volatile("mbarrier.arrive.release.cluster.shared::cluster.b64 _, [%0];" ::"r"(a) : "memory"); +} +// cluster-scope acquire wait (barrier receives arrivals / tx / commits from the peer CTA) +__device__ __forceinline__ void mbar_wait_cl2(uint32_t a, uint32_t parity) { + uint32_t ok = 0; + while (!ok) { + asm volatile( + "{ .reg .pred p; mbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 p, [%1], %2; selp.u32 %0, 1, 0, p; }" + : "=r"(ok) + : "r"(a), "r"(parity) + : "memory"); + } +} +// cluster-scope acquire test / suspend-hinted wait (o_proj pair epilogue accumulator wait) +__device__ __forceinline__ bool mbar_test_cl2(uint32_t a, uint32_t parity) { + uint32_t ok; + asm volatile("{ .reg .pred p; mbarrier.test_wait.parity.acquire.cluster.shared::cta.b64 p, [%1], %2; selp.u32 %0, 1, 0, p; }" + : "=r"(ok) : "r"(a), "r"(parity) : "memory"); + return ok != 0; +} +__device__ __forceinline__ void mbar_wait_cl2_hint(uint32_t a, uint32_t parity) { + uint32_t ok = 0; + while (!ok) { + asm volatile("{ .reg .pred p; mbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 p, [%1], %2, %3; selp.u32 %0, 1, 0, p; }" + : "=r"(ok) : "r"(a), "r"(parity), "r"(10000000u) : "memory"); + } +} +// cluster-scope acquire wait, test-first then try_wait with the suspend-time hint (SR QKV pair epilogue tfull) +__device__ __forceinline__ void mbar_wait_cl2_tf(uint32_t a, uint32_t parity) { + uint32_t ok; + asm volatile("{ .reg .pred p; mbarrier.test_wait.parity.acquire.cluster.shared::cta.b64 p, [%1], %2; selp.u32 %0, 1, 0, p; }" + : "=r"(ok) : "r"(a), "r"(parity) : "memory"); + while (!ok) { + asm volatile( + "{ .reg .pred p; mbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 p, [%1], %2, %3; selp.u32 %0, 1, 0, p; }" + : "=r"(ok) : "r"(a), "r"(parity), "r"(10000000u) : "memory"); + } +} +// shared::cta address -> shared::cluster address of the same offset in CTA `rank` +__device__ __forceinline__ uint32_t mapa_sh(uint32_t a, uint32_t rank) { + uint32_t r; + asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(r) : "r"(a), "r"(rank)); + return r; +} +// 2-CTA TMA: data lands in THIS CTA's smem, complete_tx is signalled on `bar` (shared::cluster address of the +// leader CTA's full barrier); L2 cache-policy hint +__device__ __forceinline__ void tma_load_2d_cg2(uint32_t dst, const CUtensorMap* map, int x, int y, uint32_t bar, + uint64_t pol) { + asm volatile( + "cp.async.bulk.tensor.2d.cta_group::2.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], " + "[%1, {%2, %3}], [%4], %5;" ::"r"(dst), + "l"((uint64_t)map), "r"(x), "r"(y), "r"(bar), "l"(pol) + : "memory"); +} +// 2-CTA MMA (leader issues): A rows split across the pair by M (128 per CTA), B rows split by N (128 per CTA), +// D = each CTA's own 128 TMEM lanes x N columns +__device__ __forceinline__ void mma_f16_cg2(uint32_t tmem, uint64_t ad, uint64_t bd, uint32_t idesc, uint32_t acc) { + asm volatile( + "{ .reg .pred p; setp.ne.b32 p, %4, 0; tcgen05.mma.cta_group::2.kind::f16 [%0], %1, %2, %3, p; }" ::"r"(tmem), + "l"(ad), "l"(bd), "r"(idesc), "r"(acc)); +} +// FP8 (kind::f8f6f4, e4m3 x e4m3 -> f32; same instruction-descriptor bits as kind::f16 with a/b format 0 = E4M3, +// K = 32 per MMA = 32 bytes of the 128B-swizzled K-major rows, so the descriptor stepping is identical) +__device__ __forceinline__ void mma_f8_ss(uint32_t tmem, uint64_t ad, uint64_t bd, uint32_t idesc, uint32_t acc) { + asm volatile( + "{ .reg .pred p; setp.ne.b32 p, %4, 0; tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %3, p; }" ::"r"(tmem), + "l"(ad), "l"(bd), "r"(idesc), "r"(acc)); +} +__device__ __forceinline__ void mma_f8_cg2(uint32_t tmem, uint64_t ad, uint64_t bd, uint32_t idesc, uint32_t acc) { + asm volatile( + "{ .reg .pred p; setp.ne.b32 p, %4, 0; tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], %1, %2, %3, p; }" ::"r"(tmem), + "l"(ad), "l"(bd), "r"(idesc), "r"(acc)); +} +// 1-CTA MMA commit multicast to the mbarrier at the same smem offset in every CTA of the cluster mask +__device__ __forceinline__ void mma_commit_mc(uint32_t bar, uint16_t mask) { + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%0], %1;" + ::"r"(bar), "h"(mask) : "memory"); +} +// TMA 2D load multicast to the same smem offset (data + complete_tx on the same-offset mbarrier) of every CTA in mask +__device__ __forceinline__ void tma_load_2d_mc(uint32_t dst, const CUtensorMap* map, int x, int y, uint32_t bar, + uint16_t mask, uint64_t pol) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.multicast::cluster.L2::cache_hint " + "[%0], [%1, {%2, %3}], [%4], %5, %6;" ::"r"(dst), "l"((uint64_t)map), "r"(x), "r"(y), "r"(bar), "h"(mask), "l"(pol) + : "memory"); +} +// cta_group::2 TS MMA (A from each CTA's TMEM, B split along N across the pair) +__device__ __forceinline__ void mma_f16_ts_cg2(uint32_t tmem, uint32_t a_tmem, uint64_t bd, uint32_t idesc, uint32_t acc) { + asm volatile( + "{ .reg .pred p; setp.ne.b32 p, %4, 0; tcgen05.mma.cta_group::2.kind::f16 [%0], [%1], %2, %3, p; }" ::"r"(tmem), + "r"(a_tmem), "l"(bd), "r"(idesc), "r"(acc)); +} +// cta_group::2 commit multicast to an explicit cluster CTA mask (pair inside a larger cluster) +__device__ __forceinline__ void mma_commit_cg2m(uint32_t bar, uint16_t mask) { + asm volatile( + "tcgen05.commit.cta_group::2.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%0], %1;" ::"r"(bar), + "h"(mask) + : "memory"); +} +// commit: arrive on the mbarrier at the same smem offset in BOTH CTAs of the pair (cta mask 0b11) +__device__ __forceinline__ void mma_commit_cg2(uint32_t bar) { + asm volatile( + "tcgen05.commit.cta_group::2.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%0], %1;" ::"r"(bar), + "h"((uint16_t)3) + : "memory"); +} + +// ------------------------------------------------------------------ tcgen05 GEMM (persistent) +// One CTA per SM (320 threads), static round-robin over output tiles of 128 x 256. +// QKV / OPROJ use fp16 operands (kind::f16, 64 K-elements per stage), GATEUP / DOWN use fp32 operands +// (kind::tf32, 32 K-elements per stage); a stage is always 128 B of K per row. +// warp 0 : TMA producer, 4-stage smem ring {A 128 rows (16 KB), B 256 rows (32 KB)}, 128B swizzle +// warp 1 : TMEM allocator (512 cols = 2 accumulator buffers x 256) + single-thread MMA issuer +// warps 2-9 : epilogue; warp w reads TMEM lane quadrant (w % 4) and column half ((w-2) / 4). +// EPI_ROUTER: logits[T,128] += 3xTF32 split-K GEMM (x_hi Wr_hi + x_hi Wr_lo + x_lo Wr_hi), fp32-accurate. +enum { EPI_QKV = 0, EPI_OPROJ = 1, EPI_GATEUP = 2, EPI_DOWN = 3, EPI_ROUTER = 4 }; +constexpr int TBM = 128, TBN = 256, TBK = 32; +constexpr int TSTAGES = 4; +constexpr int A_BYTES = TBM * TBK * 4, B_BYTES = TBN * TBK * 4, STAGE_BYTES = A_BYTES + B_BYTES; +constexpr int TC_SMEM = TSTAGES * STAGE_BYTES + 1024 + 256; +// DOWN epilogue: per epilogue warp a 32 row x 16 col fp32 staging tile (2 KB, XOR-swizzled float4 groups) +constexpr int DOWN_STG_FLOATS = 32 * 16; +constexpr int TC_SMEM_DOWN = TC_SMEM + 8 * DOWN_STG_FLOATS * 4; +// OPROJ: 8 warps x 2 x 2 KB resid/h slots for the TMA epilogue (1024-aligned), after the barriers (+512: slot mbarriers) +constexpr int OPJ_STG_OFF = TSTAGES * STAGE_BYTES + 1024; +constexpr int TC_SMEM_OPROJ = OPJ_STG_OFF + 8 * 4096 + 1024; +static_assert(TC_SMEM_OPROJ <= 232448, "o_proj smem"); +constexpr int QKV_NW_OFF = TSTAGES * STAGE_BYTES + 256; // sr kernel stages q/k norm weights here (+1 KB) +// QKV (T < 2048) idle warps 2-3 convert Wo units during the GEMM: 2 x 16 KB fp32 staging buffers at ring + 2 KB +constexpr int QKV_CONV_OFF = TSTAGES * STAGE_BYTES + 2048; +constexpr int TC_SMEM_QKV = QKV_CONV_OFF + 2 * 16384 + 1024; +static_assert(TC_SMEM_QKV <= 232448, "qkv smem"); +template constexpr int tc_smem() { return EPI == EPI_DOWN ? TC_SMEM_DOWN : (EPI == EPI_OPROJ ? TC_SMEM_OPROJ : (EPI == EPI_QKV ? TC_SMEM_QKV : TC_SMEM)); } +constexpr int OPJ_FS_OFF = OPJ_STG_OFF + 8 * 4096; +static_assert(TC_SMEM_OPROJ + 1024 <= 232448, "o_proj F8 smem"); +template constexpr int tc_smem_q() { return (EPI == EPI_QKV && QF) ? TC_SMEM + 1024 : ((EPI == EPI_OPROJ && QF) ? TC_SMEM_OPROJ + 1024 : tc_smem()); } +constexpr int TC_THREADS = 320; +template constexpr int tc_threads() { return EPI == EPI_QKV ? 384 : TC_THREADS; } +// spill-reduced QKV kernel (tc_gemm_sr_kernel): SR_NEW = 3 epilogue warpgroups (warps 4..15, 512 threads) pull +// (tile, head) jobs over the 2 TMEM accumulator buffers -> up to 3 head epilogues in flight per SM (was 2) +constexpr int SR_NEW = 3; +template constexpr int tc_threads_sr() { return EPI == EPI_QKV ? 128 + 128 * SR_NEW : TC_THREADS; } +constexpr uint32_t IDESC_TF32 = (1u << 4) | (2u << 7) | (2u << 10) | ((256u >> 3) << 17) | ((128u >> 4) << 24); +constexpr uint32_t IDESC_F16 = (1u << 4) | (0u << 7) | (0u << 10) | ((256u >> 3) << 17) | ((128u >> 4) << 24); + +struct TcArgs { + int M, KB, NT; + int S, Spad; float eps; + const float* bias0; const float* bias1; const float* bias2; + const float* resid; + float* out; + const float* cs; const float* sn; const float* qnw; const float* knw; + __half* q; __half* k; __half* v; + const int* tile_expert; const int* tile_mstart; const int* total_tiles; + const int* offsets; const int* counts; const int* perm_tok; const float* perm_w; + float* ssq; // OPROJ: per-row sum of squares of h (atomically accumulated, zeroed by rmsnorm1) + int BN; // output tile width (QKV: 256|128, OPROJ: 256|128|64, others 256), picked on the host for SM fill + int qsplit; // QKV (BN=256): #tail tiles of the last partial wave split into 2 one-head N=128 tiles (host-computed) + // OPROJ (BN=256): #tail tiles split into ospl sub-tiles of N = 256/ospl (host-computed) + int ospl; // OPROJ tail split factor (2: N=128 halves, 4: N=64 quarters) + const unsigned long long* side_ctr; // OPROJ: side-stream completion counter (Wo16 producer), acquired before TMA + unsigned long long side_target; + sidew::ConvJob conv; // OPROJ: convert units claimable / stealable by the pre-wait acquire (warp 0) + unsigned long long* probe; // debug probe: 8 globaltimer stamps per CTA (nullptr = off) + unsigned long long* cprobe; // TC_PROBE builds only: 16 clock64 accumulators per CTA + int pmode; // TC_PROBE builds only: 0 real, 1 MMA-only (no full wait), 2 feed-only (no MMAs) + unsigned* vmax; // QKV: global max |V| (fp32 bits, atomicMax) for the fp8 attention-output scale (nullptr = off) + // OPROJ fp8: read to recover the attention-output scale + const float* wsc; // OPROJ fp8: per-output-column inverse Wo scale 1 / s_n + const unsigned* qkb; // QKV (QF epilogue): non-null -> q / k written as e4m3 x qk8_scale (FA4 FP8 QK^T path) + unsigned* qkb_reset; // OPROJ: zero the 4 QK bound slots for the next forward (after its PDL wait) + L2Discard dl; // OPROJ: QKV/attention-side dead buffers L2-discarded by the idle epilogue warps + const float* qws; // QKV fp8 (QF): inverse per-Wqkv-row (= output column) e4m3 scales [5120] + const float* qxs; // QKV fp8 (QF): inverse per-xn-row e4m3 scales [T] + const float* pfg; const float* pfu; + int pf_t0, pf_t1, pf_kb, pf_krot; // items [pf_t0, pf_t1) of the fused fp16 MoE, first pf_kb rotated k-blocks + int abl; // ABL_PROBE builds only: bit0 epilogue off, bit1 MMA off, bit2 TMA off + int csteal; + int* mtctr; + int* qbc; + int ores; // OPROJ e4m3 1-CTA: last tile's resid half-chunks k >= 2 staged in the dead ring + int kd2; +}; +#ifdef TC_PROBE +#define CPT(v) const long long v = clock64() +#define CPA(i, d) do { cacc[i] += (unsigned long long)(d); } while (0) +#else +#define CPT(v) do { } while (0) +#define CPA(i, d) do { } while (0) +#endif + +__device__ __forceinline__ unsigned long long gtime() { unsigned long long t; asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t) :: "memory"); return t; } +// Debug probe stamps (globaltimer per CTA: entry, griddep release, first stage landed, mainloop end, first/last +// accumulator ready, epilogue end, CTA end). Compiled out; enable with: +// #define PRB(i) do { if (p.probe) p.probe[blockIdx.x * 8 + (i)] = gtime(); } while (0) +#define PRB(i) do { } while (0) +__device__ __forceinline__ uint4 pack8_h(const float* f) { + uint4 u; + u.x = pack_h2(f[0], f[1]); u.y = pack_h2(f[2], f[3]); u.z = pack_h2(f[4], f[5]); u.w = pack_h2(f[6], f[7]); + return u; +} + +template +__device__ __forceinline__ uint32_t tc_gemm_dev(const CUtensorMap& tA, const CUtensorMap& tB0, const CUtensorMap& tB1, + const CUtensorMap& tB2, const CUtensorMap& tB3, const CUtensorMap& tB4, + const TcArgs& p, const int bidx, const int gdim) { + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = (uint8_t*)(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023); + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + constexpr bool grouped = (EPI == EPI_GATEUP || EPI == EPI_DOWN); + constexpr bool F16 = (EPI == EPI_QKV || EPI == EPI_OPROJ); + constexpr bool F8 = (EPI == EPI_OPROJ && QF) || (EPI == EPI_QKV && QF && Q8); // Q8 = false: QF epilogue, fp16 QKV operands + static_assert(!VS || (EPI == EPI_QKV && F8), "VS: QKV fp8 only"); + constexpr int KE = F8 ? 128 : (F16 ? 64 : 32); + constexpr bool PAIR = (CG >= 2); + constexpr int KD = CG >= 3 ? 2 : 1; // 64-K sub-blocks per pair stage + constexpr uint32_t KBOFF = CG == 4 ? 16384u : 8192u; // B sub-block stride inside a KD == 2 stage + static_assert(!PAIR || F16, "2-CTA path only for the dense fp16 GEMMs"); + // SW (merged o_proj + router launch only, T < 2048): the 16 CTAs of a cluster compute the 16 N tiles (128 Wo + // rows each) of ONE 128-row token tile. Cluster ranks (2p, 2p+1) form a cta_group::2 pair running SWAP-AB + // m256n128k16 MMAs: A = each CTA's own 128 Wo rows (its N tile, M/2 = 128 per CTA), B = the 128 attn token rows, + // split 64 / 64 between the pair (each CTA TMA-loads only its 64-row half). D in each CTA = h^T: TMEM lane = output + // column of its N tile, column = token. Per k-block an SM ingests 16 KB Wo + 8 KB attn (was 32 KB). 8-stage ring of + // 24 KB {Wo 16 KB, attn half 8 KB}; the leader (even rank) expects both CTAs' 48 KB, issues the MMAs and multicasts + // commits to both CTAs; the epilogue transposes the accumulator through the per-warp resid smem slots. + // TMEM: each CTA allocates its own 512 columns with cta_group::1 (1 CTA / SM -> both bases are 0, identical). + constexpr bool SW = MRG && EPI == EPI_OPROJ && CG == 1; + // SW: Wo is consumed as fp32 (no side-stream fp16 Wo copy): warp 14 TMA-loads raw fp32 Wo k-blocks (128 rows x + // 64 K = 2 boxes of 32 floats, 32 KB) into a 3-stage raw ring at SW_RAW_OFF; converter warps 10..13 (thread = Wo row) + // convert each to fp16 x 2^4 (bit-identical to convert_w16) into the 128B-swizzled A slot of a 4-stage {Wo16 16 KB, + // attn half 8 KB} ring, then arrive (release.cluster) on the pair leader's full barrier (count 1 + 2 x 4). + // W32 (QKV, T < 2048, non-QF epilogue): the B operand is consumed as fp32 Wq / Wk / Wv (no fp16 Wqkv copy + // written by prep_qkv): warp 0 TMA-loads raw fp32 half k-blocks (BN rows x 32 floats = 64-row boxes of tB2 / tB3 / + // tB4, 128B swizzle) into a 4-slot raw ring (the first 4 slots BEFORE griddepcontrol.wait: weights are inputs), the + // idle warps 2, 3 convert them to fp16 x 2^4 (bit-identical to prep's conversion) into the 128B-swizzled B half of + // a 2-stage {A 16 KB, B 32 KB} ring and arrive on its full barrier (count 1 + 2 warps x 2 halves). + static_assert(!W32 || (EPI == EPI_QKV && !QF && CG == 1 && !MRG), "W32: QKV non-QF 1-CTA only"); + // OP4 (e4m3 o_proj 2-CTA pairs, BN = 256): 5-stage ring (160 KB); the freed 32 KB at [5 x 32 KB, RB) holds + // resid slots 2, 3 of every epilogue warp -> 4-slot resid ring per warp, loads 3 half-chunks ahead (was 1) + constexpr bool OP4 = EPI == EPI_OPROJ && CG == 2 && F8; + constexpr int OSL = OP4 ? 4 : 2; // resid slots per epilogue warp + constexpr int NST = PAIR ? (CG == 4 ? 3 : KD == 2 ? 4 : (OP4 ? 5 : 6)) : (SW ? 4 : (W32 ? 2 : TSTAGES)); + constexpr int SBYTES = PAIR ? (CG == 4 ? 65536 : KD == 2 ? 49152 : 32768) : (SW ? 24576 : STAGE_BYTES); + static_assert(KD == 1 || EPI == EPI_OPROJ, "KD 2: o_proj BN = 128 pairs only"); + constexpr int RB = TSTAGES * STAGE_BYTES; // barrier area offset (all variants) + constexpr int SW_RAW_OFF = 4 * 24576; + static_assert(SW ? (NST * SBYTES + 3 * 32768 <= RB) : (W32 ? (NST * SBYTES + 3 * 32768 == RB) : (OP4 ? (NST * SBYTES + 8 * 4096 == RB) : (NST * SBYTES == RB))), "smem layout"); + const uint32_t rank = PAIR ? cl_ctarank() : 0u; + // MC (merged o_proj + router launch only): the 16 CTAs of a cluster compute the 16 N tiles of ONE 128-row M tile, + // so they all stream the SAME A (attn) rows. Groups of 4 CTAs (cluster ranks 4g..4g+3) share A by TMA multicast: CTA + // j of a group loads A rows 32j..32j+31 (4 KB of the 16 KB 128B-swizzled stage tile, 1024 B-aligned) into the same + // smem offset of all 4 CTAs (complete_tx on each CTA's own full barrier, which still expects 16 KB A + 16 KB B). + // A stage is refilled only after all 4 CTAs' MMAs released it: empty barriers count 4, the MMA commit is multicast + // to the group. Per-SM L2->SM A traffic is unchanged but aggregate L2 reads per k-block drop from 32 KB to 20 KB per + // CTA. + constexpr bool MC = false; // A multicast replaced by the SW pair path + const uint32_t swrank = SW ? cl_ctarank() : 0u; + const uint32_t swlead = swrank & ~1u; // pair leader (even cluster rank) + const uint16_t swmask = (uint16_t)(3u << swlead); + const uint32_t mcrank = MC ? cl_ctarank() : 0u; + const uint32_t mcj = mcrank & 3u; + const uint16_t mcmask = (uint16_t)(0xFu << (mcrank & ~3u)); + const int cid = PAIR ? (int)(bidx >> 1) : (int)bidx; // tile-scheduler id (cluster id) + const int ncl = PAIR ? (int)(gdim >> 1) : (int)gdim; + + const uint32_t sbase = smem_u32(smem); + const uint32_t bar_full = sbase + RB; + const uint32_t bar_empty = bar_full + NST * 8; + const uint32_t bar_tfull = bar_empty + NST * 8; + const uint32_t bar_tempty = bar_tfull + 16; + const uint32_t tslot = bar_tempty + 16; + volatile uint32_t* tslot_ptr = (volatile uint32_t*)(smem + RB + NST * 16 + 32); + const uint32_t sw_raw_full = bar_full + 128, sw_raw_empty = bar_full + 152; // SW only: [3] each + const uint32_t w32_raw_full = bar_full + 192, w32_raw_empty = bar_full + 224; // W32 only: [4] each + // W32 raw slot r (32 KB): slots 0..2 after the 2 fp16 stages, slot 3 in the (unused) convert-steal staging area + auto w32_raw_off = [&](int r) -> uint32_t { return r < 3 ? (uint32_t)(NST * SBYTES + 32768 * r) : (uint32_t)QKV_CONV_OFF; }; + // accumulator release: PAIR -> the leader's tempty barrier (both CTAs' epilogues, count 16) + auto tempty_arrive = [&](int b) { + if (PAIR || SW) mbar_arrive_cl(mapa_sh(bar_tempty + 8 * b, SW ? swlead : 0u)); + else mbar_arrive(bar_tempty + 8 * b); + }; + if (threadIdx.x == 0) PRB(0); +#ifdef TC_PROBE + unsigned long long cacc[16]; +#pragma unroll + for (int i = 0; i < 16; i++) cacc[i] = 0; + const long long cta_t0 = clock64(); +#endif + + if (threadIdx.x == 0) { + for (int s = 0; s < NST; s++) { mbar_init(bar_full + 8 * s, SW ? 9 : (W32 ? 5 : 1)); mbar_init(bar_empty + 8 * s, MC ? 4 : 1); } + for (int b = 0; b < 2; b++) { mbar_init(bar_tfull + 8 * b, 1); mbar_init(bar_tempty + 8 * b, (PAIR || SW) ? 16 : 8); } + if (SW) for (int i = 0; i < 3; i++) { mbar_init(sw_raw_full + 8 * i, 1); mbar_init(sw_raw_empty + 8 * i, 4); } + if (EPI == EPI_OPROJ) // resid slot barriers of the TMA epilogue (8 warps x 2 slots) + for (int i = 0; i < 8 * OSL; i++) mbar_init(sbase + TSTAGES * STAGE_BYTES + 512 + 8 * i, 1); + if (EPI == EPI_OPROJ && !PAIR && !SW) // per-warp last-tile resid bulk barrier (slot-2 address) + for (int w = 0; w < 8; w++) mbar_init(sbase + TSTAGES * STAGE_BYTES + 512 + 128 + 16 * w, 1); + if (EPI == EPI_OPROJ && OP4) // pair last-tile resid bulk barrier per warp (after the 32 slot barriers) + for (int w = 0; w < 8; w++) mbar_init(sbase + TSTAGES * STAGE_BYTES + 768 + 8 * w, 1); + if (W32) { + for (int i = 0; i < 4; i++) { mbar_init(w32_raw_full + 8 * i, 1); mbar_init(w32_raw_empty + 8 * i, 2); } + } else if (EPI == EPI_QKV && !QF) { // convert-steal staging barriers (warps 2, 3 x 2 half-unit slots) + for (int i = 0; i < 4; i++) mbar_init(sbase + TSTAGES * STAGE_BYTES + 192 + 8 * i, 1); + } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tA) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tB0) : "memory"); + // prefetch EVERY descriptor this CTA may use (tail-split tB1, VS / SW / grouped tB2, o_proj epilogue + // h-store tB3 / resid-load tB4) before griddepcontrol.wait, so the first TMA of each map does not pay the + // descriptor fetch latency on the critical path (descriptors are __grid_constant__ params, read-only) + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tB1) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tB2) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tB3) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tB4) : "memory"); + } + if (warp == 1) { + if (PAIR || SW) { // both CTAs of the pair allocate collectively + asm volatile("tcgen05.alloc.cta_group::2.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(tslot), "r"(512)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::2.sync.aligned;"); + } else { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(tslot), "r"(512)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + } + tc_fence_before(); + __syncthreads(); + if (PAIR || SW) cl_sync_all(); // peer barriers initialised before any remote arrive / TMA complete_tx + tc_fence_after(); + const uint32_t tbase = *tslot_ptr; + const int KB = p.KB; + // runtime N tile width (wave-quantization selector, host side); B TMA box rows == BN + const int BN = p.BN; + const uint32_t stage_tx = (uint32_t)(A_BYTES + BN * 128); + const uint32_t idesc_f16 = (1u << 4) | ((uint32_t)(BN >> 3) << 17) | ((128u >> 4) << 24); + CHN(3 + EPI, 0); + // o_proj pre-PDL-wait work: Wo16 comes from the SIDE stream (completion counter), not from the predecessor + // (flash attention), so the producer warp acquires it and L2-prefetches the B (Wo16) boxes of the first 8 + // k-blocks of this CTA's first tile while attention is still draining. A only (attn) depends on the predecessor. + int opre = 0; // o_proj stages whose B operand was issued before griddepcontrol.wait (warp 0) + if (EPI == EPI_OPROJ && !SW && warp == 0) { + // acquire with work stealing (executes still-unclaimed convert units itself: deadlock-free) + sidew::conv_acquire_steal(p.conv, (int)(((long long)bidx * p.conv.n) / gdim)); + const int nmo = (p.M + TBM - 1) / TBM; + const int nm2 = PAIR ? (nmo + 1) / 2 : nmo; + const int nfo = nm2 * p.NT, nso = PAIR ? 0 : p.qsplit, splo = p.ospl; + const int nto = nfo + nso * (splo - 1); + const int t = cid; + if (t < nto && lane < 8) { + int f = t, sub = -1; + const int fs = nfo - nso; + if (t >= fs) { f = fs + (t - fs) / splo; sub = (t - fs) % splo; } + int mt = f / p.NT, nt = f - mt * p.NT; + if (false && p.M >= 2048) { // o_proj row-major raster + const int band = f / (8 * p.NT), first = band * 8; + const int gsz = nm2 - first < 8 ? nm2 - first : 8; + nt = (f - band * 8 * p.NT) / gsz; + } + const CUtensorMap* bm = &tB0; + int r0 = nt * BN; + if (PAIR) r0 = nt * BN + (BN >> 1) * (int)rank; // BN = 256 or 128 (o_proj m256n128 pairs) + else if (sub >= 0) { bm = &tB1; r0 = nt * 256 + sub * (256 / splo); } + if (lane < KB) + asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile [%0, {%1, %2}];" ::"l"((uint64_t)bm), + "r"(lane * KE), "r"(r0) : "memory"); + } + __syncwarp(); + // 1-CTA o_proj, full first tile: the B (Wo16) operand of the first ring stages is TMA-loaded into smem + // BEFORE griddepcontrol.wait (Wo16 is a side-stream product, acquired above; fresh ring -> stages free). + // Only the tx count is added here (mbarrier.expect_tx, no arrival); after the wait the producer arrives with + // the A (attn) bytes, so a stage still completes only when both A and B have landed. Same bytes / MMA order. + if (!PAIR && !MC && t < nto && t < nfo - nso) { + int mt = t / p.NT, nt = t - mt * p.NT; + if (false && p.M >= 2048) { + const int band = t / (8 * p.NT), first = band * 8; + const int gsz = nm2 - first < 8 ? nm2 - first : 8; + nt = (t - band * 8 * p.NT) / gsz; + } + asm volatile("fence.proxy.async.global;" ::: "memory"); // Wo16 generic writes (side / stolen) -> TMA + const bool kd2p = !F8 && p.kd2; + const int kbp = KB / (kd2p ? 2 : 1), nsp = kd2p ? 3 : TSTAGES; + opre = kbp < nsp ? kbp : nsp; + const uint64_t kpol = keep_pol(); + if (elect_one()) { + for (int i = 0; i < opre; i++) { + const uint32_t fb = bar_full + 8 * i; + if (kd2p) { + asm volatile("mbarrier.expect_tx.relaxed.cta.shared::cta.b64 [%0], %1;" ::"r"(fb), + "r"((uint32_t)(2 * BN * 128)) : "memory"); + const uint32_t sa = sbase + (uint32_t)i * 65536u; + for (int jd = 0; jd < 2; jd++) + tma_load_2d_hint(sa + 32768u + 16384u * jd, &tB0, (2 * i + jd) * KE, nt * BN, fb, kpol); + } else { + asm volatile("mbarrier.expect_tx.relaxed.cta.shared::cta.b64 [%0], %1;" ::"r"(fb), + "r"((uint32_t)(BN * 128)) : "memory"); + tma_load_2d_hint(sbase + i * STAGE_BYTES + A_BYTES, &tB0, i * KE, nt * BN, fb, kpol); + } + } + } + __syncwarp(); + } + // 2-CTA o_proj pairs, full first pair tile: each CTA TMA-loads ITS B (Wo) half of the first ring stages + // BEFORE griddepcontrol.wait (Wo copy acquired above; fresh ring). Its own B bytes are added to the LEADER's + // full barrier with a remote mbarrier.expect_tx (no arrival); after the wait the leader's arrive.expect_tx + // covers only both CTAs' A bytes, so a stage still completes only when all A + B bytes landed. Both CTAs of a + // pair derive the same opre (same tile id). Same bytes / MMA order (bit-identical). + if (PAIR && t < nm2 * p.NT - p.qsplit) { + int nt = t % p.NT; + if (false && p.M >= 2048) { + const int band = t / (8 * p.NT), first = band * 8; + const int gsz = nm2 - first < 8 ? nm2 - first : 8; + nt = (t - band * 8 * p.NT) / gsz; + } + asm volatile("fence.proxy.async.global;" ::: "memory"); // Wo generic writes (side / stolen) -> TMA + const int kbp = KB / KD; + opre = kbp < NST ? kbp : NST; + const uint64_t kpol = keep_pol(); + if (elect_one()) { + for (int i = 0; i < opre; i++) { + const uint32_t fb = bar_full + 8 * i, fbl = mapa_sh(fb, 0); + const uint32_t sa = sbase + (uint32_t)i * SBYTES; + asm volatile("mbarrier.expect_tx.relaxed.cluster.shared::cluster.b64 [%0], %1;" ::"r"(fbl), + "r"((uint32_t)(KD * (BN >> 1) * 128)) : "memory"); + if (KD == 2) { + for (int jd = 0; jd < 2; jd++) + tma_load_2d_cg2(sa + 32768u + KBOFF * jd, &tB0, (i * 2 + jd) * KE, nt * BN + (BN >> 1) * (int)rank, fbl, kpol); + } else { + tma_load_2d_cg2(sa + A_BYTES, &tB0, i * KE, nt * BN + (BN >> 1) * (int)rank, fbl, kpol); + } + } + } + __syncwarp(); + } + } + // the QKV convert-steal warps 2, 3 touch only Wo (input) / Wo16 (read by o_proj after attention; the previous + // call's readers and L2 discard completed before this grid could launch) -> they skip griddepcontrol.wait + // SW Wo stream warps (10..14) read only the fp32 Wo input and write this CTA's smem -> no griddepcontrol.wait + // W32: warp 0 waits itself (after its pre-wait raw weight loads); converter warps 2, 3 touch smem only + if (!(EPI == EPI_QKV && !QF && p.csteal > 0 && (warp == 2 || warp == 3)) && !(SW && warp >= 10 && warp <= 14) && + !(W32 && warp <= 3 && warp != 1)) pdl_wait(); + CHN(3 + EPI, 1); + // QK bound slots: every reader (QKV epilogue, attention) has completed (PDL chain) -> reset for the next forward + if (EPI == EPI_OPROJ && p.qkb_reset && bidx == 0 && threadIdx.x < 4) p.qkb_reset[threadIdx.x] = 0u; + if (threadIdx.x == 0) PRB(1); + pdl_trigger(); + const int num_m1 = grouped ? *p.total_tiles : (p.M + TBM - 1) / TBM; + const int num_m = PAIR ? (num_m1 + 1) / 2 : num_m1; // PAIR: M-tile pairs (one per cluster tile) + const int num_full = num_m * p.NT; // tiles of the nominal 128 x 256 shape + int nsplit = 0, spl = 2; + // QKV wave-tail split (exact on the host since M is known): the last r <= grid/2 full 256-wide (two-head) tiles + // run as 2r one-head N=128 tiles (B rows via the 128-row map tB1), so the tail costs ~half a tile, not a full one. + // QKV ospl = 4 (T < 2048 only, host-gated): the r tail tiles are V-head tiles (see coords) split into 4 N=64 + // quarters (V needs no per-head norm): a quarter costs ~A + B/4 bytes per k-block instead of A + B/2 for a half. + if (EPI == EPI_QKV && !PAIR) { nsplit = p.qsplit; spl = p.ospl == 8 ? 8 : (p.ospl == 4 ? 4 : 2); } // + V eighths + // o_proj wave-tail split (host-computed, BN = 256 only): the last r tiles of a partial wave (r <= grid/2, or + // <= grid/4 for quarters) run as ospl narrower N tiles (B rows via the (256/ospl)-row map tB1), so a tiny last + // wave (e.g. 12 of 148 SMs at T=7184) costs ~1/ospl of a tile instead of a full one. + // also PAIR (e4m3 o_proj m256 pair tiles): the last partial wave of pair tiles runs as N = 256/spl sub-tiles + if (EPI == EPI_OPROJ) { nsplit = p.qsplit; spl = p.ospl; } + if (grouped) { + if (p.BN == 128) nsplit = num_full; + else { + const int r = num_full % (int)gdim; + if (r > 0 && 2 * r <= (int)gdim) nsplit = r; + if (EPI == EPI_GATEUP && r > 0 && 4 * r <= (int)gdim) spl = 4; + } + } + const int num_tiles = num_full + nsplit * (spl - 1); + + // tile t -> (M tile, N tile, sub): sub = -1 full 256-wide tile, 0/1 = lower/upper N=128 half of a split tile + auto coords = [&](int t, int& m0, int& mend, int& e, int& nt, int& sub) { + int f = t; + sub = -1; + if (grouped || EPI == EPI_QKV || EPI == EPI_OPROJ) { + const int fs = num_full - nsplit; + if (t >= fs) { f = fs + (t - fs) / spl; sub = (t - fs) % spl; } + // o_proj walks M tiles row-major (all N tiles of an M tile adjacent), so its per-M-tile router handoff + // counters (mtctr) complete progressively through the waves instead of at band ends; same per-tile math + } + int mt = f / p.NT; + nt = f - mt * p.NT; + if (!grouped && EPI != EPI_ROUTER && EPI != EPI_OPROJ && p.M >= 2048) { + // M-tile-grouped rasterization (large T): tiles walk a band of GM = 8 M tiles M-fastest, then the next + // N tile, so a wave of concurrently running CTAs touches only 8 A row-blocks x ~grid/8 B tiles + // (bounded L2 working set, each A/B tile shared by many co-scheduled CTAs). Bijection over [0, num_full). + constexpr int GM = 8; + const int nm = num_m; // PAIR: bands of 8 M-tile pairs + const int band = f / (GM * p.NT), first = band * GM; + const int gsz = nm - first < GM ? nm - first : GM; + const int loc = f - band * GM * p.NT; + mt = first + loc % gsz; + nt = loc / gsz; + } else if (EPI == EPI_QKV && !PAIR && spl >= 4) { + // V-last order (bijection over [0, num_full)): all q/k tiles (n tiles 0..NT-3) M-major first, then + // the V tiles (n tiles NT-2, NT-1), so the split tail tiles are always V tiles (host: r <= 2 * num_m) + const int nqk = p.NT - 2, nonv = num_m * nqk; + if (f < nonv) { mt = f / nqk; nt = f - mt * nqk; } + else { const int g = f - nonv; mt = g >> 1; nt = nqk + (g & 1); } + } + if (grouped) { + e = p.tile_expert[mt]; + m0 = p.tile_mstart[mt]; + mend = p.offsets[e] + p.counts[e]; + } else { + e = 0; m0 = (PAIR ? 2 * mt + (int)rank : mt) * TBM; mend = p.M; // PAIR: rows >= M zero-filled, masked + } + }; + + constexpr int EW0 = EPI == EPI_QKV ? 4 : 2; // first epilogue warp + // QKV: per-warpgroup register rebalance inside the role branches (warp-uniform per warpgroup) + if (EPI == EPI_QKV ? warp < 4 : warp < 2) { + if constexpr (EPI == EPI_QKV) asm volatile("setmaxnreg.dec.sync.aligned.u32 40;\n" ::: "memory"); + if (warp == 0) { + if constexpr (W32) { + // ---------------- W32 producer: raw fp32 weight half k-blocks (cursor rt / rkb / rh, global index rq, + // raw slot rq & 3) + fp16 A (xn) tiles into the 2-stage ring + const uint64_t kpol = keep_pol(); + int rt = cid, rkb = 0, rh = 0, rq = 0; + auto issue_raw = [&]() -> bool { + if (rt >= num_tiles) return false; + int m0, mend, e, nt, sub; + coords(rt, m0, mend, e, nt, sub); + const int brow = sub >= 0 ? 256 / spl : BN; + const int row0 = sub >= 0 ? nt * 256 + sub * brow : nt * BN; + const CUtensorMap* mp = row0 < 4096 ? &tB2 : (row0 < 4608 ? &tB3 : &tB4); + const int rl = row0 < 4096 ? row0 : (row0 < 4608 ? row0 - 4096 : row0 - 4608); + const int r = rq & 3; + mbar_wait(w32_raw_empty + 8 * r, ((rq >> 2) & 1) ^ 1); + __syncwarp(); + if (elect_one()) { + const uint32_t fb = w32_raw_full + 8 * r, dst = sbase + w32_raw_off(r); + mbar_expect_tx(fb, (uint32_t)brow * 128u); + for (int j = 0; j < brow / 64; j++) tma_load_2d(dst + 8192u * j, mp, rkb * 64 + 32 * rh, rl + 64 * j, fb); + } + __syncwarp(); + rq++; + if (++rh == 2) { rh = 0; if (++rkb == KB) { rkb = 0; rt += ncl; } } + return true; + }; + for (int i = 0; i < 4; i++) issue_raw(); // pre-PDL-wait: fp32 Wqkv is a kernel input + pdl_wait(); + int g = 0; + for (int t = cid; t < num_tiles; t += ncl) { + int m0, mend, e, nt, sub; + coords(t, m0, mend, e, nt, sub); + for (int kb = 0; kb < KB; kb++, g++) { + const int s = g % NST; + mbar_wait(bar_empty + 8 * s, ((g / NST) & 1) ^ 1); + __syncwarp(); + if (elect_one()) { + const uint32_t fb = bar_full + 8 * s; + mbar_expect_tx(fb, (uint32_t)A_BYTES); + tma_load_2d_hint(sbase + s * SBYTES, &tA, kb * KE, m0, fb, kpol); + } + __syncwarp(); + while (rq < 2 * g + 4 && issue_raw()) { } // raw weights kept 2 k-blocks ahead + } + } + } else { + // ---------------- TMA producer: the WHOLE warp runs the loop (warp-uniform empty-barrier waits and tile + // arithmetic), one elect.sync lane issues expect_tx + the cp.async.bulk.tensor loads (same structure as + // the MMA issuer; a lane-0-only divergent branch costs ~55 cycles per async op) + int it = 0; + const uint64_t kpol = keep_pol(); // QKV/OPROJ: A and B tiles are re-read by other tiles -> EVICT_LAST + if (EPI == EPI_OPROJ && !SW) { + __syncwarp(); + asm volatile("fence.proxy.async.global;" ::: "memory"); + } + for (int t = cid; t < num_tiles; t += ncl) { + int m0, mend, e, nt, sub; + coords(t, m0, mend, e, nt, sub); + // grouped remainder tile (<= 64 valid rows): only 64 A rows are loaded (M=64 MMA, tB2 = 64-row A map) + const bool m64 = grouped && (mend - m0 <= 64); + const uint32_t tx = grouped ? (uint32_t)((m64 ? A_BYTES / 2 : A_BYTES) + (sub < 0 ? 256 : 256 / spl) * 128) + : (sub >= 0 ? (uint32_t)(A_BYTES + (256 / spl) * 128) : stage_tx); + const bool vt = VS && nt * BN >= 4608; // VS: fp16 V tile (2x the k-blocks of 64 K) + const bool kd2t = EPI == EPI_OPROJ && !F8 && !SW && !PAIR && p.kd2; + const int kbt = (vt ? 2 * KB : KB) / KD / (kd2t ? 2 : 1); // KD 2 / kd2: stages of two 64-K sub-blocks + for (int kb = 0; kb < kbt; kb++, it++) { + if constexpr (SW) { + const int s = it % NST; + mbar_wait_cl2(bar_empty + 8 * s, ((it / NST) & 1) ^ 1); + const uint32_t fb = bar_full + 8 * s; + const uint32_t sa = sbase + s * SBYTES, sb = sa + A_BYTES; + const uint32_t fbl = mapa_sh(fb, swlead); // leader's full barrier tracks both CTAs' bytes + __syncwarp(); + (void)sa; + if (elect_one()) { + if (swrank == swlead) mbar_expect_tx(fb, 2 * 8192); // both CTAs' attn halves (A: converters) + tma_load_2d_cg2(sb, &tB2, kb * KE, m0 + 64 * (int)(swrank & 1u), fbl, kpol); // 64 attn rows (B) + } + __syncwarp(); + continue; + } + if (PAIR) { + const int s = it % NST; + // o_proj pair producer stage-empty wait test-first, then suspend-hinted cluster try_wait + // (producer warp sleeps instead of spinning; sync only, numerics identical) + if (EPI == EPI_OPROJ) { if (!mbar_test_cl2(bar_empty + 8 * s, ((it / NST) & 1) ^ 1)) mbar_wait_cl2_hint(bar_empty + 8 * s, ((it / NST) & 1) ^ 1); } + else mbar_wait_cl2(bar_empty + 8 * s, ((it / NST) & 1) ^ 1); + const uint32_t fb = bar_full + 8 * s; + const uint32_t sa = sbase + s * SBYTES, sb = sa + A_BYTES; + const uint32_t fbl = mapa_sh(fb, 0); // leader's full barrier tracks both CTAs' bytes + __syncwarp(); +#ifdef ABL_PROBE + if (p.abl & 4) { if (elect_one() && rank == 0) mbar_arrive(fb); __syncwarp(); continue; } +#endif + if (elect_one()) { // whole warp waits, one elected lane issues expect_tx + both TMAs + // o_proj pair tail sub-tile: each CTA loads (256/spl)/2 Wo rows (tB1 box) instead of BN/2 + const int bhalf = (EPI == EPI_OPROJ && sub >= 0) ? ((256 / spl) >> 1) : (BN >> 1); + const bool bpre = EPI == EPI_OPROJ && it < opre; // B half issued pre-wait + if (rank == 0) mbar_expect_tx(fb, bpre ? 2u * KD * (uint32_t)A_BYTES : 2u * KD * (uint32_t)(A_BYTES + bhalf * 128)); // both CTAs: A 16 KB + B (BN/2 rows) per sub-block + if (KD == 2) { +#pragma unroll + for (int jd = 0; jd < KD; jd++) { // sub-block jd: A at sa + 16 KB jd, B at sa + 32 KB + 8 KB jd + tma_load_2d_cg2(sa + 16384u * jd, &tA, (kb * KD + jd) * KE, m0, fbl, kpol); + if (!bpre) { + if (EPI == EPI_OPROJ && sub >= 0) // tail sub-tile (tB1 box of bhalf rows) + tma_load_2d_cg2(sa + 32768u + KBOFF * jd, &tB1, (kb * KD + jd) * KE, nt * 256 + sub * (256 / spl) + bhalf * (int)rank, fbl, kpol); + else + tma_load_2d_cg2(sa + 32768u + KBOFF * jd, &tB0, (kb * KD + jd) * KE, nt * BN + (BN >> 1) * (int)rank, fbl, kpol); + } + } + } else if (bpre) { + tma_load_2d_cg2(sa, &tA, kb * KE, m0, fbl, kpol); + } else if (vt) { + tma_load_2d_cg2(sa, &tB4, kb * 64, m0, fbl, kpol); + tma_load_2d_cg2(sb, &tB3, kb * 64, nt * 256 - 4608 + 128 * (int)rank, fbl, kpol); + } else { + tma_load_2d_cg2(sa, &tA, kb * KE, m0, fbl, kpol); + if (EPI == EPI_OPROJ && sub >= 0) + tma_load_2d_cg2(sb, &tB1, kb * KE, nt * 256 + sub * (256 / spl) + bhalf * (int)rank, fbl, kpol); + else + tma_load_2d_cg2(sb, &tB0, kb * KE, nt * BN + (BN >> 1) * (int)rank, fbl, kpol); + } + } + __syncwarp(); + continue; + } + if (kd2t) { + // stage s (64 KB) = {A sub 0, A sub 1, B sub 0, B sub 1} (16 KB each, 128B swizzle) + const int s = it % 3; + mbar_wait(bar_empty + 8 * s, ((it / 3) & 1) ^ 1); + const uint32_t fb = bar_full + 8 * s; + __syncwarp(); + if (elect_one()) { + const bool bpre = it < opre; // B already issued pre-wait + mbar_expect_tx(fb, bpre ? 2u * (uint32_t)A_BYTES : 2u * (uint32_t)(A_BYTES + BN * 128)); + const uint32_t sa = sbase + (uint32_t)s * 65536u; +#pragma unroll + for (int jd = 0; jd < 2; jd++) { + tma_load_2d_hint(sa + 16384u * jd, &tA, (2 * kb + jd) * KE, m0, fb, kpol); + if (!bpre) tma_load_2d_hint(sa + 32768u + 16384u * jd, &tB0, (2 * kb + jd) * KE, nt * BN, fb, kpol); + } + } + __syncwarp(); + continue; + } + const int s = it % TSTAGES; + const uint32_t ph = (it / TSTAGES) & 1; + CPT(pe0); + // 1-CTA QKV producer stage-empty wait test-first, then suspend-hinted try_wait (producer warp + // sleeps instead of polling, freeing issue slots for the epilogue warps; sync only, bit-identical) + if (MC) mbar_wait_cl2(bar_empty + 8 * s, ph ^ 1); + // T<2048 non-QF QKV (ring-handshake bound per ABL) producer empty wait = plain try_wait spin + // (no suspend-wake latency on stage refills); QF instantiations keep test-first + hint + // also the fp16-operand QF QKV instantiation (T>=2048, S<256: 16x128 class, Q8 = false) + else if (EPI == EPI_QKV && (!QF || !Q8)) mbar_wait(bar_empty + 8 * s, ph ^ 1); + else if (EPI == EPI_QKV) { if (!mbar_test(bar_empty + 8 * s, ph ^ 1)) mbar_wait_hint(bar_empty + 8 * s, ph ^ 1); } + else mbar_wait(bar_empty + 8 * s, ph ^ 1); + CPT(pe1); + CPA(8, pe1 - pe0); + CPA(11, 1); + const uint32_t fb = bar_full + 8 * s; + __syncwarp(); +#ifdef TC_PROBE + if (p.pmode == 1 || p.pmode == 3) { if (elect_one()) mbar_arrive(fb); __syncwarp(); continue; } // MMA-only probe +#endif + if (EPI == EPI_OPROJ && !SW && it < opre) { + // first-tile stage whose B operand was TMA-loaded before griddepcontrol.wait: A only + if (elect_one()) { + mbar_expect_tx(fb, (uint32_t)A_BYTES); + tma_load_2d_hint(sbase + s * STAGE_BYTES, &tA, kb * KE, m0, fb, kpol); + } + __syncwarp(); + continue; + } + if (elect_one()) { + mbar_expect_tx(fb, EPI == EPI_ROUTER ? (uint32_t)STAGE_BYTES : tx); + const uint32_t sa = sbase + s * STAGE_BYTES, sb = sa + A_BYTES; + const int kx = kb * KE; + if (EPI == EPI_ROUTER) { + const int g = nt * KB + kb, pass = g >> 6, gx = (g & 63) * 32; + tma_load_2d(sa, pass < 2 ? &tA : &tB2, gx, m0, fb); + tma_load_2d(sb, pass == 1 ? &tB1 : &tB0, gx, 0, fb); + } else if (vt) { + const int kv = kb * 64; + tma_load_2d_hint(sa, &tB2, kv, m0, fb, kpol); + if (sub >= 0) tma_load_2d_hint(sb, &tB4, kv, nt * 256 - 4608 + sub * 128, fb, kpol); + else tma_load_2d_hint(sb, &tB3, kv, nt * BN - 4608, fb, kpol); + } else { + if (MC) tma_load_2d_mc(sa + 4096u * mcj, &tB2, kx, m0 + 32 * (int)mcj, fb, mcmask, kpol); // A slice -> 4 CTAs + else if (F16) tma_load_2d_hint(sa, &tA, kx, m0, fb, kpol); + else tma_load_2d(sa, (grouped && m64) ? &tB2 : &tA, kx, m0, fb); + if (EPI == EPI_QKV && sub >= 0) { + tma_load_2d_hint(sb, &tB1, kx, nt * 256 + sub * (256 / spl), fb, kpol); // tail half (one head) / V quarter + } else if (EPI == EPI_OPROJ && sub >= 0) { + // tail sub-tile: 256/spl Wo rows of the (BN = 256) n tile + tma_load_2d_hint(sb, &tB1, kx, nt * 256 + sub * (256 / spl), fb, kpol); + } else if (EPI == EPI_QKV || EPI == EPI_OPROJ) { + tma_load_2d_hint(sb, &tB0, kx, nt * BN, fb, kpol); + } else if (EPI == EPI_GATEUP) { + // gate/up maps use 64-row boxes. Full tile: gate rows r0..r0+127 -> sb, up -> sb + 16 KB. + // Half tile: 64 gate rows -> sb, 64 up rows -> sb + 8 KB (an N=128 B operand). + // Quarter tile: 32 gate rows -> sb, 32 up rows -> sb + 4 KB (N=64 B operand). + const int r0 = e * INTER + nt * 128 + (sub > 0 ? sub * (128 / spl) : 0); + if (sub >= 0 && spl == 4) { + tma_load_2d(sb, &tB3, kx, r0, fb); + tma_load_2d(sb + 4096, &tB4, kx, r0, fb); + } else if (sub < 0) { + tma_load_2d(sb, &tB0, kx, r0, fb); + tma_load_2d(sb + 8192, &tB0, kx, r0 + 64, fb); + tma_load_2d(sb + 16384, &tB1, kx, r0, fb); + tma_load_2d(sb + 24576, &tB1, kx, r0 + 64, fb); + } else { + tma_load_2d(sb, &tB0, kx, r0, fb); + tma_load_2d(sb + 8192, &tB1, kx, r0, fb); + } + } else { + // down map uses 128-row boxes: full tile = 2 boxes, half tile = 1 box + const int r0 = e * HID + nt * TBN + (sub > 0 ? 128 : 0); + tma_load_2d(sb, &tB0, kx, r0, fb); + if (sub < 0) tma_load_2d(sb + 16384, &tB0, kx, r0 + 128, fb); + } + } + } // elect_one + __syncwarp(); +#ifdef TC_PROBE + { CPT(pe2); CPA(9, pe2 - pe1); } +#endif + } + } + if (PAIR || SW) { + // drain: every stage's last multicast commit has landed in this CTA before it can exit + for (int i = 0; i < NST; i++, it++) mbar_wait_cl2(bar_empty + 8 * (it % NST), ((it / NST) & 1) ^ 1); + } + } + } else if (warp == 1) { + if ((!PAIR || rank == 0) && (!SW || swrank == swlead)) { // PAIR / SW: the leader CTA issues the cta_group::2 MMAs + // ---------------- MMA issuer: the WHOLE warp runs the loop (barrier waits, descriptor / ring arithmetic + // stay warp-uniform -> uniform registers), one elected lane issues the tcgen05.mma / commit (CUTLASS-style + // elect_one_sync). probe at T=2984 (clock64, o_proj): with the former lane-0-only divergent loop the + // 4 MMAs of a k-block took ~222 cycles to ISSUE independent of N (N=128 tensor time = 256/kb), and the + // loop ran at ~512-530 cycles/kb for BOTH N=256 and N=128 even with no TMA (MMA-only) -> issue-bound at + // N=128; feed-only (no MMA) ran ~555/kb at N=256, skeleton (no TMA, no MMA) ~317/kb. + int it = 0, tc = 0; + int rs = 0; // smem ring stage (incremental, == it % TSTAGES) + uint32_t rph = 0; // its full-barrier parity (== (it / TSTAGES) & 1) + const uint64_t adesc0 = make_sdesc(sbase); // stage-0 A descriptor; others = + immediates +#ifdef TC_PROBE + const long long mt0 = clock64(); + const int pmode = p.pmode; +#else + constexpr int pmode = 0; +#endif + for (int t = cid; t < num_tiles; t += ncl, tc++) { + const int buf = tc & 1; + const uint32_t aph = (tc >> 1) & 1; + int idesc_tf32 = (int)IDESC_TF32; + uint32_t idesc_h = idesc_f16; + bool f8t = F8; // VS: per-tile operand kind + const bool kd2t = EPI == EPI_OPROJ && !F8 && !SW && !PAIR && p.kd2; + int kbt = KB / KD / (kd2t ? 2 : 1); + if (VS) { + int m0, mend, e, nt, sub; + coords(t, m0, mend, e, nt, sub); + if (nt * BN >= 4608) { f8t = false; kbt = 2 * KB; } + } + int tsub = -1; // this tile's sub index (pair N width) + if ((EPI == EPI_QKV || EPI == EPI_OPROJ) && nsplit > 0) { + int m0, mend, e, nt, sub; + coords(t, m0, mend, e, nt, sub); + tsub = sub; + if (sub >= 0) // N = 256 / spl (QKV: 128; OPROJ: 128 or 64) + idesc_h = (1u << 4) | ((uint32_t)((256 / spl) >> 3) << 17) | ((128u >> 4) << 24); + } + if (grouped) { + int m0, mend, e, nt, sub; + coords(t, m0, mend, e, nt, sub); + if (sub >= 0) // N = 256 / spl (128 or 64) + idesc_tf32 = (int)((IDESC_TF32 & ~(0x3Fu << 17)) | ((uint32_t)((256 / spl) >> 3) << 17)); + // remainder tile with <= 64 valid rows: M=64 MMA (idesc M field bits 24..28 = M >> 4) + if (mend - m0 <= 64) idesc_tf32 = (int)(((uint32_t)idesc_tf32 & ~(0x1Fu << 24)) | ((64u >> 4) << 24)); + } + CPT(te0); + if (EPI == EPI_OPROJ && PAIR) { if (!mbar_test_cl2(bar_tempty + 8 * buf, aph ^ 1)) mbar_wait_cl2_hint(bar_tempty + 8 * buf, aph ^ 1); } // o_proj pair MMA issuer accumulator-free wait test-first + suspend hint + else if (PAIR || SW) mbar_wait_cl2(bar_tempty + 8 * buf, aph ^ 1); // both CTAs' epilogues drained it + else if (!mbar_test(bar_tempty + 8 * buf, aph ^ 1)) mbar_wait_hint(bar_tempty + 8 * buf, aph ^ 1); // test-first (no suspend round trip when the accumulator is already drained) + CPT(te1); + CPA(3, te1 - te0); + tc_fence_after(); + const uint32_t dt = tbase + buf * TBN; + const uint32_t idsc = F16 ? idesc_h : (uint32_t)idesc_tf32; + if constexpr (SW) { + // swap-AB pair MMA: M = 256 (2 x 128 Wo rows), N = 128 tokens (64 per CTA), K = 16 per MMA + constexpr uint32_t IDESC_SW = (1u << 4) | ((128u >> 3) << 17) | ((256u >> 4) << 24); + for (int kb = 0; kb < kbt; kb++) { + mbar_wait_cl2(bar_full + 8 * rs, rph); + tc_fence_after(); + const uint64_t ad = adesc0 + (uint64_t)(rs * (SBYTES >> 4)); + const uint64_t bd = ad + (uint64_t)(A_BYTES >> 4); + __syncwarp(); + if (elect_one()) { + mma_f16_cg2(dt, ad, bd, IDESC_SW, kb > 0 ? 1u : 0u); + mma_f16_cg2(dt, ad + 2, bd + 2, IDESC_SW, 1u); + mma_f16_cg2(dt, ad + 4, bd + 4, IDESC_SW, 1u); + mma_f16_cg2(dt, ad + 6, bd + 6, IDESC_SW, 1u); + mma_commit_cg2m(bar_empty + 8 * rs, swmask); // stage free in both CTAs + } + __syncwarp(); + if (++rs == NST) { rs = 0; rph ^= 1u; } + } + it += kbt; + __syncwarp(); + if (elect_one()) mma_commit_cg2m(bar_tfull + 8 * buf, swmask); // accumulator complete (both CTAs) + __syncwarp(); + continue; + } + if (PAIR) { + // leader: m256n256k16 cta_group::2 MMAs, A = both CTAs' 128-row A halves, B = both 128-row B halves + const uint32_t pN = (EPI == EPI_OPROJ && tsub >= 0) ? (uint32_t)(256 / spl) : (uint32_t)BN; // tail sub-tile N + const uint32_t IDESC_F16_M256 = (1u << 4) | ((pN >> 3) << 17) | ((256u >> 4) << 24); // N = BN + for (int kb = 0; kb < kbt; kb++) { + mbar_wait_cl2(bar_full + 8 * rs, rph); + tc_fence_after(); + const uint64_t ad = adesc0 + (uint64_t)(rs * (SBYTES >> 4)); + const uint64_t bd = ad + (uint64_t)(A_BYTES >> 4); + __syncwarp(); +#ifdef ABL_PROBE + if (p.abl & 2) { if (elect_one()) mma_commit_cg2(bar_empty + 8 * rs); __syncwarp(); if (++rs == NST) { rs = 0; rph ^= 1u; } continue; } +#endif + if (KD == 2) { + if (elect_one()) { +#pragma unroll + for (int jd = 0; jd < KD; jd++) { // A sub-block at +16 KB jd, B at +32 KB + 8 KB jd + const uint64_t a2 = ad + (uint64_t)((16384 * jd) >> 4), b2 = ad + (uint64_t)((32768 + KBOFF * jd) >> 4); + if (F8 && f8t) { // CG 4: e4m3, K = 32 per MMA (128 B row per sub-block) + mma_f8_cg2(dt, a2, b2, IDESC_F16_M256, (kb > 0 || jd > 0) ? 1u : 0u); + mma_f8_cg2(dt, a2 + 2, b2 + 2, IDESC_F16_M256, 1u); + mma_f8_cg2(dt, a2 + 4, b2 + 4, IDESC_F16_M256, 1u); + mma_f8_cg2(dt, a2 + 6, b2 + 6, IDESC_F16_M256, 1u); + } else { + mma_f16_cg2(dt, a2, b2, IDESC_F16_M256, (kb > 0 || jd > 0) ? 1u : 0u); + mma_f16_cg2(dt, a2 + 2, b2 + 2, IDESC_F16_M256, 1u); + mma_f16_cg2(dt, a2 + 4, b2 + 4, IDESC_F16_M256, 1u); + mma_f16_cg2(dt, a2 + 6, b2 + 6, IDESC_F16_M256, 1u); + } + } + mma_commit_cg2(bar_empty + 8 * rs); + } + } else + if (elect_one()) { + if (f8t) mma_f8_cg2(dt, ad, bd, IDESC_F16_M256, kb > 0 ? 1u : 0u); else mma_f16_cg2(dt, ad, bd, IDESC_F16_M256, kb > 0 ? 1u : 0u); + if (f8t) mma_f8_cg2(dt, ad + 2, bd + 2, IDESC_F16_M256, 1u); else mma_f16_cg2(dt, ad + 2, bd + 2, IDESC_F16_M256, 1u); + if (f8t) mma_f8_cg2(dt, ad + 4, bd + 4, IDESC_F16_M256, 1u); else mma_f16_cg2(dt, ad + 4, bd + 4, IDESC_F16_M256, 1u); + if (f8t) mma_f8_cg2(dt, ad + 6, bd + 6, IDESC_F16_M256, 1u); else mma_f16_cg2(dt, ad + 6, bd + 6, IDESC_F16_M256, 1u); + mma_commit_cg2(bar_empty + 8 * rs); // stage free in both CTAs once these MMAs retire + } + __syncwarp(); + if (++rs == NST) { rs = 0; rph ^= 1u; } + } + it += kbt; + __syncwarp(); + if (elect_one()) mma_commit_cg2(bar_tfull + 8 * buf); // accumulator complete (both CTAs) + __syncwarp(); + continue; + } + // issue diet: the k-block body has no per-MMA descriptor construction (stage descriptors = + // precomputed base + immediates, +2 per 16/8-K step = 32 B), no it % TSTAGES / it / TSTAGES + // (incremental ring index + parity), kb = 0 peeled so the accumulate predicate is a constant, and + // the full-barrier wait uses try_wait with a suspend-time hint (no hot polling loop). + auto kbody = [&](auto first_tag) { + constexpr bool FIRST = decltype(first_tag)::value; + CPT(m0c); + // T<2048 non-QF QKV (1 tile/CTA, ring-handshake bound per ABL): MMA full wait = plain try_wait + // spin (no suspend-wake latency per k-block); other instantiations keep the suspend hint. Sync only. + if constexpr (EPI == EPI_QKV && (!QF || !Q8)) mbar_wait(bar_full + 8 * rs, rph); // + fp16 QF + else mbar_wait_hint(bar_full + 8 * rs, rph); + CPT(m1c); + CPA(0, m1c - m0c); + CPA(4, 1); + tc_fence_after(); + const uint64_t ad = adesc0 + (uint64_t)(rs * (STAGE_BYTES >> 4)); + const uint64_t bd = ad + (uint64_t)(A_BYTES >> 4); + __syncwarp(); + if (pmode >= 2) { + if (elect_one()) { if (MC) mma_commit_mc(bar_empty + 8 * rs, mcmask); else mma_commit(bar_empty + 8 * rs); } + } else if (elect_one()) { + if (F8 && f8t) { + mma_f8_ss(dt, ad, bd, idsc, FIRST ? 0u : 1u); + mma_f8_ss(dt, ad + 2, bd + 2, idsc, 1u); + mma_f8_ss(dt, ad + 4, bd + 4, idsc, 1u); + mma_f8_ss(dt, ad + 6, bd + 6, idsc, 1u); + } else if (F16) { + mma_f16_ss(dt, ad, bd, idsc, FIRST ? 0u : 1u); + mma_f16_ss(dt, ad + 2, bd + 2, idsc, 1u); + mma_f16_ss(dt, ad + 4, bd + 4, idsc, 1u); + mma_f16_ss(dt, ad + 6, bd + 6, idsc, 1u); + } else { + mma_tf32(dt, ad, bd, idsc, FIRST ? 0u : 1u); + mma_tf32(dt, ad + 2, bd + 2, idsc, 1u); + mma_tf32(dt, ad + 4, bd + 4, idsc, 1u); + mma_tf32(dt, ad + 6, bd + 6, idsc, 1u); + } + if (MC) mma_commit_mc(bar_empty + 8 * rs, mcmask); else mma_commit(bar_empty + 8 * rs); + } + __syncwarp(); + CPT(m2c); + CPA(1, m2c - m1c); + CPT(m3c); + CPA(2, m3c - m2c); + if (++rs == NST) { rs = 0; rph ^= 1u; } + }; + if (kd2t) { + // 3-stage ring of 64 KB double-K stages (same MMA k order as the 64-K path) +#pragma unroll 1 + for (int kb = 0; kb < kbt; kb++) { + mbar_wait(bar_full + 8 * rs, rph); // plain try_wait spin (no suspend-wake latency per double-K stage) + tc_fence_after(); + const uint64_t ad0 = adesc0 + (uint64_t)(rs * (65536 >> 4)); + __syncwarp(); + if (elect_one()) { +#pragma unroll + for (int jd = 0; jd < 2; jd++) { + const uint64_t a2 = ad0 + (uint64_t)((16384 * jd) >> 4), b2 = ad0 + (uint64_t)((32768 + 16384 * jd) >> 4); + mma_f16_ss(dt, a2, b2, idsc, (kb > 0 || jd > 0) ? 1u : 0u); + mma_f16_ss(dt, a2 + 2, b2 + 2, idsc, 1u); + mma_f16_ss(dt, a2 + 4, b2 + 4, idsc, 1u); + mma_f16_ss(dt, a2 + 6, b2 + 6, idsc, 1u); + } + mma_commit(bar_empty + 8 * rs); + } + __syncwarp(); + if (++rs == 3) { rs = 0; rph ^= 1u; } + } + it += kbt; + __syncwarp(); + if (elect_one()) mma_commit(bar_tfull + 8 * buf); + __syncwarp(); + continue; + } + kbody(std::integral_constant{}); +#pragma unroll 1 + for (int kb = 1; kb < kbt; kb++) kbody(std::integral_constant{}); + it += kbt; + __syncwarp(); + if (elect_one()) mma_commit(bar_tfull + 8 * buf); + __syncwarp(); + } +#ifdef TC_PROBE + CPA(5, clock64() - mt0); +#endif + PRB(3); + } + } else if constexpr (W32) { + // ---------------- W32 converters (warps 2, 3, 64 threads): raw half q = 2 g + h (k 32h..32h+31 of k-block + // g) -> fp16 x 2^4 chunks 4h..4h+3 of each B row. Raw row r: logical 16 B chunk j at physical j ^ (r & 7); + // fp16 row r: logical chunk c at c ^ (r & 7) (the layout a 128B-swizzle TMA of the fp16 copy would produce). + const int ct = (warp - 2) * 32 + lane; + int g = 0; + for (int t = cid; t < num_tiles; t += ncl) { + int m0, mend, e, nt, sub; + coords(t, m0, mend, e, nt, sub); + const int nu = (sub >= 0 ? 256 / spl : BN) * 4; // 16 B output units per half + for (int kb = 0; kb < KB; kb++, g++) { + const int s = g % NST; + mbar_wait(bar_empty + 8 * s, ((g / NST) & 1) ^ 1); // MMAs of the previous use of stage s done + uint8_t* bst = smem + s * SBYTES + A_BYTES; +#pragma unroll 1 + for (int h = 0; h < 2; h++) { + const int q = 2 * g + h, r = q & 3; + mbar_wait(w32_raw_full + 8 * r, (q >> 2) & 1); + const uint8_t* raw = smem + w32_raw_off(r); +#pragma unroll 2 + for (int u = ct; u < nu; u += 64) { + const int row = u >> 2, cl = u & 3, sw = row & 7; + const uint4 a = *reinterpret_cast(raw + row * 128 + 16 * ((2 * cl) ^ sw)); + const uint4 b = *reinterpret_cast(raw + row * 128 + 16 * ((2 * cl + 1) ^ sw)); + uint4 o; + o.x = pack_h2(__uint_as_float(a.x) * 16.f, __uint_as_float(a.y) * 16.f); + o.y = pack_h2(__uint_as_float(a.z) * 16.f, __uint_as_float(a.w) * 16.f); + o.z = pack_h2(__uint_as_float(b.x) * 16.f, __uint_as_float(b.y) * 16.f); + o.w = pack_h2(__uint_as_float(b.z) * 16.f, __uint_as_float(b.w) * 16.f); + *reinterpret_cast(bst + row * 128 + 16 * ((4 * h + cl) ^ sw)) = o; + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // generic smem writes -> tcgen05.mma + __syncwarp(); + if (elect_one()) { mbar_arrive(w32_raw_empty + 8 * r); mbar_arrive(bar_full + 8 * s); } + } + } + } + } else if constexpr (EPI == EPI_QKV && !QF) { + // ---------------- (T < 2048): idle warps 2, 3 execute the side-stream Wo -> fp16 convert units [0, csteal) + // while the GEMM runs (the side convert grid then only launches the remaining units + router-weight units, so it + // no longer floods the SMs freed by the QKV tail ahead of flash attention). Warp k of the 2 x grid steal warps + // owns the contiguous unit slice [k csteal / (2 grid), (k + 1) csteal / (2 grid)) (<= 8 units): claims them all + // at once (claim protocol of side_steal.cuh: o_proj's acquire may steal unclaimed ones), then streams each + // claimed unit (1024 float4 fp32 Wo) as two 8 KB halves through a 2-slot smem ring (cp.async.bulk, half h + 1 + // in flight while half h is converted) and writes fp16 x 2^4 - bit-identical bytes to conv_unit_warp / + // convert_w16_kernel (f8 = 0). Wo is a kernel input and Wo16 is only read by o_proj (after attention), and the + // previous call's readers / discards of Wo16 completed before this grid could launch (PDL chain) -> safe + // before griddepcontrol.wait. + const sidew::ConvJob& J = p.conv; + if (p.csteal > 0 && J.f8 == 0) { + const int w2 = warp - 2; + const int nw = 2 * (int)gdim, wk = 2 * (int)bidx + w2; + const int ua = (int)(((long long)wk * p.csteal) / nw), ub = (int)(((long long)(wk + 1) * p.csteal) / nw); + const bool mine = lane < ub - ua && sidew::claim(J.st, ua + lane, J.ep); + uint32_t own = __ballot_sync(0xffffffffu, mine); + const uint32_t cbuf = sbase + QKV_CONV_OFF + (uint32_t)w2 * 16384u; // slot h: + 8 KB h + const uint32_t cbar = sbase + TSTAGES * STAGE_BYTES + 192 + 16 * w2; // slot h: + 8 h + const float4* sv = reinterpret_cast(smem + QKV_CONV_OFF + w2 * 16384); + const uint64_t rf = first_pol(), kp = keep_pol(); + uint32_t cph = 0; // bit h: parity of slot h + auto issue = [&](int u, int h) { // half h of unit u -> slot h + __syncwarp(); + if (elect_one()) { + mbar_expect_tx(cbar + 8 * h, 8192u); + asm volatile( + "cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1], %2, [%3], %4;" + ::"r"(cbuf + 8192u * (uint32_t)h), "l"(J.src + (size_t)u * 4096 + 2048 * h), "r"(8192u), + "r"(cbar + 8 * h), "l"(rf) : "memory"); + } + __syncwarp(); + }; + auto convert = [&](int u, int h) { + { if (!mbar_test(cbar + 8 * h, (cph >> h) & 1u)) mbar_wait_hint(cbar + 8 * h, (cph >> h) & 1u); } + cph ^= 1u << h; + uint2* d = reinterpret_cast(J.dst) + (size_t)u * 1024 + 512 * h; + const float4* sh = sv + 512 * h; +#pragma unroll 4 + for (int j = 0; j < 16; j++) { + const float4 v = sh[j * 32 + lane]; + st_u2_pol(d + j * 32 + lane, make_uint2(pack_h2(v.x * 16.f, v.y * 16.f), pack_h2(v.z * 16.f, v.w * 16.f)), kp); + } + __syncwarp(); // all lanes read slot h before it is refilled + }; + int cur = own ? __ffs(own) - 1 : -1, ndone = 0; + if (cur >= 0) { own &= own - 1; issue(ua + cur, 0); } + while (cur >= 0) { + issue(ua + cur, 1); + convert(ua + cur, 0); + const int nxt = own ? __ffs(own) - 1 : -1; + if (nxt >= 0) { own &= own - 1; issue(ua + nxt, 0); } + convert(ua + cur, 1); + ndone++; + cur = nxt; + } + // release once for all units of this warp (one membar instead of one per unit) + if (ndone) { + __syncwarp(); // warp-ordered, lane 0's fence below is cumulative (single membar.gl) + if (lane == 0) { asm volatile("red.release.gpu.global.add.u64 [%0], %1;" ::"l"(J.done), "l"((unsigned long long)(ndone)) : "memory"); } + } + } + } + } else if (warp < EW0 + 8) { + // ---------------- epilogue warps EW0..EW0+7 (2..9; QKV: 4..11) + if constexpr (EPI == EPI_QKV) asm volatile("setmaxnreg.inc.sync.aligned.u32 232;\n" ::: "memory"); + if constexpr (EPI == EPI_QKV && !QF) { + // q / k norm weights (kernel inputs) staged once per CTA in smem (QKV_NW_OFF, 1 KB free in the + // barrier area) by the 8 epilogue warps; the RoPE chunk loop reads them as warp-broadcast LDS instead of + // per-chunk global loads (same values -> bit-identical). Named barrier 1 = the 256 epilogue threads. + const int et = (warp - EW0) * 32 + lane; // 0..255 + reinterpret_cast(smem + QKV_NW_OFF)[et] = et < 128 ? __ldg(p.qnw + et) : __ldg(p.knw + et - 128); + asm volatile("bar.sync 1, 256;" ::: "memory"); + } + if constexpr (EPI == EPI_OPROJ) { + // L2 discard of buffers dead once attention has completed (Wqkv16, xn, q, k, V^T, fp16 xn copy): + // griddepcontrol.wait above returned -> QKV GEMM + attention (their only readers) are complete; their next + // writers (prep_qkv / QKV of the NEXT call) are ordered after this call's router/MoE (PDL chain). Done by + // the epilogue warps before their first accumulator wait (they are idle during the mainloop), so the + // router (critical path) only discards Wo16 / attn. Each range is fully rewritten before its next read. + const unsigned long long nth = (unsigned long long)gdim * 256ull; + const unsigned long long gt = (unsigned long long)bidx * 256ull + (unsigned long long)((warp - 2) * 32 + lane); + for (int r = 0; r < p.dl.n; r++) { + const char* base = reinterpret_cast(p.dl.p[r]); + const unsigned long long nl = (p.dl.bytes[r] + 127) >> 7; + for (unsigned long long i = gt; i < nl; i += nth) + asm volatile("discard.global.L2 [%0], 128;" ::"l"(base + (i << 7)) : "memory"); + } + // second-wave MoE weight L2 prefetch (expert weights are kernel INPUTS; fire-and-forget, results never + // depend on it). Fused fp16 MoE (T < 2048, one group per expert): gate/up item t = (expert t / 12, n-tile + // t % 12 of 64 gate + 64 up rows), rotated k order starting at (t * krot) % 32. DRAM is idle during o_proj. + if (p.pfg != nullptr && (warp - 2) * 32 + lane < 128) { + const int lt = (warp - 2) * 32 + lane, r = lt & 63; + const float* pb = lt < 64 ? p.pfg : p.pfu; + for (int t = p.pf_t0 + bidx; t < p.pf_t1; t += gdim) { + const int e = t / 12, nt = t - e * 12; + const char* rowp = reinterpret_cast(pb + ((size_t)e * INTER + nt * 64 + r) * HID); + const int k0 = p.pf_krot > 0 ? (t * p.pf_krot) % (HID / 64) : 0; + const int n1 = k0 + p.pf_kb <= HID / 64 ? p.pf_kb : HID / 64 - k0; + asm volatile("cp.async.bulk.prefetch.L2.global [%0], %1;" ::"l"(rowp + k0 * 256), "r"((uint32_t)(n1 * 256)) : "memory"); + if (n1 < p.pf_kb) + asm volatile("cp.async.bulk.prefetch.L2.global [%0], %1;" ::"l"(rowp), "r"((uint32_t)((p.pf_kb - n1) * 256)) : "memory"); + } + } + } + // o_proj fp8 dequant row factor hoisted out of the per-tile loop (vmax final after the PDL wait) + const float rf8c = (EPI == EPI_OPROJ && F8) ? 1024.f / f8_scale(__uint_as_float(*p.vmax) * 0.0009765625f, 7) : 0.f; + const int q = warp & 3; + const int half = (warp - EW0) >> 2; + const int row = q * 32 + lane; + int tc = 0; + // OPROJ TMA epilogue I/O: per-warp 2 x 2 KB slots (32 rows x 16 fp32 = 64 B rows, 64B swizzle: 16 B unit j of + // row r at unit j ^ ((r >> 1) & 3), conflict-free per quarter warp) + one mbarrier per slot; rph = slot parities + const uint32_t opj_slot0 = sbase + OPJ_STG_OFF + (uint32_t)(warp - 2) * 4096u; + const uint32_t opj_bar0 = sbase + TSTAGES * STAGE_BYTES + 512 + (uint32_t)(warp - 2) * 16u; + uint32_t rph = 0; + int opj_row0 = 0; // first tile row of this warp (set per tile) + // lane 0 only: TMA load of the resid half-chunk k (columns col .. col+15, rows opj_row0 .. +31) into slot k & 1 + // slot sl (0..OSL-1): slots 0, 1 at opj_slot0, slots 2, 3 (OP4) in the freed ring tail; barriers of + // slots 2, 3 at +128 B after the 16 slot-0/1 barriers + const uint32_t opj_slotx = sbase + (uint32_t)(NST * SBYTES) + (uint32_t)(warp - 2) * 4096u; + const uint32_t opj_barx = opj_bar0 + 128u; + auto opj_saddr = [&](int sl) -> uint32_t { return sl < 2 ? opj_slot0 + 2048u * (uint32_t)sl : opj_slotx + 2048u * (uint32_t)(sl - 2); }; + auto opj_baddr = [&](int sl) -> uint32_t { return sl < 2 ? opj_bar0 + 8u * (uint32_t)sl : opj_barx + 8u * (uint32_t)(sl - 2); }; + auto opj_rload = [&](int k, int col) { + const int sl = OP4 ? (k & 3) : (k & 1); + const uint32_t bar = opj_baddr(sl); + mbar_expect_tx(bar, 2048u); + tma_load_2d(opj_saddr(sl), &tB4, col, opj_row0, bar); + }; + for (int t = cid; t < num_tiles; t += ncl, tc++) { + int m0, mend, e, nt, sub; + coords(t, m0, mend, e, nt, sub); + opj_row0 = m0 + q * 32; + if constexpr (EPI == EPI_OPROJ && F8 && !SW) { + // per-tile dequant factor table fs[i] = wsc[nt*BN + i] * rf8 (exact pow2 x pow2, same product the + // per-element FMUL2 formed before -> bit-identical), one column per epilogue thread. Named barrier 1 + // (the 256 epilogue threads) before (previous tile's reads done) and after (table visible). + float* fst = reinterpret_cast(smem + OPJ_FS_OFF); + const int et = (warp - EW0) * 32 + lane, col = nt * BN + et; + const float fv = col < HID ? __ldg(p.wsc + col) * rf8c : 0.f; + asm volatile("bar.sync 1, 256;" ::: "memory"); + fst[et] = fv; + asm volatile("bar.sync 1, 256;" ::: "memory"); + } + const int tbn = ((grouped || EPI == EPI_OPROJ) && sub >= 0) ? 256 / spl : (grouped ? TBN : BN); // this tile's N width + const int sub_off = sub > 0 ? 1 : 0; + const int buf = tc & 1; + const uint32_t aph = (tc >> 1) & 1; + if constexpr (SW) { + // ---- swapped epilogue: lane = output column ncol = nt*128 + 32q + lane, TMEM column = token. + // Warp (q, half) owns tokens m0 + 64 half + 32 c (c = 0, 1) x columns 32q .. +31. Per 32-token chunk: + // resid box pair (32 tokens x 16 cols, 64B swizzle) TMA-loaded into the 2 per-warp slots, h written + // in place (element (t, col) by lane col), then lane = token re-reads its row for the RMS statistics, + // and lane 0 TMA-stores both boxes (rows >= M clipped). + const int ncol0 = nt * BN + 32 * q; + const float bcol = __ldg(p.bias0 + ncol0 + lane); + const int tk0 = m0 + 64 * half; + if (lane == 0 && tk0 < p.M) { + asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); + opj_row0 = tk0; + opj_rload(0, ncol0); + opj_rload(1, ncol0 + 16); + } + mbar_wait_cl2(bar_tfull + 8 * buf, aph); + tc_fence_after(); + const uint32_t trw = tbase + ((uint32_t)(q * 32) << 16) + buf * TBN + 64 * half; + float acc[64]; + tmem_ld32x2(trw, acc, trw + 32, acc + 32); + tc_fence_before(); + __syncwarp(); + if (elect_one()) tempty_arrive(buf); + const int sl = lane >> 4, uj = (lane & 15) >> 2, ue = lane & 3; +#pragma unroll 1 + for (int c = 0; c < 2; c++) { + const int tok0 = tk0 + 32 * c; + if (tok0 >= p.M) break; // warp-uniform + if (c == 1 && lane == 0) { + asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); // chunk 0 stores read the slots + opj_row0 = tok0; + opj_rload(0, ncol0); + opj_rload(1, ncol0 + 16); + } + mbar_wait(opj_bar0, rph & 1u); + mbar_wait(opj_bar0 + 8u, (rph >> 1) & 1u); + rph ^= 3u; + uint8_t* sbuf = smem + OPJ_STG_OFF + (warp - 2) * 4096; + float* colp = reinterpret_cast(sbuf + sl * 2048 + ue * 4); +#pragma unroll + for (int t = 0; t < 32; t++) { + float* ep = reinterpret_cast(reinterpret_cast(colp) + t * 64 + ((uj ^ ((t >> 1) & 3)) << 4)); + *ep = *ep + fmaf(acc[32 * c + t], 64.f, bcol); // h = resid + (acc * 2^6 + bias) + } + __syncwarp(); + // statistics: lane = token row, 32 columns = both slots' row `lane` + float2 ss2 = make_float2(0.f, 0.f); + // the 4 physical 16 B chunks of row `lane` are LOADED in swizzled order (load kk reads chunk + // kk ^ sx, sx = (lane >> 1) & 3: 8 lanes of a phase hit 8 distinct bank groups; was 4-way conflict + // on lane * 64 + 16 j), then accumulated in the original physical order j = 0..3 (chunk j sits in + // r4[j ^ sx], picked with compile-time-indexed selects) -> bit-identical sums + const int sx = (lane >> 1) & 3; +#pragma unroll + for (int s2 = 0; s2 < 2; s2++) { + float4 r4[4]; +#pragma unroll + for (int kk = 0; kk < 4; kk++) + r4[kk] = *reinterpret_cast(sbuf + s2 * 2048 + lane * 64 + ((kk ^ sx) << 4)); +#pragma unroll + for (int j = 0; j < 4; j++) { + const float4 v4 = sx == 0 ? r4[j] : (sx == 1 ? r4[j ^ 1] : (sx == 2 ? r4[j ^ 2] : r4[j ^ 3])); + ss2 = ffma2(make_float2(v4.x, v4.y), make_float2(v4.x, v4.y), ss2); + ss2 = ffma2(make_float2(v4.z, v4.w), make_float2(v4.z, v4.w), ss2); + } + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // generic smem writes -> TMA + __syncwarp(); + if (lane == 0) { +#pragma unroll + for (int s2 = 0; s2 < 2; s2++) + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group [%0, {%1, %2}], [%3];" ::"l"( + (uint64_t)&tB3), "r"(ncol0 + 16 * s2), "r"(tok0), "r"(opj_slot0 + 2048u * (uint32_t)s2) + : "memory"); + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + } + if (tok0 + lane < p.M) atomicAdd(p.ssq + tok0 + lane, ss2.x + ss2.y); + } + continue; + } + // M=64 accumulator layout (1-CTA): row r lives in TMEM lane (r % 16) + 32 * (r / 16), i.e. lanes 0-15 of + // each warp quadrant; lanes 16-31 of the quadrant hold nothing for that tile. + const bool m64 = grouped && (mend - m0 <= 64); + const int erow = m64 ? q * 16 + lane : row; + const int pos = m0 + erow; + const bool valid = (!m64 || lane < 16) && pos < mend; +#ifdef ABL_PROBE + if (p.abl & 1) { + if (PAIR) mbar_wait_cl2(bar_tfull + 8 * buf, aph); else mbar_wait(bar_tfull + 8 * buf, aph); + tc_fence_after(); tc_fence_before(); __syncwarp(); + if (elect_one()) tempty_arrive(buf); + continue; + } +#endif + // DOWN: prefetch this tile's routing metadata (token index / weight of each row, and the per-lane + // row token indices for the coalesced scatter) BEFORE waiting on the accumulator, so the global-load + // latency overlaps the mainloop of this tile instead of sitting on the epilogue critical path. + int tok = 0; float rw = 0.f; + int rtok[4]; bool rval[4]; + if (EPI == EPI_DOWN) { + if (valid) { tok = __ldg(p.perm_tok + pos); rw = __ldg(p.perm_w + pos); } +#pragma unroll + for (int it = 0; it < 4; it++) { + const int r = it * 8 + (lane >> 2); + rtok[it] = __shfl_sync(0xffffffff, tok, r); + rval[it] = __shfl_sync(0xffffffff, (int)valid, r) != 0; + } + } + // OPROJ: residual of this warp's 32 rows is TMA-loaded per 16-column half-chunk k (column + // on0 + 16 k) into a 2-slot per-warp smem ring; the first two half-chunks are issued here, BEFORE the + // accumulator wait (resid is a kernel input), the rest one half-chunk ahead inside the chunk loop. + const int on0 = nt * BN + (sub >= 0 ? sub * tbn : 0) + half * (tbn >> 1); // o_proj column of chunk 0 + const bool wact = EPI == EPI_OPROJ && m0 + q * 32 < p.M; // warp-uniform: any valid row in this warp + // last tile of this CTA (e4m3 1-CTA o_proj): the operand ring is dead after its tfull, so the resid + // half-chunks k >= 2 are TMA-loaded at once into this warp's 16 KB ring region (one barrier) instead of the + // 2-slot refill chain (store-read wait -> load -> wait per chunk). Same bytes / math. + // also e4m3 2-CTA pairs (OP4): the tfull multicast commit follows every MMA of the leader, which reads + // both CTAs' rings -> both rings dead; half-chunks k >= OSL (= 4) staged, slots 0..3 preloaded as before + const bool tlast = EPI == EPI_OPROJ && (OP4 || !PAIR) && !SW && p.ores != 0 && t + ncl >= num_tiles && (tbn >> 5) > OSL; + const uint32_t tlbar = OP4 ? sbase + (uint32_t)(TSTAGES * STAGE_BYTES + 768) + 8u * (uint32_t)(warp - 2) : opj_barx; + const uint32_t ofreg = sbase + (uint32_t)(warp - 2) * 16384u; + if (EPI == EPI_OPROJ && wact && lane == 0) { + asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); // previous stores done reading slots + opj_rload(0, on0); + opj_rload(1, on0 + 16); + if (OP4) for (int kk = 2; kk < 4 && kk < (tbn >> 5); kk++) opj_rload(kk, on0 + 16 * kk); + // L2 prefetch of the remaining resid half-chunks of this warp's 32 rows (input-only data) before + // the accumulator wait: the in-loop TMA loads (one half-chunk ahead) then hit L2 instead of DRAM + for (int kk = OSL; kk < (tbn >> 5); kk++) + asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile [%0, {%1, %2}];" ::"l"((uint64_t)&tB4), + "r"(on0 + 16 * kk), "r"(opj_row0) : "memory"); + } + // QKV q/k heads: RoPE table prefetch, QPF chunks ahead. A chunk jj (j = q_j0 + jj) = the 8 cos / 8 sin + // values of columns 8j..8j+7 and 64+8j..+7 of this row (transposed tables: float4 group g at cr4[g*32]). + // The first QPF chunks are issued at the start of pass 1, the rest + // QPF chunks ahead inside the RoPE loop, so the L2 latency is no longer paid once per chunk. + // (Issued inside the q/k branch, not before the accumulator wait: keeping them live into the V-head + // branch, whose 128-float row is register-resident, made ptxas spill.) + // e4m3-operand instantiations prefetch no table chunks ahead (register pressure); fp16 keep 3 + constexpr int QPF = F8 ? QKV_QPF_F8 : 3; + uint4 qc[8][2], qs[8][2]; // [chunk][0: cols 8j.., 1: cols 64+8j..] fp16 x 2^-4 + int q_hidx = 0, q_j0 = 0, q_nj = 0; + float q_rx = 0.f; + const uint4* q_cr4 = nullptr; + const uint4* q_sr4 = nullptr; + auto q_ld = [&](int jj) { + const int j = q_j0 + jj; + qc[jj][0] = __ldg(q_cr4 + j * 32); qc[jj][1] = __ldg(q_cr4 + (8 + j) * 32); + qs[jj][0] = __ldg(q_sr4 + j * 32); qs[jj][1] = __ldg(q_sr4 + (8 + j) * 32); + }; + if (EPI == EPI_QKV && QF) { + const bool qfull = BN == 256 && sub < 0; + q_hidx = BN == 256 ? (sub < 0 ? nt * 2 + half : nt * 2 + sub) : nt; + q_j0 = qfull ? 0 : half * 4; + q_nj = qfull ? 8 : 4; + const int posc = pos < p.M ? pos : p.M - 1; // rows past M (zero-filled tile rows): clamp, never stored + q_cr4 = reinterpret_cast(p.cs) + (size_t)(posc >> 5) * 512 + (posc & 31); + q_sr4 = reinterpret_cast(p.sn) + (size_t)(posc >> 5) * 512 + (posc & 31); + if constexpr (F8) q_rx = __ldg(p.qxs + posc); // inverse e4m3 scale of this xn row + } +#ifdef TC_PROBE + const long long ew0 = clock64(); +#endif + // o_proj epilogue warps sleep (test-first + suspend-hint try_wait) during the mainloop instead of + // polling tfull, freeing issue slots for the producer / MMA warps (sync only, numerics identical) + if (EPI == EPI_OPROJ && PAIR) { if (!mbar_test_cl2(bar_tfull + 8 * buf, aph)) mbar_wait_cl2_hint(bar_tfull + 8 * buf, aph); } + else if (EPI == EPI_OPROJ) { if (!mbar_test(bar_tfull + 8 * buf, aph)) mbar_wait_hint(bar_tfull + 8 * buf, aph); } + // T < 2048 QKV epilogue warps sleep on tfull (test-first + suspend hint) during the mainloop (sync only) + else if (EPI == EPI_QKV && !QF) { if (!mbar_test(bar_tfull + 8 * buf, aph)) mbar_wait_hint(bar_tfull + 8 * buf, aph); } + else if (PAIR) mbar_wait_cl2(bar_tfull + 8 * buf, aph); + else mbar_wait(bar_tfull + 8 * buf, aph); +#ifdef TC_PROBE + if (warp == 2 && lane == 0) { CPA(12, clock64() - ew0); CPA(13, 1); } +#endif + if (warp == 2 && lane == 0) { if (tc == 0) PRB(4); PRB(5); } + tc_fence_after(); + if (tlast && wact && lane == 0) { // ring dead (all MMAs of this CTA complete) + mbar_expect_tx(tlbar, (uint32_t)((tbn >> 5) - OSL) * 2048u); + for (int kk = OSL; kk < (tbn >> 5); kk++) + tma_load_2d(ofreg + 2048u * (uint32_t)kk, &tB4, on0 + 16 * kk, opj_row0, tlbar); + } + const uint32_t trow = tbase + ((uint32_t)(q * 32) << 16) + buf * TBN; + if (EPI == EPI_QKV && QF) { + // T >= QKV_F16TAB_MIN_T: fp16 RoPE tables (x 2^-4), accumulator streamed from TMEM in two passes + // BN=256: two heads per tile, warpgroup `half` owns head nt*2+half entirely. + // BN=128 / split tail tile: one head per tile; both warpgroups read the full head row (needed for the + // q/k RMSNorm) and each handles the RoPE chunks j in [half*4, half*4+4) (pairs d <-> d+64). + const bool full = BN == 256 && sub < 0; + const int hidx = q_hidx; + const uint32_t cb = trow + (full ? half * 128 : 0); // this head's 128 accumulator columns + const int b = pos / p.S, s = pos - b * p.S; + if (hidx < 36) { + // ---- q / k head. The accumulator row is NOT kept in registers: pass 1 streams it from TMEM in + // 32-column chunks (bias + sum of squares), pass 2 re-reads the 16 columns of each RoPE chunk + // from TMEM; the freed registers hold the prefetched RoPE tables. TMEM is released after pass 2. + // Arithmetic (op order, accumulator assignment) identical to the former register-resident version. + const float* bb = hidx < 32 ? p.bias0 + hidx * 128 : p.bias1 + (hidx - 32) * 128; +#pragma unroll + for (int jj = 0; jj < QPF; jj++) q_ld(jj); // first RoPE chunks: latency overlaps pass 1 + float2 ssa[4]; +#pragma unroll + for (int i = 0; i < 4; i++) ssa[i] = make_float2(0.f, 0.f); + const uint32_t ycb = full ? cb : cb + 128; // where pass 1 leaves y for pass 2 + const float2 sc16 = make_float2(0.0625f, 0.0625f); + const float* wsc = F8 ? p.qws + hidx * 128 : nullptr; // this head's Wqkv rows + const float2 rx2 = make_float2(q_rx, q_rx); +#pragma unroll + for (int c = 0; c < 4; c++) { + float a[32]; + // bias / Wqkv scale columns of this chunk loaded before the TMEM load wait + float4 qb4[8], qw4[8]; +#pragma unroll + for (int d = 0; d < 8; d++) { + qb4[d] = __ldg(reinterpret_cast(bb + c * 32 + 4 * d)); + if constexpr (F8) qw4[d] = __ldg(reinterpret_cast(wsc + c * 32 + 4 * d)); + } + tmem_ld32(cb + c * 32, a); +#pragma unroll + for (int d = 0; d < 32; d += 4) { // packed FFMA2: acc * 2^-4 + bias, then sum of squares + const float4 b4 = qb4[d >> 2]; + float2 f01 = sc16, f23 = sc16; + if constexpr (F8) { // per-column dequant factor (both scales exact powers of 2) + const float4 w4 = qw4[d >> 2]; + f01 = fmul2(make_float2(w4.x, w4.y), rx2); f23 = fmul2(make_float2(w4.z, w4.w), rx2); + } + const float2 y0 = ffma2(make_float2(a[d], a[d + 1]), f01, make_float2(b4.x, b4.y)); + const float2 y1 = ffma2(make_float2(a[d + 2], a[d + 3]), f23, make_float2(b4.z, b4.w)); + ssa[(d >> 1) & 3] = ffma2(y0, y0, ssa[(d >> 1) & 3]); + ssa[((d + 2) >> 1) & 3] = ffma2(y1, y1, ssa[((d + 2) >> 1) & 3]); + a[d] = y0.x; a[d + 1] = y0.y; a[d + 2] = y1.x; a[d + 3] = y1.y; + } + // dequantized + biased y written back over its accumulator columns (this tile owns the + // buffer until tempty_arrive): pass 2 reads y directly (no bias / scale reloads, no re-FFMA) + // full head per warpgroup: in place. Shared head (BN=128 / split tail): both warpgroups read all + // 4 raw chunks, so each writes ONLY its own RoPE chunks into the unused upper 128 columns of + // this accumulator buffer (the N=128 MMA never writes them) + if (full || (c & 1) == half) tmem_st32_e(ycb + c * 32, a); + } + asm volatile("tcgen05.wait::st.sync.aligned;" ::: "memory"); +#ifdef TC_PROBE + if (warp == 2 && lane == 0) CPA(6, clock64() - ew0); +#endif + const float ss = ((ssa[0].x + ssa[0].y) + (ssa[1].x + ssa[1].y)) + ((ssa[2].x + ssa[2].y) + (ssa[3].x + ssa[3].y)); + // rstd with the output 2^-6 pre-scale folded in (exact power of 2) + // x 2^4 compensates the 2^-4 fp16 table pre-scale (exact): net 2^-2 + const float r = rsqrtf(ss * (1.f / 128.f) + p.eps) * 0.25f; + const float* w = hidx < 32 ? p.qnw : p.knw; + __half* dst = hidx < 32 ? p.q + (((size_t)b * 32 + hidx) * p.S + s) * 128 + : p.k + (((size_t)b * 4 + (hidx - 32)) * p.S + s) * 128; + // FP8 QK^T mode: same row index, 128 e4m3 bytes per row; o (= natural x 2^-6) x (64 x scale) + uint8_t* dst8 = hidx < 32 ? reinterpret_cast(p.q) + (((size_t)b * 32 + hidx) * p.S + s) * 128 + : reinterpret_cast(p.k) + (((size_t)b * 4 + (hidx - 32)) * p.S + s) * 128; + const float q8m = p.qkb ? 64.f * qk8_scale(p.qkb, hidx < 32 ? 0 : 1) : 0.f; + // q8m is an exact power of 2 -> w * (a * (r q8m)) == (w * (a * r)) * q8m (bit-identical) + const float rq = p.qkb ? r * q8m : r; + const float2 rv2 = make_float2(rq, rq); +#if QKV_CST + // target rows of the transposed stores = rows (lane & ~3) + i of this warp (row pointers and + // validity shuffled once per tile; consecutive tokens may straddle a batch boundary) + const int cg4 = lane & 3; + char* ctr[4]; + bool ctv[4]; + { + const unsigned long long rp = (unsigned long long)(p.qkb ? reinterpret_cast(dst8) : reinterpret_cast(dst)); +#pragma unroll + for (int i = 0; i < 4; i++) { + ctr[i] = reinterpret_cast(__shfl_sync(0xffffffffu, rp, (lane & ~3) + i)); + ctv[i] = __shfl_sync(0xffffffffu, (int)valid, (lane & ~3) + i) != 0; + } + } + uint4 cul[4], cuh[4]; + auto tr4 = [&](uint4* u) { // u[c] = own unit c -> u[i] = unit (lane & 3) of row (lane & ~3) + i +#pragma unroll + for (int m = 1; m <= 2; m <<= 1) { + const bool bit = (lane & m) != 0; +#pragma unroll + for (int c0 = 0; c0 < 4; c0++) { + if (c0 & m) continue; + const int c1 = c0 | m; + const uint4 snd = bit ? u[c0] : u[c1]; + uint4 rcv; + rcv.x = __shfl_xor_sync(0xffffffffu, snd.x, m); + rcv.y = __shfl_xor_sync(0xffffffffu, snd.y, m); + rcv.z = __shfl_xor_sync(0xffffffffu, snd.z, m); + rcv.w = __shfl_xor_sync(0xffffffffu, snd.w, m); + if (bit) u[c0] = rcv; else u[c1] = rcv; + } + } + }; +#endif + // RoPE chunk loop, chunk count NJ (8 full head, 4 half head) as a compile-time constant + auto rope = [&](auto nj_tag) { + constexpr int NJ = decltype(nj_tag)::value; + uint2 pl8 = make_uint2(0u, 0u), ph8 = make_uint2(0u, 0u); // held even-chunk e4m3 bytes + float pr_a1[8], pr_a2[8]; // PR2: next (odd) chunk y +#pragma unroll + for (int jj = 0; jj < NJ; jj++) { + constexpr bool PR2 = QKV_PR2 && QPF == 0; // chunk pairs (j0 even -> jj parity == j parity) + if (PR2) { if ((jj & 1) == 0) { q_ld(jj); q_ld(jj + 1); } } + else if (jj + QPF < NJ) q_ld(jj + QPF); // keep QPF chunks in flight + const int j = q_j0 + jj; + float a1[8], a2[8], w1[8], w2[8]; +#ifdef TC_PROBE + const long long rl0 = clock64(); +#endif + if (PR2) { // y of chunks j, j+1 loaded together (one wait) at the even chunk + if ((jj & 1) == 0) + tmem_ld8x4(ycb + j * 8, a1, ycb + 64 + j * 8, a2, ycb + (j + 1) * 8, pr_a1, ycb + 64 + (j + 1) * 8, pr_a2); + else { +#pragma unroll + for (int i = 0; i < 8; i++) { a1[i] = pr_a1[i]; a2[i] = pr_a2[i]; } + } + } else + tmem_ld8x2(ycb + j * 8, a1, ycb + 64 + j * 8, a2); +#ifdef TC_PROBE + if (warp == 2 && lane == 0) CPA(7, clock64() - rl0); +#endif + // a1 / a2 = y (biased, dequantized) from pass 1 + *reinterpret_cast(w1) = __ldg(reinterpret_cast(w + j * 8)); + *reinterpret_cast(w1 + 4) = __ldg(reinterpret_cast(w + j * 8 + 4)); + *reinterpret_cast(w2) = __ldg(reinterpret_cast(w + 64 + j * 8)); + *reinterpret_cast(w2 + 4) = __ldg(reinterpret_cast(w + 64 + j * 8 + 4)); + float c1[8], c2[8], s1[8], s2[8]; + { + auto unpack8 = [](const uint4 u, float* f) { + const uint32_t w4[4] = {u.x, u.y, u.z, u.w}; +#pragma unroll + for (int k = 0; k < 4; k++) { + const float2 t = __half22float2(*reinterpret_cast(&w4[k])); + f[2 * k] = t.x; f[2 * k + 1] = t.y; + } + }; + unpack8(qc[jj][0], c1); unpack8(qc[jj][1], c2); + unpack8(qs[jj][0], s1); unpack8(qs[jj][1], s2); + } + float o1[8], o2[8]; +#pragma unroll + for (int i = 0; i < 8; i += 2) { // packed: x = w * (a * r); RoPE as FMUL2 + FFMA2 + const float2 x1 = fmul2(make_float2(w1[i], w1[i + 1]), fmul2(make_float2(a1[i], a1[i + 1]), rv2)); + const float2 x2 = fmul2(make_float2(w2[i], w2[i + 1]), fmul2(make_float2(a2[i], a2[i + 1]), rv2)); + // s1 is stored negated (prep_qkv): o1 = x1*c1 - x2*s1, o2 = x2*c2 + x1*s2 + const float2 y1 = ffma2(x1, make_float2(c1[i], c1[i + 1]), fmul2(x2, make_float2(s1[i], s1[i + 1]))); + const float2 y2 = ffma2(x2, make_float2(c2[i], c2[i + 1]), fmul2(x1, make_float2(s2[i], s2[i + 1]))); + o1[i] = y1.x; o1[i + 1] = y1.y; o2[i] = y2.x; o2[i + 1] = y2.y; + } +#ifdef TC_PROBE + const uint4 h1_ = pack8_h(o1), h2_ = pack8_h(o2); + const long long rs0 = clock64(); + if (valid) { + *reinterpret_cast(dst + j * 8) = h1_; + *reinterpret_cast(dst + 64 + j * 8) = h2_; + } + if (warp == 2 && lane == 0) CPA(2, clock64() - rs0); +#else +#if QKV_CST + // coalesced q/k stores: a lane's row segment of 4 x 16 B units is 4x4-transposed inside its + // 4-lane group (2 xor-shuffle rounds), so each st.v4 writes 8 rows x 64 contiguous bytes (full + // sectors) instead of 32 rows x 16 B. fp16: groups of 4 chunks (units = chunk lo / hi 16 B); + // e4m3 full head (NJ = 8): all 8 chunks buffered (unit = 2 chunks' 8 B). Identical bytes. + if (p.qkb && NJ == 8) { + const uint2 l8 = make_uint2(cvt_e4m3x4(o1[0], o1[1], o1[2], o1[3]), + cvt_e4m3x4(o1[4], o1[5], o1[6], o1[7])); + const uint2 h8 = make_uint2(cvt_e4m3x4(o2[0], o2[1], o2[2], o2[3]), + cvt_e4m3x4(o2[4], o2[5], o2[6], o2[7])); + if ((jj & 1) == 0) { cul[(jj >> 1) & 3].x = l8.x; cul[(jj >> 1) & 3].y = l8.y; cuh[(jj >> 1) & 3].x = h8.x; cuh[(jj >> 1) & 3].y = h8.y; } + else { cul[(jj >> 1) & 3].z = l8.x; cul[(jj >> 1) & 3].w = l8.y; cuh[(jj >> 1) & 3].z = h8.x; cuh[(jj >> 1) & 3].w = h8.y; } + if (jj == NJ - 1) { + tr4(cul); tr4(cuh); +#pragma unroll + for (int i = 0; i < 4; i++) + if (ctv[i]) { + *reinterpret_cast(ctr[i] + 16 * cg4) = cul[i]; + *reinterpret_cast(ctr[i] + 64 + 16 * cg4) = cuh[i]; + } + } + } else if (!p.qkb) { + cul[jj & 3] = pack8_h(o1); cuh[jj & 3] = pack8_h(o2); + if ((jj & 3) == 3) { + tr4(cul); tr4(cuh); + const int jb = j - 3; +#pragma unroll + for (int i = 0; i < 4; i++) + if (ctv[i]) { + *reinterpret_cast(ctr[i] + 16 * jb + 16 * cg4) = cul[i]; + *reinterpret_cast(ctr[i] + 128 + 16 * jb + 16 * cg4) = cuh[i]; + } + } + } else +#endif + if (valid && p.qkb) { + const uint2 l8 = make_uint2(cvt_e4m3x4(o1[0], o1[1], o1[2], o1[3]), + cvt_e4m3x4(o1[4], o1[5], o1[6], o1[7])); + const uint2 h8 = make_uint2(cvt_e4m3x4(o2[0], o2[1], o2[2], o2[3]), + cvt_e4m3x4(o2[4], o2[5], o2[6], o2[7])); + if ((jj & 1) == 0) { pl8 = l8; ph8 = h8; } + else { + *reinterpret_cast(dst8 + (j - 1) * 8) = make_uint4(pl8.x, pl8.y, l8.x, l8.y); + *reinterpret_cast(dst8 + 64 + (j - 1) * 8) = make_uint4(ph8.x, ph8.y, h8.x, h8.y); + } + } else if (valid) { // q/k consumed by flash attention: EVICT_LAST + *reinterpret_cast(dst + j * 8) = pack8_h(o1); + *reinterpret_cast(dst + 64 + j * 8) = pack8_h(o2); + } +#endif + } + }; + if (q_nj == 8) rope(std::integral_constant{}); + else rope(std::integral_constant{}); + tc_fence_before(); + __syncwarp(); + if (elect_one()) tempty_arrive(buf); // all TMEM reads of this tile done + } else { + // ---- V head: whole row to registers, release TMEM, bias, transposed store + float a[128]; +#pragma unroll + for (int c = 0; c < 4; c += 2) tmem_ld32x2(cb + c * 32, a + c * 32, cb + c * 32 + 32, a + c * 32 + 32); // two loads per wait + tc_fence_before(); + __syncwarp(); + if (elect_one()) tempty_arrive(buf); + float vmx = 0.f; // max |V| of this thread's stored columns (fp8 o_proj scale) + // S % 8 == 0 -> 8-lane groups hold 8 consecutive tokens of one batch (T % 8 == 0: a group is + // all valid or all past M): transposed 16 B stores; all lanes compute so the shuffles are complete + const bool vt8 = QKV_VT8 && (p.S & 7) == 0; + if (valid || vt8) { + const float* bb = p.bias2 + (hidx - 36) * 128; + const float* wsc = F8 ? p.qws + hidx * 128 : nullptr; + const float2 rx2 = make_float2(q_rx, q_rx); +#pragma unroll + for (int d = 0; d < 128; d += 4) { + const float4 b4 = __ldg(reinterpret_cast(bb + d)); + float2 sc = make_float2(0.0625f, 0.0625f), sc23 = sc; + if constexpr (F8 && !VS) { // VS: V tiles are fp16 (x 2^4) - + const float4 w4 = __ldg(reinterpret_cast(wsc + d)); + sc = fmul2(make_float2(w4.x, w4.y), rx2); sc23 = fmul2(make_float2(w4.z, w4.w), rx2); + } + const float2 y0 = ffma2(make_float2(a[d], a[d + 1]), sc, make_float2(b4.x, b4.y)); + const float2 y1 = ffma2(make_float2(a[d + 2], a[d + 3]), sc23, make_float2(b4.z, b4.w)); + a[d] = y0.x; a[d + 1] = y0.y; a[d + 2] = y1.x; a[d + 3] = y1.y; + } + // V stored transposed (V^T [b][kv_head][d][Spad], x 2^-10: keeps |V| up to ~6.7e7 inside fp16 + // range, so large activations do not overflow to inf): K-major B operand for P.V + __half* dst = p.v + ((size_t)(b * 4 + (hidx - 36)) * 128) * p.Spad + s; + if (vt8) { + // 8x8 fp16 transpose inside each 8-lane group: lane t ends with d = 8k + t for the group's + // 8 tokens -> ONE 16 B store per 8 d instead of 8 2-byte stores. Identical fp16 bytes. + const int t = lane & 7; + __half* gdst = dst - t; // token s0 = s - t (multiple of 8) +#pragma unroll + for (int kk = 0; kk < 16; kk++) { + if (!(full || (kk >> 3) == half)) continue; + const float* av = a + 8 * kk; + if (valid) +#pragma unroll + for (int i = 0; i < 8; i++) vmx = fmaxf(vmx, fabsf(av[i])); + const uint4 o = vt8_transpose(av, lane); + if (valid) *reinterpret_cast(gdst + (size_t)(8 * kk + t) * p.Spad) = o; + } + } else { +#pragma unroll + for (int d = 0; d < 128; d++) + if (full || (d >> 6) == half) { + dst[(size_t)d * p.Spad] = __float2half_rn(a[d] * 0.0009765625f); + vmx = fmaxf(vmx, fabsf(a[d])); + } + } + } + // fp8 o_proj path: warp max of |V| -> global atomicMax (bounds every attention output element) + if (p.vmax) { + const unsigned m = __reduce_max_sync(0xffffffffu, __float_as_uint(vmx)); + if (lane == 0 && m) atomicMax(p.vmax, m); + } + } +#ifdef TC_PROBE + if (warp == 2 && lane == 0) CPA(10, clock64() - ew0); +#endif + } else if (EPI == EPI_QKV && !QF && spl >= 4 && sub >= 0) { + // V quarter tile (N = 64) / V eighth tile (N = 32): columns w (sub % (128 / w)).. +w-1 of V + // head nt * 2 + sub / (128 / w), w = 256 / spl; warpgroup `half` owns w / 2 of them (a 32-column TMEM + // load from its first column; eighths use the first 16 values). Same per-element math as the full V path. + const int w = 256 / spl, per = 128 / w, nw = w >> 1; + const int hidx = nt * 2 + sub / per; + const int col0 = (sub % per) * w + half * nw; + float a[32]; + tmem_ld32(trow + half * nw, a); + tc_fence_before(); + __syncwarp(); + if (elect_one()) tempty_arrive(buf); + float vmx = 0.f; + if (valid) { + const float* bb = p.bias2 + (hidx - 36) * 128 + col0; + const int b = pos / p.S, s = pos - b * p.S; + __half* dst = p.v + ((size_t)(b * 4 + (hidx - 36)) * 128 + col0) * p.Spad + s; +#pragma unroll + for (int d = 0; d < 32; d += 4) { + if (d >= nw) break; + const float4 b4 = __ldg(reinterpret_cast(bb + d)); + const float2 sc = make_float2(0.0625f, 0.0625f); + const float2 y0 = ffma2(make_float2(a[d], a[d + 1]), sc, make_float2(b4.x, b4.y)); + const float2 y1 = ffma2(make_float2(a[d + 2], a[d + 3]), sc, make_float2(b4.z, b4.w)); + a[d] = y0.x; a[d + 1] = y0.y; a[d + 2] = y1.x; a[d + 3] = y1.y; + } +#pragma unroll + for (int d = 0; d < 32; d++) { + if (d >= nw) break; + dst[(size_t)d * p.Spad] = __float2half_rn(a[d] * 0.0009765625f); + vmx = fmaxf(vmx, fabsf(a[d])); + } + } + if (p.vmax) { + const unsigned m = __reduce_max_sync(0xffffffffu, __float_as_uint(vmx)); + if (lane == 0 && m) atomicMax(p.vmax, m); + } + } else if (EPI == EPI_QKV) { + // T < QKV_F16TAB_MIN_T: fp32 RoPE tables, register-resident accumulator row + // BN=256: two heads per tile, warpgroup `half` owns head nt*2+half entirely. + // BN=128: one head per tile; both warpgroups load the full head row (needed for q/k RMSNorm and + // the RoPE d <-> d+64 pairing) and each writes half of the output columns. + const bool full = BN == 256 && sub < 0; + const int hidx = BN == 256 ? (sub < 0 ? nt * 2 + half : nt * 2 + sub) : nt; + const int j0 = full ? 0 : half * 4, j1 = full ? 8 : half * 4 + 4; + float a[128]; + static_assert(QKV_CST, "v447 bias interleave assumes all lanes compute"); + const float* bb = hidx < 32 ? p.bias0 + hidx * 128 + : (hidx < 36 ? p.bias1 + (hidx - 32) * 128 : p.bias2 + (hidx - 36) * 128); + // per 32-col chunk, the chunk's 8 bias float4 are issued BEFORE its TMEM load + wait (their L2 + // latency overlaps the tcgen05.ld round trip), then acc * 2^-4 + bias as packed FFMA2 (same values) +#pragma unroll + for (int c = 0; c < 4; c++) { + float4 qb4[8]; +#pragma unroll + for (int d = 0; d < 8; d++) qb4[d] = __ldg(reinterpret_cast(bb + c * 32 + 4 * d)); + tmem_ld32(trow + (full ? half * 128 : 0) + c * 32, a + c * 32); +#pragma unroll + for (int d = 0; d < 8; d++) { + const float4 b4 = qb4[d]; + const int e = c * 32 + 4 * d; + const float2 sc = make_float2(0.0625f, 0.0625f); + const float2 y0 = ffma2(make_float2(a[e], a[e + 1]), sc, make_float2(b4.x, b4.y)); + const float2 y1 = ffma2(make_float2(a[e + 2], a[e + 3]), sc, make_float2(b4.z, b4.w)); + a[e] = y0.x; a[e + 1] = y0.y; a[e + 2] = y1.x; a[e + 3] = y1.y; + } + } + tc_fence_before(); + __syncwarp(); + if (elect_one()) tempty_arrive(buf); + float vmx = 0.f; // max |V| of this thread's stored columns (fp8 o_proj scale) + // all lanes compute (rows past M: zero accumulator, clamped table row, never stored) so the + // q/k 4-lane transposed stores and the V^T 8x8 lane transpose have complete warps + const bool vt8 = QKV_VT8 && (p.S & 7) == 0; + { + const int posc = pos < p.M ? pos : p.M - 1; + const int b = posc / p.S, s = posc - b * p.S; + if (hidx < 36) { + // sum of squares: 4 packed FFMA2 pair accumulators + float2 ssa[4]; +#pragma unroll + for (int i = 0; i < 4; i++) ssa[i] = make_float2(0.f, 0.f); +#pragma unroll + for (int d = 0; d < 128; d += 2) { + const float2 x = make_float2(a[d], a[d + 1]); + ssa[(d >> 1) & 3] = ffma2(x, x, ssa[(d >> 1) & 3]); + } + const float ss = ((ssa[0].x + ssa[0].y) + (ssa[1].x + ssa[1].y)) + ((ssa[2].x + ssa[2].y) + (ssa[3].x + ssa[3].y)); + // rstd with the output 2^-6 pre-scale folded in (exact power of 2) + const float r = rsqrtf(ss * (1.f / 128.f) + p.eps) * 0.015625f; + const float* w = reinterpret_cast(smem + QKV_NW_OFF) + (hidx < 32 ? 0 : 128); // smem copy + // transposed RoPE tables (see prep_qkv_kernel): float4 group g of this row at cr4[g * 32] + const float4* cr4 = reinterpret_cast(p.cs) + (size_t)(posc >> 5) * 1024 + (posc & 31); + const float4* sr4 = reinterpret_cast(p.sn) + (size_t)(posc >> 5) * 1024 + (posc & 31); + __half* dst = hidx < 32 ? p.q + (((size_t)b * 32 + hidx) * p.S + s) * 128 + : p.k + (((size_t)b * 4 + (hidx - 32)) * p.S + s) * 128; +#if QKV_CST + // target rows of the transposed stores = rows (lane & ~3) + i of this warp + const int cg4 = lane & 3; + char* ctr[4]; + bool ctv[4]; + { + const unsigned long long rp = (unsigned long long)reinterpret_cast(dst); +#pragma unroll + for (int i = 0; i < 4; i++) { + ctr[i] = reinterpret_cast(__shfl_sync(0xffffffffu, rp, (lane & ~3) + i)); + ctv[i] = __shfl_sync(0xffffffffu, (int)valid, (lane & ~3) + i) != 0; + } + } + uint4 cul[4], cuh[4]; +#endif +#pragma unroll + for (int j = 0; j < 8; j++) { + if (j < j0 || j >= j1) continue; // RoPE pair chunk owned by the other warpgroup (warp-uniform) + float c1[8], c2[8], s1[8], s2[8], w1[8], w2[8]; + *reinterpret_cast(c1) = __ldg(cr4 + (2 * j) * 32); + *reinterpret_cast(c1 + 4) = __ldg(cr4 + (2 * j + 1) * 32); + *reinterpret_cast(c2) = __ldg(cr4 + (16 + 2 * j) * 32); + *reinterpret_cast(c2 + 4) = __ldg(cr4 + (16 + 2 * j + 1) * 32); + *reinterpret_cast(s1) = __ldg(sr4 + (2 * j) * 32); + *reinterpret_cast(s1 + 4) = __ldg(sr4 + (2 * j + 1) * 32); + *reinterpret_cast(s2) = __ldg(sr4 + (16 + 2 * j) * 32); + *reinterpret_cast(s2 + 4) = __ldg(sr4 + (16 + 2 * j + 1) * 32); + *reinterpret_cast(w1) = *reinterpret_cast(w + j * 8); + *reinterpret_cast(w1 + 4) = *reinterpret_cast(w + j * 8 + 4); + *reinterpret_cast(w2) = *reinterpret_cast(w + 64 + j * 8); + *reinterpret_cast(w2 + 4) = *reinterpret_cast(w + 64 + j * 8 + 4); + float o1[8], o2[8]; + const float2 rv2 = make_float2(r, r); +#pragma unroll + for (int i = 0; i < 8; i += 2) { // packed: x = w * (a * r); RoPE as FMUL2 + FFMA2 + const int d = j * 8 + i; + const float2 x1 = fmul2(make_float2(w1[i], w1[i + 1]), fmul2(make_float2(a[d], a[d + 1]), rv2)); + const float2 x2 = fmul2(make_float2(w2[i], w2[i + 1]), + fmul2(make_float2(a[d + 64], a[d + 65]), rv2)); + // s1 is stored negated (prep_qkv): o1 = x1*c1 - x2*s1, o2 = x2*c2 + x1*s2 + const float2 y1 = ffma2(x1, make_float2(c1[i], c1[i + 1]), + fmul2(x2, make_float2(s1[i], s1[i + 1]))); + const float2 y2 = ffma2(x2, make_float2(c2[i], c2[i + 1]), + fmul2(x1, make_float2(s2[i], s2[i + 1]))); + o1[i] = y1.x; o1[i + 1] = y1.y; o2[i] = y2.x; o2[i + 1] = y2.y; + } +#if QKV_CST + // coalesced stores: groups of 4 chunks (j0 is 0 or 4), units 4x4-transposed inside each + // 4-lane group -> each st.v4 writes 8 rows x 64 contiguous bytes. Identical bytes. + cul[j & 3] = pack8_h(o1); cuh[j & 3] = pack8_h(o2); + if ((j & 3) == 3) { +#pragma unroll + for (int hl = 0; hl < 2; hl++) { + uint4* u = hl ? cuh : cul; +#pragma unroll + for (int m = 1; m <= 2; m <<= 1) { + const bool bit = (lane & m) != 0; +#pragma unroll + for (int c0 = 0; c0 < 4; c0++) { + if (c0 & m) continue; + const int c1_ = c0 | m; + const uint4 snd = bit ? u[c0] : u[c1_]; + uint4 rcv; + rcv.x = __shfl_xor_sync(0xffffffffu, snd.x, m); + rcv.y = __shfl_xor_sync(0xffffffffu, snd.y, m); + rcv.z = __shfl_xor_sync(0xffffffffu, snd.z, m); + rcv.w = __shfl_xor_sync(0xffffffffu, snd.w, m); + if (bit) u[c0] = rcv; else u[c1_] = rcv; + } + } + } + const int jb = j - 3; +#pragma unroll + for (int i = 0; i < 4; i++) + if (ctv[i]) { + *reinterpret_cast(ctr[i] + 16 * jb + 16 * cg4) = cul[i]; + *reinterpret_cast(ctr[i] + 128 + 16 * jb + 16 * cg4) = cuh[i]; + } + } +#else + *reinterpret_cast(dst + j * 8) = pack8_h(o1); + *reinterpret_cast(dst + 64 + j * 8) = pack8_h(o2); +#endif + } + } else { + // V stored transposed (V^T [b][kv_head][d][Spad], x 2^-10: keeps |V| up to ~6.7e7 inside fp16 range, so large + // activations do not overflow to inf): K-major B operand for P.V + __half* dst = p.v + ((size_t)(b * 4 + (hidx - 36)) * 128) * p.Spad + s; + if (vt8) { + // 8x8 fp16 transpose inside each 8-lane group (S % 8 == 0 -> a group = 8 consecutive + // tokens of one batch, all valid or all past M): one 16 B store per 8 d. Identical bytes. + const int t = lane & 7; + __half* gdst = dst - t; +#pragma unroll + for (int kk = 0; kk < 16; kk++) { + if (!(full || (kk >> 3) == half)) continue; + const float* av = a + 8 * kk; + if (valid) +#pragma unroll + for (int i = 0; i < 8; i++) vmx = fmaxf(vmx, fabsf(av[i])); + const uint4 o = vt8_transpose(av, lane); + if (valid) *reinterpret_cast(gdst + (size_t)(8 * kk + t) * p.Spad) = o; + } + } else if (valid) { +#pragma unroll + for (int d = 0; d < 128; d++) + if (full || (d >> 6) == half) { + dst[(size_t)d * p.Spad] = __float2half_rn(a[d] * 0.0009765625f); + vmx = fmaxf(vmx, fabsf(a[d])); + } + } + } + } + if (hidx >= 36) { + // fp8 o_proj path: warp max of |V| -> global atomicMax (bounds every attention output element) + if (p.vmax) { + const unsigned m = __reduce_max_sync(0xffffffffu, __float_as_uint(vmx)); + if (lane == 0 && m) atomicMax(p.vmax, m); + } + } + } else if (EPI == EPI_GATEUP) { + // TMEM cols [0,128) = gate, [128,256) = up; this half owns act cols half*64 .. +63 + // full tile: gate cols [0,128), up [128,256); half tile: gate [0,64), up [64,128). + // each warpgroup half owns gw = tbn/4 act columns. + // quarter tile (tbn = 64): gate [0,32), up [32,64); warpgroup 0 owns all 32 act cols, warpgroup 1 idles. + const int gw = tbn == 64 ? (half == 0 ? 32 : 0) : tbn >> 2, ngc = gw >> 5; + if (ngc == 0) { + tc_fence_before(); + __syncwarp(); + if (elect_one()) tempty_arrive(buf); + } +#pragma unroll 1 + for (int c = 0; c < ngc; c++) { + float g[32], u[32]; + tmem_ld32(trow + half * gw + c * 32, g); + tmem_ld32(trow + (tbn >> 1) + half * gw + c * 32, u); + if (c == ngc - 1) { + tc_fence_before(); + __syncwarp(); + if (elect_one()) tempty_arrive(buf); + } + if (valid) { + float4* dst = reinterpret_cast(p.out + (size_t)pos * INTER + nt * 128 + (sub > 0 ? sub * (tbn >> 1) : 0) + half * gw + c * 32); +#pragma unroll + for (int j = 0; j < 8; j++) { + float r4[4]; +#pragma unroll + for (int i = 0; i < 4; i++) { + const float gv = g[4 * j + i]; + r4[i] = gv / (1.f + __expf(-gv)) * u[4 * j + i]; + } + dst[j] = make_float4(r4[0], r4[1], r4[2], r4[3]); + } + } + } + } else { + // DOWN: lane L of this warp reduces rows it*8 + L/4 (it = 0..3), float4 group L%4 of a 16-col slab; + // tok / rw / rtok / rval were prefetched above (before the tfull wait). + float ssl = 0.f; // OPROJ: this thread's partial sum of squares of h over its 128 columns + const float rf8 = rf8c; + const int hw = tbn >> 1; // columns per warpgroup half + const int nch = tbn >> 6; // 32-column chunks per half +#pragma unroll 1 + for (int c = 0; c < nch; c++) { + float a[32]; + float4 pb[8], pw[8]; + if (EPI == EPI_OPROJ && wact) { + const int n0 = nt * BN + (sub >= 0 ? sub * tbn : 0) + half * hw + c * 32; +#pragma unroll + for (int j = 0; j < 8; j++) { + pb[j] = __ldg(reinterpret_cast(p.bias0 + n0) + j); + if (F8) pw[j] = reinterpret_cast(smem + OPJ_FS_OFF)[(n0 - nt * BN) / 4 + j]; // fs table + } + } + tmem_ld32(trow + half * hw + c * 32, a); + if (c == nch - 1) { + tc_fence_before(); + __syncwarp(); + if (elect_one()) tempty_arrive(buf); + } + if (EPI == EPI_DOWN) { + // Routing-weighted scatter-add, coalesced: the 32x32 (rows x cols) chunk is transposed through + // smem in two 16-col slabs so each red.global.add.v4.f32 instruction covers 8 rows x 64 + // contiguous bytes (full 32 B sectors) instead of 32 rows x 16 B. + float* stg = reinterpret_cast(smem + TSTAGES * STAGE_BYTES + 256) + + (warp - 2) * DOWN_STG_FLOATS; + const int n = nt * TBN + sub_off * 128 + half * hw + c * 32; +#pragma unroll + for (int hh = 0; hh < 2; hh++) { + __syncwarp(); // previous slab fully read +#pragma unroll + for (int j = 0; j < 4; j++) { // row = lane, group j stored at slot j ^ ((row>>1)&3) + const int slot = j ^ ((lane >> 1) & 3); + *reinterpret_cast(stg + lane * 16 + slot * 4) = + make_float4(rw * a[hh * 16 + 4 * j], rw * a[hh * 16 + 4 * j + 1], + rw * a[hh * 16 + 4 * j + 2], rw * a[hh * 16 + 4 * j + 3]); + } + __syncwarp(); +#pragma unroll + for (int it = 0; it < 4; it++) { + const int r = it * 8 + (lane >> 2), g = lane & 3; + const float4 v = + *reinterpret_cast(stg + r * 16 + (g ^ ((r >> 1) & 3)) * 4); + if (rval[it]) red_add_v4(p.out + (size_t)rtok[it] * HID + n + hh * 16 + g * 4, v); + } + } + continue; + } + if (!valid && EPI != EPI_OPROJ) continue; // OPROJ: whole warp joins the TMA store + if (EPI == EPI_ROUTER) { + if (half == 0) { + float4* dst = reinterpret_cast(p.out + (size_t)pos * NEXP + c * 32); +#pragma unroll + for (int j = 0; j < 8; j++) + atomicAdd(dst + j, make_float4(a[4 * j], a[4 * j + 1], a[4 * j + 2], a[4 * j + 3])); + } + continue; + } + const int n = nt * BN + (sub >= 0 ? sub * tbn : 0) + half * hw + c * 32; // + o_proj tail sub-tile offset + if (EPI == EPI_OPROJ) { + // TMA epilogue: per 16-column half-chunk k = 2c + hh, thread = row reads its 4 resid units + // from the slot (TMA-loaded, zero-filled past M), overwrites them with h (own row only: no + // cross-thread hazard) and one lane TMA-stores the 32 x 16 box (rows >= M clipped). Replaces the + // per-thread 16 B loads / stores whose warp instructions each touched 32 rows = 32 lines. + if (!wact) continue; + const int nk = tbn >> 5; // half-chunks of this warpgroup half + float2 ss2 = make_float2(0.f, 0.f); +#pragma unroll + for (int hh = 0; hh < 2; hh++) { + const int k = 2 * c + hh, sl = k & (OSL - 1); + const bool rgk = tlast && k >= OSL; // chunk staged in the dead ring + const uint32_t rsa_ = rgk ? ofreg + 2048u * (uint32_t)k : opj_saddr(sl); + if (rgk) { + if (k == OSL) { if (!mbar_test(tlbar, 0u)) mbar_wait_hint(tlbar, 0u); } + } else { + if (!tlast && k >= 1 && k + OSL - 1 < nk && lane == 0) { + asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); // store k-1 read slot + opj_rload(k + OSL - 1, on0 + 16 * (k + OSL - 1)); // into slot (k - 1) % OSL + } + { const uint32_t rb_ = opj_baddr(sl), rp_ = (rph >> sl) & 1u; if (!mbar_test(rb_, rp_)) mbar_wait_hint(rb_, rp_); } // resid slot wait test-first + suspend hint + rph ^= 1u << sl; + } + uint8_t* rs = smem + (rsa_ - sbase) + lane * 64; + const int nh = n + 16 * hh; +#pragma unroll + for (int j = 0; j < 4; j++) { + float4* up = reinterpret_cast(rs + ((j ^ ((lane >> 1) & 3)) << 4)); + const float4 rv = *up; + const float4 bv = pb[4 * hh + j]; + const float* aj = a + 16 * hh + 4 * j; + // acc = natural x 2^-6 (attn kept at V's 2^-10, Wo16 at 2^4): exact 2^6 rescale + // packed: h = resid + (acc * 64 + bias) as FFMA2 + FADD2, ssq as FFMA2 + float2 k64 = make_float2(64.f, 64.f), k64b = k64; + if (F8) { // per-column dequant factor precomputed in the tile table (wsc * rf8) + const float4 w4 = pw[4 * hh + j]; + k64 = make_float2(w4.x, w4.y); + k64b = make_float2(w4.z, w4.w); + (void)rf8; + } + const float2 h01 = fadd2(make_float2(rv.x, rv.y), + ffma2(make_float2(aj[0], aj[1]), k64, make_float2(bv.x, bv.y))); + const float2 h23 = fadd2(make_float2(rv.z, rv.w), + ffma2(make_float2(aj[2], aj[3]), k64b, make_float2(bv.z, bv.w))); + *up = make_float4(h01.x, h01.y, h23.x, h23.y); + ss2 = ffma2(h01, h01, ss2); + ss2 = ffma2(h23, h23, ss2); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // generic smem writes -> TMA + __syncwarp(); + if (lane == 0) { + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group [%0, {%1, %2}], [%3];" ::"l"( + (uint64_t)&tB3), "r"(nh), "r"(opj_row0), "r"(rsa_) + : "memory"); + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + } + } + ssl += ss2.x + ss2.y; + } else { + float4* dst = reinterpret_cast(p.out + (size_t)tok * HID + n); +#pragma unroll + for (int j = 0; j < 8; j++) + atomicAdd(dst + j, make_float4(rw * a[4 * j], rw * a[4 * j + 1], rw * a[4 * j + 2], + rw * a[4 * j + 3])); + } + } + // fused post-attention RMSNorm statistics: one fp32 atomic per (row, 128-column half-tile) + if (EPI == EPI_OPROJ && valid) atomicAdd(p.ssq + pos, ssl); + // M-tile handoff to the router (T >= 2048): this warp's h rows (TMA stores complete, not only + // read) + ssq atomics released, then counter[m0 / 128] += its column count (target 4 x 2048 = 8192) + if (EPI == EPI_OPROJ && p.mtctr != nullptr) { + if (lane == 0) { + asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); + asm volatile("fence.proxy.async.global;" ::: "memory"); + } + __syncwarp(); // one cumulative membar.gl (lane 0) instead of two + // release-RMW (red.release.gpu: acq_rel fence semantics, lighter than membar.gl + relaxed atomic) + if (lane == 0) + asm volatile("red.release.gpu.global.add.s32 [%0], %1;" ::"l"(p.mtctr + (m0 >> 7)), "r"(tbn >> 1) : "memory"); + } + } + // QKV (T < 2048, non-QF) per-M-tile completion counter: this warp's q / k / V^T stores of the tile are + // released (generic + async proxy, consumed by attention TMA) and counter[m0 / 128] += its column count + // (tile width / 2 per warp; complete M tile = 8 warps x sum of widths / 2 = 4 x NQKV) + if constexpr (EPI == EPI_QKV && !QF) { + if (p.qbc != nullptr) { + // per-lane proxy fence, then warp sync + ONE cumulative membar.gl by lane 0 + asm volatile("fence.proxy.async.global;" ::: "memory"); + __syncwarp(); + const int qw = sub >= 0 ? 256 / spl : BN; + if (lane == 0 && m0 < p.M) { asm volatile("red.release.gpu.global.add.s32 [%0], %1;" ::"l"(p.qbc + (m0 >> 7)), "r"(qw >> 1) : "memory"); } + } + } + } + } else if constexpr (SW) { + // ---------------- fp32 Wo stream (merged o_proj + router, T < 2048): one tile per CTA (Wo rows nt*128..) + int m0, mend, e, nt, sub; + const bool has = cid < num_tiles; + if (has) coords(cid, m0, mend, e, nt, sub); + (void)m0; (void)mend; (void)e; (void)sub; + if (has && warp == 14) { + // raw producer: fp32 Wo k-block kb (64 K) = 2 boxes of 32 floats x 128 rows (128B swizzle) -> raw stage kb % 3 + for (int kb = 0; kb < KB; kb++) { + const int r = kb % 3; + mbar_wait(sw_raw_empty + 8 * r, ((kb / 3) & 1) ^ 1); + __syncwarp(); + if (elect_one()) { + const uint32_t fb = sw_raw_full + 8 * r, dst = sbase + SW_RAW_OFF + r * 32768; + mbar_expect_tx(fb, 32768u); + tma_load_2d(dst, &tB0, kb * 64, nt * BN, fb); + tma_load_2d(dst + 16384, &tB0, kb * 64 + 32, nt * BN, fb); + } + __syncwarp(); + } + } else if (has && warp >= 10 && warp < 14) { + // converters: thread = Wo row rr (0..127): raw logical 16 B chunk j of box b (k = 32b + 4j) at physical + // chunk j ^ (rr & 7); fp16 chunk c (k = 8c..8c+7) = raw chunks 2c, 2c+1 x 2^4, written at c ^ (rr & 7) + const int rr = (warp - 10) * 32 + lane, sw = rr & 7; + for (int kb = 0; kb < KB; kb++) { + const int r = kb % 3, s = kb % NST; + mbar_wait(sw_raw_full + 8 * r, (kb / 3) & 1); + const uint8_t* src = smem + SW_RAW_OFF + r * 32768 + rr * 128; + uint4 v[16]; +#pragma unroll + for (int j = 0; j < 8; j++) { + v[j] = *reinterpret_cast(src + 16 * (j ^ sw)); + v[8 + j] = *reinterpret_cast(src + 16384 + 16 * (j ^ sw)); + } + __syncwarp(); + if (elect_one()) mbar_arrive(sw_raw_empty + 8 * r); // raw stage consumed (values in registers) + mbar_wait_cl2(bar_empty + 8 * s, ((kb / NST) & 1) ^ 1); // converted stage free (MMA commit) + // packed x16 cvt asm blocks, 32-bit smem addresses (row base hoisted) + st.shared.v4 + const uint32_t dsta = sbase + (uint32_t)(s * SBYTES + rr * 128); +#pragma unroll + for (int c = 0; c < 8; c++) { + const uint2 lo = cvt_h2x4p16(v[2 * c]), hi = cvt_h2x4p16(v[2 * c + 1]); + sts128(dsta + (uint32_t)(16 * (c ^ sw)), lo.x, lo.y, hi.x, hi.y); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // generic smem writes -> tcgen05.mma + __syncwarp(); + if (elect_one()) mbar_arrive_cl(mapa_sh(bar_full + 8 * s, swlead)); + } + } + } + // OPROJ: every h TMA store of this warp complete (global writes performed) before the CTA exits + if (EPI == EPI_OPROJ && warp >= 2 && lane == 0) asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); + // MRG: async-proxy h stores ordered before the generic release (cluster barrier) that hands h to the router phase + if (MRG && EPI == EPI_OPROJ && warp >= 2 && lane == 0) asm volatile("fence.proxy.async.global;" ::: "memory"); +#ifdef TC_PROBE + if (threadIdx.x == 0) CPA(14, clock64() - cta_t0); + if (p.cprobe && lane == 0) { +#pragma unroll + for (int i = 0; i < 16; i++) if (cacc[i]) atomicAdd(&p.cprobe[bidx * 16 + i], cacc[i]); + } +#endif + tc_fence_before(); + __syncthreads(); + if (PAIR || SW) cl_sync_all(); // peer done with all remote arrivals / MMAs before TMEM dealloc + exit + CHN(3 + EPI, 2); + if (threadIdx.x == 0) PRB(7); + if (MRG) return tbase; // merged o_proj+router launch: TMEM stays allocated for the router phase + if (warp == 1) { + __syncwarp(); + tc_fence_after(); + if (PAIR) asm volatile("tcgen05.dealloc.cta_group::2.sync.aligned.b32 %0, %1;" ::"r"(tbase), "r"(512)); + else asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tbase), "r"(512)); + } + return tbase; +} +template +__global__ void __launch_bounds__(tc_threads(), 1) tc_gemm_kernel(const __grid_constant__ CUtensorMap tA, + const __grid_constant__ CUtensorMap tB0, + const __grid_constant__ CUtensorMap tB1, + const __grid_constant__ CUtensorMap tB2, + const __grid_constant__ CUtensorMap tB3, + const __grid_constant__ CUtensorMap tB4, + const __grid_constant__ TcArgs p) { + tc_gemm_dev(tA, tB0, tB1, tB2, tB3, tB4, p, (int)blockIdx.x, (int)gridDim.x); +} + +template +__global__ void __launch_bounds__(tc_threads_sr(), 1) tc_gemm_sr_kernel(const __grid_constant__ CUtensorMap tA, + const __grid_constant__ CUtensorMap tB0, + const __grid_constant__ CUtensorMap tB1, + const __grid_constant__ CUtensorMap tB2, + const __grid_constant__ CUtensorMap tB3, + const __grid_constant__ CUtensorMap tB4, const __grid_constant__ TcArgs p) { + // TcArgs as __grid_constant__ (read-only param space, no per-thread copy of the ~0.5 KB struct) + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = (uint8_t*)(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023); + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + constexpr bool grouped = (EPI == EPI_GATEUP || EPI == EPI_DOWN); + constexpr bool F16 = (EPI == EPI_QKV || EPI == EPI_OPROJ); + constexpr bool F8 = (EPI == EPI_OPROJ && QF) || (EPI == EPI_QKV && QF && Q8); // Q8 = false: QF epilogue, fp16 QKV operands + static_assert(!VS || (EPI == EPI_QKV && F8), "VS: QKV fp8 only"); + constexpr int KE = F8 ? 128 : (F16 ? 64 : 32); + // CG == 2 (dense fp16 QKV / OPROJ only, BN = 256): 2-CTA cluster along M. One 256 x 256 tile per cluster: CTA r + // TMA-loads its own 128 A rows (M tile 2 mp + r) and B rows nt*256 + 128 r .. +127 (its N half) into a 6-stage + // ring {A 16 KB, B 16 KB}; every TMA signals the LEADER's full barrier (leader expects 64 KB per stage). The leader + // issues tcgen05.mma.cta_group::2 m256n256k16, so each SM ingests 32 KB per k-block instead of 48 KB (B bytes per + // SM halved; the 1-CTA BN=256 mainloop is L2->SM feed-bound at ~87 B/clk/SM). Commits are multicast to both CTAs' + // empty / tfull barriers; both CTAs' 8 epilogue warps release the accumulator on the leader's tempty barrier + // (count 16). Each CTA's TMEM holds its own 128 rows x 256 cols (double-buffered): epilogues unchanged. + constexpr bool PAIR = (CG == 2); + static_assert(!PAIR || F16, "2-CTA path only for the dense fp16 GEMMs"); + constexpr int NST = PAIR ? 6 : TSTAGES; + constexpr int SBYTES = PAIR ? 32768 : STAGE_BYTES; + static_assert(NST * SBYTES == TSTAGES * STAGE_BYTES, "smem layout"); + const uint32_t rank = PAIR ? cl_ctarank() : 0u; + const int cid = PAIR ? (int)(blockIdx.x >> 1) : (int)blockIdx.x; // tile-scheduler id (cluster id) + const int ncl = PAIR ? (int)(gridDim.x >> 1) : (int)gridDim.x; + + const uint32_t sbase = smem_u32(smem); + const uint32_t bar_full = sbase + NST * SBYTES; + const uint32_t bar_empty = bar_full + NST * 8; + const uint32_t bar_tfull = bar_empty + NST * 8; + const uint32_t bar_tempty = bar_tfull + 16; + const uint32_t tslot = bar_tempty + 16; + volatile uint32_t* tslot_ptr = (volatile uint32_t*)(smem + NST * SBYTES + NST * 16 + 32); + // accumulator release: PAIR -> the leader's tempty barrier (both CTAs' epilogues, count 16) + auto tempty_arrive = [&](int b) { + if (PAIR) mbar_arrive_cl(mapa_sh(bar_tempty + 8 * b, 0)); + else mbar_arrive(bar_tempty + 8 * b); + }; + if (threadIdx.x == 0) PRB(0); +#ifdef TC_PROBE + unsigned long long cacc[16]; +#pragma unroll + for (int i = 0; i < 16; i++) cacc[i] = 0; + const long long cta_t0 = clock64(); +#endif + + if (threadIdx.x == 0) { + for (int s = 0; s < NST; s++) { mbar_init(bar_full + 8 * s, 1); mbar_init(bar_empty + 8 * s, 1); } + for (int b = 0; b < 2; b++) { mbar_init(bar_tfull + 8 * b, 1); mbar_init(bar_tempty + 8 * b, PAIR ? 16 : 8); } + if (EPI == EPI_OPROJ) // resid slot barriers of the TMA epilogue (8 warps x 2 slots) + for (int i = 0; i < 16; i++) mbar_init(sbase + TSTAGES * STAGE_BYTES + 512 + 8 * i, 1); + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tA) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tB0) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tB1) : "memory"); // tail / VS maps + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tB2) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tB3) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tB4) : "memory"); + } + if (warp == 1) { + if (PAIR) { // both CTAs of the pair allocate collectively + asm volatile("tcgen05.alloc.cta_group::2.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(tslot), "r"(512)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::2.sync.aligned;"); + } else { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(tslot), "r"(512)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + } + tc_fence_before(); + __syncthreads(); + if (PAIR) cl_sync_all(); // peer barriers initialised before any remote arrive / TMA complete_tx + tc_fence_after(); + const uint32_t tbase = *tslot_ptr; + const int KB = p.KB; + // runtime N tile width (wave-quantization selector, host side); B TMA box rows == BN + const int BN = p.BN; + const uint32_t stage_tx = (uint32_t)(A_BYTES + BN * 128); + const uint32_t idesc_f16 = (1u << 4) | ((uint32_t)(BN >> 3) << 17) | ((128u >> 4) << 24); + CHN(3 + EPI, 0); + // o_proj pre-PDL-wait work: Wo16 comes from the SIDE stream (completion counter), not from the predecessor + // (flash attention), so the producer warp acquires it and L2-prefetches the B (Wo16) boxes of the first 8 + // k-blocks of this CTA's first tile while attention is still draining. A only (attn) depends on the predecessor. + if (EPI == EPI_OPROJ && warp == 0) { + // acquire with work stealing (executes still-unclaimed convert units itself: deadlock-free) + sidew::conv_acquire_steal(p.conv, (int)(((long long)blockIdx.x * p.conv.n) / gridDim.x)); + const int nmo = (p.M + TBM - 1) / TBM; + const int nm2 = PAIR ? (nmo + 1) / 2 : nmo; + const int nfo = nm2 * p.NT, nso = PAIR ? 0 : p.qsplit, splo = p.ospl; + const int nto = nfo + nso * (splo - 1); + const int t = cid; + if (t < nto && lane < 8) { + int f = t, sub = -1; + const int fs = nfo - nso; + if (t >= fs) { f = fs + (t - fs) / splo; sub = (t - fs) % splo; } + int mt = f / p.NT, nt = f - mt * p.NT; + if (p.M >= 2048) { + const int band = f / (8 * p.NT), first = band * 8; + const int gsz = nm2 - first < 8 ? nm2 - first : 8; + nt = (f - band * 8 * p.NT) / gsz; + } + const CUtensorMap* bm = &tB0; + int r0 = nt * BN; + if (PAIR) r0 = nt * 256 + 128 * (int)rank; + else if (sub >= 0) { bm = &tB1; r0 = nt * 256 + sub * (256 / splo); } + if (lane < KB) + asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile [%0, {%1, %2}];" ::"l"((uint64_t)bm), + "r"(lane * KE), "r"(r0) : "memory"); + } + __syncwarp(); + } + pdl_wait(); + CHN(3 + EPI, 1); + // QK bound slots: every reader (QKV epilogue, attention) has completed (PDL chain) -> reset for the next forward + if (EPI == EPI_OPROJ && p.qkb_reset && blockIdx.x == 0 && threadIdx.x < 4) p.qkb_reset[threadIdx.x] = 0u; + if (threadIdx.x == 0) PRB(1); + pdl_trigger(); + int num_m1 = 0, num_m = 0, num_full = 0, nsplit = 0, spl = 2, num_tiles = 0; + auto calc_geom = [&]() { + num_m1 = grouped ? *p.total_tiles : (p.M + TBM - 1) / TBM; + num_m = PAIR ? (num_m1 + 1) / 2 : num_m1; // PAIR: M-tile pairs (one per cluster tile) + num_full = num_m * p.NT; // tiles of the nominal 128 x 256 shape + nsplit = 0; spl = 2; + // QKV wave-tail split (exact on the host since M is known): the last r <= grid/2 full 256-wide (two-head) tiles + // run as 2r one-head N=128 tiles (B rows via the 128-row map tB1), so the tail costs ~half a tile, not a full one. + // QKV ospl = 4 (T < 2048 only, host-gated): the r tail tiles are V-head tiles (see coords) split into 4 N=64 + // quarters (V needs no per-head norm): a quarter costs ~A + B/4 bytes per k-block instead of A + B/2 for a half. + if (EPI == EPI_QKV && !PAIR) { nsplit = p.qsplit; spl = p.ospl == 4 ? 4 : 2; } + // o_proj wave-tail split (host-computed, BN = 256 only): the last r tiles of a partial wave (r <= grid/2, or + // <= grid/4 for quarters) run as ospl narrower N tiles (B rows via the (256/ospl)-row map tB1), so a tiny last + // wave (e.g. 12 of 148 SMs at T=7184) costs ~1/ospl of a tile instead of a full one. + if (EPI == EPI_OPROJ && !PAIR) { nsplit = p.qsplit; spl = p.ospl; } + if (grouped) { + if (p.BN == 128) nsplit = num_full; + else { + const int r = num_full % (int)gridDim.x; + if (r > 0 && 2 * r <= (int)gridDim.x) nsplit = r; + if (EPI == EPI_GATEUP && r > 0 && 4 * r <= (int)gridDim.x) spl = 4; + } + } + num_tiles = num_full + nsplit * (spl - 1); + }; + + // tile t -> (M tile, N tile, sub): sub = -1 full 256-wide tile, 0/1 = lower/upper N=128 half of a split tile + auto coords = [&](int t, int& m0, int& mend, int& e, int& nt, int& sub) { + int f = t; + sub = -1; + if (grouped || EPI == EPI_QKV || EPI == EPI_OPROJ) { + const int fs = num_full - nsplit; + if (t >= fs) { f = fs + (t - fs) / spl; sub = (t - fs) % spl; } + } + int mt = f / p.NT; + nt = f - mt * p.NT; + if (!grouped && EPI != EPI_ROUTER && p.M >= 2048) { + // M-tile-grouped rasterization (large T): tiles walk a band of GM = 8 M tiles M-fastest, then the next + // N tile, so a wave of concurrently running CTAs touches only 8 A row-blocks x ~grid/8 B tiles + // (bounded L2 working set, each A/B tile shared by many co-scheduled CTAs). Bijection over [0, num_full). + constexpr int GM = 8; + const int nm = num_m; // PAIR: bands of 8 M-tile pairs + const int band = f / (GM * p.NT), first = band * GM; + const int gsz = nm - first < GM ? nm - first : GM; + const int loc = f - band * GM * p.NT; + mt = first + loc % gsz; + nt = loc / gsz; + } else if (EPI == EPI_QKV && !PAIR && spl == 4) { + // V-last order (bijection over [0, num_full)): all q/k tiles (n tiles 0..NT-3) M-major first, then + // the V tiles (n tiles NT-2, NT-1), so the split tail tiles are always V tiles (host: r <= 2 * num_m) + const int nqk = p.NT - 2, nonv = num_m * nqk; + if (f < nonv) { mt = f / nqk; nt = f - mt * nqk; } + else { const int g = f - nonv; mt = g >> 1; nt = nqk + (g & 1); } + } + if (grouped) { + e = p.tile_expert[mt]; + m0 = p.tile_mstart[mt]; + mend = p.offsets[e] + p.counts[e]; + } else { + e = 0; m0 = (PAIR ? 2 * mt + (int)rank : mt) * TBM; mend = p.M; // PAIR: rows >= M zero-filled, masked + } + }; + + constexpr int EW0 = EPI == EPI_QKV ? 4 : 2; // first epilogue warp + // QKV: per-warpgroup register rebalance inside the role branches (warp-uniform per warpgroup) + if (EPI == EPI_QKV ? warp < 4 : warp < 2) { + if constexpr (EPI == EPI_QKV) asm volatile("setmaxnreg.dec.sync.aligned.u32 24;\n" ::: "memory"); + calc_geom(); + if (warp == 0) { + { + // ---------------- TMA producer: the WHOLE warp runs the loop (warp-uniform empty-barrier waits and tile + // arithmetic), one elect.sync lane issues expect_tx + the cp.async.bulk.tensor loads (same structure as + // the MMA issuer; a lane-0-only divergent branch costs ~55 cycles per async op) + int it = 0; + const uint64_t kpol = keep_pol(); // QKV/OPROJ: A and B tiles are re-read by other tiles -> EVICT_LAST + if (EPI == EPI_OPROJ) { + // Wo16 is written by convert_w16 on the side stream: acquire, then order generic writes -> TMA reads + if (elect_one()) side_acquire(p.side_ctr, p.side_target); + __syncwarp(); + asm volatile("fence.proxy.async.global;" ::: "memory"); + } + for (int t = cid; t < num_tiles; t += ncl) { + int m0, mend, e, nt, sub; + coords(t, m0, mend, e, nt, sub); + // grouped remainder tile (<= 64 valid rows): only 64 A rows are loaded (M=64 MMA, tB2 = 64-row A map) + const bool m64 = grouped && (mend - m0 <= 64); + const uint32_t tx = grouped ? (uint32_t)((m64 ? A_BYTES / 2 : A_BYTES) + (sub < 0 ? 256 : 256 / spl) * 128) + : (sub >= 0 ? (uint32_t)(A_BYTES + (256 / spl) * 128) : stage_tx); + const bool vt = VS && nt * BN >= 4608; // VS: fp16 V tile (2x the k-blocks of 64 K) + const int kbt = vt ? 2 * KB : KB; + for (int kb = 0; kb < kbt; kb++, it++) { + if (PAIR) { + const int s = it % NST; + mbar_wait_cl2(bar_empty + 8 * s, ((it / NST) & 1) ^ 1); + const uint32_t fb = bar_full + 8 * s; + const uint32_t sa = sbase + s * SBYTES, sb = sa + A_BYTES; + const uint32_t fbl = mapa_sh(fb, 0); // leader's full barrier tracks both CTAs' bytes + __syncwarp(); +#ifdef ABL_PROBE + if (p.abl & 4) { if (elect_one() && rank == 0) mbar_arrive(fb); __syncwarp(); continue; } +#endif + if (elect_one()) { // whole warp waits, one elected lane issues expect_tx + both TMAs + if (rank == 0) mbar_expect_tx(fb, 2 * SBYTES); + if (vt) { + tma_load_2d_cg2(sa, &tB4, kb * 64, m0, fbl, kpol); + tma_load_2d_cg2(sb, &tB3, kb * 64, nt * 256 - 4608 + 128 * (int)rank, fbl, kpol); + } else { + tma_load_2d_cg2(sa, &tA, kb * KE, m0, fbl, kpol); + tma_load_2d_cg2(sb, &tB0, kb * KE, nt * 256 + 128 * (int)rank, fbl, kpol); + } + } + __syncwarp(); + continue; + } + const int s = it % TSTAGES; + const uint32_t ph = (it / TSTAGES) & 1; + CPT(pe0); + mbar_wait(bar_empty + 8 * s, ph ^ 1); + CPT(pe1); + CPA(8, pe1 - pe0); + CPA(11, 1); + const uint32_t fb = bar_full + 8 * s; + __syncwarp(); +#ifdef TC_PROBE + if (p.pmode == 1 || p.pmode == 3) { if (elect_one()) mbar_arrive(fb); __syncwarp(); continue; } // MMA-only probe +#endif + if (elect_one()) { + mbar_expect_tx(fb, EPI == EPI_ROUTER ? (uint32_t)STAGE_BYTES : tx); + const uint32_t sa = sbase + s * STAGE_BYTES, sb = sa + A_BYTES; + const int kx = kb * KE; + if (EPI == EPI_ROUTER) { + const int g = nt * KB + kb, pass = g >> 6, gx = (g & 63) * 32; + tma_load_2d(sa, pass < 2 ? &tA : &tB2, gx, m0, fb); + tma_load_2d(sb, pass == 1 ? &tB1 : &tB0, gx, 0, fb); + } else if (vt) { + const int kv = kb * 64; + tma_load_2d_hint(sa, &tB2, kv, m0, fb, kpol); + if (sub >= 0) tma_load_2d_hint(sb, &tB4, kv, nt * 256 - 4608 + sub * 128, fb, kpol); + else tma_load_2d_hint(sb, &tB3, kv, nt * BN - 4608, fb, kpol); + } else { + if (F16) tma_load_2d_hint(sa, &tA, kx, m0, fb, kpol); + else tma_load_2d(sa, (grouped && m64) ? &tB2 : &tA, kx, m0, fb); + if (EPI == EPI_QKV && sub >= 0) { + tma_load_2d_hint(sb, &tB1, kx, nt * 256 + sub * (256 / spl), fb, kpol); // tail half (one head) / V quarter + } else if (EPI == EPI_OPROJ && sub >= 0) { + // tail sub-tile: 256/spl Wo rows of the (BN = 256) n tile + tma_load_2d_hint(sb, &tB1, kx, nt * 256 + sub * (256 / spl), fb, kpol); + } else if (EPI == EPI_QKV || EPI == EPI_OPROJ) { + tma_load_2d_hint(sb, &tB0, kx, nt * BN, fb, kpol); + } else if (EPI == EPI_GATEUP) { + // gate/up maps use 64-row boxes. Full tile: gate rows r0..r0+127 -> sb, up -> sb + 16 KB. + // Half tile: 64 gate rows -> sb, 64 up rows -> sb + 8 KB (an N=128 B operand). + // Quarter tile: 32 gate rows -> sb, 32 up rows -> sb + 4 KB (N=64 B operand). + const int r0 = e * INTER + nt * 128 + (sub > 0 ? sub * (128 / spl) : 0); + if (sub >= 0 && spl == 4) { + tma_load_2d(sb, &tB3, kx, r0, fb); + tma_load_2d(sb + 4096, &tB4, kx, r0, fb); + } else if (sub < 0) { + tma_load_2d(sb, &tB0, kx, r0, fb); + tma_load_2d(sb + 8192, &tB0, kx, r0 + 64, fb); + tma_load_2d(sb + 16384, &tB1, kx, r0, fb); + tma_load_2d(sb + 24576, &tB1, kx, r0 + 64, fb); + } else { + tma_load_2d(sb, &tB0, kx, r0, fb); + tma_load_2d(sb + 8192, &tB1, kx, r0, fb); + } + } else { + // down map uses 128-row boxes: full tile = 2 boxes, half tile = 1 box + const int r0 = e * HID + nt * TBN + (sub > 0 ? 128 : 0); + tma_load_2d(sb, &tB0, kx, r0, fb); + if (sub < 0) tma_load_2d(sb + 16384, &tB0, kx, r0 + 128, fb); + } + } + } // elect_one + __syncwarp(); +#ifdef TC_PROBE + { CPT(pe2); CPA(9, pe2 - pe1); } +#endif + } + } + if (PAIR) { + // drain: every stage's last multicast commit has landed in this CTA before it can exit + for (int i = 0; i < NST; i++, it++) mbar_wait_cl2(bar_empty + 8 * (it % NST), ((it / NST) & 1) ^ 1); + } + } + } else if (warp == 1) { + if (!PAIR || rank == 0) { // PAIR: the leader CTA issues the cta_group::2 MMAs + // ---------------- MMA issuer: the WHOLE warp runs the loop (barrier waits, descriptor / ring arithmetic + // stay warp-uniform -> uniform registers), one elected lane issues the tcgen05.mma / commit (CUTLASS-style + // elect_one_sync). probe at T=2984 (clock64, o_proj): with the former lane-0-only divergent loop the + // 4 MMAs of a k-block took ~222 cycles to ISSUE independent of N (N=128 tensor time = 256/kb), and the + // loop ran at ~512-530 cycles/kb for BOTH N=256 and N=128 even with no TMA (MMA-only) -> issue-bound at + // N=128; feed-only (no MMA) ran ~555/kb at N=256, skeleton (no TMA, no MMA) ~317/kb. + int it = 0, tc = 0; + int rs = 0; // smem ring stage (incremental, == it % TSTAGES) + uint32_t rph = 0; // its full-barrier parity (== (it / TSTAGES) & 1) + const uint64_t adesc0 = make_sdesc(sbase); // stage-0 A descriptor; others = + immediates +#ifdef TC_PROBE + const long long mt0 = clock64(); + const int pmode = p.pmode; +#else + constexpr int pmode = 0; +#endif + for (int t = cid; t < num_tiles; t += ncl, tc++) { + const int buf = tc & 1; + const uint32_t aph = (tc >> 1) & 1; + int idesc_tf32 = (int)IDESC_TF32; + uint32_t idesc_h = idesc_f16; + bool f8t = F8; // VS: per-tile operand kind + int kbt = KB; + if (VS) { + int m0, mend, e, nt, sub; + coords(t, m0, mend, e, nt, sub); + if (nt * BN >= 4608) { f8t = false; kbt = 2 * KB; } + } + if ((EPI == EPI_QKV || EPI == EPI_OPROJ) && nsplit > 0) { + int m0, mend, e, nt, sub; + coords(t, m0, mend, e, nt, sub); + if (sub >= 0) // N = 256 / spl (QKV: 128; OPROJ: 128 or 64) + idesc_h = (1u << 4) | ((uint32_t)((256 / spl) >> 3) << 17) | ((128u >> 4) << 24); + } + if (grouped) { + int m0, mend, e, nt, sub; + coords(t, m0, mend, e, nt, sub); + if (sub >= 0) // N = 256 / spl (128 or 64) + idesc_tf32 = (int)((IDESC_TF32 & ~(0x3Fu << 17)) | ((uint32_t)((256 / spl) >> 3) << 17)); + // remainder tile with <= 64 valid rows: M=64 MMA (idesc M field bits 24..28 = M >> 4) + if (mend - m0 <= 64) idesc_tf32 = (int)(((uint32_t)idesc_tf32 & ~(0x1Fu << 24)) | ((64u >> 4) << 24)); + } + CPT(te0); + // SR pair leader tempty wait test-first then suspend-hinted cluster try_wait (sync only) + if (PAIR) { if (!mbar_test_cl2(bar_tempty + 8 * buf, aph ^ 1)) mbar_wait_cl2_hint(bar_tempty + 8 * buf, aph ^ 1); } // both CTAs' epilogues drained it + else if (!mbar_test(bar_tempty + 8 * buf, aph ^ 1)) mbar_wait_hint(bar_tempty + 8 * buf, aph ^ 1); // SR 1-CTA test-first + CPT(te1); + CPA(3, te1 - te0); + tc_fence_after(); + const uint32_t dt = tbase + buf * TBN; + const uint32_t idsc = F16 ? idesc_h : (uint32_t)idesc_tf32; + if (PAIR) { + // leader: m256n256k16 cta_group::2 MMAs, A = both CTAs' 128-row A halves, B = both 128-row B halves + constexpr uint32_t IDESC_F16_M256 = (1u << 4) | ((256u >> 3) << 17) | ((256u >> 4) << 24); + for (int kb = 0; kb < kbt; kb++) { + mbar_wait_cl2(bar_full + 8 * rs, rph); + tc_fence_after(); + const uint64_t ad = adesc0 + (uint64_t)(rs * (SBYTES >> 4)); + const uint64_t bd = ad + (uint64_t)(A_BYTES >> 4); + __syncwarp(); +#ifdef ABL_PROBE + if (p.abl & 2) { if (elect_one()) mma_commit_cg2(bar_empty + 8 * rs); __syncwarp(); if (++rs == NST) { rs = 0; rph ^= 1u; } continue; } +#endif + if (elect_one()) { + if (f8t) mma_f8_cg2(dt, ad, bd, IDESC_F16_M256, kb > 0 ? 1u : 0u); else mma_f16_cg2(dt, ad, bd, IDESC_F16_M256, kb > 0 ? 1u : 0u); + if (f8t) mma_f8_cg2(dt, ad + 2, bd + 2, IDESC_F16_M256, 1u); else mma_f16_cg2(dt, ad + 2, bd + 2, IDESC_F16_M256, 1u); + if (f8t) mma_f8_cg2(dt, ad + 4, bd + 4, IDESC_F16_M256, 1u); else mma_f16_cg2(dt, ad + 4, bd + 4, IDESC_F16_M256, 1u); + if (f8t) mma_f8_cg2(dt, ad + 6, bd + 6, IDESC_F16_M256, 1u); else mma_f16_cg2(dt, ad + 6, bd + 6, IDESC_F16_M256, 1u); + mma_commit_cg2(bar_empty + 8 * rs); // stage free in both CTAs once these MMAs retire + } + __syncwarp(); + if (++rs == NST) { rs = 0; rph ^= 1u; } + } + it += kbt; + __syncwarp(); + if (elect_one()) mma_commit_cg2(bar_tfull + 8 * buf); // accumulator complete (both CTAs) + __syncwarp(); + continue; + } + // issue diet: the k-block body has no per-MMA descriptor construction (stage descriptors = + // precomputed base + immediates, +2 per 16/8-K step = 32 B), no it % TSTAGES / it / TSTAGES + // (incremental ring index + parity), kb = 0 peeled so the accumulate predicate is a constant, and + // the full-barrier wait uses try_wait with a suspend-time hint (no hot polling loop). + auto kbody = [&](auto first_tag) { + constexpr bool FIRST = decltype(first_tag)::value; + CPT(m0c); + if (!mbar_test(bar_full + 8 * rs, rph)) mbar_wait_hint(bar_full + 8 * rs, rph); // SR 1-CTA test-first full wait + CPT(m1c); + CPA(0, m1c - m0c); + CPA(4, 1); + tc_fence_after(); + const uint64_t ad = adesc0 + (uint64_t)(rs * (STAGE_BYTES >> 4)); + const uint64_t bd = ad + (uint64_t)(A_BYTES >> 4); + __syncwarp(); + if (pmode >= 2) { + if (elect_one()) mma_commit(bar_empty + 8 * rs); + } else if (elect_one()) { + if (F8 && f8t) { + mma_f8_ss(dt, ad, bd, idsc, FIRST ? 0u : 1u); + mma_f8_ss(dt, ad + 2, bd + 2, idsc, 1u); + mma_f8_ss(dt, ad + 4, bd + 4, idsc, 1u); + mma_f8_ss(dt, ad + 6, bd + 6, idsc, 1u); + } else if (F16) { + mma_f16_ss(dt, ad, bd, idsc, FIRST ? 0u : 1u); + mma_f16_ss(dt, ad + 2, bd + 2, idsc, 1u); + mma_f16_ss(dt, ad + 4, bd + 4, idsc, 1u); + mma_f16_ss(dt, ad + 6, bd + 6, idsc, 1u); + } else { + mma_tf32(dt, ad, bd, idsc, FIRST ? 0u : 1u); + mma_tf32(dt, ad + 2, bd + 2, idsc, 1u); + mma_tf32(dt, ad + 4, bd + 4, idsc, 1u); + mma_tf32(dt, ad + 6, bd + 6, idsc, 1u); + } + mma_commit(bar_empty + 8 * rs); + } + __syncwarp(); + CPT(m2c); + CPA(1, m2c - m1c); + CPT(m3c); + CPA(2, m3c - m2c); + if (++rs == TSTAGES) { rs = 0; rph ^= 1u; } + }; + kbody(std::integral_constant{}); +#pragma unroll 1 + for (int kb = 1; kb < kbt; kb++) kbody(std::integral_constant{}); + it += kbt; + __syncwarp(); + if (elect_one()) mma_commit(bar_tfull + 8 * buf); + __syncwarp(); + } +#ifdef TC_PROBE + CPA(5, clock64() - mt0); +#endif + PRB(3); + } + } + } else { + // ---------------- epilogue warps EW0..EW0+7 (2..9; QKV: 4..11) + if constexpr (EPI == EPI_QKV) { + // 3 epilogue warpgroups x 160 regs (128 x 24 + 384 x 160 = 64512 <= 64K regs per SM) + asm volatile("setmaxnreg.inc.sync.aligned.u32 160;\n" ::: "memory"); + // q / k norm weights -> smem (read per RoPE chunk as warp-broadcast ld.shared instead of global loads + // that ptxas hoisted across the unrolled chunk loop -> register pressure / spills). Epilogue warps only. + const int et = (warp - EW0) * 32 + lane; // 0..383 + if (et < 256) reinterpret_cast(smem + QKV_NW_OFF)[et] = et < 128 ? __ldg(p.qnw + et) : __ldg(p.knw + et - 128); + asm volatile("bar.sync 1, %0;" ::"r"(32 * 4 * SR_NEW) : "memory"); + } + calc_geom(); + if constexpr (EPI == EPI_OPROJ) { + // L2 discard of buffers dead once attention has completed (Wqkv16, xn, q, k, V^T, fp16 xn copy): + // griddepcontrol.wait above returned -> QKV GEMM + attention (their only readers) are complete; their next + // writers (prep_qkv / QKV of the NEXT call) are ordered after this call's router/MoE (PDL chain). Done by + // the epilogue warps before their first accumulator wait (they are idle during the mainloop), so the + // router (critical path) only discards Wo16 / attn. Each range is fully rewritten before its next read. + const unsigned long long nth = (unsigned long long)gridDim.x * 256ull; + const unsigned long long gt = (unsigned long long)blockIdx.x * 256ull + (unsigned long long)((warp - 2) * 32 + lane); + for (int r = 0; r < p.dl.n; r++) { + const char* base = reinterpret_cast(p.dl.p[r]); + const unsigned long long nl = (p.dl.bytes[r] + 127) >> 7; + for (unsigned long long i = gt; i < nl; i += nth) + asm volatile("discard.global.L2 [%0], 128;" ::"l"(base + (i << 7)) : "memory"); + } + } + // o_proj fp8 dequant row factor hoisted out of the per-tile loop (vmax final after the PDL wait) + const float rf8c = (EPI == EPI_OPROJ && F8) ? 1024.f / f8_scale(__uint_as_float(*p.vmax) * 0.0009765625f, 7) : 0.f; + const int q = warp & 3; + int half = 0; // per job (head of the tile), see job loop below + const int ew_set = (warp - EW0) >> 2; // epilogue warpgroup 0..SR_NEW-1 + const int row = q * 32 + lane; + int tc = 0; + // OPROJ TMA epilogue I/O: per-warp 2 x 2 KB slots (32 rows x 16 fp32 = 64 B rows, 64B swizzle: 16 B unit j of + // row r at unit j ^ ((r >> 1) & 3), conflict-free per quarter warp) + one mbarrier per slot; rph = slot parities + const uint32_t opj_slot0 = sbase + OPJ_STG_OFF + (uint32_t)(warp - 2) * 4096u; + const uint32_t opj_bar0 = sbase + TSTAGES * STAGE_BYTES + 512 + (uint32_t)(warp - 2) * 16u; + uint32_t rph = 0; + int opj_row0 = 0; // first tile row of this warp (set per tile) + // lane 0 only: TMA load of the resid half-chunk k (columns col .. col+15, rows opj_row0 .. +31) into slot k & 1 + auto opj_rload = [&](int k, int col) { + const uint32_t bar = opj_bar0 + 8u * (uint32_t)(k & 1); + mbar_expect_tx(bar, 2048u); + tma_load_2d(opj_slot0 + 2048u * (uint32_t)(k & 1), &tB4, col, opj_row0, bar); + }; + // SR_NEW epilogue warpgroups pull (tile, head) jobs round-robin: job jb = 2 x (local tile tc) + head; + // warpgroup w handles jobs w, w + SR_NEW, ... in order (each tile's 2 jobs -> 8 tempty arrivals per CTA, as before) + for (int jb = ew_set; cid + (jb >> 1) * ncl < num_tiles; jb += SR_NEW) { + tc = jb >> 1; half = jb & 1; + const int t = cid + tc * ncl; + int m0, mend, e, nt, sub; + coords(t, m0, mend, e, nt, sub); + opj_row0 = m0 + q * 32; + const int tbn = ((grouped || EPI == EPI_OPROJ) && sub >= 0) ? 256 / spl : (grouped ? TBN : BN); // this tile's N width + const int sub_off = sub > 0 ? 1 : 0; + const int buf = tc & 1; + const uint32_t aph = (tc >> 1) & 1; + // M=64 accumulator layout (1-CTA): row r lives in TMEM lane (r % 16) + 32 * (r / 16), i.e. lanes 0-15 of + // each warp quadrant; lanes 16-31 of the quadrant hold nothing for that tile. + const bool m64 = grouped && (mend - m0 <= 64); + const int erow = m64 ? q * 16 + lane : row; + const int pos = m0 + erow; + const bool valid = (!m64 || lane < 16) && pos < mend; + // DOWN: prefetch this tile's routing metadata (token index / weight of each row, and the per-lane + // row token indices for the coalesced scatter) BEFORE waiting on the accumulator, so the global-load + // latency overlaps the mainloop of this tile instead of sitting on the epilogue critical path. + int tok = 0; float rw = 0.f; + int rtok[4]; bool rval[4]; + if (EPI == EPI_DOWN) { + if (valid) { tok = __ldg(p.perm_tok + pos); rw = __ldg(p.perm_w + pos); } +#pragma unroll + for (int it = 0; it < 4; it++) { + const int r = it * 8 + (lane >> 2); + rtok[it] = __shfl_sync(0xffffffff, tok, r); + rval[it] = __shfl_sync(0xffffffff, (int)valid, r) != 0; + } + } + // OPROJ: residual of this warp's 32 rows is TMA-loaded per 16-column half-chunk k (column + // on0 + 16 k) into a 2-slot per-warp smem ring; the first two half-chunks are issued here, BEFORE the + // accumulator wait (resid is a kernel input), the rest one half-chunk ahead inside the chunk loop. + const int on0 = nt * BN + (sub >= 0 ? sub * tbn : 0) + half * (tbn >> 1); // o_proj column of chunk 0 + const bool wact = EPI == EPI_OPROJ && m0 + q * 32 < p.M; // warp-uniform: any valid row in this warp + if (EPI == EPI_OPROJ && wact && lane == 0) { + asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); // previous stores done reading slots + opj_rload(0, on0); + opj_rload(1, on0 + 16); + // L2 prefetch of the remaining resid half-chunks of this warp's 32 rows (input-only data) before + // the accumulator wait: the in-loop TMA loads (one half-chunk ahead) then hit L2 instead of DRAM + for (int kk = 2; kk < (tbn >> 5); kk++) + asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile [%0, {%1, %2}];" ::"l"((uint64_t)&tB4), + "r"(on0 + 16 * kk), "r"(opj_row0) : "memory"); + } + // QKV q/k heads: RoPE table prefetch, QPF chunks ahead. A chunk jj (j = q_j0 + jj) = the 8 cos / 8 sin + // values of columns 8j..8j+7 and 64+8j..+7 of this row (transposed tables: float4 group g at cr4[g*32]). + // The first QPF chunks are issued at the start of pass 1, the rest + // QPF chunks ahead inside the RoPE loop, so the L2 latency is no longer paid once per chunk. + // (Issued inside the q/k branch, not before the accumulator wait: keeping them live into the V-head + // branch, whose 128-float row is register-resident, made ptxas spill.) + // e4m3-operand instantiations prefetch no table chunks ahead (register pressure); fp16 keep 3 + constexpr int QPF = F8 ? QKV_QPF_F8 : QKV_QPF_F16; + uint4 qc[8][2], qs[8][2]; // [chunk][0: cols 8j.., 1: cols 64+8j..] fp16 x 2^-4 + int q_hidx = 0, q_j0 = 0, q_nj = 0; + float q_rx = 0.f; + // ONE 32-bit uint4 offset into the fp16 RoPE tables (the two 64-bit table row pointers were live + // through pass 1 and the RoPE loop and got spilled); addresses re-formed from the param bases per load + uint32_t q_toff = 0; + auto q_ld = [&](int jj) { + const int j = q_j0 + jj; + const uint4* q_cr4 = reinterpret_cast(p.cs) + q_toff; + const uint4* q_sr4 = reinterpret_cast(p.sn) + q_toff; + // 8 B halves (register-pair destinations instead of aligned quads; same bytes / sectors) + // one 16 B read-only load per table unit (was two 8 B halves, register-pressure choice + // for the old 232-reg epilogue; same bytes / sectors, half the load instructions) + auto ld16 = [](const uint4* q) { return __ldg(q); }; + qc[jj][0] = ld16(q_cr4 + j * 32); qc[jj][1] = ld16(q_cr4 + (8 + j) * 32); + qs[jj][0] = ld16(q_sr4 + j * 32); qs[jj][1] = ld16(q_sr4 + (8 + j) * 32); + }; + if (EPI == EPI_QKV && QF) { + const bool qfull = BN == 256 && sub < 0; + q_hidx = BN == 256 ? (sub < 0 ? nt * 2 + half : nt * 2 + sub) : nt; + q_j0 = qfull ? 0 : half * 4; + q_nj = qfull ? 8 : 4; + const int posc = pos < p.M ? pos : p.M - 1; // rows past M (zero-filled tile rows): clamp, never stored + q_toff = (uint32_t)(posc >> 5) * 512u + (uint32_t)(posc & 31); + // weight-folded tables, k heads use the second table half (offset ceil(M/32) * 512 uint4) + if (q_hidx >= 32 && q_hidx < 36) q_toff += (uint32_t)((p.M + 31) >> 5) * 512u; + if constexpr (F8) q_rx = __ldg(p.qxs + posc); // inverse e4m3 scale of this xn row + } +#ifdef TC_PROBE + const long long ew0 = clock64(); +#endif +#ifdef ABL_PROBE + if (p.abl & 1) { + if (PAIR) mbar_wait_cl2(bar_tfull + 8 * buf, aph); else mbar_wait(bar_tfull + 8 * buf, aph); + tc_fence_after(); tc_fence_before(); __syncwarp(); + if (elect_one()) tempty_arrive(buf); + continue; + } +#endif + if (PAIR) mbar_wait_cl2_tf(bar_tfull + 8 * buf, aph); // epilogue warps sleep during the pair mainloop + // 1-CTA SR QKV (2048 <= T < 6000): the idle epilogue warpgroups (>= 1 of 3 always waiting on a + // buffer) sleep on tfull (test-first + suspend hint) instead of hot-polling, freeing issue slots for the + // producer / MMA warps and the active epilogue warpgroups. Sync only, numerics identical. + else { if (!mbar_test(bar_tfull + 8 * buf, aph)) mbar_wait_hint(bar_tfull + 8 * buf, aph); } +#ifdef TC_PROBE + if (warp == 2 && lane == 0) { CPA(12, clock64() - ew0); CPA(13, 1); } +#endif + if (warp == 2 && lane == 0) { if (tc == 0) PRB(4); PRB(5); } + tc_fence_after(); + const uint32_t trow = tbase + ((uint32_t)(q * 32) << 16) + buf * TBN; + if (EPI == EPI_QKV && QF) { + // T >= QKV_F16TAB_MIN_T: fp16 RoPE tables (x 2^-4), accumulator streamed from TMEM in two passes + // BN=256: two heads per tile, warpgroup `half` owns head nt*2+half entirely. + // BN=128 / split tail tile: one head per tile; both warpgroups read the full head row (needed for the + // q/k RMSNorm) and each handles the RoPE chunks j in [half*4, half*4+4) (pairs d <-> d+64). + const bool full = BN == 256 && sub < 0; + const int hidx = q_hidx; + const uint32_t cb = trow + (full ? half * 128 : 0); // this head's 128 accumulator columns + const int b = pos / p.S, s = pos - b * p.S; + if (hidx < 36) { + // ---- q / k head. The accumulator row is NOT kept in registers: pass 1 streams it from TMEM in + // 32-column chunks (bias + sum of squares), pass 2 re-reads the 16 columns of each RoPE chunk + // from TMEM; the freed registers hold the prefetched RoPE tables. TMEM is released after pass 2. + // Arithmetic (op order, accumulator assignment) identical to the former register-resident version. + const float* bb = hidx < 32 ? p.bias0 + hidx * 128 : p.bias1 + (hidx - 32) * 128; +#pragma unroll + for (int jj = 0; jj < QPF; jj++) q_ld(jj); // first RoPE chunks: latency overlaps pass 1 + float2 ssa[4]; +#pragma unroll + for (int i = 0; i < 4; i++) ssa[i] = make_float2(0.f, 0.f); + const uint32_t ycb = full ? cb : cb + 128; // where pass 1 leaves y for pass 2 + const float2 sc16 = make_float2(0.0625f, 0.0625f); + const float* wsc = F8 ? p.qws + hidx * 128 : nullptr; // this head's Wqkv rows + const float2 rx2 = make_float2(q_rx, q_rx); +#pragma unroll + for (int c = 0; c < 4; c++) { + float a[32]; + // bias / Wqkv scale columns of this chunk loaded before the TMEM load wait + float4 qb4[8], qw4[8]; +#pragma unroll + for (int d = 0; d < 8; d += 2) { + // 256-bit loads (ld.global.nc.v8.f32, sm_100; 32 B aligned: 256 B buffer bases + + // multiples of 8 floats) -> half the broadcast load instructions per chunk, same values + ldg_v8f(bb + c * 32 + 4 * d, qb4[d], qb4[d + 1]); + if constexpr (F8) ldg_v8f(wsc + c * 32 + 4 * d, qw4[d], qw4[d + 1]); + } + { // 4 x 8-column loads, one wait (8-register destination blocks) +#pragma unroll + for (int q8 = 0; q8 < 4; q8++) tmem_ld8q_nw(cb + c * 32 + 8 * q8, a + 8 * q8); + tmem_wait_ld(); + } +#pragma unroll + for (int d = 0; d < 32; d += 4) { // packed FFMA2: acc * 2^-4 + bias, then sum of squares + const float4 b4 = qb4[d >> 2]; + float2 f01 = sc16, f23 = sc16; + if constexpr (F8) { // per-column dequant factor (both scales exact powers of 2) + const float4 w4 = qw4[d >> 2]; + f01 = fmul2(make_float2(w4.x, w4.y), rx2); f23 = fmul2(make_float2(w4.z, w4.w), rx2); + } + const float2 y0 = ffma2(make_float2(a[d], a[d + 1]), f01, make_float2(b4.x, b4.y)); + const float2 y1 = ffma2(make_float2(a[d + 2], a[d + 3]), f23, make_float2(b4.z, b4.w)); + ssa[(d >> 1) & 3] = ffma2(y0, y0, ssa[(d >> 1) & 3]); + ssa[((d + 2) >> 1) & 3] = ffma2(y1, y1, ssa[((d + 2) >> 1) & 3]); + a[d] = y0.x; a[d + 1] = y0.y; a[d + 2] = y1.x; a[d + 3] = y1.y; + } + // dequantized + biased y written back over its accumulator columns (this tile owns the + // buffer until tempty_arrive): pass 2 reads y directly (no bias / scale reloads, no re-FFMA) + // full head per warpgroup: in place. Shared head (BN=128 / split tail): both warpgroups read all + // 4 raw chunks, so each writes ONLY its own RoPE chunks into the unused upper 128 columns of + // this accumulator buffer (the N=128 MMA never writes them) + if (full || (c & 1) == half) { +#pragma unroll + for (int q8 = 0; q8 < 4; q8++) tmem_st8_e(ycb + c * 32 + 8 * q8, a + 8 * q8); + } + } + asm volatile("tcgen05.wait::st.sync.aligned;" ::: "memory"); +#ifdef TC_PROBE + if (warp == 2 && lane == 0) CPA(6, clock64() - ew0); +#endif + const float ss = ((ssa[0].x + ssa[0].y) + (ssa[1].x + ssa[1].y)) + ((ssa[2].x + ssa[2].y) + (ssa[3].x + ssa[3].y)); + // rstd with the output 2^-6 pre-scale folded in (exact power of 2) + // x 2^4 compensates the 2^-4 fp16 table pre-scale (exact): net 2^-2 + const float r = rsqrtf(ss * (1.f / 128.f) + p.eps) * 0.25f; + const float* w = reinterpret_cast(smem + QKV_NW_OFF) + (hidx < 32 ? 0 : 128); // smem copy + __half* dst = hidx < 32 ? p.q + (((size_t)b * 32 + hidx) * p.S + s) * 128 + : p.k + (((size_t)b * 4 + (hidx - 32)) * p.S + s) * 128; + // FP8 QK^T mode: same row index, 128 e4m3 bytes per row; o (= natural x 2^-6) x (64 x scale) + uint8_t* dst8 = hidx < 32 ? reinterpret_cast(p.q) + (((size_t)b * 32 + hidx) * p.S + s) * 128 + : reinterpret_cast(p.k) + (((size_t)b * 4 + (hidx - 32)) * p.S + s) * 128; + const float q8m = p.qkb ? 64.f * qk8_scale(p.qkb, hidx < 32 ? 0 : 1) : 0.f; + // q8m is an exact power of 2 -> w * (a * (r q8m)) == (w * (a * r)) * q8m (bit-identical) + const float rq = p.qkb ? r * q8m : r; + const float2 rv2 = make_float2(rq, rq); +#if QKV_CST + // target rows of the transposed stores = rows (lane & ~3) + i of this warp (row pointers and + // validity shuffled once per tile; consecutive tokens may straddle a batch boundary) + const int cg4 = lane & 3; + // row pointers are NOT held as 4 live 64-bit values through the RoPE loop (register pressure -> + // spills); the own row pointer + a warp validity ballot stay live and each target row pointer is + // re-shuffled (volatile, not CSE'd/hoisted) right at the store. Same addresses / bytes. + const unsigned long long rp = (unsigned long long)(p.qkb ? reinterpret_cast(dst8) : reinterpret_cast(dst)); + const unsigned vbal = __ballot_sync(0xffffffffu, valid); + uint4 cu[4]; // 4 transposable 16 B units (one chunk pair / 4-chunk e4m3 group) + auto tr4 = [&](uint4* u) { // u[c] = own unit c -> u[i] = unit (lane & 3) of row (lane & ~3) + i +#pragma unroll + for (int m = 1; m <= 2; m <<= 1) { + const bool bit = (lane & m) != 0; +#pragma unroll + for (int c0 = 0; c0 < 4; c0++) { + if (c0 & m) continue; + const int c1 = c0 | m; + const uint4 snd = bit ? u[c0] : u[c1]; + uint4 rcv; + rcv.x = __shfl_xor_sync(0xffffffffu, snd.x, m); + rcv.y = __shfl_xor_sync(0xffffffffu, snd.y, m); + rcv.z = __shfl_xor_sync(0xffffffffu, snd.z, m); + rcv.w = __shfl_xor_sync(0xffffffffu, snd.w, m); + if (bit) u[c0] = rcv; else u[c1] = rcv; + } + } + }; +#endif + // RoPE chunk loop, chunk count NJ (8 full head, 4 half head) as a compile-time constant + // e4m3 (QB) / fp16 q-k output decided at compile time per rope instance (fewer live values) + auto rope = [&](auto nj_tag, auto qb_tag) { + constexpr int NJ = decltype(nj_tag)::value; + constexpr bool QB = decltype(qb_tag)::value; + uint2 pl8 = make_uint2(0u, 0u), ph8 = make_uint2(0u, 0u); // held even-chunk e4m3 bytes + float pr_a1[8], pr_a2[8]; // PR2: next (odd) chunk y +#pragma unroll + for (int jj = 0; jj < NJ; jj++) { + constexpr bool PR2 = QKV_PR2 && QPF == 0; // chunk pairs (j0 even -> jj parity == j parity) + if (PR2) { if ((jj & 1) == 0) { q_ld(jj); q_ld(jj + 1); } } + else if (jj + QPF < NJ) q_ld(jj + QPF); // keep QPF chunks in flight + const int j = q_j0 + jj; + float a1[8], a2[8], w1[8], w2[8]; +#ifdef TC_PROBE + const long long rl0 = clock64(); +#endif + if (PR2) { // y of chunks j, j+1 loaded together (one wait) at the even chunk + if ((jj & 1) == 0) + { + tmem_ld8q_nw(ycb + j * 8, a1); tmem_ld8q_nw(ycb + 64 + j * 8, a2); + tmem_ld8q_nw(ycb + (j + 1) * 8, pr_a1); tmem_ld8q_nw(ycb + 64 + (j + 1) * 8, pr_a2); + tmem_wait_ld(); + } + else { +#pragma unroll + for (int i = 0; i < 8; i++) { a1[i] = pr_a1[i]; a2[i] = pr_a2[i]; } + } + } else + { tmem_ld8q_nw(ycb + j * 8, a1); tmem_ld8q_nw(ycb + 64 + j * 8, a2); tmem_wait_ld(); } +#ifdef TC_PROBE + if (warp == 2 && lane == 0) CPA(7, clock64() - rl0); +#endif + // a1 / a2 = y (biased, dequantized) from pass 1 + // q/k norm weights folded into the prep RoPE tables (A = w c, B = w(j^64) s) + + + + float c1[8], c2[8], s1[8], s2[8]; + { + auto unpack8 = [](const uint4 u, float* f) { + // no address-taken local array (word -> 2 x cvt.f32.f16, bit-identical) + auto h2f = [](uint32_t w, float* o) { + o[0] = __half2float(__ushort_as_half((unsigned short)(w & 0xFFFFu))); + o[1] = __half2float(__ushort_as_half((unsigned short)(w >> 16))); + }; + h2f(u.x, f); h2f(u.y, f + 2); h2f(u.z, f + 4); h2f(u.w, f + 6); + }; + unpack8(qc[jj][0], c1); unpack8(qc[jj][1], c2); + unpack8(qs[jj][0], s1); unpack8(qs[jj][1], s2); + } + float o1[8], o2[8]; +#pragma unroll + for (int i = 0; i < 8; i += 2) { // packed: x = w * (a * r); RoPE as FMUL2 + FFMA2 + const float2 aa1 = make_float2(a1[i], a1[i + 1]), aa2 = make_float2(a2[i], a2[i + 1]); + const float2 y1 = fmul2(ffma2(aa1, make_float2(c1[i], c1[i + 1]), fmul2(aa2, make_float2(s1[i], s1[i + 1]))), rv2); + const float2 y2 = fmul2(ffma2(aa2, make_float2(c2[i], c2[i + 1]), fmul2(aa1, make_float2(s2[i], s2[i + 1]))), rv2); + + o1[i] = y1.x; o1[i + 1] = y1.y; o2[i] = y2.x; o2[i + 1] = y2.y; + } +#ifdef TC_PROBE + const uint4 h1_ = pack8_h(o1), h2_ = pack8_h(o2); + const long long rs0 = clock64(); + if (valid) { + *reinterpret_cast(dst + j * 8) = h1_; + *reinterpret_cast(dst + 64 + j * 8) = h2_; + } + if (warp == 2 && lane == 0) CPA(2, clock64() - rs0); +#else +#if QKV_CST + // coalesced q/k stores: a lane's row segment of 4 x 16 B units is 4x4-transposed inside its + // 4-lane group (2 xor-shuffle rounds), so each st.v4 writes 8 rows x 64 contiguous bytes (full + // sectors) instead of 32 rows x 16 B. fp16: groups of 4 chunks (units = chunk lo / hi 16 B); + // e4m3 full head (NJ = 8): all 8 chunks buffered (unit = 2 chunks' 8 B). Identical bytes. + if (QB && NJ == 8) { + const uint2 l8 = make_uint2(cvt_e4m3x4p(o1[0], o1[1], o1[2], o1[3]), + cvt_e4m3x4p(o1[4], o1[5], o1[6], o1[7])); + const uint2 h8 = make_uint2(cvt_e4m3x4p(o2[0], o2[1], o2[2], o2[3]), + cvt_e4m3x4p(o2[4], o2[5], o2[6], o2[7])); + // groups of 4 chunks (16 regs buffered, was all 8 chunks = 32): unit g = lo bytes of + // chunks 4m+2g, +1; unit 2+g = hi bytes. After the transpose a row's 4 lanes write two 32 B + // runs (lo / hi, 32 B aligned) per st.v4 -> still full sectors, same bytes, same #stores. + const int g = (jj >> 1) & 1; + if ((jj & 1) == 0) { cu[g].x = l8.x; cu[g].y = l8.y; cu[2 + g].x = h8.x; cu[2 + g].y = h8.y; } + else { cu[g].z = l8.x; cu[g].w = l8.y; cu[2 + g].z = h8.x; cu[2 + g].w = h8.y; } + if ((jj & 3) == 3) { + tr4(cu); + const int off = 8 * (jj - 3) + 16 * (cg4 & 1) + 64 * (cg4 >> 1); +#pragma unroll + for (int i = 0; i < 4; i++) { + char* const cti = shfl_ptr_v(rp, (lane & ~3) + i); // all lanes (convergent) + if ((vbal >> ((lane & ~3) + i)) & 1u) *reinterpret_cast(cti + off) = cu[i]; + } + } + } else if (!QB) { + // chunk pairs (j even, j + 1): units = lo j, lo j+1, hi j, hi j+1 (16 regs, was 32) + cu[jj & 1] = pack8_h(o1); cu[2 + (jj & 1)] = pack8_h(o2); + if (jj & 1) { + tr4(cu); + const int off = 16 * (j - 1) + 16 * (cg4 & 1) + 128 * (cg4 >> 1); +#pragma unroll + for (int i = 0; i < 4; i++) { + char* const cti = shfl_ptr_v(rp, (lane & ~3) + i); // all lanes (convergent) + if ((vbal >> ((lane & ~3) + i)) & 1u) *reinterpret_cast(cti + off) = cu[i]; + } + } + } else +#endif + if (valid && QB) { + const uint2 l8 = make_uint2(cvt_e4m3x4(o1[0], o1[1], o1[2], o1[3]), + cvt_e4m3x4(o1[4], o1[5], o1[6], o1[7])); + const uint2 h8 = make_uint2(cvt_e4m3x4(o2[0], o2[1], o2[2], o2[3]), + cvt_e4m3x4(o2[4], o2[5], o2[6], o2[7])); + if ((jj & 1) == 0) { pl8 = l8; ph8 = h8; } + else { + *reinterpret_cast(dst8 + (j - 1) * 8) = make_uint4(pl8.x, pl8.y, l8.x, l8.y); + *reinterpret_cast(dst8 + 64 + (j - 1) * 8) = make_uint4(ph8.x, ph8.y, h8.x, h8.y); + } + } else if (valid) { // q/k consumed by flash attention: EVICT_LAST + *reinterpret_cast(dst + j * 8) = pack8_h(o1); + *reinterpret_cast(dst + 64 + j * 8) = pack8_h(o2); + } +#endif + } + }; + if (p.qkb) { + if (q_nj == 8) rope(std::integral_constant{}, std::true_type{}); + else rope(std::integral_constant{}, std::true_type{}); + } else { + if (q_nj == 8) rope(std::integral_constant{}, std::false_type{}); + else rope(std::integral_constant{}, std::false_type{}); + } + tc_fence_before(); + __syncwarp(); + if (elect_one()) tempty_arrive(buf); // all TMEM reads of this tile done + } else { + float vmx = 0.f; // max |V| of this thread's stored columns (fp8 o_proj scale) + // S % 8 == 0 -> 8-lane groups hold 8 consecutive tokens of one batch (T % 8 == 0: a group is + // all valid or all past M): transposed 16 B stores; all lanes compute so the shuffles are complete + const bool vt8 = QKV_VT8 && (p.S & 7) == 0; + const float* bb = p.bias2 + (hidx - 36) * 128; + const float* wsc = F8 ? p.qws + hidx * 128 : nullptr; + const float2 rx2 = make_float2(q_rx, q_rx); + // V stored transposed (V^T [b][kv_head][d][Spad], x 2^-10: keeps |V| up to ~6.7e7 inside fp16 + // range, so large activations do not overflow to inf): K-major B operand for P.V + __half* dst = p.v + ((size_t)(b * 4 + (hidx - 36)) * 128) * p.Spad + s; +#pragma unroll 1 + for (int c = 0; c < 4; c++) { + float a[32]; + tmem_ld32(cb + c * 32, a); // all 4 chunks loaded by every warp (TMEM release after chunk 3) + if (c == 3) { + tc_fence_before(); + __syncwarp(); + if (elect_one()) tempty_arrive(buf); + } + if (!(full || (c >> 1) == half)) continue; // warp-uniform: columns of the other warpgroup + if (valid || vt8) { // (valid is per lane: no aligned tcgen05 ops inside) + float4 vb4[8], vw4[8]; +#pragma unroll + for (int d8 = 0; d8 < 8; d8 += 2) { + ldg_v8f(bb + c * 32 + 4 * d8, vb4[d8], vb4[d8 + 1]); + if constexpr (F8 && !VS) ldg_v8f(wsc + c * 32 + 4 * d8, vw4[d8], vw4[d8 + 1]); + } +#pragma unroll + for (int d = 0; d < 32; d += 4) { + const float4 b4 = vb4[d >> 2]; + float2 sc = make_float2(0.0625f, 0.0625f), sc23 = sc; + if constexpr (F8 && !VS) { // VS: V tiles are fp16 (x 2^4) - + const float4 w4 = vw4[d >> 2]; + sc = fmul2(make_float2(w4.x, w4.y), rx2); sc23 = fmul2(make_float2(w4.z, w4.w), rx2); + } + const float2 y0 = ffma2(make_float2(a[d], a[d + 1]), sc, make_float2(b4.x, b4.y)); + const float2 y1 = ffma2(make_float2(a[d + 2], a[d + 3]), sc23, make_float2(b4.z, b4.w)); + a[d] = y0.x; a[d + 1] = y0.y; a[d + 2] = y1.x; a[d + 3] = y1.y; + } + if (vt8) { + // 8x8 fp16 transpose inside each 8-lane group: lane t ends with d = 8k + t for the group's + // 8 tokens -> ONE 16 B store per 8 d instead of 8 2-byte stores. Identical fp16 bytes. + const int t = lane & 7; + __half* gdst = dst - t; // token s0 = s - t (multiple of 8) +#pragma unroll + for (int k4 = 0; k4 < 4; k4++) { + const int kk = 4 * c + k4; + const float* av = a + 8 * k4; + if (valid) // 3-input max (exact), 4 instead of 8 FMNMX per 8 values +#pragma unroll + for (int i = 0; i < 8; i += 2) vmx = fmax3(vmx, fabsf(av[i]), fabsf(av[i + 1])); + const uint4 o = vt8_transpose(av, lane); + if (valid) *reinterpret_cast(gdst + (size_t)(8 * kk + t) * p.Spad) = o; + } + } else { +#pragma unroll + for (int d = 0; d < 32; d++) { + dst[(size_t)(c * 32 + d) * p.Spad] = __float2half_rn(a[d] * 0.0009765625f); + vmx = fmaxf(vmx, fabsf(a[d])); + } + } + } + __syncwarp(); // reconverge before the next chunk's tcgen05.ld (.sync.aligned) + } + // fp8 o_proj path: warp max of |V| -> global atomicMax (bounds every attention output element) + if (p.vmax) { + const unsigned m = __reduce_max_sync(0xffffffffu, __float_as_uint(vmx)); + if (lane == 0 && m) atomicMax(p.vmax, m); + } + } +#ifdef TC_PROBE + if (warp == 2 && lane == 0) CPA(10, clock64() - ew0); +#endif + } else if (EPI == EPI_QKV && !QF && spl == 4 && sub >= 0) { + // V quarter tile (N = 64): columns 64 (sub & 1).. +63 of V head nt * 2 + (sub >> 1); warpgroup + // `half` owns 32 of them. Same per-element math as the full V path (acc * 2^-4 + bias, x 2^-10 fp16). + const int hidx = nt * 2 + (sub >> 1); + const int col0 = (sub & 1) * 64 + half * 32; + float a[32]; + tmem_ld32(trow + half * 32, a); + tc_fence_before(); + __syncwarp(); + if (elect_one()) tempty_arrive(buf); + float vmx = 0.f; + if (valid) { + const float* bb = p.bias2 + (hidx - 36) * 128 + col0; + const int b = pos / p.S, s = pos - b * p.S; + __half* dst = p.v + ((size_t)(b * 4 + (hidx - 36)) * 128 + col0) * p.Spad + s; +#pragma unroll + for (int d = 0; d < 32; d += 4) { + const float4 b4 = *reinterpret_cast(bb + d); + const float2 sc = make_float2(0.0625f, 0.0625f); + const float2 y0 = ffma2(make_float2(a[d], a[d + 1]), sc, make_float2(b4.x, b4.y)); + const float2 y1 = ffma2(make_float2(a[d + 2], a[d + 3]), sc, make_float2(b4.z, b4.w)); + a[d] = y0.x; a[d + 1] = y0.y; a[d + 2] = y1.x; a[d + 3] = y1.y; + } +#pragma unroll + for (int d = 0; d < 32; d++) { + dst[(size_t)d * p.Spad] = __float2half_rn(a[d] * 0.0009765625f); + vmx = fmaxf(vmx, fabsf(a[d])); + } + } + if (p.vmax) { + const unsigned m = __reduce_max_sync(0xffffffffu, __float_as_uint(vmx)); + if (lane == 0 && m) atomicMax(p.vmax, m); + } + } else if (EPI == EPI_QKV) { + // T < QKV_F16TAB_MIN_T: fp32 RoPE tables, register-resident accumulator row + // BN=256: two heads per tile, warpgroup `half` owns head nt*2+half entirely. + // BN=128: one head per tile; both warpgroups load the full head row (needed for q/k RMSNorm and + // the RoPE d <-> d+64 pairing) and each writes half of the output columns. + const bool full = BN == 256 && sub < 0; + const int hidx = BN == 256 ? (sub < 0 ? nt * 2 + half : nt * 2 + sub) : nt; + const int j0 = full ? 0 : half * 4, j1 = full ? 8 : half * 4 + 4; + float a[128]; +#pragma unroll + for (int c = 0; c < 4; c++) tmem_ld32(trow + (full ? half * 128 : 0) + c * 32, a + c * 32); + tc_fence_before(); + __syncwarp(); + if (elect_one()) tempty_arrive(buf); + float vmx = 0.f; // max |V| of this thread's stored columns (fp8 o_proj scale) + // all lanes compute (rows past M: zero accumulator, clamped table row, never stored) so the + // q/k 4-lane transposed stores and the V^T 8x8 lane transpose have complete warps + const bool vt8 = QKV_VT8 && (p.S & 7) == 0; + if (QKV_CST || valid) { + const float* bb = hidx < 32 ? p.bias0 + hidx * 128 + : (hidx < 36 ? p.bias1 + (hidx - 32) * 128 : p.bias2 + (hidx - 36) * 128); +#pragma unroll + for (int d = 0; d < 128; d += 4) { // packed FFMA2: acc * 2^-4 + bias + const float4 b4 = *reinterpret_cast(bb + d); + const float2 sc = make_float2(0.0625f, 0.0625f); + const float2 y0 = ffma2(make_float2(a[d], a[d + 1]), sc, make_float2(b4.x, b4.y)); + const float2 y1 = ffma2(make_float2(a[d + 2], a[d + 3]), sc, make_float2(b4.z, b4.w)); + a[d] = y0.x; a[d + 1] = y0.y; a[d + 2] = y1.x; a[d + 3] = y1.y; + } + const int posc = pos < p.M ? pos : p.M - 1; + const int b = posc / p.S, s = posc - b * p.S; + if (hidx < 36) { + // sum of squares: 4 packed FFMA2 pair accumulators + float2 ssa[4]; +#pragma unroll + for (int i = 0; i < 4; i++) ssa[i] = make_float2(0.f, 0.f); +#pragma unroll + for (int d = 0; d < 128; d += 2) { + const float2 x = make_float2(a[d], a[d + 1]); + ssa[(d >> 1) & 3] = ffma2(x, x, ssa[(d >> 1) & 3]); + } + const float ss = ((ssa[0].x + ssa[0].y) + (ssa[1].x + ssa[1].y)) + ((ssa[2].x + ssa[2].y) + (ssa[3].x + ssa[3].y)); + // rstd with the output 2^-6 pre-scale folded in (exact power of 2) + const float r = rsqrtf(ss * (1.f / 128.f) + p.eps) * 0.015625f; + const float* w = reinterpret_cast(smem + QKV_NW_OFF) + (hidx < 32 ? 0 : 128); // smem copy + // transposed RoPE tables (see prep_qkv_kernel): float4 group g of this row at cr4[g * 32] + const float4* cr4 = reinterpret_cast(p.cs) + (size_t)(posc >> 5) * 1024 + (posc & 31); + const float4* sr4 = reinterpret_cast(p.sn) + (size_t)(posc >> 5) * 1024 + (posc & 31); + __half* dst = hidx < 32 ? p.q + (((size_t)b * 32 + hidx) * p.S + s) * 128 + : p.k + (((size_t)b * 4 + (hidx - 32)) * p.S + s) * 128; +#if QKV_CST + // target rows of the transposed stores = rows (lane & ~3) + i of this warp + const int cg4 = lane & 3; + // target row pointers re-shuffled at the store (see QF path) + const unsigned long long rp = (unsigned long long)reinterpret_cast(dst); + const unsigned vbal = __ballot_sync(0xffffffffu, valid); + uint4 cu[4]; // 4 transposable 16 B units (one chunk pair / 4-chunk e4m3 group) +#endif +#pragma unroll + for (int j = 0; j < 8; j++) { + if (j < j0 || j >= j1) continue; // RoPE pair chunk owned by the other warpgroup (warp-uniform) + float c1[8], c2[8], s1[8], s2[8], w1[8], w2[8]; + *reinterpret_cast(c1) = cr4[(2 * j) * 32]; + *reinterpret_cast(c1 + 4) = cr4[(2 * j + 1) * 32]; + *reinterpret_cast(c2) = cr4[(16 + 2 * j) * 32]; + *reinterpret_cast(c2 + 4) = cr4[(16 + 2 * j + 1) * 32]; + *reinterpret_cast(s1) = sr4[(2 * j) * 32]; + *reinterpret_cast(s1 + 4) = sr4[(2 * j + 1) * 32]; + *reinterpret_cast(s2) = sr4[(16 + 2 * j) * 32]; + *reinterpret_cast(s2 + 4) = sr4[(16 + 2 * j + 1) * 32]; + *reinterpret_cast(w1) = *reinterpret_cast(w + j * 8); + *reinterpret_cast(w1 + 4) = *reinterpret_cast(w + j * 8 + 4); + *reinterpret_cast(w2) = *reinterpret_cast(w + 64 + j * 8); + *reinterpret_cast(w2 + 4) = *reinterpret_cast(w + 64 + j * 8 + 4); + float o1[8], o2[8]; + const float2 rv2 = make_float2(r, r); +#pragma unroll + for (int i = 0; i < 8; i += 2) { // packed: x = w * (a * r); RoPE as FMUL2 + FFMA2 + const int d = j * 8 + i; + const float2 x1 = fmul2(make_float2(w1[i], w1[i + 1]), fmul2(make_float2(a[d], a[d + 1]), rv2)); + const float2 x2 = fmul2(make_float2(w2[i], w2[i + 1]), + fmul2(make_float2(a[d + 64], a[d + 65]), rv2)); + // s1 is stored negated (prep_qkv): o1 = x1*c1 - x2*s1, o2 = x2*c2 + x1*s2 + const float2 y1 = ffma2(x1, make_float2(c1[i], c1[i + 1]), + fmul2(x2, make_float2(s1[i], s1[i + 1]))); + const float2 y2 = ffma2(x2, make_float2(c2[i], c2[i + 1]), + fmul2(x1, make_float2(s2[i], s2[i + 1]))); + o1[i] = y1.x; o1[i + 1] = y1.y; o2[i] = y2.x; o2[i + 1] = y2.y; + } +#if QKV_CST + // coalesced stores: groups of 4 chunks (j0 is 0 or 4), units 4x4-transposed inside each + // 4-lane group -> each st.v4 writes 8 rows x 64 contiguous bytes. Identical bytes. + // chunk pairs (j even, j + 1): units = lo j, lo j+1, hi j, hi j+1 (16 regs, was 32); + // after the 4-lane transpose each st.v4 writes 8 rows x two 32 B runs (full sectors) + cu[j & 1] = pack8_h(o1); cu[2 + (j & 1)] = pack8_h(o2); + if (j & 1) { +#pragma unroll + for (int m = 1; m <= 2; m <<= 1) { + const bool bit = (lane & m) != 0; +#pragma unroll + for (int c0 = 0; c0 < 4; c0++) { + if (c0 & m) continue; + const int c1_ = c0 | m; + const uint4 snd = bit ? cu[c0] : cu[c1_]; + uint4 rcv; + rcv.x = __shfl_xor_sync(0xffffffffu, snd.x, m); + rcv.y = __shfl_xor_sync(0xffffffffu, snd.y, m); + rcv.z = __shfl_xor_sync(0xffffffffu, snd.z, m); + rcv.w = __shfl_xor_sync(0xffffffffu, snd.w, m); + if (bit) cu[c0] = rcv; else cu[c1_] = rcv; + } + } + const int off = 16 * (j - 1) + 16 * (cg4 & 1) + 128 * (cg4 >> 1); +#pragma unroll + for (int i = 0; i < 4; i++) { + char* const cti = shfl_ptr_v(rp, (lane & ~3) + i); // all lanes (convergent) + if ((vbal >> ((lane & ~3) + i)) & 1u) *reinterpret_cast(cti + off) = cu[i]; + } + } +#else + *reinterpret_cast(dst + j * 8) = pack8_h(o1); + *reinterpret_cast(dst + 64 + j * 8) = pack8_h(o2); +#endif + } + } else { + // V stored transposed (V^T [b][kv_head][d][Spad], x 2^-10: keeps |V| up to ~6.7e7 inside fp16 range, so large + // activations do not overflow to inf): K-major B operand for P.V + __half* dst = p.v + ((size_t)(b * 4 + (hidx - 36)) * 128) * p.Spad + s; + if (vt8) { + // 8x8 fp16 transpose inside each 8-lane group (S % 8 == 0 -> a group = 8 consecutive + // tokens of one batch, all valid or all past M): one 16 B store per 8 d. Identical bytes. + const int t = lane & 7; + __half* gdst = dst - t; +#pragma unroll + for (int kk = 0; kk < 16; kk++) { + if (!(full || (kk >> 3) == half)) continue; + const float* av = a + 8 * kk; + if (valid) +#pragma unroll + for (int i = 0; i < 8; i++) vmx = fmaxf(vmx, fabsf(av[i])); + const uint4 o = vt8_transpose(av, lane); + if (valid) *reinterpret_cast(gdst + (size_t)(8 * kk + t) * p.Spad) = o; + } + } else if (valid) { +#pragma unroll + for (int d = 0; d < 128; d++) + if (full || (d >> 6) == half) { + dst[(size_t)d * p.Spad] = __float2half_rn(a[d] * 0.0009765625f); + vmx = fmaxf(vmx, fabsf(a[d])); + } + } + } + } + if (hidx >= 36) { + // fp8 o_proj path: warp max of |V| -> global atomicMax (bounds every attention output element) + if (p.vmax) { + const unsigned m = __reduce_max_sync(0xffffffffu, __float_as_uint(vmx)); + if (lane == 0 && m) atomicMax(p.vmax, m); + } + } + } else if (EPI == EPI_GATEUP) { + // TMEM cols [0,128) = gate, [128,256) = up; this half owns act cols half*64 .. +63 + // full tile: gate cols [0,128), up [128,256); half tile: gate [0,64), up [64,128). + // each warpgroup half owns gw = tbn/4 act columns. + // quarter tile (tbn = 64): gate [0,32), up [32,64); warpgroup 0 owns all 32 act cols, warpgroup 1 idles. + const int gw = tbn == 64 ? (half == 0 ? 32 : 0) : tbn >> 2, ngc = gw >> 5; + if (ngc == 0) { + tc_fence_before(); + __syncwarp(); + if (elect_one()) tempty_arrive(buf); + } +#pragma unroll 1 + for (int c = 0; c < ngc; c++) { + float g[32], u[32]; + tmem_ld32(trow + half * gw + c * 32, g); + tmem_ld32(trow + (tbn >> 1) + half * gw + c * 32, u); + if (c == ngc - 1) { + tc_fence_before(); + __syncwarp(); + if (elect_one()) tempty_arrive(buf); + } + if (valid) { + float4* dst = reinterpret_cast(p.out + (size_t)pos * INTER + nt * 128 + (sub > 0 ? sub * (tbn >> 1) : 0) + half * gw + c * 32); +#pragma unroll + for (int j = 0; j < 8; j++) { + float r4[4]; +#pragma unroll + for (int i = 0; i < 4; i++) { + const float gv = g[4 * j + i]; + r4[i] = gv / (1.f + __expf(-gv)) * u[4 * j + i]; + } + dst[j] = make_float4(r4[0], r4[1], r4[2], r4[3]); + } + } + } + } else { + // DOWN: lane L of this warp reduces rows it*8 + L/4 (it = 0..3), float4 group L%4 of a 16-col slab; + // tok / rw / rtok / rval were prefetched above (before the tfull wait). + float ssl = 0.f; // OPROJ: this thread's partial sum of squares of h over its 128 columns + const float rf8 = rf8c; + const int hw = tbn >> 1; // columns per warpgroup half + const int nch = tbn >> 6; // 32-column chunks per half +#pragma unroll 1 + for (int c = 0; c < nch; c++) { + float a[32]; + float4 pb[8], pw[8]; + if (EPI == EPI_OPROJ && wact) { + const int n0 = nt * BN + (sub >= 0 ? sub * tbn : 0) + half * hw + c * 32; +#pragma unroll + for (int j = 0; j < 8; j++) { + pb[j] = __ldg(reinterpret_cast(p.bias0 + n0) + j); + if (F8) pw[j] = __ldg(reinterpret_cast(p.wsc + n0) + j); + } + } + tmem_ld32(trow + half * hw + c * 32, a); + if (c == nch - 1) { + tc_fence_before(); + __syncwarp(); + if (elect_one()) tempty_arrive(buf); + } + if (EPI == EPI_DOWN) { + // Routing-weighted scatter-add, coalesced: the 32x32 (rows x cols) chunk is transposed through + // smem in two 16-col slabs so each red.global.add.v4.f32 instruction covers 8 rows x 64 + // contiguous bytes (full 32 B sectors) instead of 32 rows x 16 B. + float* stg = reinterpret_cast(smem + TSTAGES * STAGE_BYTES + 256) + + (warp - 2) * DOWN_STG_FLOATS; + const int n = nt * TBN + sub_off * 128 + half * hw + c * 32; +#pragma unroll + for (int hh = 0; hh < 2; hh++) { + __syncwarp(); // previous slab fully read +#pragma unroll + for (int j = 0; j < 4; j++) { // row = lane, group j stored at slot j ^ ((row>>1)&3) + const int slot = j ^ ((lane >> 1) & 3); + *reinterpret_cast(stg + lane * 16 + slot * 4) = + make_float4(rw * a[hh * 16 + 4 * j], rw * a[hh * 16 + 4 * j + 1], + rw * a[hh * 16 + 4 * j + 2], rw * a[hh * 16 + 4 * j + 3]); + } + __syncwarp(); +#pragma unroll + for (int it = 0; it < 4; it++) { + const int r = it * 8 + (lane >> 2), g = lane & 3; + const float4 v = + *reinterpret_cast(stg + r * 16 + (g ^ ((r >> 1) & 3)) * 4); + if (rval[it]) red_add_v4(p.out + (size_t)rtok[it] * HID + n + hh * 16 + g * 4, v); + } + } + continue; + } + if (!valid && EPI != EPI_OPROJ) continue; // OPROJ: whole warp joins the TMA store + if (EPI == EPI_ROUTER) { + if (half == 0) { + float4* dst = reinterpret_cast(p.out + (size_t)pos * NEXP + c * 32); +#pragma unroll + for (int j = 0; j < 8; j++) + atomicAdd(dst + j, make_float4(a[4 * j], a[4 * j + 1], a[4 * j + 2], a[4 * j + 3])); + } + continue; + } + const int n = nt * BN + (sub >= 0 ? sub * tbn : 0) + half * hw + c * 32; // + o_proj tail sub-tile offset + if (EPI == EPI_OPROJ) { + // TMA epilogue: per 16-column half-chunk k = 2c + hh, thread = row reads its 4 resid units + // from the slot (TMA-loaded, zero-filled past M), overwrites them with h (own row only: no + // cross-thread hazard) and one lane TMA-stores the 32 x 16 box (rows >= M clipped). Replaces the + // per-thread 16 B loads / stores whose warp instructions each touched 32 rows = 32 lines. + if (!wact) continue; + const int nk = tbn >> 5; // half-chunks of this warpgroup half + float2 ss2 = make_float2(0.f, 0.f); +#pragma unroll + for (int hh = 0; hh < 2; hh++) { + const int k = 2 * c + hh, sl = k & 1; + if (k >= 1 && k + 1 < nk && lane == 0) { + asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); // store k-1 read slot + opj_rload(k + 1, on0 + 16 * (k + 1)); + } + mbar_wait(opj_bar0 + 8u * (uint32_t)sl, (rph >> sl) & 1u); + rph ^= 1u << sl; + uint8_t* rs = smem + OPJ_STG_OFF + (warp - 2) * 4096 + sl * 2048 + lane * 64; + const int nh = n + 16 * hh; +#pragma unroll + for (int j = 0; j < 4; j++) { + float4* up = reinterpret_cast(rs + ((j ^ ((lane >> 1) & 3)) << 4)); + const float4 rv = *up; + const float4 bv = pb[4 * hh + j]; + const float* aj = a + 16 * hh + 4 * j; + // acc = natural x 2^-6 (attn kept at V's 2^-10, Wo16 at 2^4): exact 2^6 rescale + // packed: h = resid + (acc * 64 + bias) as FFMA2 + FADD2, ssq as FFMA2 + float2 k64 = make_float2(64.f, 64.f), k64b = k64; + if (F8) { // per-column dequant factor (row scale rf8 x inverse Wo row scale) + const float4 w4 = pw[4 * hh + j]; + // packed FMUL2 dequant factors (bit-identical to the scalar products) + k64 = fmul2(make_float2(w4.x, w4.y), make_float2(rf8, rf8)); + k64b = fmul2(make_float2(w4.z, w4.w), make_float2(rf8, rf8)); + } + const float2 h01 = fadd2(make_float2(rv.x, rv.y), + ffma2(make_float2(aj[0], aj[1]), k64, make_float2(bv.x, bv.y))); + const float2 h23 = fadd2(make_float2(rv.z, rv.w), + ffma2(make_float2(aj[2], aj[3]), k64b, make_float2(bv.z, bv.w))); + *up = make_float4(h01.x, h01.y, h23.x, h23.y); + ss2 = ffma2(h01, h01, ss2); + ss2 = ffma2(h23, h23, ss2); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // generic smem writes -> TMA + __syncwarp(); + if (lane == 0) { + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group [%0, {%1, %2}], [%3];" ::"l"( + (uint64_t)&tB3), "r"(nh), "r"(opj_row0), "r"(opj_slot0 + 2048u * (uint32_t)sl) + : "memory"); + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + } + } + ssl += ss2.x + ss2.y; + } else { + float4* dst = reinterpret_cast(p.out + (size_t)tok * HID + n); +#pragma unroll + for (int j = 0; j < 8; j++) + atomicAdd(dst + j, make_float4(rw * a[4 * j], rw * a[4 * j + 1], rw * a[4 * j + 2], + rw * a[4 * j + 3])); + } + } + // fused post-attention RMSNorm statistics: one fp32 atomic per (row, 128-column half-tile) + if (EPI == EPI_OPROJ && valid) atomicAdd(p.ssq + pos, ssl); + } + } + } + // OPROJ: every h TMA store of this warp complete (global writes performed) before the CTA exits + if (EPI == EPI_OPROJ && warp >= 2 && lane == 0) asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); +#ifdef TC_PROBE + if (threadIdx.x == 0) CPA(14, clock64() - cta_t0); + if (p.cprobe && lane == 0) { +#pragma unroll + for (int i = 0; i < 16; i++) if (cacc[i]) atomicAdd(&p.cprobe[blockIdx.x * 16 + i], cacc[i]); + } +#endif + tc_fence_before(); + __syncthreads(); + if (PAIR) cl_sync_all(); // peer done with all remote arrivals / MMAs before TMEM dealloc + exit + CHN(3 + EPI, 2); + if (threadIdx.x == 0) PRB(7); + // warp index / TMEM base re-derived here (S2R + volatile smem reload) instead of being kept live across the + // setmaxnreg-partitioned role branches (values live across them were spilled) + uint32_t tid2; + asm volatile("mov.u32 %0, %%tid.x;" : "=r"(tid2)); // opaque re-read (not CSE'd with the prologue's warp) + if ((tid2 >> 5) == 1) { + __syncwarp(); + tc_fence_after(); + uint32_t tb2; + { // tslot re-derived from the dynamic-smem symbol (no 64-bit generic smem pointer live across the roles) + const uint32_t sb2 = (smem_u32(smem_raw) + 1023u) & ~1023u; + asm volatile("ld.shared.u32 %0, [%1];" : "=r"(tb2) : "r"(sb2 + (uint32_t)(NST * SBYTES + NST * 16 + 32)) : "memory"); + } + if (PAIR) asm volatile("tcgen05.dealloc.cta_group::2.sync.aligned.b32 %0, %1;" ::"r"(tb2), "r"(512)); + else asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tb2), "r"(512)); + } +} + +// ------------------------------------------------------------------ fused MoE gate/up + down (TF32, T < 4096) +// ONE persistent kernel, single global work queue (atomicAdd on q[0]): +// items [0, NG) : gate/up tiles, M-tile-major (expert-sorted) order: (mt, nt in 0..5[, half]) +// act[pos][..] = silu(A Wg^T) * (A Wu^T), kind::tf32, B = 128 gate + 128 up rows (or 64+64) +// items [NG, NG + ND) : down tiles in the same M-tile order: (mt, nt in 0..7[, half]), routing-weighted +// coalesced red.global.add into out (= h + moe) +// Roles (same as tc_gemm_kernel): warp 0 = queue fetch + TMA producer (4-stage ring, sized for the 128x256 tiles), +// warp 1 = TMEM alloc (2 x 256 col accumulators) + MMA issuer, warps 2-9 = epilogue. The fetched item is broadcast to +// the MMA thread and the 8 epilogue warps through a 4-slot smem ring (it_full / it_empty mbarriers, 9 consumers). +// Maps: tA/tA64 = aperm (128/64-row boxes), tG/tU = gate/up (64-row boxes), tX/tX64 = act (128/64), tD = down (128). +// T < 4096 A operand: gate/up A rows are GATHERED by warps 10-11 (64 threads) with cp.async 16 B per (row, chunk) +// from xn2 (fp32 TF32-rounded rows, written ONCE per token [T, 2048]) via perm_tok into the 128B-swizzled K-major +// layout TMA would produce (row R at R*128 B, chunk c at physical chunk c ^ (R & 7)); rows past the expert's end are +// zero-filled. Stage full barrier count = 1 (producer expect_tx) + 64 (gather cp.async.mbarrier.arrive.noinc); +// for down items the producer adds the 64 arrivals itself. +constexpr int MF_THREADS = 384; +constexpr int MF_FULL_ARRIVALS = 64 + 1; +// 16 B global -> shared async copy (LDGSTS, L1 bypass); src_bytes = 0 zero-fills the destination without reading +__device__ __forceinline__ void cp_async16(uint32_t dst, const void* src, uint32_t src_bytes) { + asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;" ::"r"(dst), "l"(src), "r"(src_bytes) : "memory"); +} +// arrive on the mbarrier once all of this thread's prior cp.async have landed (no pending-count increment: the +// barrier's init count includes these arrivals) +// same with an L2 cache-policy hint (re-read token rows: evict_last) +__device__ __forceinline__ void cp_async16_hint(uint32_t dst, const void* src, uint32_t src_bytes, uint64_t pol) { + asm volatile("cp.async.cg.shared.global.L2::cache_hint [%0], [%1], 16, %2, %3;" ::"r"(dst), "l"(src), "r"(src_bytes), + "l"(pol) + : "memory"); +} +__device__ __forceinline__ void cp_async_mbar_arrive_noinc(uint32_t bar) { + asm volatile("cp.async.mbarrier.arrive.noinc.shared::cta.b64 [%0];" ::"r"(bar) : "memory"); +} +__device__ __forceinline__ void mbar_arrive_cnt(uint32_t a, uint32_t cnt) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0], %1;" ::"r"(a), "r"(cnt) : "memory"); +} +struct MoeArgs { + const float* xn; // fp32 xn2 [T, 2048] (TF32 hi), gathered by token + const int* tile_expert; const int* tile_mstart; const int* total_tiles; + const int* offsets; const int* counts; const int* perm_tok; const float* perm_w; + float* act; float* out; + int* qctr; // [0] = work counter, [1 + g] = ready counter of M-tile PAIR group g (zeroed per call) + const int* pgrp; // pair groups: [0] = #groups, [1 + g] = first M tile | (#tiles (1..2) << 24) + int bn_g, bn_d; // 256 or 128 (128 = split every tile into N halves) + int krot; // moe_fused1: rotated k-block order per item (mf1_rot) + const int* tile_mend; // moe_fused1: per-M-tile expert row end (offsets[e] + counts[e]) +}; +constexpr int MF_GNT = INTER / 128; // 6 gate/up n-tiles per group +constexpr int MF_DNT = HID / TBN; // 8 down n-tiles per group +// smem: 3 stages x {A tile 0 (16 KB), A tile 1 (16 KB), B (32 KB)} + barriers + 8 x 2 KB down staging slabs +constexpr int MF_STAGES = 3; +constexpr int MF_ATILE = 16384; +constexpr int MF_STAGE = 2 * MF_ATILE + 32768; +constexpr int MF_BAR = MF_STAGES * MF_STAGE; +constexpr int MF_STG = MF_BAR + 256; +constexpr int MF_SMEM = MF_STG + 8 * DOWN_STG_FLOATS * 4 + 1024; + +__global__ void __launch_bounds__(MF_THREADS, 1) moe_fused_kernel( + const __grid_constant__ CUtensorMap tG, const __grid_constant__ CUtensorMap tU, + const __grid_constant__ CUtensorMap tX, const __grid_constant__ CUtensorMap tX64, + const __grid_constant__ CUtensorMap tD, MoeArgs p) { + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = (uint8_t*)(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023); + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const uint32_t sbase = smem_u32(smem); + const uint32_t bar_full = sbase + MF_BAR; // [3] + const uint32_t bar_empty = bar_full + 24; // [3] + const uint32_t bar_tfull = bar_full + 48; // [2] per TMEM accumulator slot + const uint32_t bar_tempty = bar_full + 64; // [2] + const uint32_t tslot = bar_full + 80; + const uint32_t it_full = bar_full + 128; // [4] + const uint32_t it_empty = bar_full + 160; // [4] + volatile uint32_t* tslot_ptr = (volatile uint32_t*)(smem + MF_BAR + 80); + volatile int* item_slot = (volatile int*)(smem + MF_BAR + 192); // int[4] + + if (threadIdx.x == 0) { + for (int s = 0; s < MF_STAGES; s++) { mbar_init(bar_full + 8 * s, MF_FULL_ARRIVALS); mbar_init(bar_empty + 8 * s, 1); } + for (int b = 0; b < 2; b++) { mbar_init(bar_tfull + 8 * b, 1); mbar_init(bar_tempty + 8 * b, 8); } + for (int i = 0; i < 4; i++) { mbar_init(it_full + 8 * i, 1); mbar_init(it_empty + 8 * i, 11); } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tG) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tU) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tD) : "memory"); + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(tslot), "r"(512)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + tc_fence_before(); + __syncthreads(); + tc_fence_after(); + const uint32_t tbase = *tslot_ptr; + CHN(14, 0); + pdl_wait(); + CHN(14, 1); + pdl_trigger(); + const int ngr = p.pgrp[0]; + const int spg = p.bn_g == 128 ? 2 : 1; + const int NG = ngr * MF_GNT * spg; + const int NDF = ngr * MF_DNT; + // down tail split: if the final (approximate) wave holds r <= grid/2 full down items, split them into N halves + int nsplit = 0; + if (p.bn_d == 128) nsplit = NDF; + else { + const int r = (NG + NDF) % (int)gridDim.x; + if (r > 0 && 2 * r <= (int)gridDim.x && r <= NDF) nsplit = r; + } + const int total = NG + NDF + nsplit; + const int ready_target = 8 * MF_GNT * spg; + + // item -> (is_down, group g, n tile, sub: -1 full / 0,1 half) + group rows [m0, mend), #M tiles ntl (1..2). + // M tile j of the group covers rows m0 + 128 j .. ; it is an M=64 tile if <= 64 of its rows are valid. + auto decode = [&](int t, bool& dn, int& g, int& nt, int& sub, int& m0, int& mend, int& e, int& ntl) { + if (t < NG) { + dn = false; + const int f = t / spg; + sub = spg == 2 ? t - f * 2 : -1; + g = f / MF_GNT; nt = f - g * MF_GNT; + } else { + dn = true; + const int td = t - NG, fs = NDF - nsplit; + int f = td; + sub = -1; + if (td >= fs) { f = fs + (td - fs) / 2; sub = (td - fs) & 1; } + g = f / MF_DNT; nt = f - g * MF_DNT; + } + const int pk = p.pgrp[1 + g]; + const int mt0 = pk & 0xFFFFFF; + ntl = pk >> 24; + e = p.tile_expert[mt0]; + m0 = p.tile_mstart[mt0]; + mend = p.offsets[e] + p.counts[e]; + }; + auto get_item = [&](int ic) -> int { + const int slot = ic & 3; + mbar_wait(it_full + 8 * slot, (ic >> 2) & 1); + return item_slot[slot]; + }; + + if (warp == 0) { + if (lane == 0) { + // ---------------- queue fetch + TMA producer + int it = 0; + for (int ic = 0;; ic++) { + const int t = atomicAdd(p.qctr, 1); + const int slot = ic & 3; + mbar_wait(it_empty + 8 * slot, ((ic >> 2) & 1) ^ 1); + item_slot[slot] = t; + mbar_arrive(it_full + 8 * slot); + if (t >= total) break; + bool dn; int g, nt, sub, m0, mend, e, ntl; + decode(t, dn, g, nt, sub, m0, mend, e, ntl); + if (dn) { + // acquire: all gate/up items of this group have stored their act rows + const int* rp = p.qctr + 1 + g; + while (true) { + int v; + asm volatile("ld.acquire.gpu.global.b32 %0, [%1];" : "=r"(v) : "l"(rp) : "memory"); + if (v >= ready_target) break; + __nanosleep(64); + } + asm volatile("fence.proxy.async.global;" ::: "memory"); // generic act writes -> TMA reads + } + // gate/up: TMA only brings B (A is gathered by warps 10-11); down: A (act, per M tile) + B via TMA + uint32_t abytes = 0; + if (dn) + for (int j = 0; j < ntl; j++) abytes += (mend - (m0 + 128 * j) <= 64) ? MF_ATILE / 2 : MF_ATILE; + const uint32_t tx = abytes + (uint32_t)((sub < 0 ? 256 : 128) * 128); + const int KB = dn ? INTER / TBK : HID / TBK; + for (int kb = 0; kb < KB; kb++, it++) { + const int s = it % MF_STAGES; + const uint32_t ph = (it / MF_STAGES) & 1; + mbar_wait(bar_empty + 8 * s, ph ^ 1); + const uint32_t fb = bar_full + 8 * s; + mbar_expect_tx(fb, tx); + const uint32_t sa = sbase + s * MF_STAGE, sb = sa + 2 * MF_ATILE; + const int kx = kb * TBK; + if (!dn) { + // full: 128 gate rows -> sb, 128 up rows -> sb + 16 KB; half: 64 gate -> sb, 64 up -> sb + 8 KB + const int r0 = e * INTER + nt * 128 + (sub > 0 ? 64 : 0); + if (sub < 0) { + tma_load_2d(sb, &tG, kx, r0, fb); + tma_load_2d(sb + 8192, &tG, kx, r0 + 64, fb); + tma_load_2d(sb + 16384, &tU, kx, r0, fb); + tma_load_2d(sb + 24576, &tU, kx, r0 + 64, fb); + } else { + tma_load_2d(sb, &tG, kx, r0, fb); + tma_load_2d(sb + 8192, &tU, kx, r0, fb); + } + } else { + for (int j = 0; j < ntl; j++) { + const int mj = m0 + 128 * j; + tma_load_2d(sa + j * MF_ATILE, (mend - mj <= 64) ? &tX64 : &tX, kx, mj, fb); + } + mbar_arrive_cnt(fb, MF_FULL_ARRIVALS - 1); // on behalf of the (idle) gather threads + const int r0 = e * HID + nt * TBN + (sub > 0 ? 128 : 0); + tma_load_2d(sb, &tD, kx, r0, fb); + if (sub < 0) tma_load_2d(sb + 16384, &tD, kx, r0 + 128, fb); + } + } + } + } + } else if (warp == 1) { + { + // ---------------- MMA issuer (whole warp loops, elect.sync lane issues). M tile j of an item accumulates into TMEM slot + // (sc + j) & 1 (sc = running count of accumulator uses): a 2-tile item takes both 256-col slots, a 1-tile + // item one slot (double-buffered against the next item). Every B stage feeds the MMAs of all ntl tiles. + int it = 0, sc = 0; + for (int ic = 0;; ic++) { + const int t = get_item(ic); + __syncwarp(); + if (elect_one()) mbar_arrive(it_empty + 8 * (ic & 3)); + if (t >= total) break; + bool dn; int g, nt, sub, m0, mend, e, ntl; + decode(t, dn, g, nt, sub, m0, mend, e, ntl); + uint32_t idesc[2]; + uint32_t dt[2]; +#pragma unroll + for (int j = 0; j < 2; j++) { + uint32_t d = IDESC_TF32; + if (sub >= 0) d = (d & ~(0x3Fu << 17)) | ((128u >> 3) << 17); + if (mend - (m0 + 128 * j) <= 64) d = (d & ~(0x1Fu << 24)) | ((64u >> 4) << 24); + idesc[j] = d; + const int u = sc + j; + dt[j] = tbase + (u & 1) * TBN; + if (j < ntl) mbar_wait(bar_tempty + 8 * (u & 1), ((u >> 1) & 1) ^ 1); + } + tc_fence_after(); + const int KB = dn ? INTER / TBK : HID / TBK; + for (int kb = 0; kb < KB; kb++, it++) { + const int s = it % MF_STAGES; + const uint32_t ph = (it / MF_STAGES) & 1; + mbar_wait(bar_full + 8 * s, ph); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // cp.async-gathered A -> MMA + tc_fence_after(); + const uint32_t sa = sbase + s * MF_STAGE, sb = sa + 2 * MF_ATILE; + const uint64_t ad = make_sdesc(sa), bd = make_sdesc(sb); + __syncwarp(); + if (elect_one()) { +#pragma unroll + for (int j = 0; j < 2; j++) { // unrolled (static idesc/dt indexing, no local memory) + if (j >= ntl) break; +#pragma unroll + for (int k = 0; k < 4; k++) + mma_tf32(dt[j], ad + (uint64_t)((j * MF_ATILE + k * 32) >> 4), bd + 2 * k, idesc[j], + (kb | k) != 0); + } + mma_commit(bar_empty + 8 * s); + } + __syncwarp(); + } + if (elect_one()) for (int j = 0; j < ntl; j++) mma_commit(bar_tfull + 8 * ((sc + j) & 1)); + __syncwarp(); + sc += ntl; + } + } + } else if (warp >= 10) { + // ---------------- A gather warps 10, 11 (gate/up items only; down items just advance the stage counter) + // lane L of warp w owns chunk c = L & 7 of rows R = 8i + 4w + (L >> 3) (i = 0..15) of each M tile j (tile j + // at stage offset j * 16 KB): R & 7 = 4w + (L >> 3) is constant per lane, and each warp instruction moves 4 + // full 128 B rows. Tokens of the warp's 64 rows of tile j sit in tokr[j][m] (warp-local row k = lane + 32m + // <-> R = 8(k >> 2) + 4w + (k & 3)), broadcast with shuffles. + const int w = warp - 10; + const int c = lane & 7, rsub = lane >> 3; + const uint32_t lane_off = (uint32_t)((4 * w + rsub) * 128 + ((c ^ (4 * w + rsub)) << 4)); + int it = 0; + for (int ic = 0;; ic++) { + const int t = get_item(ic); + __syncwarp(); + if (elect_one()) mbar_arrive(it_empty + 8 * (ic & 3)); + if (t >= total) break; + bool dn; int g, nt, sub, m0, mend, e, ntl; + decode(t, dn, g, nt, sub, m0, mend, e, ntl); + if (dn) { it += INTER / TBK; continue; } + int tokr[2][2]; +#pragma unroll + for (int j = 0; j < 2; j++) +#pragma unroll + for (int m = 0; m < 2; m++) { + const int k = lane + 32 * m; + const int pos = m0 + 128 * j + 8 * (k >> 2) + 4 * w + (k & 3); + tokr[j][m] = (j < ntl && pos < mend) ? __ldg(p.perm_tok + pos) : -1; + } + for (int kb = 0; kb < HID / TBK; kb++, it++) { + const int s = it % MF_STAGES; + mbar_wait(bar_empty + 8 * s, ((it / MF_STAGES) & 1) ^ 1); + const uint32_t dst0 = sbase + s * MF_STAGE + lane_off; + const float* srck = p.xn + kb * TBK + c * 4; +#pragma unroll + for (int j = 0; j < 2; j++) { + if (j < ntl) { +#pragma unroll + for (int m = 0; m < 2; m++) { +#pragma unroll + for (int ii = 0; ii < 8; ii++) { + const int tok = __shfl_sync(0xffffffff, tokr[j][m], 4 * ii + rsub); + const int i = 8 * m + ii; // R = 8i + 4w + rsub + cp_async16(dst0 + (uint32_t)(j * MF_ATILE + i * 1024), srck + (size_t)(tok < 0 ? 0 : tok) * HID, + tok < 0 ? 0u : 16u); + } + } + } + } + cp_async_mbar_arrive_noinc(bar_full + 8 * s); + } + } + } else { + // ---------------- epilogue warps 2..9: TMEM lane quadrant q = warp % 4, column half (warp-2)/4; + // processes the item's M tiles in order, tile j from accumulator slot (sc + j) & 1 + const int q = warp & 3; + const int half = (warp - 2) >> 2; + const int row = q * 32 + lane; + float* stg = reinterpret_cast(smem + MF_STG) + (warp - 2) * DOWN_STG_FLOATS; + int sc = 0; + for (int ic = 0;; ic++) { + const int t = get_item(ic); + __syncwarp(); + if (elect_one()) mbar_arrive(it_empty + 8 * (ic & 3)); + if (t >= total) break; + bool dn; int g, nt, sub, m0, mend, e, ntl; + decode(t, dn, g, nt, sub, m0, mend, e, ntl); + const int tbn = sub >= 0 ? 128 : 256; +#pragma unroll 1 + for (int jt = 0; jt < ntl; jt++) { + const int u = sc + jt; + const int buf = u & 1; + const uint32_t aph = (u >> 1) & 1; + const int mj = m0 + 128 * jt; + // M=64 accumulator: row r in TMEM lane (r % 16) + 32 * (r / 16) + const bool m64 = mend - mj <= 64; + const int erow = m64 ? q * 16 + lane : row; + const int pos = mj + erow; + const bool valid = (!m64 || lane < 16) && pos < mend; + int tok = 0; float rw = 0.f; + int rtok[4]; bool rval[4]; + if (dn) { // routing metadata prefetched before the accumulator wait + if (valid) { tok = __ldg(p.perm_tok + pos); rw = __ldg(p.perm_w + pos); } +#pragma unroll + for (int i = 0; i < 4; i++) { + const int r = i * 8 + (lane >> 2); + rtok[i] = __shfl_sync(0xffffffff, tok, r); + rval[i] = __shfl_sync(0xffffffff, (int)valid, r) != 0; + } + } + mbar_wait(bar_tfull + 8 * buf, aph); + tc_fence_after(); + const uint32_t trow = tbase + ((uint32_t)(q * 32) << 16) + buf * TBN; + if (!dn) { + // full: gate cols [0,128), up [128,256); half: gate [0,64), up [64,128); this half owns gw act cols + const int gw = tbn >> 2, ngc = gw >> 5; +#pragma unroll 1 + for (int c = 0; c < ngc; c++) { + float gg[32], uu[32]; + tmem_ld32(trow + half * gw + c * 32, gg); + tmem_ld32(trow + (tbn >> 1) + half * gw + c * 32, uu); + if (c == ngc - 1) { + tc_fence_before(); + __syncwarp(); + if (elect_one()) mbar_arrive(bar_tempty + 8 * buf); + } + if (valid) { + float4* dst = reinterpret_cast(p.act + (size_t)pos * INTER + nt * 128 + + (sub > 0 ? 64 : 0) + half * gw + c * 32); +#pragma unroll + for (int j = 0; j < 8; j++) { + float r4[4]; +#pragma unroll + for (int i = 0; i < 4; i++) { + const float gv = gg[4 * j + i]; + r4[i] = gv / (1.f + __expf(-gv)) * uu[4 * j + i]; + } + dst[j] = make_float4(r4[0], r4[1], r4[2], r4[3]); + } + } + } + } else { + const int hw = tbn >> 1, nch = tbn >> 6; + const int sub_off = sub > 0 ? 1 : 0; +#pragma unroll 1 + for (int c = 0; c < nch; c++) { + float a[32]; + tmem_ld32(trow + half * hw + c * 32, a); + if (c == nch - 1) { + tc_fence_before(); + __syncwarp(); + if (elect_one()) mbar_arrive(bar_tempty + 8 * buf); + } + // transpose the 32x32 chunk through smem in 16-col slabs -> 8 rows x 64 B per red.v4 instruction + const int n = nt * TBN + sub_off * 128 + half * hw + c * 32; +#pragma unroll + for (int hh = 0; hh < 2; hh++) { + __syncwarp(); +#pragma unroll + for (int j = 0; j < 4; j++) { + const int slot = j ^ ((lane >> 1) & 3); + *reinterpret_cast(stg + lane * 16 + slot * 4) = + make_float4(rw * a[hh * 16 + 4 * j], rw * a[hh * 16 + 4 * j + 1], + rw * a[hh * 16 + 4 * j + 2], rw * a[hh * 16 + 4 * j + 3]); + } + __syncwarp(); +#pragma unroll + for (int i = 0; i < 4; i++) { + const int r = i * 8 + (lane >> 2), g4 = lane & 3; + const float4 v = *reinterpret_cast(stg + r * 16 + (g4 ^ ((r >> 1) & 3)) * 4); + if (rval[i]) red_add_v4(p.out + (size_t)rtok[i] * HID + n + hh * 16 + g4 * 4, v); + } + } + } + } + } + sc += ntl; + if (!dn) { + // release: this warp's act stores (all M tiles of the group) -> visible (generic + async proxy) + // -> ready[g] += 1 + asm volatile("fence.proxy.async.global;" ::: "memory"); + __syncwarp(); + if (elect_one()) asm volatile("red.release.gpu.global.add.s32 [%0], %1;" ::"l"(p.qctr + 1 + g), "r"(1) : "memory"); + __syncwarp(); + } + } + } + tc_fence_before(); + __syncthreads(); + CHN(14, 2); + if (warp == 1) { + __syncwarp(); + tc_fence_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tbase), "r"(512)); + } +} + +// TWO: 2 CTAs per SM co-resident (half the TMEM = one 256-col accumulator each, 1 KB down staging slabs of +// 32 rows x 8 cols per warp), so one CTA's epilogue / item-boundary bubbles overlap the other CTA's weight stream. +template struct Mf1Cfg { + static constexpr int B_OFF = AS * 16384; + static constexpr int BAR = B_OFF + BS * 32768; + static constexpr int STG = BAR + 512; + static constexpr int SMEM = STG + 8 * (TWO ? 256 : DOWN_STG_FLOATS) * 4 + 1024; + static_assert(!TWO || 2 * (SMEM + 1024) <= 233472, "2 CTAs / SM smem"); + static_assert(AS >= 2 && AS <= 6 && BS >= 2 && BS <= 6 && SMEM <= 232448, "moe_fused1 ring config"); +}; +#ifndef MF1_KROT +#define MF1_KROT 7 +#endif +// mul = 0: no rotation; mul in [1, 99]: start = (item * mul) mod KB; mul >= 100: hashed item index +__device__ __forceinline__ int mf1_rot(int t, int KB, int mul) { + if (mul <= 0) return 0; + if (mul >= 100) return (int)(((unsigned)t * 2654435761u) >> 16) % KB; + return (t * mul) % KB; +} +// 16-column TMEM loads (32 lanes x 32 bit x 16) of two addresses, one wait (TWO-mode gate/up epilogue: fewer live regs) +__device__ __forceinline__ void tmem_ld16x2(uint32_t ta, float* va, uint32_t tb, float* vb) { + uint32_t r[16], u[16]; + asm volatile("tcgen05.ld.sync.aligned.32x32b.x16.b32 {%0,%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11,%12,%13,%14,%15}, [%16];" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]), "=r"(r[4]), "=r"(r[5]), "=r"(r[6]), "=r"(r[7]), + "=r"(r[8]), "=r"(r[9]), "=r"(r[10]), "=r"(r[11]), "=r"(r[12]), "=r"(r[13]), "=r"(r[14]), "=r"(r[15]) : "r"(ta)); + asm volatile("tcgen05.ld.sync.aligned.32x32b.x16.b32 {%0,%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11,%12,%13,%14,%15}, [%16];" + : "=r"(u[0]), "=r"(u[1]), "=r"(u[2]), "=r"(u[3]), "=r"(u[4]), "=r"(u[5]), "=r"(u[6]), "=r"(u[7]), + "=r"(u[8]), "=r"(u[9]), "=r"(u[10]), "=r"(u[11]), "=r"(u[12]), "=r"(u[13]), "=r"(u[14]), "=r"(u[15]) : "r"(tb)); + asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); +#pragma unroll + for (int i = 0; i < 16; i++) { va[i] = __uint_as_float(r[i]); vb[i] = __uint_as_float(u[i]); } +} +template +__global__ void __launch_bounds__(MF_THREADS, TWO ? 2 : 1) moe_fused1_kernel( + const __grid_constant__ CUtensorMap tG, const __grid_constant__ CUtensorMap tU, + const __grid_constant__ CUtensorMap tX, const __grid_constant__ CUtensorMap tX64, + const __grid_constant__ CUtensorMap tD, MoeArgs p) { + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = (uint8_t*)(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023); + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const uint32_t sbase = smem_u32(smem); + using C = Mf1Cfg; + constexpr uint32_t TCOLS = TWO ? 256u : 512u; // TMEM columns (TWO: single accumulator buffer) + const uint32_t bar0 = sbase + C::BAR; + const uint32_t a_full = bar0; // [AS <= 6] + const uint32_t a_empty = bar0 + 48; // [AS <= 6] + const uint32_t b_full = bar0 + 96; // [BS <= 6] + const uint32_t b_empty = bar0 + 144; // [BS <= 6] + const uint32_t bar_tfull = bar0 + 192; // [2] + const uint32_t bar_tempty = bar0 + 208; // [2] + const uint32_t tslot = bar0 + 224; + const uint32_t it_full = bar0 + 232; // [4] + const uint32_t it_empty = bar0 + 264; // [4] + volatile uint32_t* tslot_ptr = (volatile uint32_t*)(smem + C::BAR + 224); + volatile int* item_slot = (volatile int*)(smem + C::BAR + 296); // int[4] + const uint32_t pre_full = bar0 + 320; // [BS <= 6] pre-PDL-wait weight stages landed + + if (threadIdx.x == 0) { + for (int s = 0; s < AS; s++) { mbar_init(a_full + 8 * s, MF_FULL_ARRIVALS - 1); mbar_init(a_empty + 8 * s, 1); } + for (int s = 0; s < BS; s++) { mbar_init(b_full + 8 * s, 1); mbar_init(b_empty + 8 * s, 1); mbar_init(pre_full + 8 * s, 1); } + for (int b = 0; b < 2; b++) { mbar_init(bar_tfull + 8 * b, 1); mbar_init(bar_tempty + 8 * b, 8); } + for (int i = 0; i < 4; i++) { mbar_init(it_full + 8 * i, 1); mbar_init(it_empty + 8 * i, 11); } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tG) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tU) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tD) : "memory"); + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(tslot), "r"(TCOLS)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + tc_fence_before(); + __syncthreads(); + tc_fence_after(); + const uint32_t tbase = *tslot_ptr; + CHN(13, 0); + int pre_n = 0, pre_e = -1; + if (warp == 0) { // lane l prefetches one box: k-block l >> 2, tensor (l >> 1) & 1 (gate / up), 64-row half l & 1 + const int spg0 = p.bn_g == 128 ? 2 : 1; + const int f = (int)blockIdx.x / spg0, sub0 = spg0 == 2 ? (int)blockIdx.x - f * 2 : -1; + const int e0 = f / MF_GNT, nt0 = f - e0 * MF_GNT; + const int hh = lane & 1; + if (e0 < NEXP) { + pre_n = BS < HID / TBK ? BS : HID / TBK; + pre_e = e0; + const int rot0 = mf1_rot((int)blockIdx.x, HID / TBK, p.krot); + const uint32_t txb0 = (uint32_t)((sub0 < 0 ? 256 : 128) * 128); + const int r0 = e0 * INTER + nt0 * 128 + (sub0 > 0 ? 64 : 0); + __syncwarp(); + if (elect_one()) { + for (int s = 0; s < pre_n; s++) { + const uint32_t fb = pre_full + 8 * s, sb = sbase + C::B_OFF + s * 32768; + const int kx = (s + rot0) % (HID / TBK) * TBK; + mbar_expect_tx(fb, txb0); + if (sub0 < 0) { + tma_load_2d(sb, &tG, kx, r0, fb); + tma_load_2d(sb + 8192, &tG, kx, r0 + 64, fb); + tma_load_2d(sb + 16384, &tU, kx, r0, fb); + tma_load_2d(sb + 24576, &tU, kx, r0 + 64, fb); + } else { + tma_load_2d(sb, &tG, kx, r0, fb); + tma_load_2d(sb + 8192, &tU, kx, r0, fb); + } + } + } + __syncwarp(); + } + if (e0 < NEXP && (sub0 < 0 || hh == 0)) { + const int r0 = e0 * INTER + nt0 * 128 + (sub0 > 0 ? 64 : 0) + 64 * hh; + const CUtensorMap* pm = (lane & 2) ? &tU : &tG; +#pragma unroll + for (int rd = 0; rd < 2; rd++) + asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile [%0, {%1, %2}];" ::"l"((uint64_t)pm), + "r"(((lane >> 2) + 8 * rd + mf1_rot((int)blockIdx.x, HID / TBK, p.krot)) % (HID / TBK) * TBK), "r"(r0) + : "memory"); + } + } + __syncwarp(); + pdl_wait(); + CHN(13, 1); + pdl_trigger(); + const int num_m = *p.total_tiles; + const int spg = p.bn_g == 128 ? 2 : 1; + const int NG = num_m * MF_GNT * spg; + const int NDF = num_m * MF_DNT; + // down tail split: if the final (approximate) wave holds r <= grid/2 full down tiles, split them into N halves + int nsplit = 0; + if (p.bn_d == 128) nsplit = NDF; + else { + const int r = (NG + NDF) % (int)gridDim.x; + if (r > 0 && 2 * r <= (int)gridDim.x && r <= NDF) nsplit = r; + } + const int total = NG + NDF + nsplit; + const int ready_target = 8 * MF_GNT * spg; + + // item -> (is_down, M tile, n tile, sub: -1 full / 0,1 half) + rows + auto decode = [&](int t, bool& dn, int& mt, int& nt, int& sub, int& m0, int& mend, int& e) { + if (t < NG) { + dn = false; + const int f = t / spg; + sub = spg == 2 ? t - f * 2 : -1; + mt = f / MF_GNT; nt = f - mt * MF_GNT; + } else { + dn = true; + const int td = t - NG, fs = NDF - nsplit; + int f = td; + sub = -1; + if (td >= fs) { f = fs + (td - fs) / 2; sub = (td - fs) & 1; } + mt = f / MF_DNT; nt = f - mt * MF_DNT; + } + // latency chain: tile_mend[mt] (= offsets[e] + counts[e], written by the scatter CTA 0) is loaded in + // parallel with tile_expert / tile_mstart instead of after them (one dependent L2 round trip less per decode) + e = p.tile_expert[mt]; + m0 = p.tile_mstart[mt]; + mend = p.tile_mend[mt]; + }; + auto get_item = [&](int ic) -> int { + const int slot = ic & 3; + mbar_wait(it_full + 8 * slot, (ic >> 2) & 1); + return item_slot[slot]; + }; + + if (warp == 0) { + { + int it = 0; + for (int ic = 0;; ic++) { + int t0 = 0; + // static first item (= blockIdx.x), then the atomic queue offset by gridDim.x + if (ic > 0 && elect_one()) t0 = (int)gridDim.x + atomicAdd(p.qctr, 1); + const int t = ic == 0 ? (int)blockIdx.x : __shfl_sync(0xffffffffu, t0, 0); + const int slot = ic & 3; + mbar_wait(it_empty + 8 * slot, ((ic >> 2) & 1) ^ 1); + __syncwarp(); + if (elect_one()) { + item_slot[slot] = t; + mbar_arrive(it_full + 8 * slot); + } + __syncwarp(); + // speculative stages: always landed before any reuse of their smem / CTA exit + if (ic == 0) for (int s = 0; s < pre_n; s++) mbar_wait(pre_full + 8 * s, 0); + if (t >= total) break; + bool dn; int mt, nt, sub, m0, mend, e; + decode(t, dn, mt, nt, sub, m0, mend, e); + // first item matches the speculative loads (nt / sub always match by construction) + const int pre_ok = (ic == 0 && !dn && e == pre_e) ? pre_n : 0; + // this warp streams ONLY the B (weight) ring; the down items' act A tiles (and their gate/up + // readiness acquire) are issued by gather warp 10, which walks the A ring in order (the producer can + // run up to BS > AS k-blocks ahead of the MMA, so its A-ring parity waits could alias) + const uint32_t txb = (uint32_t)((sub < 0 ? 256 : 128) * 128); + const int KB = dn ? INTER / TBK : HID / TBK; + const int rot = mf1_rot(t, KB, p.krot); + for (int kb = 0; kb < KB; kb++, it++) { + const int s = it % BS; + mbar_wait(b_empty + 8 * s, ((it / BS) & 1) ^ 1); + const uint32_t fb = b_full + 8 * s; + __syncwarp(); + if (kb < pre_ok) { // weight stage already landed (pre-wait TMA): forward it to the MMA + if (elect_one()) mbar_arrive(fb); + __syncwarp(); + continue; + } + if (elect_one()) { + mbar_expect_tx(fb, txb); + const uint32_t sb = sbase + C::B_OFF + s * 32768; + const int kx = (kb + rot < KB ? kb + rot : kb + rot - KB) * TBK; // rotated k order + if (!dn) { + // full: 128 gate rows -> sb, 128 up rows -> sb + 16 KB; half: 64 gate -> sb, 64 up -> sb + 8 KB + const int r0 = e * INTER + nt * 128 + (sub > 0 ? 64 : 0); + if (sub < 0) { + tma_load_2d(sb, &tG, kx, r0, fb); + tma_load_2d(sb + 8192, &tG, kx, r0 + 64, fb); + tma_load_2d(sb + 16384, &tU, kx, r0, fb); + tma_load_2d(sb + 24576, &tU, kx, r0 + 64, fb); + } else { + tma_load_2d(sb, &tG, kx, r0, fb); + tma_load_2d(sb + 8192, &tU, kx, r0, fb); + } + } else { + const int r0 = e * HID + nt * TBN + (sub > 0 ? 128 : 0); + tma_load_2d(sb, &tD, kx, r0, fb); + if (sub < 0) tma_load_2d(sb + 16384, &tD, kx, r0 + 128, fb); + } + } // elect_one + __syncwarp(); + } + } + } + } else if (warp == 1) { + { + // ---------------- MMA issuer (whole warp loops, elect.sync lane issues MMA + commit) + int it = 0; + for (int ic = 0;; ic++) { + const int t = get_item(ic); + __syncwarp(); + if (elect_one()) mbar_arrive(it_empty + 8 * (ic & 3)); + if (t >= total) break; + bool dn; int mt, nt, sub, m0, mend, e; + decode(t, dn, mt, nt, sub, m0, mend, e); + uint32_t idesc = IDESC_TF32; + if (sub >= 0) idesc = (idesc & ~(0x3Fu << 17)) | ((128u >> 3) << 17); + if (mend - m0 <= 64) idesc = (idesc & ~(0x1Fu << 24)) | ((64u >> 4) << 24); + const int buf = TWO ? 0 : (ic & 1); + const uint32_t aph = TWO ? (ic & 1) : ((ic >> 1) & 1); + mbar_wait(bar_tempty + 8 * buf, aph ^ 1); + tc_fence_after(); + const uint32_t dt = tbase + buf * TBN; + const int KB = dn ? INTER / TBK : HID / TBK; + for (int kb = 0; kb < KB; kb++, it++) { + const int s = it % BS, sA = it % AS; + mbar_wait(a_full + 8 * sA, (it / AS) & 1); + mbar_wait(b_full + 8 * s, (it / BS) & 1); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // cp.async-gathered A -> MMA + tc_fence_after(); + const uint32_t sa = sbase + sA * 16384, sb = sbase + C::B_OFF + s * 32768; + const uint64_t ad = make_sdesc(sa), bd = make_sdesc(sb); + __syncwarp(); + if (elect_one()) { +#pragma unroll + for (int k = 0; k < 4; k++) + mma_tf32(dt, ad + 2 * k, bd + 2 * k, idesc, (kb | k) != 0); + mma_commit(a_empty + 8 * sA); + mma_commit(b_empty + 8 * s); + } + __syncwarp(); + } + if (elect_one()) mma_commit(bar_tfull + 8 * buf); + __syncwarp(); + } + } + } else if (warp >= 10) { + // ---------------- A gather warps 10, 11 (gate/up items only; down items just advance the stage counter) + // lane L of warp w owns chunk c = L & 7 of rows R = 8i + 4w + (L >> 3) (i = 0..15): R & 7 = 4w + (L >> 3) is + // constant per lane, and each warp instruction moves 4 full 128 B rows. Tokens of the warp's 64 rows sit in + // tokr[m] (warp-local row k = lane + 32m <-> R = 8(k >> 2) + 4w + (k & 3)), broadcast with shuffles. + const int w = warp - 10; + const int c = lane & 7, rsub = lane >> 3; + const uint32_t lane_off = (uint32_t)((4 * w + rsub) * 128 + ((c ^ (4 * w + rsub)) << 4)); + int it = 0; + for (int ic = 0;; ic++) { + const int t = get_item(ic); + __syncwarp(); + if (elect_one()) mbar_arrive(it_empty + 8 * (ic & 3)); + if (t >= total) break; + bool dn; int mt, nt, sub, m0, mend, e; + decode(t, dn, mt, nt, sub, m0, mend, e); + if (dn) { + // down item: warp 10 acquires the M tile's gate/up readiness (all act rows stored), then TMA-loads + // the act A tiles into the A ring (expect_tx + 63 arrivals = the a_full count of 64); warp 11 idles. + // Every later item of this CTA is a down item too (gate/up items precede all down items in the + // monotone queue), so warp 11 never waits on the A ring again. + if (w == 0) { + if (elect_one()) { + const int* rp = p.qctr + 1 + mt; + while (true) { + int v; + asm volatile("ld.acquire.gpu.global.b32 %0, [%1];" : "=r"(v) : "l"(rp) : "memory"); + if (v >= ready_target) break; + __nanosleep(64); + } + } + __syncwarp(); + asm volatile("fence.proxy.async.global;" ::: "memory"); // generic act writes -> TMA reads + const bool m64 = mend - m0 <= 64; + const uint32_t txa = (uint32_t)(m64 ? A_BYTES / 2 : A_BYTES); + const int rot = mf1_rot(t, INTER / TBK, p.krot); + for (int kb = 0; kb < INTER / TBK; kb++) { + const int s = (it + kb) % AS; + mbar_wait(a_empty + 8 * s, (((it + kb) / AS) & 1) ^ 1); + __syncwarp(); + if (elect_one()) { + const uint32_t fa = a_full + 8 * s; + mbar_expect_tx(fa, txa); + tma_load_2d(sbase + s * 16384, m64 ? &tX64 : &tX, + (kb + rot < INTER / TBK ? kb + rot : kb + rot - INTER / TBK) * TBK, m0, fa); + mbar_arrive_cnt(fa, MF_FULL_ARRIVALS - 2); + } + __syncwarp(); + } + } + it += INTER / TBK; + continue; + } + int tokr[2]; +#pragma unroll + for (int m = 0; m < 2; m++) { + const int k = lane + 32 * m; + const int pos = m0 + 8 * (k >> 2) + 4 * w + (k & 3); + tokr[m] = pos < mend ? __ldg(p.perm_tok + pos) : -1; + } + const int rot = mf1_rot(t, HID / TBK, p.krot); + for (int kb = 0; kb < HID / TBK; kb++, it++) { + const int s = it % AS; + mbar_wait(a_empty + 8 * s, ((it / AS) & 1) ^ 1); + const uint32_t dst0 = sbase + s * 16384 + lane_off; + const float* srck = p.xn + (kb + rot < HID / TBK ? kb + rot : kb + rot - HID / TBK) * TBK + c * 4; +#pragma unroll + for (int m = 0; m < 2; m++) { +#pragma unroll + for (int ii = 0; ii < 8; ii++) { + const int tok = __shfl_sync(0xffffffff, tokr[m], 4 * ii + rsub); + const int i = 8 * m + ii; // R = 8i + 4w + rsub + cp_async16(dst0 + (uint32_t)i * 1024u, srck + (size_t)(tok < 0 ? 0 : tok) * HID, + tok < 0 ? 0u : 16u); + } + } + cp_async_mbar_arrive_noinc(a_full + 8 * s); + } + } + } else { + // ---------------- epilogue warps 2..9: TMEM lane quadrant q = warp % 4, column half (warp-2)/4 + const int q = warp & 3; + const int half = (warp - 2) >> 2; + const int row = q * 32 + lane; + // act (re-read by the 8 down items of this M tile) and out (red.add target of all 8 experts of a token) are + // stored with L2 EVICT_LAST so the EVICT_FIRST weight stream does not push them to DRAM between uses. + const uint64_t keep = l2_policy_evict_last(); + for (int ic = 0;; ic++) { + const int t = get_item(ic); + __syncwarp(); + if (elect_one()) mbar_arrive(it_empty + 8 * (ic & 3)); + if (t >= total) break; + bool dn; int mt, nt, sub, m0, mend, e; + decode(t, dn, mt, nt, sub, m0, mend, e); + const int tbn = sub >= 0 ? 128 : 256; + const int buf = TWO ? 0 : (ic & 1); + const uint32_t aph = TWO ? (ic & 1) : ((ic >> 1) & 1); + // M=64 accumulator: row r in TMEM lane (r % 16) + 32 * (r / 16) + const bool m64 = mend - m0 <= 64; + const int erow = m64 ? q * 16 + lane : row; + const int pos = m0 + erow; + const bool valid = (!m64 || lane < 16) && pos < mend; + int tok = 0; float rw = 0.f; + int rtok[4]; bool rval[4]; + if (dn) { // routing metadata prefetched before the accumulator wait + if (valid) { tok = __ldg(p.perm_tok + pos); rw = __ldg(p.perm_w + pos); } +#pragma unroll + for (int i = 0; i < 4; i++) { + const int r = TWO ? ((i & 1) * 16 + (lane >> 1)) : (i * 8 + (lane >> 2)); // TWO: 8-col slab rows + rtok[i] = __shfl_sync(0xffffffff, tok, r); + rval[i] = __shfl_sync(0xffffffff, (int)valid, r) != 0; + } + } + mbar_wait(bar_tfull + 8 * buf, aph); + tc_fence_after(); + const uint32_t trow = tbase + ((uint32_t)(q * 32) << 16) + buf * TBN; + if (!dn) { + // full: gate cols [0,128), up [128,256); half: gate [0,64), up [64,128); this half owns gw act cols + const int gw = tbn >> 2, ngc = gw >> 5; + if constexpr (TWO) { + // 16-column chunks (32 live accumulator regs instead of 64: 2 CTAs / SM register budget) +#pragma unroll 1 + for (int c = 0; c < 2 * ngc; c++) { + float g[16], u[16]; + tmem_ld16x2(trow + half * gw + c * 16, g, trow + (tbn >> 1) + half * gw + c * 16, u); + if (c == 2 * ngc - 1) { + tc_fence_before(); + __syncwarp(); + if (elect_one()) mbar_arrive(bar_tempty + 8 * buf); + } + if (valid) { + float4* dst = reinterpret_cast(p.act + (size_t)pos * INTER + nt * 128 + + (sub > 0 ? 64 : 0) + half * gw + c * 16); +#pragma unroll + for (int j = 0; j < 4; j++) { + const float2 r01 = silu_mul2(make_float2(g[4 * j], g[4 * j + 1]), make_float2(u[4 * j], u[4 * j + 1])); + const float2 r23 = silu_mul2(make_float2(g[4 * j + 2], g[4 * j + 3]), make_float2(u[4 * j + 2], u[4 * j + 3])); + st_v4_hint(dst + j, make_float4(r01.x, r01.y, r23.x, r23.y), keep); + } + } + } + } else +#pragma unroll 1 + for (int c = 0; c < ngc; c++) { + float g[32], u[32]; + tmem_ld32(trow + half * gw + c * 32, g); + tmem_ld32(trow + (tbn >> 1) + half * gw + c * 32, u); + if (c == ngc - 1) { + tc_fence_before(); + __syncwarp(); + if (elect_one()) mbar_arrive(bar_tempty + 8 * buf); + } + if (valid) { + float4* dst = reinterpret_cast(p.act + (size_t)pos * INTER + nt * 128 + + (sub > 0 ? 64 : 0) + half * gw + c * 32); +#pragma unroll + for (int j = 0; j < 8; j++) { + const float2 r01 = silu_mul2(make_float2(g[4 * j], g[4 * j + 1]), make_float2(u[4 * j], u[4 * j + 1])); + const float2 r23 = silu_mul2(make_float2(g[4 * j + 2], g[4 * j + 3]), make_float2(u[4 * j + 2], u[4 * j + 3])); + st_v4_hint(dst + j, make_float4(r01.x, r01.y, r23.x, r23.y), keep); + } + } + } + // release: this warp's act stores -> visible (generic + async proxy) -> ready[mt] += 1 + asm volatile("fence.proxy.async.global;" ::: "memory"); + __syncwarp(); + if (elect_one()) asm volatile("red.release.gpu.global.add.s32 [%0], %1;" ::"l"(p.qctr + 1 + mt), "r"(1) : "memory"); + __syncwarp(); + } else { + const int hw = tbn >> 1, nch = tbn >> 6; + const int sub_off = sub > 0 ? 1 : 0; + float* stg = reinterpret_cast(smem + C::STG) + (warp - 2) * (TWO ? 256 : DOWN_STG_FLOATS); +#pragma unroll 1 + for (int c = 0; c < nch; c++) { + float a[32]; + tmem_ld32(trow + half * hw + c * 32, a); + if (c == nch - 1) { + tc_fence_before(); + __syncwarp(); + if (elect_one()) mbar_arrive(bar_tempty + 8 * buf); + } + // transpose the 32x32 chunk through smem in 16-col slabs -> 8 rows x 64 B per red.v4 instruction + const int n = nt * TBN + sub_off * 128 + half * hw + c * 32; + if constexpr (TWO) { + // 8-col slabs (32 rows x 32 B): each red.v4 instruction covers 16 rows x 32 B (full sectors) + const float2 w2 = make_float2(rw, rw); +#pragma unroll + for (int hh = 0; hh < 4; hh++) { + __syncwarp(); +#pragma unroll + for (int j = 0; j < 2; j++) { + const int slot = j ^ ((lane >> 2) & 1); + const float2 y0 = fmul2(make_float2(a[hh * 8 + 4 * j], a[hh * 8 + 4 * j + 1]), w2); + const float2 y1 = fmul2(make_float2(a[hh * 8 + 4 * j + 2], a[hh * 8 + 4 * j + 3]), w2); + *reinterpret_cast(stg + lane * 8 + slot * 4) = make_float4(y0.x, y0.y, y1.x, y1.y); + } + __syncwarp(); +#pragma unroll + for (int i = 0; i < 2; i++) { + const int r = i * 16 + (lane >> 1), g = lane & 1; + const float4 v = *reinterpret_cast(stg + r * 8 + (g ^ ((r >> 2) & 1)) * 4); + if (rval[i]) red_add_v4_hint(p.out + (size_t)rtok[i] * HID + n + hh * 8 + g * 4, v, keep); + } + } + continue; + } +#pragma unroll + for (int hh = 0; hh < 2; hh++) { + __syncwarp(); +#pragma unroll + for (int j = 0; j < 4; j++) { + const int slot = j ^ ((lane >> 1) & 3); + { // routing-weight scaling as FMUL2 + const float2 w2 = make_float2(rw, rw); + const float2 y0 = fmul2(make_float2(a[hh * 16 + 4 * j], a[hh * 16 + 4 * j + 1]), w2); + const float2 y1 = fmul2(make_float2(a[hh * 16 + 4 * j + 2], a[hh * 16 + 4 * j + 3]), w2); + *reinterpret_cast(stg + lane * 16 + slot * 4) = make_float4(y0.x, y0.y, y1.x, y1.y); + } + } + __syncwarp(); +#pragma unroll + for (int i = 0; i < 4; i++) { + const int r = i * 8 + (lane >> 2), g = lane & 3; + const float4 v = *reinterpret_cast(stg + r * 16 + (g ^ ((r >> 1) & 3)) * 4); + if (rval[i]) red_add_v4_hint(p.out + (size_t)rtok[i] * HID + n + hh * 16 + g * 4, v, keep); + } + } + } + } + } + } + tc_fence_before(); + __syncthreads(); + CHN(13, 2); + if (warp == 1) { + __syncwarp(); + tc_fence_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tbase), "r"(TCOLS)); + } +} + +__global__ void __launch_bounds__(256) mask_classify_kernel(sidew::MaskJob J) { + CHN(0, 0); + __shared__ int s_ok; + const int u = (blockIdx.z * gridDim.y + blockIdx.y) * gridDim.x + blockIdx.x; + if (threadIdx.x == 0) s_ok = sidew::claim(J.st, u, J.ep) ? 1 : 0; + __syncthreads(); + if (!s_ok) return; + sidew::mask_unit(J, u); + CHN(0, 2); +} + +constexpr int MASK_BULK_SMEM = 128 * 512; +// Classification + compact copy of one smem-staged mask tile (row r of the tile at mtl + 512 r, ncols floats valid). +// Block-level (all 256 threads). Shared by the per-tile bulk kernel and the persistent pipelined kernel below. +__device__ __forceinline__ void mask_bulk_tile(const sidew::MaskJob& J, int u, const uint8_t* mtl, int (*flags)[8], + int rel_tid = 0) { + const int tid = threadIdx.x; + const int S = J.S, nT = J.nT; + const int kt = u % nT, qt = (u / nT) % nT, b = u / (nT * nT); + const int nrows = S - qt * 128 < 128 ? S - qt * 128 : 128; + const int ncols = S - kt * 128 < 128 ? S - kt * 128 : 128; + const int warp = tid >> 5, lane = tid & 31; + const int gc0 = kt * 128 + lane * 4; + const int r0 = qt * 128 + warp * 16; + const float4* tl = reinterpret_cast(mtl) + warp * 16 * 32 + lane; // row warp*16+i at +i*32 + int notneg = 0, nonzero = 0, notcausal = 0; + if (kt != qt && nrows == 128 && ncols == 128) { + // full off-diagonal tile: branch-free bit test (2 LOP3 per element). notneg <=> some bits != bits(-inf); + // nonzero <=> some (bits & 0x7FFFFFFF) != 0 (identical to v != 0.f incl. -0.0 / NaN). Every column is > every + // row above the diagonal (notcausal = notneg) and <= every row below it (notcausal = nonzero). + uint32_t on = 0u, oz = 0u; + const uint4* tu = reinterpret_cast(tl); +#pragma unroll + for (int i = 0; i < 16; i++) { + const uint4 x = tu[i * 32]; + on |= (x.x ^ 0xFF800000u) | (x.y ^ 0xFF800000u) | (x.z ^ 0xFF800000u) | (x.w ^ 0xFF800000u); + oz |= x.x | x.y | x.z | x.w; + } + // warp-wide vote on the OR-ed bit patterns (one redux.or each) instead of a per-lane predicate + __any_sync + const uint32_t won = __reduce_or_sync(0xffffffffu, on), woz = __reduce_or_sync(0xffffffffu, oz & 0x7FFFFFFFu); + notneg = won != 0u; + nonzero = woz != 0u; + notcausal = kt > qt ? notneg : nonzero; + } else +#pragma unroll 4 + for (int i = 0; i < 16; i++) { + if (r0 + i >= S || gc0 >= S) continue; + const float4 mv = tl[i * 32]; + const float v[4] = {mv.x, mv.y, mv.z, mv.w}; +#pragma unroll + for (int e = 0; e < 4; e++) { + if (gc0 + e < S) { + notneg |= v[e] != -INFINITY; + nonzero |= v[e] != 0.f; + notcausal |= (gc0 + e > r0 + i) ? (v[e] != -INFINITY) : (v[e] != 0.f); + } + } + } + const int wn = __any_sync(0xffffffffu, notneg), wz = __any_sync(0xffffffffu, nonzero), + wc = __any_sync(0xffffffffu, notcausal); + if (lane == 0) { flags[0][warp] = wn; flags[1][warp] = wz; flags[2][warp] = wc; } + __syncthreads(); + int any_notneg = 0, any_nonzero = 0, any_notcausal = 0; +#pragma unroll + for (int w = 0; w < 8; w++) { any_notneg |= flags[0][w]; any_nonzero |= flags[1][w]; any_notcausal |= flags[2][w]; } + const bool partial = (kt * 128 + 128 > S); + const uint8_t code = !any_notneg ? 0 : ((!any_nonzero && !partial) ? 1 : (!any_notcausal ? 3 : 2)); + if (tid == 0) J.codes[((size_t)b * nT + qt) * nT + kt] = code; + if (code == 2) { + const float LOG2E = 1.4426950408889634f; + float4* dst = reinterpret_cast(J.mtile + (((size_t)b * nT + qt) * nT + kt) * 16384) + lane * 128 + + warp * 16; +#pragma unroll 4 + for (int i = 0; i < 16; i++) { + const bool rok = r0 + i < S; + float4 mv = make_float4(0.f, 0.f, 0.f, 0.f); + if (rok && gc0 < S) mv = tl[i * 32]; + const float v[4] = {mv.x, mv.y, mv.z, mv.w}; + float o[4]; +#pragma unroll + for (int e = 0; e < 4; e++) o[e] = gc0 + e >= S ? -INFINITY : (rok ? v[e] * LOG2E : 0.f); + dst[i] = make_float4(o[0], o[1], o[2], o[3]); + } + } + // release: this unit's codes / tile visible before the completion count + __syncthreads(); + if (tid == rel_tid) { asm volatile("red.release.gpu.global.add.u64 [%0], %1;" ::"l"(J.done), "l"((unsigned long long)(1ull)) : "memory"); } +} + +__global__ void __launch_bounds__(256) mask_classify_bulk_kernel(sidew::MaskJob J) { + extern __shared__ __align__(128) uint8_t mtl[]; + __shared__ __align__(8) uint64_t bar; + __shared__ int s_ok; + __shared__ int flags[3][8]; + const int u = (blockIdx.z * gridDim.y + blockIdx.y) * gridDim.x + blockIdx.x; + const int tid = threadIdx.x; + const int S = J.S, nT = J.nT; + const int kt = u % nT, qt = (u / nT) % nT, b = u / (nT * nT); + const int nrows = S - qt * 128 < 128 ? S - qt * 128 : 128; + const int ncols = S - kt * 128 < 128 ? S - kt * 128 : 128; // S % 4 == 0 -> ncols * 4 is a multiple of 16 + const uint32_t ba = smem_u32(&bar), sb = smem_u32(mtl); + if (tid == 0) { + mbar_init(ba, 1); + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + mbar_expect_tx(ba, (uint32_t)(nrows * ncols * 4)); + } + __syncthreads(); + if (tid < nrows) { // row tid of the tile: ncols floats, 512 B-aligned source (kt*512 + row * 4S, S % 4 == 0) + const float* src = J.mask + ((size_t)b * S + qt * 128 + tid) * S + kt * 128; + const uint64_t pol = sidew::pol_first(); + asm volatile( + "cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1], %2, [%3], %4;" ::"r"( + sb + (uint32_t)tid * 512u), + "l"(src), "r"((uint32_t)(ncols * 4)), "r"(ba), "l"(pol) + : "memory"); + } + if (tid == 32) s_ok = sidew::claim(J.st, u, J.ep) ? 1 : 0; // warp 1: claim while warp 0's copies are issued + mbar_wait(ba, 0); + __syncthreads(); // s_ok visible + if (!s_ok) return; + mask_bulk_tile(J, u, mtl, flags); +} + +__global__ void __launch_bounds__(256) mask_classify_tma_kernel(const __grid_constant__ CUtensorMap tm, sidew::MaskJob J) { + extern __shared__ __align__(128) uint8_t mtl[]; + __shared__ __align__(8) uint64_t bar; + __shared__ int s_ok; + __shared__ int flags[3][8]; + const int u = (blockIdx.z * gridDim.y + blockIdx.y) * gridDim.x + blockIdx.x; + const int tid = threadIdx.x; + CHN(0, 0); + const int nT = J.nT; + const int kt = u % nT, qt = (u / nT) % nT, b = u / (nT * nT); + const uint32_t ba = smem_u32(&bar), sb = smem_u32(mtl); + if (tid == 0) { + mbar_init(ba, 1); + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + mbar_expect_tx(ba, 65536u); + const uint64_t pol = sidew::pol_first(); + asm volatile( + "cp.async.bulk.tensor.3d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3, %4}], [%5], %6;" ::"r"(sb), + "l"((uint64_t)&tm), "r"(kt * 128), "r"(qt * 128), "r"(b), "r"(ba), "l"(pol) + : "memory"); + } + if (tid == 32) s_ok = sidew::claim(J.st, u, J.ep) ? 1 : 0; + __syncthreads(); // barrier init visible before any wait + mbar_wait(ba, 0); + __syncthreads(); + if (!s_ok) { CHN(0, 2); return; } + mask_bulk_tile(J, u, mtl, flags); + CHN(0, 2); +} + +// persistent classifier: grid = min(296, #tiles) CTAs (2 per SM at 64 KB smem each), CTA c walks tiles +// u = c, c + grid, ... Per tile ONE 3D TMA box load (128 x 128 fp32, 64 KB, OOB zero-filled) into its smem buffer, +// claim issued concurrently (same claim protocol / codes / compact copies as mask_classify_tma_kernel); the +// classification reads 128-bit ld.shared and votes with redux.or (mask_bulk_tile). Barrier parity flips per tile. +constexpr int MASK_PERSIST_CTAS = 296; +__global__ void __launch_bounds__(256) mask_classify_tma_persist_kernel(const __grid_constant__ CUtensorMap tm, sidew::MaskJob J) { + extern __shared__ __align__(128) uint8_t mtl[]; + __shared__ __align__(8) uint64_t bar; + __shared__ int s_ok; + __shared__ int flags[3][8]; + const int tid = threadIdx.x; + const int nT = J.nT; + const uint32_t ba = smem_u32(&bar), sb = smem_u32(mtl); + if (tid == 0) { + mbar_init(ba, 1); + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + } + __syncthreads(); + uint32_t ph = 0; + for (int u = blockIdx.x; u < J.n; u += gridDim.x, ph ^= 1u) { + const int kt = u % nT, qt = (u / nT) % nT, b = u / (nT * nT); + if (tid == 0) { + // previous tile's generic smem reads (ordered by the trailing __syncthreads) before the async-proxy overwrite + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + mbar_expect_tx(ba, 65536u); + const uint64_t pol = sidew::pol_first(); + asm volatile( + "cp.async.bulk.tensor.3d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3, %4}], [%5], %6;" ::"r"(sb), + "l"((uint64_t)&tm), "r"(kt * 128), "r"(qt * 128), "r"(b), "r"(ba), "l"(pol) + : "memory"); + } + if (tid == 32) s_ok = sidew::claim(J.st, u, J.ep) ? 1 : 0; + mbar_wait(ba, ph); + __syncthreads(); // s_ok visible + const int ok = s_ok; + if (ok) mask_bulk_tile(J, u, mtl, flags); // ends with __syncthreads (smem reads done) + else __syncthreads(); // s_ok read by all before the next tile's write + } +} + +// ------------------------------------------------------------------ tcgen05 flash attention (GQA head-pair) +// One work item = (batch, 128-query tile, kv head, head pair): the two q heads h0 = 2*pair', h0+1 (same kv head +// h0/8) are processed together over ONE K/V stream, so every K/V tile is loaded into smem once and consumed by +// both heads (halves the K/V TMA / L2 traffic vs. one item per q head). 320 threads: +// warp 0 : TMA producer. Q tiles of both heads (2 x 128 q x 128 d fp16, 64 KB) once per item, then a +// KVS-stage ring (2 for head pairs, 3 for single-head items; see FaCfg) of {K tile 128 keys x 128 d, V^T tile 128 d x 128 keys} for every non-masked key tile. +// warp 1 : TMEM allocator + MMA issuer over a stream of VIRTUAL tiles g = 2*(kv tile) + head: +// S_g = Q_head K^T (8 x SS m128n128k16 into S buffer g&1), O_head += P_g V (8 x TS m128n128k16, +// A = P read from TMEM, B = V^T smem). Order: S_A0 S_B0 | PV_A0 S_A1 | PV_B0 S_B1 | PV_A1 ... - +// the S of the next virtual tile is computed while the softmax works on the current one. +// The KV stage is released after PV of head B. +// warps 2-9 : softmax (both heads, virtual tiles in order), two warpgroups. Warp w owns TMEM lane quadrant +// q = w % 4 (32 query rows) and column half hf = (w-2)/4: S/P columns for keys hf*64..+63 and O +// columns hf*64..+63. The two halves exchange their partial row max through smem (named barrier +// per quadrant), keep per-head running max / partial row sums (combined once at the end). +// Online softmax in the exp2 domain with lazy rescaling (O rescaled only if the max grows > 2^11). +// P (fp16 pairs) is written with tcgen05.st INTO the upper 64 columns of its own S buffer (S already +// consumed into registers by both halves) - no smem round trip, no separate P columns. +// TMEM columns: [0,128) O_A, [128,256) O_B, [256,384) S/P buffer 0, [384,512) S/P buffer 1 +// (P of buffer b = columns 256 + 128 b + 64 .. +63 as fp16x2). +// Buffer reuse: S_g overwrites buffer g&1 which held P_{g-2}; the MMA thread waits for PV_{g-2} completion +// (bpv_done) before issuing S_g. Hence bs_full(g) also implies PV_{g-2} (previous PV of the same head) is done. +constexpr int FA_TILE_BYTES = 128 * 128 * 2; +constexpr int FA_Q = 0; +// smem geometry per item width NH: Q = NH tiles, then a KVS-deep ring of {K tile, V^T tile}. +// NH = 2 (head pair): 2 Q tiles + 2 KV stages = 192 KB. +// NH = 1 (single head, short sequences): only 1 Q tile is needed, so the freed 32 KB + the remaining headroom hold +// a THIRD KV stage (1 + 6 tiles = 224 KB): the K/V TMA for kv tile v+1 is then issued when PV_{v-2} completes +// instead of PV_{v-1}, taking the L2->smem load latency of each 64 KB stage off the S MMA -> softmax chain +// (single-head items only have one head's softmax per kv tile to hide it behind). +template struct FaCfg { + static constexpr int KVS = NH == 1 ? 3 : 2; + static constexpr int K0 = NH * FA_TILE_BYTES; + static constexpr int BAR = (NH + 2 * KVS) * FA_TILE_BYTES; + static constexpr int RED = BAR + 256; // float red[NRB][2 halves][128 rows]: row-max / row-sum exchange + // head-pair items (NH = 2, smem headroom) DOUBLE-BUFFER the exchange (buffer = exchange count & 1), so the + // WAR barrier before each write (barA) is not needed: a write to buffer k & 1 at exchange k + 2 happens after this + // thread passed barB(k + 1), i.e. after the partner arrived there, i.e. after the partner's read of exchange k. + // NH = 1 (224 KB of tiles) keeps the single buffer + barA. + static constexpr int NRB = NH == 2 ? 2 : 1; + static constexpr int SMEM = RED + NRB * 1024 + (NH == 2 ? 4096 : 0) + 1024; // + epilogue l slots + 1024 alignment slack +}; +static_assert(FaCfg<1>::SMEM <= 232448 && FaCfg<2>::SMEM <= 232448, "flash attention smem"); +constexpr int FA_THREADS = 320; +constexpr uint32_t FA_TS = 256; // TMEM column of S/P buffer 0 +// D=f32, A=B=f16, K-major, M=128, N=128 +constexpr uint32_t IDESC_F16_128x128 = (1u << 4) | (0u << 7) | (0u << 10) | ((128u >> 3) << 17) | ((128u >> 4) << 24); + +__device__ __forceinline__ void tmem_st32(uint32_t taddr, const float* v) { + asm volatile( + "tcgen05.st.sync.aligned.32x32b.x32.b32 [%0], {%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11,%12,%13,%14,%15,%16,%17,%18," + "%19,%20,%21,%22,%23,%24,%25,%26,%27,%28,%29,%30,%31,%32};" ::"r"(taddr), + "f"(v[0]), "f"(v[1]), "f"(v[2]), "f"(v[3]), "f"(v[4]), "f"(v[5]), "f"(v[6]), "f"(v[7]), "f"(v[8]), "f"(v[9]), + "f"(v[10]), "f"(v[11]), "f"(v[12]), "f"(v[13]), "f"(v[14]), "f"(v[15]), "f"(v[16]), "f"(v[17]), "f"(v[18]), + "f"(v[19]), "f"(v[20]), "f"(v[21]), "f"(v[22]), "f"(v[23]), "f"(v[24]), "f"(v[25]), "f"(v[26]), "f"(v[27]), + "f"(v[28]), "f"(v[29]), "f"(v[30]), "f"(v[31])); +} +// ---- attention probe instrumentation (compiled out unless FA_PROBE is defined in kernel.h) +// g_fa_mode bit 1: softmax warps skip all math (wait S, publish P at once) -> MMA/TMA-bound floor. +// g_fa_clk[]: MMA-warp (lane 0) clock64 totals over CTAs: 0 item, 1 Q-full, 2 KV-full, 3 S-free, 4 P-ready, +// 5 S issue, 6 PV issue (elected lane, incl. commits), 7 -, 8 total, 9 #CTAs +#ifdef FA_PROBE +__device__ int g_fa_mode; +__device__ unsigned long long g_fa_clk[16]; +#define FA_MODE g_fa_mode +#define PCLK(i, ...) do { const long long t0_ = clock64(); __VA_ARGS__; pc[i] += clock64() - t0_; } while (0) +#else +#define FA_MODE 0 +#define PCLK(i, ...) do { __VA_ARGS__; } while (0) +#endif +// named barrier over the two softmax warps sharing one TMEM lane quadrant (64 threads) +__device__ __forceinline__ void pair_bar(int id) { asm volatile("bar.sync %0, 64;" ::"r"(id) : "memory"); } + +// Persistent: grid = min(#SMs, #items). Work item i (fetched from a global atomic counter by the producer warp +// and broadcast through a 2-slot smem ring guarded by mbarriers) maps to +// qt = nQT-1 - i / (16*B) (descending q tile -> descending #non-empty KV tiles for causal masks: LPT order) +// b = (i % (16*B)) / 16, pair = i % 16, heads 2*pair, 2*pair+1 (the 4 pairs of one kv head are adjacent) +// TMEM, barriers and pipelines persist across items; ring indices / parities use per-CTA GLOBAL counters +// (G = virtual tiles so far, KT = kv tiles so far, per-head PV count = G/NH). +// NH = q heads per work item: 2 = head pair (above); 1 = SINGLE-head items (virtual tile = kv tile, item i -> +// qt = nQT-1 - i/(32B), b = (i%(32B))/32, head = i%32), chosen on the host when head-pair items would not fill +// ~2 waves of SMs (short sequences): half the per-item KV chain, twice the busy SMs. +// MUFU offload (port of fa4.cu exp2_poly2): degree-3 polynomial 2^x on the FMA pipe for selected exp2 pairs. +// x clamped to >= -126 (-inf -> ~2^-126, 0 after fp16 P), j = round(x) via the 1.5*2^23 magic add (FADD2), +// f = x - j in [-0.5, 0.5], 2^f by FFMA2 Horner (max rel err 7.7e-5), exponent added in the integer domain. +__device__ __forceinline__ float2 exp2_poly2(float2 x) { + x.x = fmaxf(x.x, -126.f); x.y = fmaxf(x.y, -126.f); + const float2 mg = make_float2(12582912.f, 12582912.f); + const float2 r = fadd2(x, mg); + const float2 j = fadd2(r, make_float2(-12582912.f, -12582912.f)); + const float2 f = fsub2(x, j); // sub.rn.f32x2 (bit-identical to x + (-j)) + float2 p = ffma2(make_float2(0.05508877f, 0.05508877f), f, make_float2(0.24260466f, 0.24260466f)); + p = ffma2(p, f, make_float2(0.69327628f, 0.69327628f)); + p = ffma2(p, f, make_float2(0.9999289f, 0.9999289f)); + return make_float2(__uint_as_float(__float_as_uint(p.x) + (__float_as_uint(r.x) << 23)), + __uint_as_float(__float_as_uint(p.y) + (__float_as_uint(r.y) << 23))); +} +template +__device__ __forceinline__ float2 exp2_polyd(float2 x) { + if (DEG == 3) return exp2_poly2(x); + x.x = fmaxf(x.x, -126.f); x.y = fmaxf(x.y, -126.f); + const float2 mg = make_float2(12582912.f, 12582912.f); + const float2 r = fadd2(x, mg); + const float2 j = fadd2(r, make_float2(-12582912.f, -12582912.f)); + const float2 f = fsub2(x, j); // sub.rn.f32x2 (bit-identical to x + (-j)) + float2 p = ffma2(make_float2(0.23842119f, 0.23842119f), f, make_float2(0.70343379f, 0.70343379f)); + p = ffma2(p, f, make_float2(1.00044259f, 1.00044259f)); + return make_float2(__uint_as_float(__float_as_uint(p.x) + (__float_as_uint(r.x) << 23)), + __uint_as_float(__float_as_uint(p.y) + (__float_as_uint(r.y) << 23))); +} +// fused softmax pair helpers for tc_flash_attn (bit-identical to ffma2 / fast_exp2 x2 / exp2_polyd / +// fadd2 row-sum / pack_h2): one asm block per key pair, no intermediate 64-bit mov round trips +__device__ __forceinline__ uint32_t hp_exp_pack(float s0, float s1, float2 ks, float2 nb, float2& acc) { + uint32_t pk; + asm("{ .reg .b64 rs, rk, rn, rt, ra, re; .reg .f32 t0, t1, e0, e1;\n" + " mov.b64 rs, {%3, %4}; mov.b64 rk, {%5, %6}; mov.b64 rn, {%7, %8}; mov.b64 ra, {%1, %2};\n" + " fma.rn.f32x2 rt, rs, rk, rn; mov.b64 {t0, t1}, rt;\n" + " ex2.approx.ftz.f32 e0, t0; ex2.approx.ftz.f32 e1, t1;\n" + " mov.b64 re, {e0, e1}; add.rn.f32x2 ra, ra, re; mov.b64 {%1, %2}, ra;\n" + " cvt.rn.f16x2.f32 %0, e1, e0; }" + : "=r"(pk), "+f"(acc.x), "+f"(acc.y) + : "f"(s0), "f"(s1), "f"(ks.x), "f"(ks.y), "f"(nb.x), "f"(nb.y)); + return pk; +} +template +__device__ __forceinline__ uint32_t hp_poly_pack(float s0, float s1, float2 ks, float2 nb, float2& acc) { + uint32_t pk; + // coefficients (highest first): DEG 3: c3 c2 c1 c0; DEG 2: c2 c1 c0 (c3 unused) + const float c3 = DEG == 3 ? 0.05508877f : 0.f; + const float c2 = DEG == 3 ? 0.24260466f : 0.23842119f; + const float c1 = DEG == 3 ? 0.69327628f : 0.70343379f; + const float c0 = DEG == 3 ? 0.9999289f : 1.00044259f; + if (DEG == 3) { + asm("{ .reg .b64 rs, rk, rn, rt, rx, rm, rmn, rr, rj, rf, rp, ka, kb, kc, kd, ra, re;\n" + " .reg .f32 t0, t1, x0, x1, r0, r1, p0, p1, e0, e1; .reg .b32 u0, u1, v0, v1;\n" + " mov.b64 rs, {%3, %4}; mov.b64 rk, {%5, %6}; mov.b64 rn, {%7, %8}; mov.b64 ra, {%1, %2};\n" + " mov.b64 rm, {%9, %9}; mov.b64 rmn, {%10, %10};\n" + " mov.b64 ka, {%11, %11}; mov.b64 kb, {%12, %12}; mov.b64 kc, {%13, %13}; mov.b64 kd, {%14, %14};\n" + " fma.rn.f32x2 rt, rs, rk, rn; mov.b64 {t0, t1}, rt;\n" + " max.f32 x0, t0, %15; max.f32 x1, t1, %15; mov.b64 rx, {x0, x1};\n" + " add.rn.f32x2 rr, rx, rm; add.rn.f32x2 rj, rr, rmn; sub.rn.f32x2 rf, rx, rj;\n" + " fma.rn.f32x2 rp, ka, rf, kb; fma.rn.f32x2 rp, rp, rf, kc; fma.rn.f32x2 rp, rp, rf, kd;\n" + " mov.b64 {p0, p1}, rp; mov.b64 {r0, r1}, rr;\n" + " mov.b32 u0, p0; mov.b32 u1, p1; mov.b32 v0, r0; mov.b32 v1, r1;\n" + " shl.b32 v0, v0, 23; shl.b32 v1, v1, 23; add.u32 u0, u0, v0; add.u32 u1, u1, v1;\n" + " mov.b32 e0, u0; mov.b32 e1, u1;\n" + " mov.b64 re, {e0, e1}; add.rn.f32x2 ra, ra, re; mov.b64 {%1, %2}, ra;\n" + " cvt.rn.f16x2.f32 %0, e1, e0; }" + : "=r"(pk), "+f"(acc.x), "+f"(acc.y) + : "f"(s0), "f"(s1), "f"(ks.x), "f"(ks.y), "f"(nb.x), "f"(nb.y), "f"(12582912.f), "f"(-12582912.f), + "f"(c3), "f"(c2), "f"(c1), "f"(c0), "f"(-126.f)); + } else { + asm("{ .reg .b64 rs, rk, rn, rt, rx, rm, rmn, rr, rj, rf, rp, kb, kc, kd, ra, re;\n" + " .reg .f32 t0, t1, x0, x1, r0, r1, p0, p1, e0, e1; .reg .b32 u0, u1, v0, v1;\n" + " mov.b64 rs, {%3, %4}; mov.b64 rk, {%5, %6}; mov.b64 rn, {%7, %8}; mov.b64 ra, {%1, %2};\n" + " mov.b64 rm, {%9, %9}; mov.b64 rmn, {%10, %10};\n" + " mov.b64 kb, {%11, %11}; mov.b64 kc, {%12, %12}; mov.b64 kd, {%13, %13};\n" + " fma.rn.f32x2 rt, rs, rk, rn; mov.b64 {t0, t1}, rt;\n" + " max.f32 x0, t0, %14; max.f32 x1, t1, %14; mov.b64 rx, {x0, x1};\n" + " add.rn.f32x2 rr, rx, rm; add.rn.f32x2 rj, rr, rmn; sub.rn.f32x2 rf, rx, rj;\n" + " fma.rn.f32x2 rp, kb, rf, kc; fma.rn.f32x2 rp, rp, rf, kd;\n" + " mov.b64 {p0, p1}, rp; mov.b64 {r0, r1}, rr;\n" + " mov.b32 u0, p0; mov.b32 u1, p1; mov.b32 v0, r0; mov.b32 v1, r1;\n" + " shl.b32 v0, v0, 23; shl.b32 v1, v1, 23; add.u32 u0, u0, v0; add.u32 u1, u1, v1;\n" + " mov.b32 e0, u0; mov.b32 e1, u1;\n" + " mov.b64 re, {e0, e1}; add.rn.f32x2 ra, ra, re; mov.b64 {%1, %2}, ra;\n" + " cvt.rn.f16x2.f32 %0, e1, e0; }" + : "=r"(pk), "+f"(acc.x), "+f"(acc.y) + : "f"(s0), "f"(s1), "f"(ks.x), "f"(ks.y), "f"(nb.x), "f"(nb.y), "f"(12582912.f), "f"(-12582912.f), + "f"(c2), "f"(c1), "f"(c0), "f"(-126.f)); + } + (void)c3; + return pk; +} +// PM = bitmask over (pair index c % 16): pairs with bit set use the DEG-degree FMA-pipe polynomial (compile-time, +// warp-uniform), the rest MUFU ex2. 0 = all MUFU, 0x1111 = 1/4, 0x1249 = 5/16, 0x2525 = 3/8, 0x5555 = 1/2. +template +__global__ void __launch_bounds__(FA_THREADS, 1) tc_flash_attn_kernel(const __grid_constant__ CUtensorMap tmQ, + const __grid_constant__ CUtensorMap tmK, + const __grid_constant__ CUtensorMap tmV, + const float* __restrict__ mask, + const uint8_t* __restrict__ tcode, + __half* __restrict__ out, int S, int nQT, int nKT, + float sl2, int B, int* __restrict__ work_ctr, + const sidew::MaskJob MJ, + const unsigned* __restrict__ vmax, + const float* __restrict__ pfg, + const float* __restrict__ pfu, int pf_items, + const int* __restrict__ qbc, + int pf_kb, int pf_krot, int pf_ntn) { + // vmax != nullptr: fp8 o_proj mode - O is written as e4m3 bytes [B*S, 4096] scaled by the global pow2 sa8 + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = (uint8_t*)(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023); + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int total_items = nQT * (32 / NH) * B; + constexpr int FA_KV_STAGES = FaCfg::KVS, FA_K0 = FaCfg::K0, FA_BAR = FaCfg::BAR, FA_RED = FaCfg::RED; + + const uint32_t sb = smem_u32(smem); + const uint32_t bq_full = sb + FA_BAR; // both Q tiles landed + const uint32_t bq_empty = sb + FA_BAR + 8; // last S MMA of an item done -> Q smem reusable + const uint32_t bkv_full = sb + FA_BAR + 16; // [<=3] KV stage landed + const uint32_t bkv_empty = sb + FA_BAR + 40; // [<=3] released after PV of the last head + const uint32_t bs_full = sb + FA_BAR + 64; // [2] S_g ready in buffer g&1 + const uint32_t bp_full = sb + FA_BAR + 80; // [2] P_g published (8 softmax warps) + const uint32_t bpv_done = sb + FA_BAR + 96; // [2] PV_g complete (buffer g&1 reusable) + const uint32_t bo_done = sb + FA_BAR + 112; // [2] per head: PV of that head complete + const uint32_t bit_full = sb + FA_BAR + 128; // [2] work-item slot published + const uint32_t bit_empty = sb + FA_BAR + 144; // [2] work-item slot consumed (MMA thread + 8 softmax warps) + const uint32_t tslot = sb + FA_BAR + 160; + volatile uint32_t* tslot_ptr = (volatile uint32_t*)(smem + FA_BAR + 160); + volatile int* item_slot = (volatile int*)(smem + FA_BAR + 168); // int[2] + float* red = reinterpret_cast(smem + FA_RED); // [2][128] + + if (threadIdx.x == 0) { + mbar_init(bq_full, 1); + mbar_init(bq_empty, 1); + for (int i = 0; i < FA_KV_STAGES; i++) { mbar_init(bkv_full + 8 * i, 1); mbar_init(bkv_empty + 8 * i, 1); } + for (int i = 0; i < 2; i++) { + mbar_init(bs_full + 8 * i, 1); mbar_init(bp_full + 8 * i, KS ? 4 : 8); + mbar_init(bpv_done + 8 * i, 1); mbar_init(bo_done + 8 * i, 1); + mbar_init(bit_full + 8 * i, 1); mbar_init(bit_empty + 8 * i, 9); + } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tmQ) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tmK) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tmV) : "memory"); + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(tslot), "r"(512)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + tc_fence_before(); + __syncthreads(); + tc_fence_after(); + const uint32_t tbase = *tslot_ptr; + CHN(10, 0); + // mask codes / compact tiles come from the side stream (input-only, not the PDL predecessor): acquired + // BEFORE griddepcontrol.wait (executing still-unclaimed mask units in this CTA: work stealing, deadlock-free) + // L2 prefetch of the first MoE wave's expert weights (kernel INPUTS, no dependency) while attention runs + // with DRAM mostly idle. Gate/up + // item t ~ (expert t / 6, n-tile t % 6) of the fused MoE (1 group / expert at T < 2048): 64 gate + 64 up rows, the + // first pf_kb of its rotated k-block order (start (t * krot) % 32) -> pf_kb * 256 B contiguous per row (split at + // the wrap). A wrong guess only costs extra DRAM reads; results never depend on it. + if (pfg != nullptr && threadIdx.x < 128) { + const int r = threadIdx.x & 63; + const float* base = threadIdx.x < 64 ? pfg : pfu; + for (int t = blockIdx.x; t < pf_items; t += gridDim.x) { + // pf_ntn = gate/up n-tiles (of 64 rows) per expert: 12 matches the fused fp16 MoE item decode (gu_decode + // with one group per expert); 6 = the former decode (only the first 384 rows of experts 0..24) + const int e = t / pf_ntn, nt = t - e * pf_ntn; + const char* row = reinterpret_cast(base + ((size_t)e * INTER + nt * 64 + r) * HID); + const int k0 = pf_krot > 0 ? (t * pf_krot) % (HID / 64) : 0; + const int n1 = k0 + pf_kb <= HID / 64 ? pf_kb : HID / 64 - k0; + asm volatile("cp.async.bulk.prefetch.L2.global [%0], %1;" ::"l"(row + k0 * 256), "r"((uint32_t)(n1 * 256)) : "memory"); + if (n1 < pf_kb) + asm volatile("cp.async.bulk.prefetch.L2.global [%0], %1;" ::"l"(row), "r"((uint32_t)((pf_kb - n1) * 256)) : "memory"); + } + } + sidew::mask_acquire_steal(MJ); + // no griddepcontrol.wait here - the producer acquires the per-M-tile QKV completion + // counters of each item's batch before its Q / K / V TMA loads, so attention items of finished batches start + // while the QKV GEMM's last tiles (other batches) still run. All QKV CTAs are resident (this grid launches only + // after every QKV CTA triggered) -> no deadlock. The full griddepcontrol.wait runs at kernel end (transitive chain). + // (qbc == nullptr) the producer warp 0 fetches / publishes its first item and scans its mask codes (side-stream + // products, acquired above) BEFORE its griddepcontrol.wait, which it runs right before the first Q / K / V TMA load + if (qbc == nullptr && warp != 0) pdl_wait(); + CHN(10, 1); + if (qbc != nullptr || warp != 0) pdl_trigger(); + + // item decode (LPT order: heaviest causal q tiles first); h0 = first head of the pair + auto decode = [&](int item, int& qt, int& h0, int& b) { + const int per = (32 / NH) * B; + qt = nQT - 1 - item / per; + const int r = item - (item / per) * per; + if (NH == 2) { b = r >> 4; h0 = (r & 15) * 2; } + else { b = r >> 5; h0 = r & 31; } + }; + auto get_item = [&](int ic) -> int { + const int slot = ic & 1; + { const uint32_t ba_ = bit_full + 8 * slot, bp_ = (ic >> 1) & 1; if (!mbar_test(ba_, bp_)) mbar_wait_hint(ba_, bp_); } // item slot wait sleeps + return item_slot[slot]; + }; + + if (warp == 0) { + { + // TMA producer: whole warp loops (warp-uniform waits); lane 0 fetches + broadcasts the work item, + // one elect.sync lane publishes it and issues expect_tx + the Q/K/V TMA loads + int s = 0, ph = 0, qi = 0; + unsigned long long qrdy = 0ull; // batches whose QKV rows were acquired + bool pdl_done = qbc != nullptr; + // Q/K/V TMA loads use the default L2 policy + for (int ic = 0;; ic++) { + int item0 = 0; + if (elect_one()) item0 = atomicAdd(work_ctr, 1); + const int item = __shfl_sync(0xffffffffu, item0, 0); + const int slot = ic & 1; + { const uint32_t ba_ = bit_empty + 8 * slot, bp_ = ((ic >> 1) & 1) ^ 1; if (!mbar_test(ba_, bp_)) mbar_wait_hint(ba_, bp_); } + __syncwarp(); + if (elect_one()) { + item_slot[slot] = item; + mbar_arrive(bit_full + 8 * slot); + } + __syncwarp(); + if (item >= total_items) break; + int qt, h0, b; + decode(item, qt, h0, b); + const int kvh = h0 >> 3, q0 = qt * 128; + const uint8_t* codes = tcode + ((size_t)b * nQT + qt) * nKT; + bool any = false; + for (int kt = 0; kt < nKT; kt++) if (codes[kt]) { any = true; break; } + if (!any) continue; // fully masked: no loads, no MMAs for this item + if (!pdl_done) { pdl_wait(); pdl_trigger(); pdl_done = true; } // QKV outputs needed from here + if (qbc != nullptr && !(b < 64 && ((qrdy >> b) & 1ull))) { + // tokens of batch b, + up to 128 rows of batch b+1 when S % 128 != 0 (the last head's partial Q / K + // tiles read the next batch's head-0 rows: computed only for masked / never-stored entries, but must + // be finite, i.e. already written by this call's QKV) + const int Tt = B * S; + int r1 = (b + 1) * S - 1 + (nKT * 128 - S); // exact overflow (Spad - S rows of batch b+1) + if (r1 > Tt - 1) r1 = Tt - 1; + const int t0 = (b * S) >> 7, t1 = r1 >> 7; + for (int base = t0; base <= t1; base += 32) { + const int t = base + lane; + if (t <= t1) { + while (true) { + int v; + asm volatile("ld.acquire.gpu.global.b32 %0, [%1];" : "=r"(v) : "l"(qbc + t) : "memory"); + if (v >= 4 * NQKV) break; + __nanosleep(64); + } + } + } + __syncwarp(); + asm volatile("fence.proxy.async.global;" ::: "memory"); // generic q/k/V^T writes -> TMA reads + if (b < 64) qrdy |= 1ull << b; + } + // the item's FIRST K/V stage is TMA-loaded BEFORE waiting bq_empty / loading Q (separate smem; the + // KV ring has its own empty barriers), so K/V streams while the previous item's last S MMAs still read Q. + // Same bytes / barriers / MMA order -> numerics identical. + auto load_kv = [&](int kt) { + if (!mbar_test(bkv_empty + 8 * s, ph ^ 1)) mbar_wait_hint(bkv_empty + 8 * s, ph ^ 1); // producer sleeps on KV stage refill + const uint32_t fb = bkv_full + 8 * s; + __syncwarp(); + if (elect_one()) { + mbar_expect_tx(fb, 2 * FA_TILE_BYTES); + const uint32_t kdst = sb + FA_K0 + s * 2 * FA_TILE_BYTES, vdst = kdst + FA_TILE_BYTES; + const int krow = (b * 4 + kvh) * S + kt * 128; + tma_load_2d(kdst, &tmK, 0, krow, fb); + tma_load_2d(kdst + FA_TILE_BYTES / 2, &tmK, 64, krow, fb); + const int vrow = (b * 4 + kvh) * 128; + tma_load_2d(vdst, &tmV, kt * 128, vrow, fb); + tma_load_2d(vdst + FA_TILE_BYTES / 2, &tmV, kt * 128 + 64, vrow, fb); + } // elect_one + __syncwarp(); + if (++s == FA_KV_STAGES) { s = 0; ph ^= 1; } + }; + int kt0 = 0; + while (!codes[kt0]) kt0++; // exists: any == true + load_kv(kt0); + if (qi > 0) { if (!mbar_test(bq_empty, (qi - 1) & 1)) mbar_wait_hint(bq_empty, (qi - 1) & 1); } // previous item's S MMAs done reading Q + __syncwarp(); + if (elect_one()) { + mbar_expect_tx(bq_full, NH * FA_TILE_BYTES); +#pragma unroll + for (int x = 0; x < NH; x++) { + const int qrow = (b * 32 + h0 + x) * S + q0; + tma_load_2d(sb + FA_Q + x * FA_TILE_BYTES, &tmQ, 0, qrow, bq_full); + tma_load_2d(sb + FA_Q + x * FA_TILE_BYTES + FA_TILE_BYTES / 2, &tmQ, 64, qrow, bq_full); + } + } + __syncwarp(); + qi++; + for (int kt = kt0 + 1; kt < nKT; kt++) { + if (!codes[kt]) continue; + load_kv(kt); + } + } + if (!pdl_done) { pdl_wait(); pdl_trigger(); } + } + } else if (warp == 1) { + { + // whole warp runs the issuer loop (warp-uniform waits / descriptors); elect.sync lane issues MMA + commit + int G = 0, KT = 0, qi = 0; // G: virtual tile counter, KT: kv tile counter (KV ring) +#ifdef FA_PROBE + long long pc[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0}; + const long long tstart = clock64(); +#endif + for (int ic = 0;; ic++) { + int item; + PCLK(0, item = get_item(ic)); + __syncwarp(); + if (elect_one()) mbar_arrive(bit_empty + 8 * (ic & 1)); + if (item >= total_items) break; + int qt, h0, b; + decode(item, qt, h0, b); + const uint8_t* codes = tcode + ((size_t)b * nQT + qt) * nKT; + int n = 0; + for (int kt = 0; kt < nKT; kt++) n += codes[kt] != 0; + if (n == 0) continue; + const int nv = NH * n; // virtual tiles of this item + // single-head item whose q tile holds <= 64 valid rows -> M = 64 S / PV MMAs (TMEM layout: + // row r in lane (r % 16) + 32 (r / 16)); softmax threads remap their row accordingly + const bool m64i = NH == 1 && S - qt * 128 <= 64; + const uint32_t IDQ = m64i ? ((IDESC_F16_128x128 & ~(0x1Fu << 24)) | ((64u >> 4) << 24)) : IDESC_F16_128x128; + PCLK(1, mbar_wait(bq_full, qi & 1)); + qi++; + // prepare + issue S of local virtual tile v (head v&1, kv tile v>>1) + auto issue_S = [&](int v) { + const int g = G + v, x = NH == 2 ? (v & 1) : 0, kv = KT + v / NH; + const int st = kv % FA_KV_STAGES; + if (x == 0) PCLK(2, mbar_wait(bkv_full + 8 * st, (kv / FA_KV_STAGES) & 1)); + // PV_{g-2} done: buffer free. KS: not waited - S_g is issued by this thread after PV_{g-2}, and + // tcgen05.mma from one thread execute in order, so S_g overwrites P_{g-2} only after PV_{g-2} read it + // no PV_{g-2} wait for any variant (head pairs too): in-order tcgen05 execution from this thread, + // and the bs_full(g) commit tracks PV_{g-2} as well -> identical ordering for the softmax + (void)0; + tc_fence_after(); + const uint32_t kb = sb + FA_K0 + st * 2 * FA_TILE_BYTES; + const uint32_t qb = sb + FA_Q + x * FA_TILE_BYTES; + const uint32_t d = tbase + FA_TS + (g & 1) * 128; + const uint64_t qd = make_sdesc(qb), kd = make_sdesc(kb); + __syncwarp(); + PCLK(5, { + if (elect_one()) { + for (int kk = 0; kk < 8; kk++) { + const uint32_t off = ((kk >> 2) * (FA_TILE_BYTES / 2) + (kk & 3) * 32) >> 4; + mma_f16_ss(d, qd + off, kd + off, IDQ, kk > 0); + } + mma_commit(bs_full + 8 * (g & 1)); + if (v == nv - 1) mma_commit(bq_empty); // all S MMAs of this item issued + } + __syncwarp(); }); + }; + issue_S(0); + for (int v = 0; v < nv; v++) { + if (v + 1 < nv) issue_S(v + 1); + const int g = G + v, x = NH == 2 ? (v & 1) : 0, pb = g & 1; + PCLK(4, mbar_wait(bp_full + 8 * pb, (g >> 1) & 1)); + tc_fence_after(); + const uint32_t ptm = tbase + FA_TS + pb * 128 + (KS ? 0 : 64); // KS: P in the lower 64 cols + const int st = (KT + v / NH) % FA_KV_STAGES; + const uint32_t vb = sb + FA_K0 + st * 2 * FA_TILE_BYTES + FA_TILE_BYTES; + const uint32_t ot = tbase + (KS ? pb : x) * 128; // KS: O buffer = tile parity + const uint64_t vd = make_sdesc(vb); + const bool acc0 = KS ? v >= 2 : (v / NH) > 0; // KS: first PV of each O buffer in the item + __syncwarp(); + PCLK(6, { + if (elect_one()) { + for (int kk = 0; kk < 8; kk++) { + const uint32_t off = ((kk >> 2) * (FA_TILE_BYTES / 2) + (kk & 3) * 32) >> 4; + mma_f16_ts(ot, ptm + kk * 8, vd + off, IDQ, (acc0 || kk > 0)); + } + if (x == NH - 1) mma_commit(bkv_empty + 8 * st); // both heads consumed this K/V stage + mma_commit(bpv_done + 8 * pb); + mma_commit(bo_done + 8 * (KS ? pb : x)); + } + __syncwarp(); }); + } + G += nv; + KT += n; + } +#ifdef FA_PROBE + pc[8] = clock64() - tstart; + if (lane == 0) { + for (int i = 0; i < 9; i++) atomicAdd(&g_fa_clk[i], (unsigned long long)pc[i]); + atomicAdd(&g_fa_clk[9], 1ull); + } +#endif + } + } else { + // ---------------- softmax warps 2..9 (thread = half of a query row, both heads) + const int q = warp & 3; + const int hf = (warp - 2) >> 2; // column half: keys / O columns hf*64 .. hf*64+63 + const int row = q * 32 + lane; + const uint32_t tl = tbase + ((uint32_t)(q * 32) << 16); + const int barA = 1 + q, barB = 5 + q; // named barriers 1..8 (0 = __syncthreads) + constexpr bool RDB = FaCfg::NRB == 2; // double-buffered exchange (no barA) + uint32_t xc = 0; // exchange counter (identical sequence in both halves) + uint32_t ec = 0; // epilogue l-exchange counter (head pairs) + // global fp8 output scale hoisted out of the per-item epilogue (vmax final after the PDL wait) + const float vsc8 = vmax ? f8_scale(__uint_as_float(*vmax) * 0.0009765625f, 7) : 0.f; + int G = 0; // virtual tile counter (matches the MMA thread's) + for (int ic = 0;; ic++) { + const int item = get_item(ic); + __syncwarp(); + if (elect_one()) mbar_arrive(bit_empty + 8 * (ic & 1)); + if (item >= total_items) break; + int qt, h0, b; + decode(item, qt, h0, b); + const int q0 = qt * 128; + // M = 64 items: lane < 16 of quadrant q holds row 16 q + lane; lanes >= 16 hold no row (never stored) + const bool m64i = NH == 1 && S - q0 <= 64; + const int rowe = m64i ? (lane < 16 ? q * 16 + lane : 64 + q * 16 + (lane - 16)) : row; // permutation of 0..127 + const int grow = (!m64i || lane < 16) ? q0 + rowe : S + 4 + lane; + const uint8_t* codes = tcode + ((size_t)b * nQT + qt) * nKT; + float mA = -INFINITY, lA = 0.f, mB = -INFINITY, lB = 0.f; // per-head running max / partial sum + int j = 0; + if (FA_MODE & 1) { + // probe only: no softmax math - wait S_g, publish P_g at once; finally wait the last PV of each head + int nn = 0; + for (int kt = 0; kt < nKT; kt++) nn += codes[kt] != 0; + for (int v = 0; v < NH * nn; v++) { + const int g = G + v; + mbar_wait(bs_full + 8 * (g & 1), (g >> 1) & 1); + __syncwarp(); + if (elect_one()) mbar_arrive(bp_full + 8 * (g & 1)); + } + if (nn > 0) + for (int x = 0; x < NH; x++) mbar_wait(bo_done + 8 * x, (G / NH + nn - 1) & 1); + G += NH * nn; + continue; + } + if constexpr (KS) { + // ---- kv-split: this warpgroup (hf) handles the item's virtual tiles g with g & 1 == hf, full rows + float m_used = -INFINITY, l = 0.f; + int jx = 0; // tiles processed by this warpgroup + for (int kt = 0; kt < nKT; kt++) { + const int code = codes[kt]; + if (!code) continue; + const int g = G + j; + j++; + if ((g & 1) != hf) continue; + mbar_wait(bs_full + 8 * hf, (g >> 1) & 1); + tc_fence_after(); + const uint32_t sc = tl + FA_TS + hf * 128; + // two passes over the S row (64 live S values, register cap of the 320-thread kernel): + // pass 1 = masked / scaled row max per 64-column half, pass 2 = reload, exp, pack, P store. + // code 1 / 3 keep raw scores (sl2 folded into the exp FFMA2 and the max), code 2 scales + masks. + const float ks = code == 2 ? 1.f : sl2; + const float2 sl2v = make_float2(sl2, sl2); + const float4* mt = reinterpret_cast(mask + (((size_t)b * nQT + qt) * nKT + kt) * 16384) + rowe; + const int cl = (grow < S ? grow : S - 1) - kt * 128; // code 3: last unmasked column of the tile + // loads S half ph into s[64] and applies the tile's mask transform (identical in both passes) + auto ld_half = [&](int ph, float* s) { + tmem_ld32x2(sc + 64 * ph, s, sc + 64 * ph + 32, s + 32); + if (code == 2) { +#pragma unroll + for (int cc = 0; cc < 2; cc++) { + float4 mv[8]; +#pragma unroll + for (int i = 0; i < 8; i++) mv[i] = mt[(16 * ph + 8 * cc + i) * 128]; +#pragma unroll + for (int i = 0; i < 8; i++) { + const int c4 = 8 * cc + i; + const float2 x0 = ffma2(make_float2(s[4 * c4], s[4 * c4 + 1]), sl2v, make_float2(mv[i].x, mv[i].y)); + const float2 x1 = ffma2(make_float2(s[4 * c4 + 2], s[4 * c4 + 3]), sl2v, make_float2(mv[i].z, mv[i].w)); + s[4 * c4] = x0.x; s[4 * c4 + 1] = x0.y; s[4 * c4 + 2] = x1.x; s[4 * c4 + 3] = x1.y; + } + } + } else if (code == 3) { + const int clh = cl - 64 * ph; +#pragma unroll + for (int cc = 0; cc < 64; cc++) s[cc] = cc > clh ? -INFINITY : s[cc]; + } + }; + float mxa[4]; +#pragma unroll + for (int i = 0; i < 4; i++) mxa[i] = -INFINITY; +#pragma unroll 1 + for (int ph = 0; ph < 2; ph++) { + float s[64]; + ld_half(ph, s); +#pragma unroll + for (int cc = 0; cc < 32; cc++) mxa[cc & 3] = fmax3(mxa[cc & 3], s[2 * cc], s[2 * cc + 1]); + } + float mx = fmax3(fmax3(mxa[0], mxa[1], mxa[2]), mxa[3], -INFINITY); + if (code == 1 || code == 3) mx *= sl2; + const float m_new = fmaxf(m_used, mx); + const bool need = m_new > m_used + 11.f; + if (__any_sync(0xffffffff, need)) { + const float alpha = need ? fast_exp2(m_used - m_new) : 1.f; + if (need) { l *= alpha; m_used = m_new; } + if (jx > 0) { + // previous PV into O_hf (phase (g >> 1) - 1): complete (S_g issued after PV_{g-2}) + mbar_wait(bo_done + 8 * hf, ((g >> 1) & 1) ^ 1); + tc_fence_after(); +#pragma unroll 1 + for (int cc = 0; cc < 4; cc++) { + float o[32]; + tmem_ld32(tl + hf * 128 + cc * 32, o); +#pragma unroll + for (int i = 0; i < 16; i++) { + const float2 r = fmul2(make_float2(o[2 * i], o[2 * i + 1]), make_float2(alpha, alpha)); + o[2 * i] = r.x; o[2 * i + 1] = r.y; + } + tmem_st32(tl + hf * 128 + cc * 32, o); + } + asm volatile("tcgen05.wait::st.sync.aligned;" ::: "memory"); + } + } + const float base = m_used == -INFINITY ? 0.f : m_used; + float2 rsa[4]; +#pragma unroll + for (int i = 0; i < 4; i++) rsa[i] = make_float2(0.f, 0.f); + const float2 ksv = make_float2(ks, ks), nbv = make_float2(-base, -base); + // KS: P (fp16 pairs of all 128 keys) into the LOWER 64 columns of S buffer hf: half ph's P goes to + // cols 32 ph .. +31, which only overlap S columns already consumed (half 0) -> 64 live S values +#pragma unroll 1 + for (int ph = 0; ph < 2; ph++) { + float s[64]; + ld_half(ph, s); + float pk[32]; +#pragma unroll + for (int c2 = 0; c2 < 32; c2++) { + pk[c2] = __uint_as_float(((PM >> (c2 & 15)) & 1) ? hp_poly_pack(s[2 * c2], s[2 * c2 + 1], ksv, nbv, rsa[c2 & 3]) + : hp_exp_pack(s[2 * c2], s[2 * c2 + 1], ksv, nbv, rsa[c2 & 3])); + } + tmem_st32(sc + 32 * ph, pk); + } + l += ((rsa[0].x + rsa[0].y) + (rsa[1].x + rsa[1].y)) + ((rsa[2].x + rsa[2].y) + (rsa[3].x + rsa[3].y)); + asm volatile("tcgen05.wait::st.sync.aligned;" ::: "memory"); + tc_fence_before(); + __syncwarp(); + if (elect_one()) mbar_arrive(bp_full + 8 * hf); + jx++; + } + mA = m_used; lA = l; + } else + for (int kt = 0; kt < nKT; kt++) { + const int code = codes[kt]; + if (!code) continue; +#pragma unroll 1 + for (int x = 0; x < NH; x++) { + const int g = G + NH * j + x; + const int sbuf = g & 1; + float m_used = x ? mB : mA, l = x ? lB : lA; + mbar_wait(bs_full + 8 * sbuf, (g >> 1) & 1); + tc_fence_after(); + const uint32_t sc = tl + FA_TS + sbuf * 128; + float s[64]; + // both 32-column S chunks in flight, ONE tcgen05.wait::ld (same values) + tmem_ld32x2(sc + hf * 64, s, sc + hf * 64 + 32, s + 32); + tc_fence_before(); + // row max with 8 independent accumulators. code 1 tiles keep raw scores (scale folded into the + // exp FFMA below, ks = sl2); code 2 tiles are scaled + masked here (ks = 1). + // 4 independent 3-input-max accumulators (each max3 folds 2 scores) + float mxa[4]; +#pragma unroll + for (int i = 0; i < 4; i++) mxa[i] = -INFINITY; + float ks; + if (code == 2) { + ks = 1.f; + // compact pre-scaled mask tile written by mask_classify (coalesced float4 per lane-row); + // shared by both heads (second read hits L1/L2) + const float4* mt = reinterpret_cast( + mask + (((size_t)b * nQT + qt) * nKT + kt) * 16384) + + hf * 16 * 128 + rowe; + float4 mv[16]; +#pragma unroll + for (int c4 = 0; c4 < 16; c4++) mv[c4] = mt[c4 * 128]; + const float2 sl2v = make_float2(sl2, sl2); +#pragma unroll + for (int c4 = 0; c4 < 16; c4++) { + // s = s * sl2 + mask as two packed FFMA2, then one max3 per pair + const float2 x0 = ffma2(make_float2(s[4 * c4], s[4 * c4 + 1]), sl2v, + make_float2(mv[c4].x, mv[c4].y)); + const float2 x1 = ffma2(make_float2(s[4 * c4 + 2], s[4 * c4 + 3]), sl2v, + make_float2(mv[c4].z, mv[c4].w)); + s[4 * c4] = x0.x; s[4 * c4 + 1] = x0.y; s[4 * c4 + 2] = x1.x; s[4 * c4 + 3] = x1.y; + mxa[(2 * c4) & 3] = fmax3(mxa[(2 * c4) & 3], x0.x, x0.y); + mxa[(2 * c4 + 1) & 3] = fmax3(mxa[(2 * c4 + 1) & 3], x1.x, x1.y); + } + } else if (code == 3) { + // causal tile: key gc masked iff gc > query row or gc >= S (index compare, no mask load); + // unmasked values = s * sl2 (bit-identical to the code-2 FFMA with a 0 mask entry) + // raw scores kept (sl2 folded into the exp FFMA2 argument and the row max, as code 1) + ks = sl2; + const int cl = (grow < S ? grow : S - 1) - (kt * 128 + hf * 64); // last unmasked column +#pragma unroll + for (int c = 0; c < 32; c++) { + s[2 * c] = 2 * c > cl ? -INFINITY : s[2 * c]; + s[2 * c + 1] = 2 * c + 1 > cl ? -INFINITY : s[2 * c + 1]; + mxa[c & 3] = fmax3(mxa[c & 3], s[2 * c], s[2 * c + 1]); + } + } else { + ks = sl2; +#pragma unroll + for (int c = 0; c < 32; c++) mxa[c & 3] = fmax3(mxa[c & 3], s[2 * c], s[2 * c + 1]); + } + float mx = fmax3(fmax3(mxa[0], mxa[1], mxa[2]), mxa[3], -INFINITY); + if (code == 1 || code == 3) mx *= sl2; + // exchange partial row max with the partner thread. barA: partner finished reading red[] of the + // previous exchange. barB also guarantees the partner's S loads completed (wait::ld + fence) + // before this thread overwrites the upper S columns with P below. + float* rb = red + (RDB ? (xc & 1u) * 256 : 0); + xc++; + if (!RDB) pair_bar(barA); + rb[hf * 128 + rowe] = mx; + pair_bar(barB); + tc_fence_after(); + mx = fmaxf(mx, rb[(hf ^ 1) * 128 + rowe]); + const float m_new = fmaxf(m_used, mx); + const bool need = m_new > m_used + 11.f; // lazy-rescale threshold 2^8 -> 2^11 (P <= 2048 in fp16, fewer O rescales) + if (__any_sync(0xffffffff, need)) { + const float alpha = need ? fast_exp2(m_used - m_new) : 1.f; + if (need) { l *= alpha; m_used = m_new; } + if (j > 0) { + // previous PV of this head: already complete (S_g is issued only after PV_{g-2}); the + // wait returns immediately and just provides the explicit ordering. + mbar_wait(bo_done + 8 * x, (G / NH + j - 1) & 1); + tc_fence_after(); +#pragma unroll 1 + for (int c = 0; c < 2; c++) { // this half's 64 O columns of head x + float o[32]; + tmem_ld32(tl + x * 128 + hf * 64 + c * 32, o); +#pragma unroll + for (int i = 0; i < 16; i++) { // packed FMUL2 correction + const float2 r = fmul2(make_float2(o[2 * i], o[2 * i + 1]), make_float2(alpha, alpha)); + o[2 * i] = r.x; o[2 * i + 1] = r.y; + } + tmem_st32(tl + x * 128 + hf * 64 + c * 32, o); + } + asm volatile("tcgen05.wait::st.sync.aligned;" ::: "memory"); + } + } + const float base = m_used == -INFINITY ? 0.f : m_used; + // packed: x*ks - base as FFMA2, row-sum as FADD2 into 4 pair accumulators (pair k holds the + // same columns c % 8 = 2k, 2k+1 as the former 8 scalar accumulators -> identical summation order) + float2 rsa[4]; +#pragma unroll + for (int i = 0; i < 4; i++) rsa[i] = make_float2(0.f, 0.f); + const float2 ksv = make_float2(ks, ks), nbv = make_float2(-base, -base); + // exp + row-sum + fp16 pack fused per pair (MUFU pairs: hp_exp_pack, FMA-poly pairs: + // hp_poly_pack) - same ops / order / constants as exp2_polyd + fadd2 + pack_h2 (bit-identical) + float pk[32]; +#pragma unroll + for (int c = 0; c < 32; c++) + pk[c] = __uint_as_float(((PM >> (c & 15)) & 1) ? hp_poly_pack(s[2 * c], s[2 * c + 1], ksv, nbv, rsa[c & 3]) + : hp_exp_pack(s[2 * c], s[2 * c + 1], ksv, nbv, rsa[c & 3])); + l += ((rsa[0].x + rsa[0].y) + (rsa[1].x + rsa[1].y)) + ((rsa[2].x + rsa[2].y) + (rsa[3].x + rsa[3].y)); + { + // P (fp16 pairs) into the upper 64 columns of this S buffer: half hf -> cols 64+hf*32..+31 + tmem_st32(sc + 64 + hf * 32, pk); + } + asm volatile("tcgen05.wait::st.sync.aligned;" ::: "memory"); + tc_fence_before(); + __syncwarp(); + if (elect_one()) mbar_arrive(bp_full + 8 * sbuf); + if (x) { mB = m_used; lB = l; } else { mA = m_used; lA = l; } + } + j++; + } + // ---- epilogue per head: combine the two partial row sums, O / l as fp16 [B*S, 4096] (V's x 2^-10 kept) + const int n = j; + // BOTH heads' partial row sums exchanged with ONE named barrier through a dedicated + // double-buffered epilogue slot lbx[ec & 1][head][half][row] (after the max-exchange buffers). WAR: the write + // of epilogue e + 2 follows this thread's barB of epilogue e + 1, which the partner reaches only after its + // read of epilogue e. Same sums (l + partner l) -> bit-identical. + float ltA = 0.f, ltB = 0.f; + // KS merge: chain x holds (m_x, l_x, O_x) for tiles g & 1 == x; exchange m and l with the partner + // (same row, other warpgroup), out = (a_0 O_0 + a_1 O_1) / (a_0 l_0 + a_1 l_1), a_x = 2^(m_x - m) + int ks_cnt[2] = {0, 0}; + float ks_a[2] = {0.f, 0.f}, ks_inv = 0.f; + if (KS) { + ks_cnt[0] = (n + ((G & 1) == 0 ? 1 : 0)) >> 1; + ks_cnt[1] = n - ks_cnt[0]; + float* rb = red; + pair_bar(barA); // partner done with the previous item's epilogue reads of red[] + rb[hf * 128 + rowe] = mA; + pair_bar(barB); + const float mp = rb[(hf ^ 1) * 128 + rowe]; + pair_bar(barA); + rb[hf * 128 + rowe] = lA; + pair_bar(barB); + const float lp = rb[(hf ^ 1) * 128 + rowe]; + const float m0 = hf ? mp : mA, m1 = hf ? mA : mp, l0 = hf ? lp : lA, l1 = hf ? lA : lp; + const float mm = fmaxf(m0, m1); + ks_a[0] = m0 == -INFINITY ? 0.f : fast_exp2(m0 - mm); + ks_a[1] = m1 == -INFINITY ? 0.f : fast_exp2(m1 - mm); + ks_inv = 1.f / (ks_a[0] * l0 + ks_a[1] * l1); + } else + if (RDB) { + float* lbx = red + 512 + (ec & 1u) * 512; + ec++; + lbx[hf * 128 + rowe] = lA; + lbx[256 + hf * 128 + rowe] = lB; + pair_bar(barB); + ltA = lA + lbx[(hf ^ 1) * 128 + rowe]; + ltB = lB + lbx[256 + (hf ^ 1) * 128 + rowe]; + } +#pragma unroll 1 + for (int x = 0; x < NH; x++) { + const float l = x ? lB : lA; + float lt; + if (KS) lt = 0.f; + else if (RDB) lt = x ? ltB : ltA; + else { + float* rb = red; + xc++; + pair_bar(barA); // partner finished reading the last exchange (single buffer only) + rb[hf * 128 + rowe] = l; + pair_bar(barB); + lt = l + rb[(hf ^ 1) * 128 + rowe]; + } + float inv = KS ? ks_inv : 1.f / lt; + const int h = h0 + x; + float oo[64]; + if (KS) { + // this thread's 64 output columns (half hf) of both chains' O buffers +#pragma unroll + for (int i = 0; i < 64; i++) oo[i] = 0.f; +#pragma unroll 1 + for (int ob = 0; ob < 2; ob++) { + if (ks_cnt[ob] == 0) continue; + int ge = G + n - 1; + if ((ge & 1) != ob) ge--; // last tile of chain ob in this item + mbar_wait(bo_done + 8 * ob, (ge >> 1) & 1); + tc_fence_after(); + float o2[64]; + tmem_ld32x2(tl + ob * 128 + hf * 64, o2, tl + ob * 128 + hf * 64 + 32, o2 + 32); + const float a = ks_a[ob]; +#pragma unroll + for (int i = 0; i < 64; i++) oo[i] = fmaf(a, o2[i], oo[i]); + } + } else { + if (n > 0) { + mbar_wait(bo_done + 8 * x, (G / NH + n - 1) & 1); // last PV of head x + tc_fence_after(); + } + // both 32-column O chunks of this half-row loaded with ONE tcgen05.wait::ld + if (n > 0) tmem_ld32x2(tl + x * 128 + hf * 64, oo, tl + x * 128 + hf * 64 + 32, oo + 32); + else { +#pragma unroll + for (int i = 0; i < 64; i++) oo[i] = 0.f; + } + } + const float sa8 = vmax ? vsc8 * inv : 0.f; + if (vmax) { + // fp8: this thread's 64 columns -> 64 e4m3 bytes = 4 x 16 B units (|O * sa| < 2^7). + // Coalesced: units transposed inside each 4-lane group (2 xor-shuffle rounds, warp-uniform), so + // lane g holds unit g of the group's 4 consecutive rows and each st.v4 writes 8 rows x 64 B + // (full sectors) instead of 32 rows x 16 B. Bit-identical bytes to the per-row store. + uint4 u[4]; +#pragma unroll + for (int i = 0; i < 4; i++) { + const float* oi = oo + 16 * i; + const float2 s2 = make_float2(sa8, sa8); + u[i] = make_uint4(e4m3x4_s(oi, s2), e4m3x4_s(oi + 4, s2), e4m3x4_s(oi + 8, s2), e4m3x4_s(oi + 12, s2)); + } +#pragma unroll + for (int m = 1; m <= 2; m <<= 1) { + const bool bit = (lane & m) != 0; +#pragma unroll + for (int c0 = 0; c0 < 4; c0++) { + if (c0 & m) continue; + const int c1 = c0 | m; + const uint4 snd = bit ? u[c0] : u[c1]; + uint4 rcv; + rcv.x = __shfl_xor_sync(0xffffffffu, snd.x, m); + rcv.y = __shfl_xor_sync(0xffffffffu, snd.y, m); + rcv.z = __shfl_xor_sync(0xffffffffu, snd.z, m); + rcv.w = __shfl_xor_sync(0xffffffffu, snd.w, m); + if (bit) u[c0] = rcv; else u[c1] = rcv; + } + } + // u[i] = unit (lane & 3) of row (grow - (lane & 3)) + i + const int g4 = lane & 3, rb = grow - g4; +#pragma unroll + for (int i = 0; i < 4; i++) { + if (rb + i < S) { + uint4* dst8 = reinterpret_cast(reinterpret_cast(out) + + ((size_t)b * S + rb + i) * 4096 + h * 128 + hf * 64) + g4; + *dst8 = u[i]; + } + } + } +#pragma unroll + for (int c = 0; c < (vmax ? 0 : 2); c++) { + const float* o = oo + 32 * c; + if (vmax) { + // fp8: this thread's 32 columns -> 32 e4m3 bytes (|O| <= max|V| -> |O * sa| < 2^7, no overflow) + if (grow < S) { + uint4* dst8 = reinterpret_cast(reinterpret_cast(out) + + ((size_t)b * S + grow) * 4096 + h * 128 + hf * 64 + c * 32); +#pragma unroll + for (int i = 0; i < 2; i++) { + const float* oi = o + 16 * i; + dst8[i] = make_uint4(cvt_e4m3x4(oi[0] * sa8, oi[1] * sa8, oi[2] * sa8, oi[3] * sa8), + cvt_e4m3x4(oi[4] * sa8, oi[5] * sa8, oi[6] * sa8, oi[7] * sa8), + cvt_e4m3x4(oi[8] * sa8, oi[9] * sa8, oi[10] * sa8, oi[11] * sa8), + cvt_e4m3x4(oi[12] * sa8, oi[13] * sa8, oi[14] * sa8, oi[15] * sa8)); + } + } + continue; + } + // Coalesced store: this thread's 32 columns of its row = 4 x 16 B units u[0..3]. A 4x4 transpose + // of units inside each 4-lane group (2 xor-shuffle rounds) leaves lane g holding unit g of the + // group's 4 rows, so every st.v4 instruction writes 8 rows x 64 contiguous bytes (full 32 B + // sectors) instead of 32 rows x 16 B (probe at 16x449: stores were ~3k of a ~17k cycle item). + uint4 u[4]; +#pragma unroll + for (int i = 0; i < 4; i++) { + const float2 s2 = make_float2(inv, inv); + const float* oi = o + 8 * i; + u[i] = make_uint4(h2_s(oi, s2), h2_s(oi + 2, s2), h2_s(oi + 4, s2), h2_s(oi + 6, s2)); + } +#pragma unroll + for (int m = 1; m <= 2; m <<= 1) { + const bool bit = (lane & m) != 0; +#pragma unroll + for (int c0 = 0; c0 < 4; c0++) { + if (c0 & m) continue; + const int c1 = c0 | m; // pair (c0, c1): bit-0 lane keeps c0, bit-1 lane keeps c1 + uint4 snd = bit ? u[c0] : u[c1]; + uint4 rcv; + rcv.x = __shfl_xor_sync(0xffffffffu, snd.x, m); + rcv.y = __shfl_xor_sync(0xffffffffu, snd.y, m); + rcv.z = __shfl_xor_sync(0xffffffffu, snd.z, m); + rcv.w = __shfl_xor_sync(0xffffffffu, snd.w, m); + if (bit) u[c0] = rcv; else u[c1] = rcv; + } + } + // now u[i] = unit (lane & 3) of row (lane & ~3) + i of this warp's 32 rows + const int g4 = lane & 3, rb = grow - g4; +#pragma unroll + for (int i = 0; i < 4; i++) { + if (rb + i < S) { + uint4* dst = reinterpret_cast(out + ((size_t)b * S + rb + i) * 4096 + h * 128 + + hf * 64 + c * 32) + g4; + *dst = u[i]; // attn (default L2 policy) + } + } + } + } + tc_fence_before(); // O reads ordered before the next item's P publish (-> PV overwrite of O) + // KS: both warpgroups read both O buffers -> partner done before either publishes the next item's P + if (KS) pair_bar(barA); + G += NH * n; + } + } + tc_fence_before(); + __syncthreads(); + if (qbc != nullptr) pdl_wait(); // QKV grid complete before this grid completes (keeps the PDL chain transitive) + CHN(10, 2); + if (warp == 1) { + __syncwarp(); + tc_fence_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tbase), "r"(512)); + } +} + +// ------------------------------------------------------------------ router + top-k (fused, cluster split-K) +// router_select: one warp per token, lane holds logits of experts lane + 32*j (j = 0..3): +// softmax over 128 logits, top-8 (ties -> lower index, NaN highest, as torch.topk), renormalize, expert histogram. +__device__ __forceinline__ void router_select(const float* l, int t, int lane, int* __restrict__ topk_idx, + float* __restrict__ topk_w, int* __restrict__ counts) { + float mx = fmaxf(fmaxf(l[0], l[1]), fmaxf(l[2], l[3])); + for (int o = 16; o; o >>= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffff, mx, o)); + float pr[4], sum = 0.f; +#pragma unroll + for (int j = 0; j < 4; j++) { pr[j] = expf(l[j] - mx); sum += pr[j]; } + for (int o = 16; o; o >>= 1) sum += __shfl_xor_sync(0xffffffff, sum, o); + const float inv = 1.f / sum; +#pragma unroll + for (int j = 0; j < 4; j++) pr[j] *= inv; + uint32_t key[4]; +#pragma unroll + for (int j = 0; j < 4; j++) { + const uint32_t u = __float_as_uint(pr[j]); + key[j] = (pr[j] != pr[j]) ? 0xFFFFFFFFu : ((u & 0x80000000u) ? ~u : (u | 0x80000000u)); + } + // Top-8 selection with warp reductions (redux.sync): per round each lane offers its best untaken key + // (ties inside a lane -> lower j = lower expert index), the warp max key is found with ONE redux.max, then the + // lowest expert index holding that key with ONE redux.min (torch.topk tie order). The winning lane records the + // round's slot locally; results are written in parallel by the owning lanes after the loop (2 redux per round + // instead of 5 dependent rounds of 3 shuffles, and no 24-op serial tail on lane 0). + unsigned taken = 0u; + int slot_of[4] = {0, 0, 0, 0}; + float wloc = 0.f; // sum of this lane's selected probabilities +#pragma unroll + for (int kk = 0; kk < TOPK; kk++) { + uint32_t bk = 0u; int bi = 0x7FFFFFFF; +#pragma unroll + for (int j = 0; j < 4; j++) + if (!((taken >> j) & 1u) && key[j] > bk) { bk = key[j]; bi = lane + 32 * j; } + const uint32_t wm = __reduce_max_sync(0xffffffffu, bk); // > 0: >= 120 untaken real/NaN keys remain + const uint32_t wi = __reduce_min_sync(0xffffffffu, bk == wm ? (uint32_t)bi : 0x7FFFFFFFu); + if ((int)wi == bi) { + const int j = bi >> 5; + taken |= 1u << j; + slot_of[j] = kk; + wloc += pr[j]; + } + } + float wsum = wloc; + for (int o = 16; o; o >>= 1) wsum += __shfl_xor_sync(0xffffffff, wsum, o); + const float iw = 1.f / wsum; +#pragma unroll + for (int j = 0; j < 4; j++) { + if ((taken >> j) & 1u) { + const int e = lane + 32 * j; + topk_idx[t * TOPK + slot_of[j]] = e; + topk_w[t * TOPK + slot_of[j]] = pr[j] * iw; + atomicAdd(&counts[e], 1); + } + } +} + +__device__ __forceinline__ void router_select_exact(float4 lv, int t, int lane, const float* hx, const float* lnw, + float rstd, const float* wr, int* __restrict__ topk_idx, + float* __restrict__ topk_w, int* counts, int* rec_e, int* rec_r, + float* rec_w) { + auto keyof = [](float lg) -> uint32_t { + const uint32_t u = __float_as_uint(lg); + return (lg != lg) ? 0xFFFFFFFFu : ((u & 0x80000000u) ? ~u : (u | 0x80000000u)); + }; + uint32_t hk[4]; + int hi[4]; +#pragma unroll + for (int j = 0; j < 4; j++) { hk[j] = keyof((&lv.x)[j]); hi[j] = 4 * lane + j; } + auto ce = [&](int a, int b) { + const bool sw = hk[b] > hk[a] || (hk[b] == hk[a] && hi[b] < hi[a]); + const uint32_t ka = hk[a], kb = hk[b]; + const int ia = hi[a], ib = hi[b]; + hk[a] = sw ? kb : ka; hk[b] = sw ? ka : kb; + hi[a] = sw ? ib : ia; hi[b] = sw ? ia : ib; + }; + ce(0, 1); ce(2, 3); ce(0, 2); ce(1, 3); ce(1, 2); + constexpr int NC = 12; + int cand = 0; +#pragma unroll 1 + for (int kk = 0; kk < NC; kk++) { + const uint32_t wm = __reduce_max_sync(0xffffffffu, hk[0]); + const uint32_t wi = __reduce_min_sync(0xffffffffu, hk[0] == wm ? (uint32_t)hi[0] : 0x7FFFFFFFu); + if ((uint32_t)hi[0] == wi) { + hk[0] = hk[1]; hi[0] = hi[1]; hk[1] = hk[2]; hi[1] = hi[2]; hk[2] = hk[3]; hi[2] = hi[3]; + hk[3] = 0u; hi[3] = 0x7FFFFFFF; + } + if (lane == kk) cand = (int)wi; + } + // fp32 xn2 row: lane holds float4 groups lane + 32 j (j < 16) + const float4* hr = reinterpret_cast(hx + (size_t)t * HID); + const float4* lw4 = reinterpret_cast(lnw); + float4 x[16]; +#pragma unroll + for (int j = 0; j < 16; j++) { + const float4 v = __ldcg(hr + lane + 32 * j); + const float4 w = __ldg(lw4 + lane + 32 * j); + x[j] = make_float4(w.x * (v.x * rstd), w.y * (v.y * rstd), w.z * (v.z * rstd), w.w * (v.w * rstd)); + } + float ex = 0.f; +#pragma unroll 1 + for (int c = 0; c < NC; c += 2) { + const int e0 = __shfl_sync(0xffffffffu, cand, c), e1 = __shfl_sync(0xffffffffu, cand, c + 1); + const float4* w0 = reinterpret_cast(wr + (size_t)e0 * HID); + const float4* w1 = reinterpret_cast(wr + (size_t)e1 * HID); + float s0 = 0.f, s1 = 0.f; +#pragma unroll + for (int j = 0; j < 16; j++) { + const float4 a = __ldg(w0 + lane + 32 * j), b = __ldg(w1 + lane + 32 * j); + s0 = fmaf(x[j].x, a.x, s0); s0 = fmaf(x[j].y, a.y, s0); s0 = fmaf(x[j].z, a.z, s0); s0 = fmaf(x[j].w, a.w, s0); + s1 = fmaf(x[j].x, b.x, s1); s1 = fmaf(x[j].y, b.y, s1); s1 = fmaf(x[j].z, b.z, s1); s1 = fmaf(x[j].w, b.w, s1); + } +#pragma unroll + for (int o = 16; o; o >>= 1) { + s0 += __shfl_xor_sync(0xffffffffu, s0, o); + s1 += __shfl_xor_sync(0xffffffffu, s1, o); + } + if (lane == c) ex = s0; + if (lane == c + 1) ex = s1; + } + // exact top-8 among the 12 candidates (lanes 0..11) + uint32_t key = lane < NC ? keyof(ex) : 0u; + uint32_t sel_k = 0u; + int sel_e = 0; +#pragma unroll 1 + for (int kk = 0; kk < TOPK; kk++) { + const uint32_t wm = __reduce_max_sync(0xffffffffu, key); + const uint32_t wi = __reduce_min_sync(0xffffffffu, (lane < NC && key == wm) ? (uint32_t)cand : 0x7FFFFFFFu); + if (lane < NC && (uint32_t)cand == wi) key = 0u; + if (lane == kk) { sel_k = wm; sel_e = (int)wi; } + } + const float lg = __uint_as_float((sel_k & 0x80000000u) ? (sel_k & 0x7FFFFFFFu) : ~sel_k); + const float l0 = __shfl_sync(0xffffffffu, lg, 0); + const float sp = lane < TOPK ? expf(lg - l0) : 0.f; + float ws = sp; +#pragma unroll + for (int o = 1; o < 8; o <<= 1) ws += __shfl_xor_sync(0xffffffffu, ws, o); + if (lane < TOPK) { + const float wgt = sp * (1.f / ws); + topk_idx[t * TOPK + lane] = sel_e; + topk_w[t * TOPK + lane] = wgt; + const int rk = atomicAdd(&counts[sel_e], 1); + if (rec_e) { rec_e[lane] = sel_e; rec_r[lane] = rk; rec_w[lane] = wgt; } + } +} + +template // RSTR: record row stride +__device__ __forceinline__ void router_select_batch(const float4* lv, const int* tok, int lane, + int* __restrict__ topk_idx, float* __restrict__ topk_w, + int* __restrict__ counts, int* rec_e = nullptr, + int* rec_r = nullptr, float* rec_w = nullptr) { + uint32_t key[RS][4]; +#pragma unroll + for (int i = 0; i < RS; i++) +#pragma unroll + for (int j = 0; j < 4; j++) { + const float lg = tok[i] >= 0 ? (&lv[i].x)[j] : 0.f; // expert 4*lane + j + const uint32_t u = __float_as_uint(lg); + key[i][j] = (lg != lg) ? 0xFFFFFFFFu : ((u & 0x80000000u) ? ~u : (u | 0x80000000u)); + } + uint32_t hk[RS][4]; + int hi[RS][4]; +#pragma unroll + for (int i = 0; i < RS; i++) { +#pragma unroll + for (int j = 0; j < 4; j++) { hk[i][j] = key[i][j]; hi[i][j] = 4 * lane + j; } + auto ce = [&](int a, int b) { // put the better of (a, b) at a: key desc, expert asc + const bool sw = hk[i][b] > hk[i][a] || (hk[i][b] == hk[i][a] && hi[i][b] < hi[i][a]); + const uint32_t ka = hk[i][a], kb = hk[i][b]; + const int ia = hi[i][a], ib = hi[i][b]; + hk[i][a] = sw ? kb : ka; hk[i][b] = sw ? ka : kb; + hi[i][a] = sw ? ib : ia; hi[i][b] = sw ? ia : ib; + }; + ce(0, 1); ce(2, 3); ce(0, 2); ce(1, 3); ce(1, 2); + } + uint32_t sel_k[RS]; + int sel_e[RS]; +#pragma unroll + for (int i = 0; i < RS; i++) { sel_k[i] = 0u; sel_e[i] = 0; } + // NOT unrolled: compact round loop (the router's code is cold in the instruction cache every forward) +#pragma unroll 1 + for (int kk = 0; kk < TOPK; kk++) { + uint32_t wm[RS], wi[RS]; +#pragma unroll + for (int i = 0; i < RS; i++) wm[i] = __reduce_max_sync(0xffffffffu, hk[i][0]); +#pragma unroll + for (int i = 0; i < RS; i++) + wi[i] = __reduce_min_sync(0xffffffffu, hk[i][0] == wm[i] ? (uint32_t)hi[i][0] : 0x7FFFFFFFu); +#pragma unroll + for (int i = 0; i < RS; i++) { + if ((uint32_t)hi[i][0] == wi[i]) { + hk[i][0] = hk[i][1]; hi[i][0] = hi[i][1]; + hk[i][1] = hk[i][2]; hi[i][1] = hi[i][2]; + hk[i][2] = hk[i][3]; hi[i][2] = hi[i][3]; + hk[i][3] = 0u; hi[i][3] = 0x7FFFFFFF; + } + if (lane == kk) { sel_k[i] = wm[i]; sel_e[i] = (int)wi[i]; } + } + } + // the CTA-local rank atomics (smem histogram, returning) and the expert-index stores depend only on the + // selected experts -> issued right after the rounds, so their latency overlaps the exp / normalize chain below + // (was serialized after it, ~930 cycles per 2-row batch). Same atomics per lane in the same row order; the + // selection itself is untouched (exact torch.topk order). + int rk[RS]; +#pragma unroll + for (int i = 0; i < RS; i++) rk[i] = 0; + if (lane < TOPK) { +#pragma unroll + for (int i = 0; i < RS; i++) { + if (tok[i] < 0) continue; + rk[i] = atomicAdd(&counts[sel_e[i]], 1); // counts = the CTA smem histogram (router_kernel) + topk_idx[tok[i] * TOPK + lane] = sel_e[i]; + if (rec_e) rec_e[i * RSTR + lane] = sel_e[i]; + } + } + // lanes 0..7: slot `lane` of each row. key -> logit (inverse order map; NaN key 0xFFFFFFFF -> NaN), weight = + // exp(l - l_top1) normalized over the 8 selected (lane 0 holds the top-1 logit) + float sp[RS], ws[RS]; +#pragma unroll + for (int i = 0; i < RS; i++) { + const uint32_t kk = sel_k[i]; + const float lg = __uint_as_float((kk & 0x80000000u) ? (kk & 0x7FFFFFFFu) : ~kk); + const float l0 = __shfl_sync(0xffffffffu, lg, 0); + sp[i] = lane < TOPK ? expf(lg - l0) : 0.f; + ws[i] = sp[i]; + } +#pragma unroll + for (int o = 1; o < 8; o <<= 1) // sum over each 8-lane group (lanes 0..7 hold the 8 selected weights) +#pragma unroll + for (int i = 0; i < RS; i++) ws[i] += __shfl_xor_sync(0xffffffff, ws[i], o); + if (lane < TOPK) { +#pragma unroll + for (int i = 0; i < RS; i++) { + if (tok[i] < 0) continue; + const int t = tok[i]; + topk_w[t * TOPK + lane] = sp[i] * (1.f / ws[i]); + if (rec_e) { rec_r[i * RSTR + lane] = rk[i]; rec_w[i * RSTR + lane] = sp[i] * (1.f / ws[i]); } + } + } +} + +constexpr int RT_STAGES = 4; +constexpr int RT_OP = 128 * 32 * 4; // one operand tile: 128 rows x 128 B +constexpr int RT_STAGE = 3 * RT_OP; // 48 KB +// smem: h ring RT_HST x 16 KB | Wr ring RT_WST x 32 KB | barriers (256 B) | ln2 weight K slice (8 KB, staged once) +// a k-block = 64 K. h stage = 2 fp32 boxes (128 tok x 32 k, 16 KB each) = 32 KB; Wr stage = fp16 +// [256 rows (hi | lo)][64 k] = 32 KB (one 128B-swizzle box). 3 h stages + 4 Wr stages = 224 KB. +// the Wr stage holds only the 128 Wr_hi rows (16 KB; the lo rows are no longer read), which frees smem for the +// staged ln2 weight vector (RT_LNW) and a 4th h stage. +constexpr int RT_HST = 4, RT_WST = 4; // bar_hfull/hempty arrays hold <= 5 stages, bar_full/empty/conv <= 4 +constexpr int RT_HSTAGE = 2 * RT_OP, RT_WSTAGE = 128 * 128; +constexpr int RT_WOFF = RT_HST * RT_HSTAGE; +// standalone router (!MRG, Wr ring = 3 stages) holds a 5th 32 KB h stage at RT_H4OFF (right after the 3 Wr +// stages; the merged launch's 4th Wr stage overlaps it but the merged launch keeps a 4-stage h ring) +constexpr int RT_H4OFF = RT_WOFF + 3 * RT_WSTAGE; +constexpr int RT_BAR = RT_H4OFF + RT_HSTAGE; +static_assert(RT_BAR >= RT_WOFF + RT_WST * RT_WSTAGE, "router Wr ring vs barriers"); +constexpr int RT_SINV = RT_BAR + 256; // float[128]: 1 / (sx * s_e) per expert column +// full ln2 weight vector (2048 fp32 = 8 KB) staged in smem by the converter warps (they already load it for +// max|ln2w|). RS_PROBE (T=8192, seed): the router mainloop was converter-bound - the +// per-k-block ln2w __ldg (prefetched only one k-block ahead, L2 latency under the h stream) sat on the serial +// per-warp converter chain (producer blocked on h-empty, MMA blocked on conv; a deeper h ring changed nothing). +constexpr int RT_LNW = RT_SINV + 512; +// per-CTA expert histogram in its own 512 B slot (zeroed in the prologue, off the post-reduction path) +constexpr int RT_HIST = RT_LNW + 8192; +// standalone router h full barriers indexed by k-block % 8 (8 x 8 B): the 4-stage h ring is consumed by 3 +// converter sets out of order, so a per-stage parity wait could alias a phase two uses back; with an 8-deep barrier +// ring the previous phase of barrier i % 8 (k-block i - 8) always completed before k-block i was issued +constexpr int RT_HB8 = RT_HIST + 512; +constexpr int RT_SMEM = RT_HB8 + 64 + 1024; +static_assert(RT_HST <= 5 && RT_WST <= 4, "router barrier arrays"); +static_assert(RT_SMEM <= 232448, "router smem"); +constexpr int RT_THREADS = 512; +constexpr uint32_t IDESC_TF32_128x128 = (1u << 4) | (2u << 7) | (2u << 10) | ((128u >> 3) << 17) | ((128u >> 4) << 24); +constexpr uint32_t IDESC_TF32_128x256 = (1u << 4) | (2u << 7) | (2u << 10) | ((256u >> 3) << 17) | ((128u >> 4) << 24); +// TS tf32 MMA: A (M=128 x K=8 tf32) read from TMEM (lane = row, column = K element), B from smem. +__device__ __forceinline__ void mma_tf32_ts(uint32_t tmem, uint32_t a_tmem, uint64_t bd, uint32_t idesc, uint32_t acc) { + asm volatile( + "{ .reg .pred p; setp.ne.b32 p, %4, 0; tcgen05.mma.cta_group::1.kind::tf32 [%0], [%1], %2, %3, p; }" ::"r"( + tmem), + "r"(a_tmem), "l"(bd), "r"(idesc), "r"(acc)); +} + +__device__ __forceinline__ void cluster_sync_all() { + asm volatile("barrier.cluster.arrive.release.aligned;\nbarrier.cluster.wait.acquire.aligned;" ::: "memory"); +} +__device__ __forceinline__ uint32_t cluster_ctarank() { + uint32_t r; + asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(r)); + return r; +} +__device__ __forceinline__ float ld_dsmem(uint32_t local_addr, uint32_t rank) { + uint32_t ra; + asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(ra) : "r"(local_addr), "r"(rank)); + float v; + asm volatile("ld.shared::cluster.f32 %0, [%1];" : "=f"(v) : "r"(ra) : "memory"); + return v; +} + +// 16 B DSMEM load from CTA `rank` of the cluster (no memory clobber, so independent loads can be in flight together; +// ordering vs. remote writes is provided by the cluster barrier). +__device__ __forceinline__ float4 ld_dsmem_v4(uint32_t local_addr, uint32_t rank) { + uint32_t ra; + asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(ra) : "r"(local_addr), "r"(rank)); + float4 v; + asm volatile("ld.shared::cluster.v4.f32 {%0, %1, %2, %3}, [%4];" : "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w) : "r"(ra)); + return v; +} + +// 32-bit DSMEM load without a memory clobber (independent loads overlap; ordered after the preceding cluster barrier) +__device__ __forceinline__ int ld_dsmem_u32_nc(uint32_t local_addr, uint32_t rank) { + uint32_t ra; + asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(ra) : "r"(local_addr), "r"(rank)); + int v; + asm volatile("ld.shared::cluster.u32 %0, [%1];" : "=r"(v) : "r"(ra)); + return v; +} + +__device__ __forceinline__ void tmem_st16(uint32_t taddr, const float* v) { + asm volatile( + "tcgen05.st.sync.aligned.32x32b.x16.b32 [%0], {%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11,%12,%13,%14,%15,%16};" ::"r"(taddr), + "f"(v[0]), "f"(v[1]), "f"(v[2]), "f"(v[3]), "f"(v[4]), "f"(v[5]), "f"(v[6]), "f"(v[7]), "f"(v[8]), "f"(v[9]), + "f"(v[10]), "f"(v[11]), "f"(v[12]), "f"(v[13]), "f"(v[14]), "f"(v[15])); +} +// Debug probe stamps (globaltimer per CTA: entry, griddep release, accumulator ready, after partial sync, after +// reduce, after select/histogram sync, end). Compiled out; enable with a device pointer g_rt_probe and +// #define RTP(i) do { if (g_rt_probe) g_rt_probe[(blockIdx.y * gridDim.x + blockIdx.x) * 8 + (i)] = gtime(); } while (0) +#ifdef RS_PROBE +__device__ unsigned long long* g_rt_probe; +#define RTP(i) do { if (g_rt_probe) g_rt_probe[(blockIdx.y * gridDim.x + blockIdx.x) * 8 + (i)] = gtime(); } while (0) +#else +#define RTP(i) do { } while (0) +#endif +// merged o_proj + router launch (T < 2048): phase hand-off data for the router phase +#ifdef RTA_PROBE +__device__ int g_rt_abl; +void rta_set(int v) { cudaMemcpyToSymbol(g_rt_abl, &v, 4); } +#define RTA(b) ((g_rt_abl & (b)) != 0) +#else +#define RTA(b) false +#endif +// compile-time ring-stage loop. Visits i in [i0, i1) with the ring stage P = i % N as a template constant +// (immediate smem / mbarrier / TMEM offsets in f) and the stage phase bit ph = (i / N) & 1 tracked incrementally. +template +__device__ __forceinline__ void ring_loop_ct(int i0, int i1, F&& f) { + static_assert(N >= 1 && N <= 6, "ring_loop_ct: <= 6 stages"); + int i = i0, p = i0 % N; + uint32_t ph = (uint32_t)((i0 / N) & 1); +#pragma unroll 1 + while (i < i1) { +#define RLSTEP(PP) if constexpr (PP < N) { if (p == PP) { f(i, std::integral_constant{}, ph); if (PP == N - 1) ph ^= 1u; p = (PP + 1) % N; if (++i >= i1) break; } } + RLSTEP(0) RLSTEP(1) RLSTEP(2) RLSTEP(3) RLSTEP(4) RLSTEP(5) +#undef RLSTEP + } +} +struct RtMerge { uint32_t tbase; int sctr_old; const char* wo16; const char* attn; }; +template +__device__ __forceinline__ void router_dev(const CUtensorMap& tH, const CUtensorMap& tBh, const CUtensorMap& tBl, int T, + const float* __restrict__ lnw, const float* __restrict__ ssq, float eps, + const float* __restrict__ wscale, int* __restrict__ topk_idx, + float* __restrict__ topk_w, int* __restrict__ counts, + const float* __restrict__ pf0, const float* __restrict__ pf1, uint32_t pf_bytes, + const sidew::ConvJob& CJ, __half* __restrict__ xn16, uint8_t* __restrict__ xn8, + float* __restrict__ f8inv, const L2Discard& DL, const RtMerge& MG, + int* __restrict__ btok = nullptr, float* __restrict__ bw = nullptr, + const float* hx = nullptr, const int* mtctr = nullptr) { + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = (uint8_t*)(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023); + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int KS = gridDim.x; + // L2 prefetch of the first MoE items' expert weights (the leading pf_bytes of the gate and up tensors = the + // lowest-index experts, which the expert-sorted MoE work queue starts with). Inputs only -> no PDL dependency; + // the CTAs split the range evenly (16 B aligned), 64 KB per bulk prefetch. + if (threadIdx.x == 32 && pf_bytes > 0) { + const uint32_t ncta = gridDim.x * gridDim.y, cid = blockIdx.y * gridDim.x + blockIdx.x; + const uint32_t per = ((pf_bytes / ncta) + 15u) & ~15u; + const uint32_t lo = cid * per; + for (int w = 0; w < 2; w++) { + const char* base = reinterpret_cast(w ? pf1 : pf0); + for (uint32_t o = lo; o < lo + per && o < pf_bytes; o += 65536u) { + uint32_t n = lo + per - o; + if (n > 65536u) n = 65536u; + if (o + n > pf_bytes) n = pf_bytes - o; + asm volatile("cp.async.bulk.prefetch.L2.global [%0], %1;" ::"l"(base + o), "r"(n) : "memory"); + } + } + } + if (threadIdx.x == 0) RTP(0); + const uint32_t rank = cluster_ctarank(); + const int m0 = blockIdx.y * 128; + const int NKB = HID / 64; // 64-K k-blocks + const int kb0 = (int)rank * NKB / KS, nkb = ((int)rank + 1) * NKB / KS - kb0; // this CTA's K slice + + const uint32_t sbase = smem_u32(smem); + // Decoupled rings (probe at T=7184: a single {h, Wr} ring stays allocated through TMA + conversion + MMA): + // h ring : HST x 32 KB, freed by the converters as soon as they have read the tile into registers + // Wr ring : WST x 32 KB ({Wr_hi; Wr_lo} fp16 = the N=256 B operand), freed by the MMA commit + // standalone router (!MRG): 3 converter warp sets (warps 2-5, 6-9, 12-15), set j owns k-blocks i = j mod 3 + // (both 32-K halves) -> 3-stage h / Wr / TMEM-A rings, stage j used only by set j (no phase skipping); the merged + // launch keeps the 2-set half split over 4 stages + constexpr int HST = MRG ? RT_HST : 5, WST = MRG ? RT_WST : 3; // standalone h ring 4 -> 5 stages + auto hoff = [](int st) -> uint32_t { return st < 4 ? (uint32_t)(st * RT_HSTAGE) : (uint32_t)RT_H4OFF; }; // standalone router h ring 3 -> 4 stages (decoupled from the 3 converter sets) + const uint32_t bar_hfull = sbase + RT_BAR; // [HST] h tile landed + const uint32_t bar_hempty = bar_hfull + 40; // [HST] 8 converter warps read the h tile + const uint32_t bar_full = bar_hfull + 80; // [WST] Wr tile landed + const uint32_t bar_empty = bar_hfull + 112; // [WST] MMAs done (Wr smem stage + TMEM A slot) + const uint32_t bar_conv = bar_hfull + 144; // [WST] hi/lo written to TMEM A slot (8 warps) + const uint32_t bar_acc = bar_hfull + 176; // accumulator complete + const uint32_t tslot = bar_hfull + 184; + volatile uint32_t* tslot_ptr = (volatile uint32_t*)(smem + RT_BAR + 184); + float* sred = reinterpret_cast(smem + RT_BAR + 192); // [8] max|ln2w| partials of the converter warps + float* part = reinterpret_cast(smem); // [128][128] partial logits (ring smem reused after the mainloop) + + if (threadIdx.x == 0) { + for (int s = 0; s < HST; s++) { mbar_init(bar_hfull + 8 * s, 1); mbar_init(bar_hempty + 8 * s, MRG ? 8 : 4); } + for (int s = 0; s < WST; s++) { + mbar_init(bar_full + 8 * s, 1); mbar_init(bar_empty + 8 * s, 1); mbar_init(bar_conv + 8 * s, MRG ? 16 : 4); + } + mbar_init(bar_acc, 1); + if (!MRG) for (int s = 0; s < 8; s++) mbar_init(sbase + RT_HB8 + 8 * s, 1); + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tH) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tBh) : "memory"); + } + if (threadIdx.x >= 384 && threadIdx.x < 384 + NEXP) // histogram zeroed before the prologue barrier + reinterpret_cast(smem + RT_HIST)[threadIdx.x - 384] = 0; + if (MRG) { // merged launch: TMEM (512 cols) was allocated by the o_proj phase; publish its base + if (threadIdx.x == 0) *tslot_ptr = MG.tbase; + } else if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(tslot), "r"(512)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + tc_fence_before(); + __syncthreads(); + // MRG: the router MMAs run as cta_group::2 pairs (cluster ranks 2p, 2p+1; ptxas forbids mixing cta_group::1 + // and ::2 in one kernel and the o_proj phase uses pairs). The leader (even rank) issues m256n256k16 TS MMAs: + // A = each CTA's own TMEM A slot (its 128 tokens x its own K slice), B = [leader Wr stage; peer Wr stage] (128 + // experts x 64 K each, each CTA's own K slice). D in CTA r: columns [128 r, 128 r + 128) = A_r x Wr(slice r) - the + // same partial as the 1-CTA path; the other half pairs mismatched K slices and is ignored. Barriers of the peer: + // Wr TMA complete_tx and converter arrivals go to the leader's full / conv barriers; commits multicast to both. + if (MRG) cluster_sync_all(); // all CTAs' router barriers initialised before any remote arrival + tc_fence_after(); + const uint32_t tbase = *tslot_ptr; + const uint32_t prk = MRG ? cluster_ctarank() : 0u, plead = prk & ~1u; + const uint16_t pmask = (uint16_t)(3u << plead); + CHN(11, 0); + // router pre-PDL-wait work: Wr hi/lo is a SIDE-stream product (completion counter), independent of o_proj: + // the Wr producer warp acquires it and L2-prefetches this CTA's first 4 Wr k-blocks before griddepcontrol.wait. + const unsigned long long* side_ctr = CJ.done; + const unsigned long long side_target = CJ.target; + int wpre = 0; // Wr stages issued before griddepcontrol.wait (warp 10) + if (warp == 10) { + // acquire with work stealing (executes still-unclaimed convert units itself: deadlock-free) + sidew::conv_acquire_steal(CJ, (int)(((long long)(blockIdx.y * gridDim.x + blockIdx.x) * CJ.n) / + (gridDim.x * gridDim.y))); + if (lane < 4 && lane < nkb) + asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile [%0, {%1, %2}];" ::"l"((uint64_t)&tBh), + "r"((kb0 + lane) * 64), "r"(0) : "memory"); + __syncwarp(); + // the side-stream Wr fp16 copy is complete (acquired above), so the + // first WST Wr stages are TMA-loaded into the smem ring BEFORE griddepcontrol.wait (fresh ring: empty waits + // pass trivially). After the wait only the h loads, MMAs, reduction and select remain on the critical path. + if (!MRG && T >= 897) { // also T >= 2048 (Wr stages before the M-tile acquire / PDL wait) + asm volatile("fence.proxy.async.global;" ::: "memory"); // generic Wr writes (side / stolen) -> TMA reads + wpre = nkb < WST ? nkb : WST; + for (int i = 0; i < wpre; i++) { + const uint32_t fb = bar_full + 8 * i; + if (elect_one()) { + mbar_expect_tx(fb, RT_WSTAGE); + tma_load_2d_hint(sbase + RT_WOFF + i * RT_WSTAGE, &tBh, (kb0 + i) * 64, 0, fb, keep_pol()); // Wr re-read by all clusters + } + __syncwarp(); + } + } + } + // prologue: converter warps 2..9 stage the ln2 weight vector (kernel INPUT) in smem and derive the x scale + // sx BEFORE griddepcontrol.wait, so the global-load latency + named barrier overlap the o_proj tail + float sx_pre = 1.f; + if (!MRG && warp >= 12) { + asm volatile("bar.sync 1, 384;" ::: "memory"); // sred / staged ln2w of warps 2..9 complete + float m8 = 0.f; +#pragma unroll + for (int w8 = 0; w8 < 8; w8++) m8 = fmaxf(m8, sred[w8]); + sx_pre = pow2_scale(46.f * m8); + } + if (warp >= 2 && warp < 10) { + { + const int ct = (int)threadIdx.x - 64; // 0..255: 8 ln2 weights each + const float4 a0 = __ldg(reinterpret_cast(lnw) + 2 * ct); + const float4 a1 = __ldg(reinterpret_cast(lnw) + 2 * ct + 1); + float mw = fmaxf(fmaxf(fmaxf(fabsf(a0.x), fabsf(a0.y)), fmaxf(fabsf(a0.z), fabsf(a0.w))), + fmaxf(fmaxf(fabsf(a1.x), fabsf(a1.y)), fmaxf(fabsf(a1.z), fabsf(a1.w)))); + #pragma unroll + for (int o = 16; o; o >>= 1) mw = fmaxf(mw, __shfl_xor_sync(0xffffffff, mw, o)); + if (lane == 0) sred[warp - 2] = mw; + float4* lws = reinterpret_cast(smem + RT_LNW); // stage ln2w (read per k-block below) + lws[2 * ct] = a0; + lws[2 * ct + 1] = a1; + if (!MRG) asm volatile("bar.sync 1, 384;" ::: "memory"); // converter warps 2..9, 12..15 + else asm volatile("bar.sync 1, 256;" ::: "memory"); // converter warps 2..9 only (also orders the lws writes) + float m8 = 0.f; + #pragma unroll + for (int w8 = 0; w8 < 8; w8++) m8 = fmaxf(m8, sred[w8]); + sx_pre = pow2_scale(46.f * m8); // |y| <= sqrt(2048) * max|ln2w| < 46 max|ln2w| + } + } + if (!MRG) { // merged launch: the o_proj phase already passed griddepcontrol.wait / launch_dependents + if (mtctr != nullptr) { + // acquire this M tile's o_proj completion counter (h rows + ssq of rows m0..m0+127) + // instead of griddepcontrol.wait, so router tiles start while o_proj's last wave still runs. All o_proj + // CTAs are resident (this grid launches only after every o_proj CTA triggered) -> no deadlock. Warp 11 + // (L2 discards of Wo16 / attn, still read by o_proj) waits for full o_proj completion below. + if (threadIdx.x == 0) { + const int* rp = mtctr + blockIdx.y; + while (true) { + int v; + asm volatile("ld.acquire.gpu.global.b32 %0, [%1];" : "=r"(v) : "l"(rp) : "memory"); + if (v >= 4 * HID) break; + __nanosleep(20); // shorter poll interval on the o_proj -> router M-tile handoff + } + } + __syncthreads(); + if (warp == 11) pdl_wait(); + } else pdl_wait(); + CHN(11, 1); + pdl_trigger(); + } + if (threadIdx.x == 0) RTP(1); + + if (warp == 0) { + { + // ---------------- h TMA producer (whole warp loops, elect.sync lane issues expect_tx + TMA): + // 2 boxes (128 tokens x 32 k fp32) per 64-K k-block -> h ring + const uint64_t hpol = keep_pol(); // h re-read by norm_gather / as MoE residual + // MRG: h was written (TMA bulk stores, generic-released at the cluster barrier) by this cluster's o_proj + // phase -> order those writes before this thread's async-proxy (TMA) reads + if (MRG || mtctr != nullptr) asm volatile("fence.proxy.async.global;" ::: "memory"); + ring_loop_ct(0, nkb, [&](int i, auto ptag, uint32_t ph) { + constexpr int s = decltype(ptag)::value; + mbar_wait(bar_hempty + 8 * s, ph ^ 1u); + const uint32_t fb = MRG ? bar_hfull + 8 * s : sbase + RT_HB8 + 8 * (i & 7), dst = sbase + hoff(s); + __syncwarp(); + if (elect_one()) { + mbar_expect_tx(fb, RT_HSTAGE); + tma_load_2d_hint(dst, &tH, (kb0 + i) * 64, m0, fb, hpol); + tma_load_2d_hint(dst + RT_OP, &tH, (kb0 + i) * 64 + 32, m0, fb, hpol); + } + __syncwarp(); + if (i == 0) CHNT(7, 0, 0); + }); + } + } else if (warp == 10) { + { + // ---------------- Wr TMA producer (whole warp loops, elect.sync lane issues): + // fp16 [Wr_hi (rows 0..127); Wr_lo (rows 128..255)] x 64 k + // Wr hi/lo are written by the side-stream convert kernel (already complete when o_proj ran; re-acquired + // here so the visibility to this kernel's TMA reads does not rely on transitivity) + if (elect_one()) side_acquire(side_ctr, side_target); + __syncwarp(); + asm volatile("fence.proxy.async.global;" ::: "memory"); + ring_loop_ct(wpre, nkb, [&](int i, auto ptag, uint32_t ph) { + constexpr int s = decltype(ptag)::value; + if (MRG) mbar_wait_cl2(bar_empty + 8 * s, ph ^ 1u); + else mbar_wait(bar_empty + 8 * s, ph ^ 1u); + const uint32_t fb = bar_full + 8 * s; + __syncwarp(); + if (elect_one()) { + if (MRG) { // pair: both CTAs' Wr stages complete on the leader's full barrier + if (prk == plead) mbar_expect_tx(fb, 2 * RT_WSTAGE); + tma_load_2d_cg2(sbase + RT_WOFF + s * RT_WSTAGE, &tBh, (kb0 + i) * 64, 0, mapa_sh(fb, plead), keep_pol()); + } else { + mbar_expect_tx(fb, RT_WSTAGE); // Wr_hi rows only (single fp16 product) + tma_load_2d_hint(sbase + RT_WOFF + s * RT_WSTAGE, &tBh, (kb0 + i) * 64, 0, fb, keep_pol()); // Wr re-read by all clusters + } + } + __syncwarp(); + }); + } + } else if (warp == 1) { + if (MRG) { + // ---------------- pair MMA issuer (leader only): m256n256k16 cta_group::2 TS MMAs + constexpr uint32_t ID256 = (1u << 4) | ((256u >> 3) << 17) | ((256u >> 4) << 24); + if (prk == plead) { + ring_loop_ct(0, nkb, [&](int i, auto ptag, uint32_t ph) { + constexpr int s = decltype(ptag)::value; + mbar_wait_cl2(bar_conv + 8 * s, ph); + mbar_wait_cl2(bar_full + 8 * s, ph); + tc_fence_after(); + const uint32_t bh = sbase + RT_WOFF + s * RT_WSTAGE; + const uint32_t at = tbase + 256 + 64 * s; + const uint64_t bd0 = make_sdesc(bh); + __syncwarp(); + if (elect_one()) { +#pragma unroll + for (int k = 0; k < 4; k++) mma_f16_ts_cg2(tbase, at + k * 8, bd0 + 2 * k, ID256, (i | k) != 0); + mma_commit_cg2m(bar_empty + 8 * s, pmask); + } + __syncwarp(); + }); + if (elect_one()) mma_commit_cg2m(bar_acc, pmask); + __syncwarp(); + } + } else { + // ---------------- MMA issuer (TS, kind::f16; whole warp loops, elect.sync lane issues): D[0,256) += Ah [Bh;Bl]^T ; D[0,128) += Al Bh^T + constexpr uint32_t ID128 = (1u << 4) | ((128u >> 3) << 17) | ((128u >> 4) << 24); + ring_loop_ct(0, nkb, [&](int i, auto ptag, uint32_t ph) { + constexpr int s = decltype(ptag)::value; + mbar_wait(bar_conv + 8 * s, ph); + mbar_wait(bar_full + 8 * s, ph); + if (i == 0) CHNT(8, 0, 32); + tc_fence_after(); + const uint32_t bh = sbase + RT_WOFF + s * RT_WSTAGE; // Wr_hi rows 0..127, Wr_lo rows 128..255 + const uint32_t at = tbase + 256 + 64 * s; // A slot: hi cols [0,32), lo cols [32,64) + const uint64_t bd0 = make_sdesc(bh); + __syncwarp(); + if (elect_one()) { + if (!RTA(1)) +#pragma unroll + for (int k = 0; k < 4; k++) { // 16 K per MMA = 32 B of the B row, 8 TMEM columns of A + const uint64_t bd = bd0 + 2 * k; + // single fp16 x fp16 product hi(x) x hi(Wr) (lo terms dropped: accuracy-gated trim) + mma_f16_ts(tbase, at + k * 8, bd, ID128, (i | k) != 0); + } + mma_commit(bar_empty + 8 * s); + } + __syncwarp(); + }); + if (elect_one()) mma_commit(bar_acc); + __syncwarp(); + CHNT(8, 1, 32); + } + } else if (warp == 11) { + // ---------------- L2 discard of dead intermediates. Every reader of these buffers (prep -> QKV -> + // attention -> o_proj, side-stream convert / mask) completed before this grid's griddepcontrol.wait returned + // (transitive PDL chain; the side stream of the next call forks after this call's main-stream work), and the + // next forward fully rewrites them before reading. discard.global.L2 drops the (dirty, EVICT_LAST) lines + // without a DRAM write-back, so they neither occupy L2 nor cost write bandwidth in the DRAM-bound MoE phase. + // Ranges start 256 B aligned (workspace carver) and are rounded up to 128 B inside their own padded slice. + // ordering proof (verified): (a) same-call readers: Wqkv16/xn (QKV GEMM), q/k/V^T (attention), Wo16/attn + // (o_proj) are all complete (griddepcontrol.wait chain; side convert units all counted done before o_proj + // could start its mainloop; claim-losing side CTAs never touch Wo16). (b) next-call writers: prep_qkv(N+1) + // (Wqkv16, xn, V^T pad) is on the same stream after MoE(N) and its griddepcontrol.wait transitively waits for + // this router; convert_w16(N+1) (Wo16) runs on the side stream only after cudaStreamWaitEvent(ev_fork(N+1)), + // recorded on the main stream after all of call N's launches -> full completion of this router. No overlap. + // Every discarded byte is fully rewritten before it is read next call (K/Q tile overreads hit the next + // head's rows or TMA OOB zero-fill; V^T padding re-zeroed by prep). Stress (DISCARD_PROBE, 1500 b2b calls + // with vs without discard, 1x1024 2x2048 16x449 1x8192 3x77): identical deviation statistics, 0 NaN, no hang. + if (DL.late) mbar_wait(bar_acc, 0); // probe: discards after the router mainloop + const unsigned long long nct = (unsigned long long)gridDim.x * gridDim.y; + const unsigned long long cidl = (unsigned long long)(blockIdx.y * gridDim.x + blockIdx.x); + for (int r = 0; r < DL.n; r++) { + const char* base = reinterpret_cast(DL.p[r]); + const unsigned long long nl = (DL.bytes[r] + 127) >> 7; + for (unsigned long long i = cidl * 32 + lane; i < nl; i += nct * 32) + asm volatile("discard.global.L2 [%0], 128;" ::"l"(base + (i << 7)) : "memory"); + } + if (MRG) { + // merged launch: attn rows of this M tile were read only by this cluster's o_proj tiles (all complete at + // the cluster barrier) -> rank r discards rows m0 + 8r .. +7. Wo16 rows 128 r .. +127 are read by rank r of + // EVERY cluster: the last cluster to arrive on sctr[r] (atomic, no waiting) discards that 1 MB slice. + const int r0 = m0 + 8 * (int)rank, r1 = min(r0 + 8, T); + if (r1 > r0) { + const char* ab = MG.attn + (size_t)r0 * 8192; + const int nl = (r1 - r0) * 64; // 8192 B per fp16 attn row = 64 lines + for (int i = lane; i < nl; i += 32) asm volatile("discard.global.L2 [%0], 128;" ::"l"(ab + ((size_t)i << 7)) : "memory"); + } + int last = 0; + if (lane == 0) last = MG.sctr_old == (int)gridDim.y - 1; + if (MG.wo16 && __shfl_sync(0xffffffffu, last, 0)) { + const char* wb = MG.wo16 + (size_t)rank * 128 * 8192; + for (int i = lane; i < 8192; i += 32) asm volatile("discard.global.L2 [%0], 128;" ::"l"(wb + ((size_t)i << 7)) : "memory"); + } + } + } else if (warp < 10 || (!MRG && warp >= 12)) { + // ---------------- converter warps 2..9 (256 threads): thread = token row = TMEM lane (warp quadrant q); + // warp set cs = 0 (warps 2-5) converts k 0..31 of each 64-K k-block (h box 0), cs = 1 (warps 6-9) k 32..63. + // y = ln2w * h * rstd, x = y * sx (exact power of 2, |x| < 2^14 by the bound |h_k| rstd <= sqrt(2048)), + // hi = f16(x), lo = f16(x - hi) packed as fp16x2 (column j = K elements 2j, 2j+1) into the TMEM A slot. + const int q = warp & 3, cs = (warp >= 6 && warp < 10) ? 1 : 0; // MRG: K half; !MRG: set 0 = warps 2-5 + const int row = q * 32 + lane; + const uint32_t tl = tbase + ((uint32_t)(q * 32) << 16); + const float rstd = (m0 + row) < T ? rsqrtf(ssq[m0 + row] / (float)HID + eps) : 0.f; // same as rms_row_ss + const int sw = row & 7; + const float sx = sx_pre; // computed before griddepcontrol.wait (ln2w is a kernel input) + if (xn8 != nullptr && blockIdx.x == 0 && blockIdx.y == 0 && threadIdx.x == 64) *f8inv = 64.f / sx; + // ln2 weights of this thread's 32 k of the current k-block from the smem copy (warp-uniform address -> + // broadcast), prefetched one k-block ahead + const float4* lw = reinterpret_cast(smem + RT_LNW) + (kb0 * 64 + cs * 32) / 4; + float4 v[8]; // h row segment of the current k-block (128B-swizzled box cs: chunk c at physical c ^ (row & 7)) + auto load_h = [&](int ii) { + const int hs = ii % HST; + mbar_wait(bar_hfull + 8 * hs, (ii / HST) & 1); + const uint8_t* hr = smem + hoff(hs) + cs * RT_OP + row * 128; +#pragma unroll + for (int c = 0; c < 8; c++) v[c] = *reinterpret_cast(hr + 16 * (c ^ sw)); + __syncwarp(); + if (elect_one()) mbar_arrive(bar_hempty + 8 * hs); // h tile consumed (values in registers) + }; + if constexpr (!MRG) { + // set j = cset processes k-blocks i = j, j + 3,... (stage i % 3 == j), both 32-K halves per block + const int cset = warp >= 12 ? 2 : (warp >= 6 ? 1 : 0); + const float4* lw0 = reinterpret_cast(smem + RT_LNW) + kb0 * 16; + const float2 r2 = make_float2(rstd, rstd), s2 = make_float2(sx, sx), q2 = make_float2(0.015625f, 0.015625f); + const bool w16 = xn16 != nullptr, w8 = xn8 != nullptr; + // warp set index as a template constant (immediate h-stage smem, mbarrier and TMEM A-slot offsets) + auto conv_set = [&](auto ctag) { + constexpr int s = decltype(ctag)::value; // == cset == i % 3 +#pragma unroll 1 + for (int i = s; i < nkb; i += 3) { + const uint32_t ph = (uint32_t)((i / 3) & 1); + // h stage i % HST (4-deep ring, one more 32 KB h k-block in flight); TMEM A / Wr stage stays s + const int hs = i % HST; + mbar_wait(sbase + RT_HB8 + 8 * (i & 7), (uint32_t)((i >> 3) & 1)); // k-block i landed (RT_HB8) +#pragma unroll + for (int h = 0; h < 2; h++) { + const uint8_t* hr = smem + hoff(hs) + h * RT_OP + row * 128; +#pragma unroll + for (int c = 0; c < 8; c++) v[c] = *reinterpret_cast(hr + 16 * (c ^ sw)); + if (h == 1) { + __syncwarp(); + if (elect_one()) mbar_arrive(bar_hempty + 8 * hs); // h tile consumed (values in registers) + } + float hi[16]; + uint32_t x8[8]; + uint32_t xh[16]; +#pragma unroll + for (int c = 0; c < 8; c++) { + const float4 wv = lw0[i * 16 + h * 8 + c]; + const float2 z01 = fmul2(make_float2(wv.x, wv.y), fmul2(make_float2(v[c].x, v[c].y), r2)); + const float2 z23 = fmul2(make_float2(wv.z, wv.w), fmul2(make_float2(v[c].z, v[c].w), r2)); + if (w16) { xh[2 * c] = pack_h2(z01.x, z01.y); xh[2 * c + 1] = pack_h2(z23.x, z23.y); } + const float2 y01 = fmul2(z01, s2), y23 = fmul2(z23, s2); + hi[2 * c] = __uint_as_float(cvt_h2(__float_as_uint(y01.x), __float_as_uint(y01.y))); + hi[2 * c + 1] = __uint_as_float(cvt_h2(__float_as_uint(y23.x), __float_as_uint(y23.y))); + if (w8) { + const float2 e01 = fmul2(y01, q2), e23 = fmul2(y23, q2); + x8[c] = cvt_e4m3x4(e01.x, e01.y, e23.x, e23.y); + } + } + if (w8 && m0 + row < T) { + uint4* dst = reinterpret_cast(xn8 + (size_t)(m0 + row) * HID + (kb0 + i) * 64 + h * 32); + const uint64_t kp = keep_pol(); + asm volatile("st.global.L2::cache_hint.v8.b32 [%0], {%1, %2, %3, %4, %5, %6, %7, %8}, %9;" ::"l"(dst), + "r"(x8[0]), "r"(x8[1]), "r"(x8[2]), "r"(x8[3]), "r"(x8[4]), "r"(x8[5]), "r"(x8[6]), "r"(x8[7]), + "l"(kp) : "memory"); + } + if (w16 && m0 + row < T) { + uint4* dst = reinterpret_cast(xn16 + (size_t)(m0 + row) * HID + (kb0 + i) * 64 + h * 32); + const uint64_t kp = keep_pol(); +#pragma unroll + for (int u = 0; u < 4; u++) + st_u4_hint(dst + u, make_uint4(xh[4 * u], xh[4 * u + 1], xh[4 * u + 2], xh[4 * u + 3]), kp); + } + if (h == 0) { // TMEM A slot s free once the MMAs of k-block i - 3 completed + mbar_wait(bar_empty + 8 * s, ph ^ 1u); + tc_fence_after(); + } + tmem_st16(tl + 256 + 64 * s + 16 * h, hi); + } + asm volatile("tcgen05.wait::st.sync.aligned;" ::: "memory"); + tc_fence_before(); + __syncwarp(); + if (elect_one()) mbar_arrive(bar_conv + 8 * s); + } + }; + if (cset == 0) conv_set(std::integral_constant{}); + else if (cset == 1) conv_set(std::integral_constant{}); + else conv_set(std::integral_constant{}); + } else { + if (nkb > 0) load_h(0); + for (int i = 0; i < nkb; i++) { + const int s = i % WST; + float4 wc[8]; +#pragma unroll + for (int c = 0; c < 8; c++) wc[c] = lw[i * 16 + c]; + if (i == 0) CHNT(7, 1, 64); + float hi[16]; + uint32_t x8[8]; // e4m3 xn2 * s8 (FP8 MoE path) + uint32_t xh[16]; // fp16 xn2 (unscaled) of this thread's 32 k: same expression as rms_row_ss + // instruction diet: packed FMUL2 (per-lane IEEE.rn, bit-identical to the scalar products), fp16 xn2 + // packs only when xn16 is written, e4m3 conversion only when xn8 is written (warp-uniform branches) + const float2 r2 = make_float2(rstd, rstd), s2 = make_float2(sx, sx), q2 = make_float2(0.015625f, 0.015625f); + const bool w16 = xn16 != nullptr, w8 = xn8 != nullptr; +#pragma unroll + for (int c = 0; c < 8; c++) { + const float2 z01 = fmul2(make_float2(wc[c].x, wc[c].y), fmul2(make_float2(v[c].x, v[c].y), r2)); + const float2 z23 = fmul2(make_float2(wc[c].z, wc[c].w), fmul2(make_float2(v[c].z, v[c].w), r2)); + if (w16) { xh[2 * c] = pack_h2(z01.x, z01.y); xh[2 * c + 1] = pack_h2(z23.x, z23.y); } + const float2 y01 = fmul2(z01, s2), y23 = fmul2(z23, s2); + hi[2 * c] = __uint_as_float(cvt_h2(__float_as_uint(y01.x), __float_as_uint(y01.y))); + hi[2 * c + 1] = __uint_as_float(cvt_h2(__float_as_uint(y23.x), __float_as_uint(y23.y))); + if (w8) { + const float2 e01 = fmul2(y01, q2), e23 = fmul2(y23, q2); + x8[c] = cvt_e4m3x4(e01.x, e01.y, e23.x, e23.y); + } + } + if (i + 1 < nkb) load_h(i + 1); // next k-block's h loads overlap this block's stores / TMEM store + if (xn8 != nullptr && m0 + row < T) { + // 32 contiguous bytes of row m0+row: k = (kb0 + i) * 64 + cs * 32 .. +31 + uint4* dst = reinterpret_cast(xn8 + (size_t)(m0 + row) * HID + (kb0 + i) * 64 + cs * 32); + const uint64_t kp = keep_pol(); + // ONE 256-bit store (full 32 B sector, 32 B aligned) instead of two 16 B half-sector stores + asm volatile("st.global.L2::cache_hint.v8.b32 [%0], {%1, %2, %3, %4, %5, %6, %7, %8}, %9;" ::"l"(dst), + "r"(x8[0]), "r"(x8[1]), "r"(x8[2]), "r"(x8[3]), "r"(x8[4]), "r"(x8[5]), "r"(x8[6]), "r"(x8[7]), + "l"(kp) : "memory"); + } + if (xn16 != nullptr && m0 + row < T) { + // 64 contiguous bytes of row m0+row: k = (kb0 + i) * 64 + cs * 32 .. +31 (EVICT_LAST: MoE gathers it) + uint4* dst = reinterpret_cast(xn16 + (size_t)(m0 + row) * HID + (kb0 + i) * 64 + cs * 32); + const uint64_t kp = keep_pol(); +#pragma unroll + for (int u = 0; u < 4; u++) + st_u4_hint(dst + u, make_uint4(xh[4 * u], xh[4 * u + 1], xh[4 * u + 2], xh[4 * u + 3]), kp); + } + // TMEM A slot s is free once the MMAs of k-block i - WST completed + if (MRG) mbar_wait_cl2(bar_empty + 8 * s, ((i / WST) & 1) ^ 1); + else mbar_wait(bar_empty + 8 * s, ((i / WST) & 1) ^ 1); + tc_fence_after(); + const uint32_t at = tl + 256 + 64 * s + 16 * cs; + tmem_st16(at, hi); // single product: hi only (A slot cols [32,64) unused) + asm volatile("tcgen05.wait::st.sync.aligned;" ::: "memory"); + tc_fence_before(); + __syncwarp(); + if (elect_one()) { + if (MRG) mbar_arrive_cl(mapa_sh(bar_conv + 8 * s, plead)); // leader's conv barrier (count 16) + else mbar_arrive(bar_conv + 8 * s); + } + if (i == 0) CHNT(7, 2, 64); + } + } + if (warp >= 2 && warp < 6) { + // ---------------- epilogue: TMEM partial (cols [0,128) + [128,256)), unscaled by 1/(sx s_e) -> smem + // per-expert scales s_e (wrl) come from the side-stream convert kernel: acquire its completion counter + // one acquiring lane per warp (was all 128 threads spinning ld.acquire.gpu), warp sync orders the rest + if (elect_one()) side_acquire(side_ctr, side_target); + __syncwarp(); + float* sinv = reinterpret_cast(smem + RT_SINV); + sinv[row] = (1.f / sx) * (1.f / __ldg(wscale + row)); // exact: powers of 2 within [2^-120, 2^120] + asm volatile("bar.sync 2, 128;" ::: "memory"); // epilogue warps 2..5 + if (MRG) mbar_wait_cl2(bar_acc, 0); else mbar_wait(bar_acc, 0); + if (threadIdx.x == 64) RTP(2); + CHNT(5, 0, 64); + tc_fence_after(); + float* prow = part + row * 128; + // two 32-column TMEM loads in flight per wait (2 waits instead of 4); sinv read as float4 (same products) +#pragma unroll 1 + for (int c2 = 0; c2 < 4; c2 += 2) { + float a[64]; + const uint32_t ta = tl + 128u * (prk & 1u) + c2 * 32; // single-product accumulator (MRG pair: cols [128 r, +128)) + tmem_ld32x2(ta, a, ta + 32, a + 32); +#pragma unroll + for (int j = 0; j < 16; j++) { + const float4 s4 = reinterpret_cast(sinv)[c2 * 8 + j]; + a[4 * j] *= s4.x; a[4 * j + 1] *= s4.y; a[4 * j + 2] *= s4.z; a[4 * j + 3] *= s4.w; + } +#pragma unroll + for (int j = 0; j < 16; j++) { + const int g = (c2 * 8 + j) ^ (row & 7); + *reinterpret_cast(prow + g * 4) = make_float4(a[4 * j], a[4 * j + 1], a[4 * j + 2], a[4 * j + 3]); + } + } + tc_fence_before(); + } + } + __syncwarp(); + cluster_sync_all(); // all partials of the cluster written + if (threadIdx.x == 0) RTP(3); + CHN(5, 1); + + // ---------------- cross-CTA reduction (all RT_THREADS threads, float4 DSMEM loads, all KS loads of a unit in + // flight at once, summed in rank order -> deterministic, bit-identical to a serial rank-order sum) into a local + // [rows][128] buffer (stage 1 smem, free after the mainloop; only stage 0 'part' is read remotely), then + // softmax / top-8 per row (warp per token row) from local smem. + const int r_lo = (int)rank * 128 / KS, r_hi = ((int)rank + 1) * 128 / KS; + const uint32_t pbase = smem_u32(part); + // per-CTA expert histogram in smem (stage 2 area, unused after the mainloop): the select phase counts into it with + // shared atomics; the cluster then pushes ONE global atomic per (cluster, expert). + int* shist = reinterpret_cast(smem + RT_HIST); // zeroed in the prologue (no extra CTA barrier) + if (threadIdx.x == 0) RTP(4); + // rows split EVENLY into contiguous per-warp blocks of per = ceil(rows / 12); each warp processes its block + // in ONE batch of RS >= per rows (RS in {1, 2, 4, 6}; 6-row batches loop only for KS = 1). The lane's logits + // (experts 4*lane .. 4*lane+3 = float4 group `lane`) are summed over the KS partials straight from DSMEM into + // registers (rank order -> deterministic) - no smem round trip, no extra barrier. + { + const int nrows = r_hi - r_lo, NW = RT_THREADS / 32; + const int per = (nrows + NW - 1) / NW; + const int w0 = warp * per; + const int wcnt = nrows - w0 < per ? nrows - w0 : per; + // split final cluster barrier - each thread ARRIVES (release) right after its last DSMEM read of the + // peers' partials (before the serial top-8 select of its last rows) and WAITS (acquire) only right before + // exit, so the select / histogram / bucket tail no longer waits on the slowest CTA of the cluster. + bool cl_arrived = false; + auto cl_arrive = [&]() { + __syncwarp(); + asm volatile("barrier.cluster.arrive.release.aligned;" ::: "memory"); + cl_arrived = true; + }; + if (wcnt > 0) { + auto run_rows = [&](auto rs_tag) { + constexpr int RS = decltype(rs_tag)::value; +#pragma unroll 1 + for (int bb = 0; bb < wcnt; bb += RS) { + int tok[RS]; + uint32_t off[RS]; + float4 acc[RS]; +#pragma unroll + for (int i = 0; i < RS; i++) { + const int r = r_lo + w0 + bb + i; + const bool ok = bb + i < wcnt && m0 + r < T; + tok[i] = ok ? m0 + r : -1; + off[i] = (uint32_t)(r * 128 + ((lane ^ (r & 7)) << 2)) * 4u; + acc[i] = make_float4(0.f, 0.f, 0.f, 0.f); + } + // chunks of KC ranks: ALL KC*RS DSMEM loads issued back to back (one round-trip latency per + // chunk instead of one per rank pair: KS = 16 at small T was 8 serial round trips), then summed + // in rank order (deterministic, same order as before). + // (897 <= T < 2048, K split > 8, chain probe at 1x1024: KS = 10 -> two serial 8-rank DSMEM + // round trips on the router -> MoE critical path): all <= 16 rank loads of the row in ONE chunk. + // Summation stays in rank order (bit-identical). + constexpr int KC = RS == 1 ? 16 : (RS <= 2 ? 8 : 4); + const int kcs = (RS == 1 && KS > 8 && T >= 897 && T < 2048) ? 16 : (RS <= 2 ? 8 : 4); + if (!RTA(16)) for (int k0 = 0; k0 < KS; k0 += kcs) { + float4 v[KC][RS]; +#pragma unroll + for (int kk = 0; kk < KC; kk++) +#pragma unroll + for (int i = 0; i < RS; i++) + if (tok[i] >= 0 && kk < kcs && k0 + kk < KS) v[kk][i] = ld_dsmem_v4(pbase + off[i], (uint32_t)(k0 + kk)); +#pragma unroll + for (int kk = 0; kk < KC; kk++) +#pragma unroll + for (int i = 0; i < RS; i++) + if (tok[i] >= 0 && kk < kcs && k0 + kk < KS) { + acc[i].x += v[kk][i].x; acc[i].y += v[kk][i].y; acc[i].z += v[kk][i].z; acc[i].w += v[kk][i].w; + } + } + int* rce = btok ? reinterpret_cast(smem + 65536) + (w0 + bb) * 8 : nullptr; + if (RS == 1 && hx != nullptr) { + if (tok[0] >= 0) { + const float rs_ = rsqrtf(__ldcg(ssq + tok[0]) / (float)HID + eps); + router_select_exact(acc[0], tok[0], lane, hx, lnw, rs_, CJ.wr, topk_idx, topk_w, shist, rce, + rce ? rce + 1024 : nullptr, rce ? reinterpret_cast(rce + 2048) : nullptr); + } + } else + if (!RTA(4)) router_select_batch(acc, tok, lane, topk_idx, topk_w, shist, rce, rce ? rce + 1024 : nullptr, + rce ? reinterpret_cast(rce + 2048) : nullptr); + } + }; + if (!MRG && hx == nullptr && KS <= 4 && !RTA(16) && !RTA(4)) { + // software-pipelined reduce + + // select. The KS raw DSMEM partials of row bb + 1 are loaded into registers BEFORE the (serial, redux + // bound) top-8 select of row bb, so the DSMEM round trip overlaps the select instead of preceding it. + // Summation stays 0 + p_0 + p_1 + ... in rank order (bit-identical to run_rows). + auto ldrow = [&](int bb, float4* v, int& tk) { + const int r = r_lo + w0 + bb; + tk = (bb < wcnt && m0 + r < T) ? m0 + r : -1; + const uint32_t of = (uint32_t)(r * 128 + ((lane ^ (r & 7)) << 2)) * 4u; +#pragma unroll + for (int kk = 0; kk < 4; kk++) + if (tk >= 0 && kk < KS) v[kk] = ld_dsmem_v4(pbase + of, (uint32_t)kk); + }; + float4 vc[2][4], vn[2][4]; + int tc[2], tn[2]; + ldrow(0, vc[0], tc[0]); + ldrow(1, vc[1], tc[1]); +#pragma unroll 1 + for (int bb = 0; bb < wcnt; bb += 2) { + if (bb + 2 < wcnt) { ldrow(bb + 2, vn[0], tn[0]); ldrow(bb + 3, vn[1], tn[1]); } + else { tn[0] = -1; tn[1] = -1; } + float4 acc[2]; +#pragma unroll + for (int i = 0; i < 2; i++) { + acc[i] = make_float4(0.f, 0.f, 0.f, 0.f); +#pragma unroll + for (int kk = 0; kk < 4; kk++) + if (tc[i] >= 0 && kk < KS) { acc[i].x += vc[i][kk].x; acc[i].y += vc[i][kk].y; acc[i].z += vc[i][kk].z; acc[i].w += vc[i][kk].w; } + } + if (bb + 2 >= wcnt) cl_arrive(); // last pair: every DSMEM partial of this warp consumed (warp-uniform) + int* rce = btok ? reinterpret_cast(smem + 65536) + (w0 + bb) * 8 : nullptr; + router_select_batch<2>(acc, tc, lane, topk_idx, topk_w, shist, rce, rce ? rce + 1024 : nullptr, + rce ? reinterpret_cast(rce + 2048) : nullptr); +#pragma unroll + for (int i = 0; i < 2; i++) { +#pragma unroll + for (int kk = 0; kk < 4; kk++) vc[i][kk] = vn[i][kk]; + tc[i] = tn[i]; + } + } + } else + run_rows(std::integral_constant{}); + } + if (!cl_arrived) cl_arrive(); // warps without rows / 1-row path: after all their DSMEM reads + } + // per-CTA histogram pushed straight to global counts (<= 8 rows x 8 experts nonzero per CTA at KS = 16), + // instead of cluster barrier + DSMEM cross-rank histogram reduce + second barrier: one cluster barrier and one + // DSMEM round trip fewer on the router -> scatter critical path. Integer counts -> bit-identical result. + __syncthreads(); // all smem histogram atomics of this CTA done + { + // records (h ring smem 64 KB .. 76.5 KB: free after the mainloop; only [0, 64 KB) is read remotely) + int* rec = reinterpret_cast(smem + 65536); + int* sbase = rec + 3072; + if (threadIdx.x < NEXP && !RTA(8)) { + const int c = shist[threadIdx.x]; + const int old = c ? atomicAdd(&counts[threadIdx.x], c) : 0; // global base of this CTA's range + if (btok) sbase[threadIdx.x] = old; + } + if (btok && !RTA(8)) { + __syncthreads(); + const int nrec = (r_hi - r_lo) * 8; + for (int i = threadIdx.x; i < nrec; i += RT_THREADS) { + const int r = r_lo + (i >> 3); + if (m0 + r < T) { + const int e = rec[i]; + const size_t idx = (size_t)e * T + sbase[e] + rec[1024 + i]; + btok[idx] = m0 + r; + bw[idx] = reinterpret_cast(rec + 2048)[i]; + } + } + } + } + if (threadIdx.x == 0) RTP(5); + CHN(5, 2); + __syncwarp(); + // remote partial reads of the cluster done before any CTA exits (its smem is read via DSMEM): wait half of the + // split barrier (arrive issued after this thread's last DSMEM read above) + asm volatile("barrier.cluster.wait.acquire.aligned;" ::: "memory"); + if (threadIdx.x == 0) RTP(6); + CHN(11, 2); + if (warp == 1) { + tc_fence_after(); + if (MRG) asm volatile("tcgen05.dealloc.cta_group::2.sync.aligned.b32 %0, %1;" ::"r"(tbase), "r"(512)); + else asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tbase), "r"(512)); + } +} +__global__ void __launch_bounds__(RT_THREADS, 1) router_kernel(const __grid_constant__ CUtensorMap tH, + const __grid_constant__ CUtensorMap tBh, + const __grid_constant__ CUtensorMap tBl, int T, + const float* __restrict__ lnw, + const float* __restrict__ ssq, float eps, + const float* __restrict__ wscale, + int* __restrict__ topk_idx, float* __restrict__ topk_w, + int* __restrict__ counts, + const float* __restrict__ pf0, + const float* __restrict__ pf1, uint32_t pf_bytes, + const __grid_constant__ sidew::ConvJob CJ, + __half* __restrict__ xn16, + uint8_t* __restrict__ xn8, float* __restrict__ f8inv, + const __grid_constant__ L2Discard DL, + int* __restrict__ btok, float* __restrict__ bw, + const int* __restrict__ mtctr) { + router_dev(tH, tBh, tBl, T, lnw, ssq, eps, wscale, topk_idx, topk_w, counts, pf0, pf1, pf_bytes, CJ, xn16, xn8, + f8inv, DL, RtMerge{0u, 0, nullptr, nullptr}, btok, bw, nullptr, mtctr); +} + +// ------------------------------------------------------------------ small-T router (897 <= T < 2048) +// One CTA per 8 (NTT = 1) or 16 (NTT = 2) tokens, FULL K per CTA (no cluster K split, no DSMEM reduction, no TMEM): +// 1. pre-PDL-wait: ln2w (input) max -> exact pow2 x scale sx (same as router_dev), Wr fp16 side-stream acquire (steal) +// 2. post-wait: h rows of the CTA's tokens -> xn2 = ln2w * (h * rstd) (rstd from the o_proj ssq; identical expression +// to router_dev), fp16 xn2 rows written to xn16 (MoE gather operand), fp16(xn2 * sx) staged in smem +// 3. warp w computes logits of experts 16w..16w+15 x all tokens with mma.sync m16n8k16 (fp16 in, fp32 accumulate): +// A = Wr_hi rows streamed from L2 (16 B per lane per 32-K chunk, double-buffered register groups), B = staged x. +// The K order inside a 32-K chunk is permuted identically for A and B (lane t owns k = 8t .. 8t+7: one 16 B load), +// so every fragment is a single 128-bit load. Logits = acc * 1 / (sx s_e) (exact powers of 2). +// 4. per token: top-8 select (router_select_batch<1>, logit domain), CTA histogram, one global atomic per +// (CTA, expert), router buckets btok / bw (self-table MoE), then L2 discards of dead buffers. +__device__ __forceinline__ void mma16816(float* c, uint32_t a0, uint32_t a1, uint32_t a2, uint32_t a3, uint32_t b0, + uint32_t b1) { + asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};" + : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) + : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1)); +} +constexpr int RS_XS = HID * 2 + 64; // smem bytes per staged fp16 x row (+64 B pad: conflict-free 16 B fragment loads) +// logits rows padded to RS_LGS = 132 floats: the mma.sync fragment stores (lanes t = lane & 3 write rows 2t, 2t+1 +// of the same expert column) hit 4 distinct bank groups (row offset 8t words) instead of one 4-way-conflicting bank +constexpr int RS_LGS = 132; +template constexpr int rs_base() { return 8 * NTT * RS_XS + 8 * NTT * RS_LGS * 4 + 3 * 8 * NTT * 8 * 4; } +// per-warp cp.async ring of Wr fragments (RS_SG 32-K chunks per stage, lane-private 16 B slots for rows g / g + 8) +constexpr int RS_SG = 4; +template constexpr int rs_nst() { return NTT == 1 ? 5 : 4; } +template constexpr int rs_smem() { return rs_base() + 8 * rs_nst() * RS_SG * 2 * 32 * 16; } +__device__ __forceinline__ uint4 rs_lds128(uint32_t a) { + uint4 v; + asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4];" : "=r"(v.x), "=r"(v.y), "=r"(v.z), "=r"(v.w) : "r"(a) : "memory"); + return v; +} +template +__global__ void __launch_bounds__(256, 1) router_small_kernel(const float* __restrict__ h, const float* __restrict__ lnw, + const float* __restrict__ ssq, float eps, + const __half* __restrict__ wrh, + const float* __restrict__ wscale, int T, + int* __restrict__ topk_idx, float* __restrict__ topk_w, + int* __restrict__ counts, + const __grid_constant__ sidew::ConvJob CJ, + __half* __restrict__ xn16, + const __grid_constant__ L2Discard DL, + int* __restrict__ btok, float* __restrict__ bw, + const float* __restrict__ pfg, const float* __restrict__ pfu, + int pf_t0, int pf_t1, int pf_kb, int pf_krot) { + constexpr int TPC = 8 * NTT; + extern __shared__ __align__(16) uint8_t rsm[]; + uint8_t* xs = rsm; // [TPC][RS_XS] fp16 x * sx + float* lg = reinterpret_cast(rsm + TPC * RS_XS); // [TPC][128] logits + int* rec = reinterpret_cast(lg + TPC * RS_LGS); // [3][TPC * 8] select records + __shared__ float red[8]; + __shared__ int shist[NEXP], sbase[NEXP]; + __shared__ float sinv[NEXP]; + const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31; + const int t0 = blockIdx.x * TPC; + CHN(11, 0); + // ---- pre-PDL-wait: Wr fp16 (side stream) acquire with work stealing; ln2w scale (kernel input) + // ln2w (kernel input) loads issued BEFORE warp 0's side-stream acquire spin (latency overlaps it) + const float4 w0 = __ldg(reinterpret_cast(lnw) + tid); + const float4 w1 = __ldg(reinterpret_cast(lnw) + tid + 256); + if (warp == 0) sidew::conv_acquire_steal(CJ, (int)(((long long)blockIdx.x * CJ.n) / gridDim.x)); + // the fused MoE CTAs (~223 KB smem) cannot co-reside with router CTAs, so DRAM + // is idle during the router phase. Warps 4-7 (idle until the post-wait staging) L2-prefetch the first pf_kb rotated + // 64-K k-blocks of the odd MoE CTAs' static DRAM-streamed first gate/up items [pf_t0, pf_t1) (split first wave: + // item t = expert t / 12, n-tile t % 12 of 64 gate + 64 up rows, k start (t * krot) % 32). Weights are kernel + // inputs; prefetch only (a wrong guess costs DRAM reads, results never depend on it). + if (pfg != nullptr && tid >= 128) { + const int lt = tid - 128, r = lt & 63; + const float* pb = lt < 64 ? pfg : pfu; + for (int t = pf_t0 + (int)blockIdx.x; t < pf_t1; t += (int)gridDim.x) { + const int e = t / 12, nt = t - e * 12; + const char* rowp = reinterpret_cast(pb + ((size_t)e * INTER + nt * 64 + r) * HID); + const int k0 = pf_krot > 0 ? (t * pf_krot) % (HID / 64) : 0; + const int n1 = k0 + pf_kb <= HID / 64 ? pf_kb : HID / 64 - k0; + asm volatile("cp.async.bulk.prefetch.L2.global [%0], %1;" ::"l"(rowp + k0 * 256), "r"((uint32_t)(n1 * 256)) : "memory"); + if (n1 < pf_kb) + asm volatile("cp.async.bulk.prefetch.L2.global [%0], %1;" ::"l"(rowp), "r"((uint32_t)((pf_kb - n1) * 256)) : "memory"); + } + } + { + float mw = fmaxf(fmaxf(fmaxf(fabsf(w0.x), fabsf(w0.y)), fmaxf(fabsf(w0.z), fabsf(w0.w))), + fmaxf(fmaxf(fabsf(w1.x), fabsf(w1.y)), fmaxf(fabsf(w1.z), fabsf(w1.w)))); +#pragma unroll + for (int o = 16; o; o >>= 1) mw = fmaxf(mw, __shfl_xor_sync(0xffffffffu, mw, o)); + if (lane == 0) red[warp] = mw; + } + if (tid < NEXP) shist[tid] = 0; + // Wr fp16 (side-stream product, acquired by warp 0 above; not written by the PDL predecessor) streamed with + // cp.async into a per-warp NST-stage smem ring: the first NST stages are issued BEFORE griddepcontrol.wait + // (overlapping the o_proj tail), the rest NST stages ahead of the MMAs (was: 64 KB register-double-buffered + // __ldcg per CTA, L2-latency bound). Each lane reads back only its own slots -> cp.async.wait_group suffices. + constexpr int NST = rs_nst(), NGR = 64 / RS_SG; + const int rg = lane >> 2, rt = lane & 3; + const uint4* wa = reinterpret_cast(wrh + (size_t)(16 * warp + rg) * HID + 8 * rt); + const uint4* wb = wa + (8 * HID) / 8; // row + 8 + const uint32_t rbase = smem_u32(rsm + rs_base()) + (uint32_t)(warp * NST * RS_SG * 2 * 32 + lane) * 16u; + auto rslot = [&](int st, int c, int hh) -> uint32_t { return rbase + (uint32_t)(((st * RS_SG + c) * 2 + hh) * 32 * 16); }; + auto rissue = [&](int gi) { + const int st = gi % NST; +#pragma unroll + for (int c = 0; c < RS_SG; c++) { + const int kc = gi * RS_SG + c; + cp_async16(rslot(st, c, 0), wa + 4 * kc, 16u); + cp_async16(rslot(st, c, 1), wb + 4 * kc, 16u); + } + }; + __syncthreads(); // warp 0's acquire of the side-stream Wr ordered before every warp's Wr reads +#pragma unroll + for (int gi = 0; gi < NST; gi++) { rissue(gi); asm volatile("cp.async.commit_group;" ::: "memory"); } + float m8 = 0.f; +#pragma unroll + for (int w8 = 0; w8 < 8; w8++) m8 = fmaxf(m8, red[w8]); + const float sx = pow2_scale(46.f * m8); // |y| <= sqrt(2048) * max|ln2w| < 46 max|ln2w| (as router_dev) + if (tid < NEXP) sinv[tid] = (1.f / sx) * (1.f / __ldcg(wscale + tid)); + pdl_wait(); + CHN(11, 1); + pdl_trigger(); + // ---- L2 discard of dead buffers issued right after griddepcontrol.wait (all readers - o_proj - completed; + // see router_dev) instead of at the CTA end: fire-and-forget, overlaps the h-row loads below instead of delaying + // the grid completion (= the MoE PDL gate) + { + const unsigned long long nth = (unsigned long long)gridDim.x * 256ull; + const unsigned long long gt = (unsigned long long)blockIdx.x * 256ull + tid; + for (int r = 0; r < DL.n; r++) { + const char* base = reinterpret_cast(DL.p[r]); + const unsigned long long nl = (DL.bytes[r] + 127) >> 7; + for (unsigned long long i = gt; i < nl; i += nth) + asm volatile("discard.global.L2 [%0], 128;" ::"l"(base + (i << 7)) : "memory"); + } + } + // x scale / per-expert logit scales computed BEFORE griddepcontrol.wait (red, shist and warp 0's side-stream + // acquire are all ordered by the barrier above; ln2w / Wr scales are not PDL-predecessor outputs) -> the former + // post-wait __syncthreads is gone (sinv is read only after the staging barrier below). Bit-identical. + // ---- normalization + staging (thread owns float4 groups tid, tid + 256 of every row) + { + float4 v[TPC][2]; + float rs[TPC]; +#pragma unroll + for (int r = 0; r < TPC; r++) { + const int t = t0 + r; + if (t < T) { + const float4* hr = reinterpret_cast(h + (size_t)t * HID); + v[r][0] = __ldcg(hr + tid); v[r][1] = __ldcg(hr + tid + 256); + rs[r] = rsqrtf(__ldcg(ssq + t) / (float)HID + eps); + } else { + v[r][0] = v[r][1] = make_float4(0.f, 0.f, 0.f, 0.f); + rs[r] = 0.f; + } + } + const uint64_t kp = keep_pol(); +#pragma unroll + for (int r = 0; r < TPC; r++) { + const int t = t0 + r; +#pragma unroll + for (int hh = 0; hh < 2; hh++) { + const float4 a = v[r][hh], w = hh ? w1 : w0; + const float z0 = w.x * (a.x * rs[r]), z1 = w.y * (a.y * rs[r]); + const float z2 = w.z * (a.z * rs[r]), z3 = w.w * (a.w * rs[r]); + const int g4 = tid + 256 * hh; + if (xn16 != nullptr && t < T) + st_u2_pol(reinterpret_cast(xn16 + (size_t)t * HID) + g4, + make_uint2(pack_h2(z0, z1), pack_h2(z2, z3)), kp); + *reinterpret_cast(xs + r * RS_XS + 8 * g4) = + make_uint2(pack_h2(z0 * sx, z1 * sx), pack_h2(z2 * sx, z3 * sx)); + } + } + } + __syncthreads(); + // ---- logits: warp = 16 experts x TPC tokens, mma.sync m16n8k16 over K = 2048 (64 chunks of 32) + { + const int g = lane >> 2, t = lane & 3; + const uint8_t* xb = xs + g * RS_XS + 16 * t; + float acc[NTT][4]; +#pragma unroll + for (int n = 0; n < NTT; n++) acc[n][0] = acc[n][1] = acc[n][2] = acc[n][3] = 0.f; + ring_loop_ct(0, NGR, [&](int gi, auto ptag, uint32_t) { + asm volatile("cp.async.wait_group %0;" ::"n"(NST - 1) : "memory"); // group gi landed (own slots) + constexpr int st = decltype(ptag)::value; +#pragma unroll + for (int c = 0; c < RS_SG; c++) { + const int kc = gi * RS_SG + c; + const uint4 A0 = rs_lds128(rslot(st, c, 0)), A1 = rs_lds128(rslot(st, c, 1)); +#pragma unroll + for (int n = 0; n < NTT; n++) { + const uint4 X = *reinterpret_cast(xb + n * 8 * RS_XS + 64 * kc); + mma16816(acc[n], A0.x, A1.x, A0.y, A1.y, X.x, X.y); + mma16816(acc[n], A0.z, A1.z, A0.w, A1.w, X.z, X.w); + } + } + // refill the consumed stage (its values were consumed by the MMAs above: same-thread WAR ordered) + if (gi + NST < NGR) rissue(gi + NST); + asm volatile("cp.async.commit_group;" ::: "memory"); + }); + const int e0 = 16 * warp + g, e1 = e0 + 8; + const float s0 = sinv[e0], s1 = sinv[e1]; +#pragma unroll + for (int n = 0; n < NTT; n++) { + const int c0 = n * 8 + 2 * t; + lg[c0 * RS_LGS + e0] = acc[n][0] * s0; + lg[(c0 + 1) * RS_LGS + e0] = acc[n][1] * s0; + lg[c0 * RS_LGS + e1] = acc[n][2] * s1; + lg[(c0 + 1) * RS_LGS + e1] = acc[n][3] * s1; + } + } + __syncthreads(); +#pragma unroll 1 + for (int i = 0; i < NTT; i++) { + const int tl = warp + 8 * i; + const int tok = t0 + tl < T ? t0 + tl : -1; + if (tok < 0) continue; // warp-uniform + const float4 lv = reinterpret_cast(lg + tl * RS_LGS)[lane]; + const float rs_ = rsqrtf(__ldcg(ssq + tok) / (float)HID + eps); // same rstd as the staging above + router_select_exact(lv, tok, lane, h, lnw, rs_, CJ.wr, topk_idx, topk_w, shist, rec + tl * 8, + rec + TPC * 8 + tl * 8, reinterpret_cast(rec + 2 * TPC * 8 + tl * 8)); + } + __syncthreads(); + if (tid < NEXP) { + const int c = shist[tid]; + sbase[tid] = c ? atomicAdd(&counts[tid], c) : 0; + } + if (btok != nullptr) { + __syncthreads(); + if (tid < TPC * 8) { + const int tl = tid >> 3; + if (t0 + tl < T) { + const int e = rec[tid]; + const size_t idx = (size_t)e * T + sbase[e] + rec[TPC * 8 + tid]; + btok[idx] = t0 + tl; + bw[idx] = reinterpret_cast(rec + 2 * TPC * 8)[tid]; + } + } + } + CHN(11, 2); +} + +// ------------------------------------------------------------------ merged o_proj + router launch (T < 2048) +// ONE launch replaces tc_gemm + router_kernel when o_proj runs BN = 128 tiles (NT = 16) and the router uses a +// K split of 16: grid (16, mt), cluster (16, 1, 1). Phase 1: CTA (r, b) computes o_proj tile (M tile b, n tile r) +// with the unchanged tc_gemm body (scheduler id b * 16 + r == tile id, exactly one tile per CTA) - so cluster b writes +// ALL h columns / ssq partial sums of rows [128 b, +128). Hand-off: every h TMA bulk store complete (wait_group 0 + +// fence.proxy.async), ssq atomics done, then a cluster barrier (release / acquire); the dependency is cluster-local +// (the hardware co-schedules a cluster), so no inter-CTA spin and no co-residency assumption. Phase 2: the unchanged +// router body on the same M tile (TMEM allocation kept, smem / mbarriers re-initialised). Numerics bit-identical to +// the two-launch path (same instructions per tile / row). The L2 discards of Wo16 / attn (formerly by the router's +// idle warp 11 after griddepcontrol.wait) are done without waiting: attn tile b by its own cluster after the barrier, +// Wo16 slice r by the last cluster arriving on a per-slice counter (sctr, zeroed by prep_qkv). +constexpr int MOR_SMEM = TC_SMEM_OPROJ > RT_SMEM ? TC_SMEM_OPROJ : RT_SMEM; +__global__ void __launch_bounds__(RT_THREADS, 1) oproj_router_kernel( + const __grid_constant__ CUtensorMap tA, const __grid_constant__ CUtensorMap tB0, const __grid_constant__ CUtensorMap tB1, + const __grid_constant__ CUtensorMap tB3, const __grid_constant__ CUtensorMap tB4, const __grid_constant__ TcArgs p, + const __grid_constant__ CUtensorMap tA32, // attn map with 64-row boxes (SW pair B halves) + const __grid_constant__ CUtensorMap tH, const __grid_constant__ CUtensorMap tBh, int T, const float* __restrict__ lnw, + const float* __restrict__ ssq, float eps, const float* __restrict__ wscale, int* __restrict__ topk_idx, + float* __restrict__ topk_w, int* __restrict__ counts, const __grid_constant__ sidew::ConvJob CJ, + int* __restrict__ sctr, const char* wo16, const char* attn, uint8_t* __restrict__ xn8, float* __restrict__ f8inv, __half* __restrict__ xn16, + int* __restrict__ btok, float* __restrict__ bw, const float* __restrict__ pfg, const float* __restrict__ pfu, + int pf_t0, int pf_t1, int pf_kb, int pf_krot) { + extern __shared__ uint8_t smem_raw[]; + const int bid = (int)(blockIdx.y * gridDim.x + blockIdx.x); + // L2 prefetch of the SECOND MoE wave (fused fp16 MoE gate/up items [pf_t0, pf_t1), T < 2048: one group per + // expert -> item t ~ (expert t / 12, n-tile t % 12 of 64 gate + 64 up rows)), first pf_kb k-blocks of each item's + // rotated k order (start (t * krot) % 32). Issued by the idle warps 10..13 (128 threads = 64 gate + 64 up rows) + // before phase 1; inputs only, fire-and-forget (a wrong guess only costs DRAM reads, results never depend on it). + if (pfg != nullptr && threadIdx.x >= 320 && threadIdx.x < 448) { + const int lt = (int)threadIdx.x - 320, r = lt & 63; + const float* base = lt < 64 ? pfg : pfu; + const int ncta = (int)(gridDim.x * gridDim.y); + for (int t = pf_t0 + bid; t < pf_t1; t += ncta) { + const int e = t / 12, nt = t - e * 12; + const char* row = reinterpret_cast(base + ((size_t)e * INTER + nt * 64 + r) * HID); + const int k0 = pf_krot > 0 ? (t * pf_krot) % (HID / 64) : 0; + const int n1 = k0 + pf_kb <= HID / 64 ? pf_kb : HID / 64 - k0; + asm volatile("cp.async.bulk.prefetch.L2.global [%0], %1;" ::"l"(row + k0 * 256), "r"((uint32_t)(n1 * 256)) : "memory"); + if (n1 < pf_kb) + asm volatile("cp.async.bulk.prefetch.L2.global [%0], %1;" ::"l"(row), "r"((uint32_t)((pf_kb - n1) * 256)) : "memory"); + } + } + // phase 1: o_proj tile bid (warps 0..9; warps 10..15 only join the CTA barriers) + const uint32_t tb = tc_gemm_dev(tA, tB0, tB1, tA32, tB3, tB4, p, bid, + (int)(gridDim.x * gridDim.y)); + // o_proj mbarriers (stage full/empty, accumulator tfull/tempty, epilogue slot barriers) invalidated before the + // router phase re-uses their smem (all phases completed: last CTA barrier of phase 1 passed) + if (threadIdx.x == 0) { + const uint32_t sb = (smem_u32(smem_raw) + 1023u) & ~1023u; + const uint32_t b0 = sb + TSTAGES * STAGE_BYTES; + for (int i = 0; i < 2 * 4 + 4; i++) asm volatile("mbarrier.inval.shared::cta.b64 [%0];" ::"r"(b0 + 8 * i) : "memory"); + for (int i = 0; i < 6; i++) asm volatile("mbarrier.inval.shared::cta.b64 [%0];" ::"r"(b0 + 128 + 8 * i) : "memory"); + for (int i = 0; i < 16; i++) asm volatile("mbarrier.inval.shared::cta.b64 [%0];" ::"r"(b0 + 512 + 8 * i) : "memory"); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // phase-1 generic smem writes vs phase-2 TMA writes + __threadfence(); + int old = 0; + if (sctr && threadIdx.x == 11 * 32) old = atomicAdd(sctr + blockIdx.x, 1); // this CTA's reads of Wo16 slice r are done + cluster_sync_all(); // h / ssq of M tile blockIdx.y complete (written by the 16 CTAs of this cluster) + router_dev(tH, tBh, tBh, T, lnw, ssq, eps, wscale, topk_idx, topk_w, counts, nullptr, nullptr, 0u, CJ, xn16, + xn8, f8inv, L2Discard{}, RtMerge{tb, old, wo16, attn}, btok, bw, p.out); // e4m3 xn2 rows for the FP8 MoE +} + +// ------------------------------------------------------------------ large-T MoE gate/up: fp16 with amortized +// in-kernel weight conversion. +// Work item = (M-tile group g, n-tile nt): a group is up to 4 consecutive 128-row M tiles of ONE expert, nt selects +// 64 gate rows + the matching 64 up rows (B operand N = 128: rows 0-63 gate, 64-127 up). The whole group shares +// every converted B stage: fp32 weights are read from DRAM and converted to fp16 exactly once per (group, nt), +// and each converted stage feeds up to 4 kind::f16 m128n128k16 x4 MMA chains (4 TMEM accumulators x 128 cols = +// 512 cols). Items ordered g-major / nt-minor so the 12 n-tile CTAs of one group run concurrently and share the +// group's fp16 A rows through L2. +// warp 0 : raw producer: TMA fp32 gate/up k-block (64 K = 2 boxes of 32 floats, 64 rows each) -> 32 KB raw +// stage (3-stage ring, 128B swizzle) +// warp 10 : A producer: TMA fp16 A tiles (128 rows x 64 K, 16 KB each, nm per stage) -> 2-stage ring +// warps 2-5 : converters: thread = B row r; reads raw row r of both boxes (256 B), writes the 128B-swizzled fp16 +// row (x 2^4) IN PLACE over box 0 row r (only this thread touches row r -> no cross-thread hazard) +// warp 1 : TMEM alloc (512) + single-thread MMA issuer +// warps 6-9, 11-14 : epilogue (8 warps): act = silu(g/16) * (u/16) for the group's rows, fp32 act[pos][nt*64 + c]. +// The 512-col accumulator set is single-buffered, so the epilogue is NOT overlapped with the next item's +// mainloop; two warps per TMEM lane quadrant (warps 6-9: act cols 0-31, warps 11-14: cols 32-63) halve +// its length, and both TMEM loads of a chunk are issued before one wait. +// DOWN=true instantiation (same pipeline, same warp roles): item = (group, down n-tile of 128 output columns); +// B = 128 Wd rows (one 128-row fp32 TMA box per 32 K, 2 boxes per 64-K stage, 2-stage raw ring), K = 768 +// (12 k-blocks), A = fp16 act rows written by the fp16 gate/up epilogue (act16 = 1). Epilogue (8 warps, 2 per TMEM +// lane quadrant, warp set c owns accumulator cols c*64..+63, both 32-col TMEM loads issued before one wait): +// acc/16 * routing weight, transposed per warp through a 32x16 smem slab and scatter-added into out[token] with +// coalesced red.global.add.v4.f32. The accumulator is released (acc_empty) right after the LAST TMEM load of the +// item, so the next item's MMAs overlap the final M tile's scatter-adds. +constexpr int GU_A_STAGE = 4 * 16384, GU_A_STAGES = 2; +constexpr int GU_RAW = 32768; +constexpr int GU_RAW_OFF = GU_A_STAGES * GU_A_STAGE; // 128 KB +constexpr int GU_THREADS = 480; +// per-instantiation geometry: gate/up 3 raw stages (224 KB), down 2 raw stages + 8 x 2 KB epilogue slabs +template struct GuCfg { + static constexpr int RAW_STAGES = DOWN ? 2 : 3; + static constexpr int BAR = GU_RAW_OFF + RAW_STAGES * GU_RAW; + static constexpr int STG = BAR + 256; // DOWN epilogue staging (16 KB) + static constexpr int SMEM = STG + (DOWN ? 8 * 2048 : 0) + 1024; + static constexpr int NT = DOWN ? HID / 128 : INTER / 64; // 16 / 12 n-tiles per group + static constexpr int KB = DOWN ? INTER / 64 : HID / 64; // 12 / 32 k-blocks +}; + +// Item -> (group g, n-tile nt). The groups of one expert (gfirst .. gfirst+ng-1) own the contiguous item range +// [gfirst*NT, (gfirst+ng)*NT); inside it items are nt-major / group-minor, so the ng groups that share the same +// expert weight n-tile are CONSECUTIVE queue entries -> run concurrently on neighbouring CTAs and the 2nd..ng-th +// fp32 weight reads hit L2 instead of DRAM. grp[3G+1+g] = (gfirst << 12) | ng. +__device__ __forceinline__ void gu_decode(const int* grp, int max_groups, int NT, int t, int& g, int& nt) { + const int pk = grp[3 * max_groups + 1 + t / NT]; + const int gfirst = pk >> 12, ng = pk & 4095; + const int loc = t - gfirst * NT; + nt = loc / ng; + g = gfirst + (loc - nt * ng); +} + +template +__global__ void __launch_bounds__(GU_THREADS, 1) moe_gateup_f16_kernel(const __grid_constant__ CUtensorMap tA, + const __grid_constant__ CUtensorMap tG, + const __grid_constant__ CUtensorMap tU, + const int* __restrict__ grp, int max_groups, + const int* __restrict__ offsets, + const int* __restrict__ counts, + float* __restrict__ act, int act16, + const int* __restrict__ perm_tok, + const float* __restrict__ perm_w) { + // DOWN: act = output (h + moe, scatter-added); A operand = fp16 act via tA, tG = Wd map (128-row boxes) + constexpr int GU_RAW_STAGES = GuCfg::RAW_STAGES, GU_BAR = GuCfg::BAR; + constexpr int GU_NT = GuCfg::NT, GU_KB = GuCfg::KB; + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = (uint8_t*)(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023); + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const uint32_t sbase = smem_u32(smem); + const uint32_t raw_full = sbase + GU_BAR; // [3] + const uint32_t raw_conv = raw_full + 24; // [3] 4 converter warps + const uint32_t raw_empty = raw_full + 48; // [3] + const uint32_t a_full = raw_full + 72; // [2] + const uint32_t a_empty = raw_full + 88; // [2] + const uint32_t acc_full = raw_full + 104; + const uint32_t acc_empty = raw_full + 112; // 8 epilogue warps + const uint32_t tslot = raw_full + 128; + volatile uint32_t* tslot_ptr = (volatile uint32_t*)(smem + GU_BAR + 128); + if (threadIdx.x == 0) { + for (int s = 0; s < GU_RAW_STAGES; s++) { + mbar_init(raw_full + 8 * s, 1); mbar_init(raw_conv + 8 * s, 4); mbar_init(raw_empty + 8 * s, 1); + } + for (int s = 0; s < GU_A_STAGES; s++) { mbar_init(a_full + 8 * s, 1); mbar_init(a_empty + 8 * s, 1); } + mbar_init(acc_full, 1); mbar_init(acc_empty, 8); + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tA) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tG) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tU) : "memory"); + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(tslot), "r"(512)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + tc_fence_before(); + __syncthreads(); + tc_fence_after(); + const uint32_t tbase = *tslot_ptr; + pdl_wait(); + pdl_trigger(); + const int num_items = grp[3 * max_groups] * GU_NT; + const uint32_t IDESC = (1u << 4) | ((128u >> 3) << 17) | ((128u >> 4) << 24); // f32 acc, f16 A/B, M=N=128 + + if (warp == 0) { + if (lane == 0) { + // ---------------- raw fp32 weight producer + int it = 0; + for (int t = blockIdx.x; t < num_items; t += gridDim.x) { + int g, nt; + gu_decode(grp, max_groups, GU_NT, t, g, nt); + const int r0 = DOWN ? grp[g] * HID + nt * 128 : grp[g] * INTER + nt * 64; + for (int kb = 0; kb < GU_KB; kb++, it++) { + const int s = it % GU_RAW_STAGES; + mbar_wait(raw_empty + 8 * s, ((it / GU_RAW_STAGES) & 1) ^ 1); + const uint32_t fb = raw_full + 8 * s, dst = sbase + GU_RAW_OFF + s * GU_RAW; + mbar_expect_tx(fb, GU_RAW); + if (DOWN) { + // Wd rows r0..r0+127 (128-row box): box 0 = k 0..31, box 1 = k 32..63 + tma_load_2d(dst, &tG, kb * 64, r0, fb); + tma_load_2d(dst + 16384, &tG, kb * 64 + 32, r0, fb); + continue; + } + tma_load_2d(dst, &tG, kb * 64, r0, fb); // box 0 (k 0..31): gate rows 0..63 + tma_load_2d(dst + 8192, &tU, kb * 64, r0, fb); // up rows -> B rows 64..127 + tma_load_2d(dst + 16384, &tG, kb * 64 + 32, r0, fb); // box 1 (k 32..63) + tma_load_2d(dst + 24576, &tU, kb * 64 + 32, r0, fb); + } + } + } + } else if (warp == 10) { + if (lane == 0) { + // ---------------- fp16 A producer (nm tiles of 128 rows per stage) + int it = 0; + for (int t = blockIdx.x; t < num_items; t += gridDim.x) { + int g, nt; + gu_decode(grp, max_groups, GU_NT, t, g, nt); + const int m0 = grp[max_groups + g], nm = grp[2 * max_groups + g]; + for (int kb = 0; kb < GU_KB; kb++, it++) { + const int s = it % GU_A_STAGES; + mbar_wait(a_empty + 8 * s, ((it / GU_A_STAGES) & 1) ^ 1); + const uint32_t fb = a_full + 8 * s, dst = sbase + s * GU_A_STAGE; + mbar_expect_tx(fb, (uint32_t)nm * 16384u); + for (int j = 0; j < nm; j++) tma_load_2d(dst + j * 16384, &tA, kb * 64, m0 + j * 128, fb); + } + } + } + } else if (warp == 1) { + if (lane == 0) { + // ---------------- MMA issuer + int it = 0, tc = 0; + for (int t = blockIdx.x; t < num_items; t += gridDim.x, tc++) { + int g, nt; + gu_decode(grp, max_groups, GU_NT, t, g, nt); + const int nm = grp[2 * max_groups + g]; + mbar_wait(acc_empty, (tc & 1) ^ 1); + tc_fence_after(); + for (int kb = 0; kb < GU_KB; kb++, it++) { + const int rs = it % GU_RAW_STAGES, as = it % GU_A_STAGES; + mbar_wait(raw_conv + 8 * rs, (it / GU_RAW_STAGES) & 1); + mbar_wait(a_full + 8 * as, (it / GU_A_STAGES) & 1); + tc_fence_after(); + const uint32_t bb = sbase + GU_RAW_OFF + rs * GU_RAW, ab = sbase + as * GU_A_STAGE; + for (int j = 0; j < nm; j++) { +#pragma unroll + for (int k = 0; k < 4; k++) + mma_f16_ss(tbase + j * 128, make_sdesc(ab + j * 16384 + k * 32), make_sdesc(bb + k * 32), + IDESC, (kb | k) != 0); + } + mma_commit(raw_empty + 8 * rs); + mma_commit(a_empty + 8 * as); + } + mma_commit(acc_full); + } + } + } else if (warp >= 2 && warp <= 5) { + // ---------------- converters: thread = B row r (0..127) + const int r = threadIdx.x - 64; + const int sw = r & 7; + int it = 0; + for (int t = blockIdx.x; t < num_items; t += gridDim.x) { + for (int kb = 0; kb < GU_KB; kb++, it++) { + const int s = it % GU_RAW_STAGES; + mbar_wait(raw_full + 8 * s, (it / GU_RAW_STAGES) & 1); + uint8_t* st = smem + GU_RAW_OFF + s * GU_RAW + r * 128; + // raw logical 16 B chunk j of box b (k = 32b + 4j) sits at physical chunk j ^ (r & 7) + uint4 v[16]; +#pragma unroll + for (int j = 0; j < 8; j++) { + v[j] = *reinterpret_cast(st + 16 * (j ^ sw)); + v[8 + j] = *reinterpret_cast(st + 16384 + 16 * (j ^ sw)); + } + // fp16 chunk c (k = 8c..8c+7) = raw chunks 2c, 2c+1, x 2^4; written at physical chunk c ^ (r & 7) +#pragma unroll + for (int c = 0; c < 8; c++) { + const uint4 a = v[2 * c], b = v[2 * c + 1]; + uint4 o; + o.x = pack_h2(__uint_as_float(a.x) * 16.f, __uint_as_float(a.y) * 16.f); + o.y = pack_h2(__uint_as_float(a.z) * 16.f, __uint_as_float(a.w) * 16.f); + o.z = pack_h2(__uint_as_float(b.x) * 16.f, __uint_as_float(b.y) * 16.f); + o.w = pack_h2(__uint_as_float(b.z) * 16.f, __uint_as_float(b.w) * 16.f); + *reinterpret_cast(st + 16 * (c ^ sw)) = o; + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // generic writes -> tcgen05.mma + __syncwarp(); + if (elect_one()) mbar_arrive(raw_conv + 8 * s); + } + } + } else if (DOWN) { + // ---------------- DOWN epilogue warps 6..9 / 11..14: TMEM lane quadrant q = warp % 4, col half c (64 cols) + const int q = warp & 3; + const int row = q * 32 + lane; + const int c = warp >= 11 ? 1 : 0; + const int ew = (warp >= 11 ? warp - 7 : warp - 6); // 0..7: staging slab index + float* stg = reinterpret_cast(smem + GuCfg::STG) + ew * 512; // 32 rows x 16 cols + int tc = 0; + for (int t = blockIdx.x; t < num_items; t += gridDim.x, tc++) { + int g, nt; + gu_decode(grp, max_groups, GU_NT, t, g, nt); + const int e = grp[g], m0 = grp[max_groups + g], nm = grp[2 * max_groups + g]; + const int mend = offsets[e] + counts[e]; + mbar_wait(acc_full, tc & 1); + tc_fence_after(); + for (int j = 0; j < nm; j++) { + const int pos = m0 + j * 128 + row; + const bool valid = pos < mend; + int tok = 0; float rw = 0.f; + if (valid) { tok = __ldg(perm_tok + pos); rw = __ldg(perm_w + pos) * 0.0625f; } // undo B x 2^4 + int rtok[4]; bool rval[4]; +#pragma unroll + for (int it = 0; it < 4; it++) { + const int r = it * 8 + (lane >> 2); + rtok[it] = __shfl_sync(0xffffffff, tok, r); + rval[it] = __shfl_sync(0xffffffff, (int)valid, r) != 0; + } + float a[64]; + const uint32_t ta = tbase + ((uint32_t)(q * 32) << 16) + j * 128 + c * 64; + tmem_ld32x2(ta, a, ta + 32, a + 32); + if (j == nm - 1) { // all TMEM reads of this item done -> accumulator free for the next item + tc_fence_before(); + __syncwarp(); + if (elect_one()) mbar_arrive(acc_empty); + } + const int n0 = nt * 128 + c * 64; +#pragma unroll + for (int hh = 0; hh < 4; hh++) { // 4 slabs of 16 columns + __syncwarp(); // previous slab fully read +#pragma unroll + for (int jj = 0; jj < 4; jj++) { // row = lane, group jj stored at slot jj ^ ((row>>1)&3) + const int slot = jj ^ ((lane >> 1) & 3); + *reinterpret_cast(stg + lane * 16 + slot * 4) = + make_float4(rw * a[hh * 16 + 4 * jj], rw * a[hh * 16 + 4 * jj + 1], + rw * a[hh * 16 + 4 * jj + 2], rw * a[hh * 16 + 4 * jj + 3]); + } + __syncwarp(); +#pragma unroll + for (int it = 0; it < 4; it++) { + const int r = it * 8 + (lane >> 2), gg = lane & 3; + const float4 v = *reinterpret_cast(stg + r * 16 + (gg ^ ((r >> 1) & 3)) * 4); + if (rval[it]) red_add_v4(act + (size_t)rtok[it] * HID + n0 + hh * 16 + gg * 4, v); + } + } + } + } + } else { + // ---------------- epilogue warps 6..9 / 11..14: TMEM lane quadrant q = warp % 4, act column half c + const int q = warp & 3; + const int row = q * 32 + lane; + const int c = warp >= 11 ? 1 : 0; + int tc = 0; + for (int t = blockIdx.x; t < num_items; t += gridDim.x, tc++) { + int g, nt; + gu_decode(grp, max_groups, GU_NT, t, g, nt); + const int e = grp[g], m0 = grp[max_groups + g], nm = grp[2 * max_groups + g]; + const int mend = offsets[e] + counts[e]; + mbar_wait(acc_full, tc & 1); + tc_fence_after(); + for (int j = 0; j < nm; j++) { + const int pos = m0 + j * 128 + row; + { + float gv[32], uv[32]; + const uint32_t ta = tbase + ((uint32_t)(q * 32) << 16) + j * 128 + c * 32; + tmem_ld32x2(ta, gv, ta + 64, uv); + if (pos < mend) { + float r[32]; +#pragma unroll + for (int i = 0; i < 32; i++) { + const float gg = gv[i] * 0.0625f, uu = uv[i] * 0.0625f; + r[i] = gg * __frcp_rn(1.f + __expf(-gg)) * uu; // silu(g) * u + } + if (act16) { + // fp16 act (A operand of the fp16 down GEMM); |act| << 65504, same 11-bit significand + uint4* dst = reinterpret_cast(reinterpret_cast<__half*>(act) + (size_t)pos * INTER + + nt * 64 + c * 32); +#pragma unroll + for (int i = 0; i < 4; i++) dst[i] = pack8_h(r + 8 * i); + } else { + float4* dst = reinterpret_cast(act + (size_t)pos * INTER + nt * 64 + c * 32); +#pragma unroll + for (int i = 0; i < 8; i++) + dst[i] = make_float4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); + } + } + } + } + tc_fence_before(); + __syncwarp(); + if (elect_one()) mbar_arrive(acc_empty); + } + } + tc_fence_before(); + __syncthreads(); + if (warp == 1) { + __syncwarp(); + tc_fence_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tbase), "r"(512)); + } +} + +#ifdef MF_PROBE +__device__ unsigned long long g_mf_probe[160][8]; +#define MFPW(i, ...) do { const long long t0_ = clock64(); __VA_ARGS__; atomicAdd(&g_mf_probe[blockIdx.x][i], (unsigned long long)(clock64() - t0_)); } while (0) +#else +#define MFPW(i, ...) do { __VA_ARGS__; } while (0) +#endif +// test-first wait (no suspend round trip when the phase already completed) for the MoE MMA issuer's per-k-block +// ta_full / a_full waits (critical-path consumer: every k-block of the TS MMA chain waits on both) +__device__ __forceinline__ void mbar_wait_tf(uint32_t a, uint32_t parity) { + if (!mbar_test(a, parity)) mbar_wait_hint(a, parity); +} +template +__device__ __forceinline__ uint4 lds128(uint32_t a) { + uint4 v; + asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4+%5];" : "=r"(v.x), "=r"(v.y), "=r"(v.z), "=r"(v.w) : "r"(a), "n"(OFF)); + return v; +} +constexpr int MF16_RAW_STAGES = 3; // raw fp32 weight ring depth (raw_full / raw_empty barriers [3]) +struct RawRing { + int s = 0; + uint32_t bits = 0; + __device__ __forceinline__ void next(bool, int& st, uint32_t& ph) { + st = s; + ph = (bits >> st) & 1u; + bits ^= 1u << st; + s = st == MF16_RAW_STAGES - 1 ? 0 : st + 1; + } +}; +constexpr int MF16_A_STAGES = 2, MF16_A_STAGE = 3 * 16384; +constexpr int MF16_RAW_OFF = MF16_A_STAGES * MF16_A_STAGE; // 96 KB +constexpr int MF16_STG = MF16_RAW_OFF + MF16_RAW_STAGES * GU_RAW; // down epilogue staging (8 x 2 KB) +constexpr int MF16_BAR = MF16_STG + 8 * 2048; +constexpr int MF16_SMEM = MF16_BAR + 512 + 1024; +static_assert(MF16_RAW_STAGES <= 3, "raw barriers sized [3]"); +static_assert(MF16_SMEM <= 232448, "fused fp16 MoE smem"); +constexpr int MF16_TA = 384; // TMEM column of A stage 0 (4 stages x 32 cols) +#ifndef MF16_KROT +#define MF16_KROT 7 // fused fp16/FP8 MoE rotated k order +#endif +#ifndef MF_LDS_AHEAD +#define MF_LDS_AHEAD 0 +#endif +constexpr int MF16_GNT = INTER / 64, MF16_DNT = HID / 128; +constexpr int MF16_READY = 8 * MF16_GNT; // epilogue warps x gate/up n-tiles per group +// 16 warps: the 15 roles of moe_gateup_f16_kernel + warp 15, the second A-gather warp (warps 10 and 15 gather the +// gate/up A rows with cp.async; warp 10 lane 0 alone TMA-loads the down A (act) tiles) +constexpr int MF16_THREADS = 512; +constexpr int MF16_GATHER_ARRIVALS = 64 + 1; // a_full count: 64 gather threads (cp.async noinc) + 1 (lane 0 of warp 10) + + +// knob-templated fused fp16 MoE. GM = max M tiles per token group (token stage = GM x 16 KB), +// RS = raw fp32 weight ring stages (32 KB each), AS = token (B operand) ring stages. Smem layout per MfCfg. +// F8C == 2 (all-FP8): every token tile (gate/up e4m3 rows, down e5m2 act) is 128 rows x 64 B = 8 KB +template struct MfCfg { + static constexpr int A_STAGE = GM * (F8C == 2 ? 8192 : 16384); + static constexpr int RAW_OFF = AS * A_STAGE; + static constexpr int STG = RAW_OFF + RS * GU_RAW; + // GM == 4 (all-FP8 only): 4 accumulator units fill TMEM, so the converted weight A operand lives in a 2-stage + // SMEM ring (128 rows x 64 B e5m2, 64B swizzle, 8 KB per 64-K block) and the MMAs are SS instead of TS + // (GM 4, AS 3, ASN 3) halves the per-warp down-epilogue staging slab (8 tokens x 32 cols = 1 KB) so the + // freed 8 KB holds a THIRD converted-weight A stage (converters run one more k-block ahead of the MMAs) + static constexpr int STG_W = (GM == 4 && AS == 3 && ASN == 3) ? 1024 : 2048; + static constexpr int ASM_OFF = STG + 8 * STG_W; + // ASN > 0 (all-FP8 only): converted weight A in an ASN-stage SMEM ring (SS MMAs), 4 TMEM accumulator units + static constexpr int BAR = ASM_OFF + ASN * 8192; + static constexpr int SMEM = BAR + 512 + 1024; + static_assert(SMEM <= 232448, "fused fp16 MoE smem"); + static_assert(RS >= 2 && RS <= 6 && AS >= 2 && AS <= 3 && GM >= 1 && GM <= 4 && (GM < 4 || (F8C == 2 && ASN > 0)) && (ASN == 0 || F8C == 2), "knob range"); +}; +template struct RawRingT { + int s = 0; + uint32_t bits = 0; + __device__ __forceinline__ void next(bool, int& st, uint32_t& ph) { + st = s; + ph = (bits >> st) & 1u; + bits ^= 1u << st; + s = st == RS - 1 ? 0 : st + 1; + } +}; +constexpr int MF_SCAP = 288; +constexpr int MF_STAB_BYTES = ((7 * MF_SCAP + 2 + 16 + 256) * 4 + 255) & ~255; +constexpr int MF_STAB_INTS = MF_STAB_BYTES / 4; +// TCP (CV8 all-FP8 GM 2 self-table variant, 2048 <= T < 3500): converted e5m2 weight A staged in smem (3 x 8 KB, +// no-swizzle K-major core-matrix layout, 128 rows x 32 B per K half) + 64 B barriers, copied to the TMEM A stage by the +// MMA thread with tcgen05.cp 128x256b (async, in-order with its MMAs) instead of per-thread tcgen05.st +constexpr int MF_TCP_NS = 3; +constexpr int MF_TCP_BYTES = 128 + MF_TCP_NS * 8192; +static_assert(MfCfg<2, 4, 2>::SMEM + MF_STAB_BYTES + 4096 <= 232448, "v433 meta smem"); +// CV8: 4 extra converter warps 16..19 (640 threads). Converter warp set cs (0: warps 2-5, 1: warps 16-19) converts raw +// box cs (K 32cs..32cs+31 of each 64-K block) into its half of the TMEM A stage: all-FP8 TS-A variants +// (2048 <= T < 6000) -> e5m2x4 columns 8cs..8cs+7; T < 2048 fp16 self-table variant -> fp16/bf16 pair columns +// 16cs..16cs+15. Two independent half-length converter chains per TMEM lane quadrant. +template +__global__ void __launch_bounds__((CV8 || (GM == 4 && F8 == 2)) ? 640 : MF16_THREADS, 1) moe_f16_fused_kernel( + const __half* __restrict__ xn16, const __grid_constant__ CUtensorMap tG, + const __grid_constant__ CUtensorMap tU, const __grid_constant__ CUtensorMap tX, + const __grid_constant__ CUtensorMap tD, int* grp_in, int max_groups_in, + const int* __restrict__ offsets, const int* __restrict__ counts, __half* __restrict__ act, + float* __restrict__ out, const int* __restrict__ perm_tok, const float* __restrict__ perm_w, + int* __restrict__ qctr, const float* __restrict__ f8inv, int pf_ng, int krot, int tsilu, + const __grid_constant__ L2Discard mdl, const __grid_constant__ CUtensorMap tE, const int* __restrict__ pcnt, int pcap) { + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = (uint8_t*)(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023); + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + // NGW cp.async token-gather warps (10, 15, or 16..19 for the GM = 4 all-FP8 MALT layout) + constexpr bool MALT = GM == 4 && F8 == 2; + static_assert(!(MALT && CV8), "MALT / CV8 layouts are exclusive"); + constexpr int NGW = MALT ? 4 : 2; + constexpr int MGL = MALT ? 16 : 10; // lead gather warp (down-item act TMA + the extra a_full arrival) + constexpr uint32_t GARR = 32u * NGW; + const uint32_t sbase = smem_u32(smem); + const uint32_t bar0 = sbase + (MfCfg::BAR); + // ASM (GM == 4): A (converted weights) in a TAS = 2 stage SMEM ring; NU = 4 accumulator units of 128 cols (else 3) + constexpr bool ASM = TAS <= 3; // SMEM A ring (TAS = 2 or 3 stages), SS fp8 MMAs + constexpr int NU = ASM ? 4 : 3; + static_assert(ASM ? (TAS >= 2 && F8 == 2) : (TAS == 4 || (TAS == 8 && F8 == 2)) && GM < 4, "A ring config"); + constexpr int TAW = 128 / TAS; // TMEM columns per A stage + constexpr bool TCP = CV8 && F8 == 2 && !ASM && SELF && GM == 2 && TAS == 4; + static_assert(!TCP || MfCfg::SMEM + MF_STAB_BYTES + MF_TCP_BYTES <= 232448, "tcp smem"); + // TCP: [cp_full 3][cp_empty 3] barriers at tcp0, staging stage s at tcp0 + 128 + 8 KB s (K half h at + 4 KB h) + const uint32_t tcp0 = bar0 + 512 + MF_STAB_BYTES; + const uint32_t cp_full = tcp0, cp_empty = tcp0 + 24; + const uint32_t raw_full = bar0 + 392; // [RS <= 6] TMA landed + const uint32_t raw_empty = bar0 + 440; // [RS <= 6] 4 converter warps finished reading the raw stage + const uint32_t a_full = bar0 + 216; // [3] token tiles (B operand) in smem + // token ring and converted-weight A ring advance in lockstep (stage = running k-block + // count % 3 in every role) and both are released by the same MMA completion -> ONE commit per k-block on ta_empty + // releases both stages (token gather warps wait on ta_empty); the separate a_empty barrier / commit are dropped + constexpr bool AEM = MALT && AS == TAS; + const uint32_t a_empty = AEM ? bar0 + 328 : bar0 + 240; // [3] (AEM: aliases ta_empty) + const uint32_t accf = bar0 + 80; // [3] accumulator unit full (MMA commit) + const uint32_t acce = bar0 + 104; // [3] accumulator unit drained (8 epilogue warps) + // unit 3 (NU = 4 only) barriers at bar0 + 488 / 496 + auto acc_full = [&](int h) -> uint32_t { return h < 3 ? accf + 8u * h : bar0 + 488; }; + auto acc_empty = [&](int h) -> uint32_t { return h < 3 ? acce + 8u * h : bar0 + 496; }; + const uint32_t ta_full = bar0 + 264; // [TAS <= 8] TMEM A stage written (4 converter warps) + const uint32_t ta_empty = bar0 + 328; // [TAS <= 8] TMEM A stage consumed (MMA commit) + const uint32_t tslot = bar0 + 128; + const uint32_t it_full = bar0 + 136; // [4] + const uint32_t it_empty = bar0 + 168; // [4] 15 consumer warps + volatile uint32_t* tslot_ptr = (volatile uint32_t*)(smem + (MfCfg::BAR) + 128); + volatile int* item_slot = (volatile int*)(smem + (MfCfg::BAR) + 200); // int[4] + if (threadIdx.x == 0) { + for (int s = 0; s < RS; s++) { + mbar_init(raw_full + 8 * s, 1); mbar_init(raw_empty + 8 * s, CV8 ? 8 : 4); + } + for (int s = 0; s < AS; s++) { + mbar_init(a_full + 8 * s, GARR); if (!AEM) mbar_init(a_empty + 8 * s, 1); + } + for (int h = 0; h < NU; h++) { mbar_init(acc_full(h), 1); mbar_init(acc_empty(h), 8); } + for (int s = 0; s < TAS; s++) { mbar_init(ta_full + 8 * s, CV8 ? 8 : 4); mbar_init(ta_empty + 8 * s, 1); } + if (TCP) for (int s = 0; s < MF_TCP_NS; s++) { mbar_init(cp_full + 8 * s, 8); mbar_init(cp_empty + 8 * s, 1); } + for (int i = 0; i < 4; i++) { mbar_init(it_full + 8 * i, 1); mbar_init(it_empty + 8 * i, CV8 ? 19 : 13 + NGW); } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tG) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tU) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tX) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tD) : "memory"); + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(tslot), "r"(512)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + tc_fence_before(); + __syncthreads(); + tc_fence_after(); + const uint32_t tbase = *tslot_ptr; + int t_pre = 0; + if (!(F8 == 0 && SELF) && warp == 0) { + if (elect_one()) t_pre = atomicAdd(qctr, 1); + t_pre = __shfl_sync(0xffffffffu, t_pre, 0); + } + if (warp == (MALT ? 8 : 6) && pf_ng > 0) { + // pf_ng = expected groups per expert x 256 (fixed point, host normal approximation): item t of the + // expert-major queue -> expert floor(256 t / (12 ng256)), n-tile floor((256 t mod 12 ng256) / ng256) + const int per = pf_ng * MF16_GNT; + const int b256 = (int)blockIdx.x * 256; + const int e0 = b256 / per, nt0 = (b256 - e0 * per) / pf_ng; + // no fp32 prefetch for experts pre-converted to e5m2 by the attention kernel (attention completed + // before this grid could launch: o_proj / router PDL chain) + const bool epre = MALT && pcnt != nullptr && e0 < pcap && __ldcg(pcnt + e0) >= 2 * INTER; + if (e0 < NEXP && !epre) { + const CUtensorMap* pm = (lane & 2) ? &tU : &tG; +#pragma unroll + for (int rd = 0; rd < 2; rd++) + if ((lane & 1) == 0) { // 3D box covers both 32-K halves of the k-block + const int kz = 2 * (((lane >> 2) + 8 * rd + mf1_rot((int)blockIdx.x, HID / 64, krot)) % (HID / 64)); + // weight prefetch with an L2 EVICT_FIRST hint (same policy as the real weight + // TMA loads) so the read-once weight stream does not displace the L2-resident xn8 / act / out lines + // EVICT_FIRST weight prefetch for every fused-MoE variant (was MALT only) + asm volatile("cp.async.bulk.prefetch.tensor.3d.L2.global.tile.L2::cache_hint [%0, {%1, %2, %3}], %4;" ::"l"((uint64_t)pm), + "r"(0), "r"(e0 * INTER + nt0 * 64), "r"(kz), "l"(l2_policy_evict_first()) : "memory"); + } + } + __syncwarp(); + } + constexpr bool PREW = F8 == 0 && SELF && !MALT; + const uint32_t pre_full = bar0 + 0; // [RS <= 6] (bar0 + [0, 80) unused otherwise) + int pre_n = 0, pre_t = -1, pre_r0 = -1; + if constexpr (PREW) { + if (threadIdx.x == 0) { + for (int s = 0; s < RS; s++) mbar_init(pre_full + 8 * s, 1); + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + } + if (warp == 0) { + const int Gd = (int)gridDim.x, Ps = 2 * Gd; + const int tg = (blockIdx.x & 1) ? Ps + ((int)blockIdx.x >> 1) : ((int)blockIdx.x >> 1); + const int eg = tg / MF16_GNT, ntg = tg - eg * MF16_GNT; + if (eg < NEXP) { + pre_n = RS < HID / 64 ? RS : HID / 64; + pre_t = tg; + pre_r0 = eg * INTER + ntg * 64; + const int rot = mf1_rot(tg, HID / 64, krot); + const uint64_t wpol = l2_policy_evict_first(); + __syncwarp(); + if (elect_one()) { + for (int s = 0; s < pre_n; s++) { + const int kr = s + rot < HID / 64 ? s + rot : s + rot - HID / 64; + const uint32_t fb = pre_full + 8 * s, dst = sbase + (MfCfg::RAW_OFF) + s * GU_RAW; + mbar_expect_tx(fb, GU_RAW); + tma_load_3d_hint(dst, &tG, 0, pre_r0, 2 * kr, fb, wpol); + tma_load_3d_hint(dst + 16384, &tU, 0, pre_r0, 2 * kr, fb, wpol); + } + } + __syncwarp(); + } + } + } + CHN(13, 0); + // L2 discard of attn / Wo16 (dead: their only reader o_proj completed before the router - + // this kernel's PDL predecessor - passed its griddepcontrol.wait and triggered this launch; next writers come + // after this kernel in the next forward). Runs in the otherwise idle pre-wait window, off the router mainloop. + if (mdl.n > 0) { + const unsigned long long nth = (unsigned long long)gridDim.x * blockDim.x; + const unsigned long long gt = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x; + for (int r = 0; r < mdl.n; r++) { + const char* base = reinterpret_cast(mdl.p[r]); + const unsigned long long nl = (mdl.bytes[r] + 127) >> 7; + for (unsigned long long i = gt; i < nl; i += nth) + asm volatile("discard.global.L2 [%0], 128;" ::"l"(base + (i << 7)) : "memory"); + } + } + pdl_wait(); + CHN(13, 1); + pdl_trigger(); + const int* grp = grp_in; + int max_groups = max_groups_in; + if constexpr (SELF) { + constexpr bool STAB_SMEM = MfCfg::SMEM + MF_STAB_BYTES <= 232448; + int* tab = STAB_SMEM ? reinterpret_cast(smem + (MfCfg::BAR) + 512) + : grp_in + (size_t)blockIdx.x * MF_STAB_INTS; + int* s_wsum = tab + 7 * MF_SCAP + 2; // [4 warps][2] + int* lpk = tab + 7 * MF_SCAP + 20; // [128] packed LPT keys (overlays lptn[2..130), only read with tsilu & 4) + const int SC = MF_SCAP, bstride = tsilu >> 8; + const int tid = threadIdx.x, ln = tid & 31, wid = tid >> 5; + int c0 = 0, nt0 = 0, ng0 = 0, i0s = 0, i1s = 0; + if (tid < NEXP) { + c0 = __ldg(counts + tid); + nt0 = (c0 + 127) >> 7; + ng0 = (nt0 + GM - 1) / GM; + if constexpr (F8 == 2 && CV8 && GM == 3) + if (nt0 >= 2 && ng0 < 2 && 32 * c0 > 3 * bstride) ng0 = 2; + i0s = c0; i1s = ng0; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int y0 = __shfl_up_sync(0xffffffffu, i0s, o), y1 = __shfl_up_sync(0xffffffffu, i1s, o); + if (ln >= o) { i0s += y0; i1s += y1; } + } + if (ln == 31) { s_wsum[2 * wid] = i0s; s_wsum[2 * wid + 1] = i1s; } + // (lptn is only read by the LPT rank: replaced by the packed lpk copy, which overlays it) + // packed (nt0 << 8 | ng0) copy for the LPT rank (16 B aligned at tab + 7 SC + 20; LPT order is only + // host-enabled for 3500 <= T < 6000 -> nt0 <= ceil(T / 128) <= 47, ng0 <= nt0 < 256: exact packing) + if (tsilu & 4) lpk[tid] = (nt0 << 8) | ng0; + } + __syncthreads(); + if (tid < NEXP) { + int b0 = 0, b1 = 0, t1 = 0; +#pragma unroll + for (int ww = 0; ww < 4; ww++) { + if (ww < wid) { b0 += s_wsum[2 * ww]; b1 += s_wsum[2 * ww + 1]; } + t1 += s_wsum[2 * ww + 1]; + } + const int off = b0 + i0s - c0; + int goff = b1 + i1s - ng0; + if (tsilu & 4) { + // LPT group order (same as moe_scatter_kernel lpt): expert ranges by descending M-tile count, ties -> + // lower expert index + // 32 x LDS.128 of packed keys instead of 256 scalar LDS (same sum, integer -> identical) + goff = 0; + const int4* lk4 = reinterpret_cast(lpk); +#pragma unroll 8 + for (int i4 = 0; i4 < NEXP / 4; i4++) { + const int4 v4 = lk4[i4]; + const int vv[4] = {v4.x, v4.y, v4.z, v4.w}; +#pragma unroll + for (int jj = 0; jj < 4; jj++) { + const int e2 = 4 * i4 + jj, n2 = vv[jj] >> 8; + if (n2 > nt0 || (n2 == nt0 && e2 < tid)) goff += vv[jj] & 255; + } + } + } + if (tid == 0) tab[3 * SC] = t1; + int tstart = 0; + for (int gi = 0; gi < ng0; gi++) { // same balanced split as moe_scatter_kernel + const int gidx = goff + gi; + int nm = nt0 / ng0 + (gi < nt0 % ng0 ? 1 : 0); + int r0 = off + tstart * 128, re = off + c0; + if (GM == 4 && ng0 == 2) { + // split expert (513..1024 rows, nt0 = 5..8 M tiles) -> TILE-aligned split: first group = + // ceil(nt0 / 2) full 128-row tiles, second = the rest (<= 4 tiles). Total token tiles stay nt0 (the + // row-balanced halves produced nt0 + 1 tiles, i.e. one more partial MMA set per k-block and + // one more epilogue tile per item); both groups of the expert are consecutive queue items per + // n-tile (gu_decode), so the second weight read overlaps the first (L2 hit). Per-token math identical. + const int hh = 128 * ((nt0 + 1) >> 1); + r0 = gi == 0 ? off : off + hh; + re = gi == 0 ? off + hh : off + c0; + nm = (re - r0 + 127) >> 7; + } + tab[gidx] = tid; + tab[SC + gidx] = r0; + tab[2 * SC + gidx] = nm; + tab[3 * SC + 1 + gidx] = (goff << 12) | ng0; + tab[5 * SC + 2 + gidx] = re; + tab[6 * SC + 2 + gidx] = tid * bstride - off; + tstart += nm; + } + } + __syncthreads(); + grp = tab; + CHN(6, 0); + max_groups = SC; + } + // bucket index adjustment of group g (0 without SELF: perm_tok / perm_w indexed by sorted row) + auto padj = [&](int g) -> int { return SELF ? grp[6 * max_groups + 2 + g] : 0; }; + const int ngroups = grp[3 * max_groups]; + const int NGU = ngroups * MF16_GNT; + const int total = NGU + ngroups * MF16_DNT; + int* ready = qctr + 1; + const uint32_t IDESC = (1u << 4) | ((128u >> 3) << 17) | ((128u >> 4) << 24); // f32 acc, f16 A/B, M=N=128 + + auto decode = [&](int t, bool& dn, int& g, int& nt) { + dn = t >= NGU; + if (dn) gu_decode(grp, max_groups, MF16_DNT, t - NGU, g, nt); + else gu_decode(grp, max_groups, MF16_GNT, t, g, nt); + }; + // item-ring waits (it_full / it_empty) test-first (mbar_wait_tf), no suspend round trip when published + // consumer side of the item ring: every lane waits, lane 0 releases the slot for the warp + auto get_item = [&](int ic) -> int { + const int slot = ic & 3; + mbar_wait_tf(it_full + 8 * slot, (ic >> 2) & 1); + const int t = item_slot[slot]; + __syncwarp(); + if (elect_one()) mbar_arrive(it_empty + 8 * slot); + return t; + }; + // per-item group metadata (g | nt | nm packed, m0, mend, bucket adj, expert) resolved ONCE + // by the producer warp (dependent global group-table loads, off the consumers' critical path: it runs up to 4 + // items ahead) and published with the item ticket in smem (bar0 + [0, 80): 4 slots x 5 ints, unused by MALT). + // Consumers read it before releasing the item slot. Same values -> numerics identical. + volatile int* item_meta = (volatile int*)(smem + (MfCfg::BAR)); + auto meta_glob = [&](int t, bool& dn, int& g, int& nt, int& nm, int& m0, int& mend) { + decode(t, dn, g, nt); + m0 = grp[max_groups + g]; nm = grp[2 * max_groups + g]; + mend = grp[5 * max_groups + 2 + g]; + }; + auto get_item_m = [&](int ic, bool& dn, int& g, int& nt, int& nm, int& m0, int& mend, int& adj) -> int { + const int slot = ic & 3; + mbar_wait_tf(it_full + 8 * slot, (ic >> 2) & 1); + const int t = item_slot[slot]; + if (MALT && t < total) { + const int pk = item_meta[5 * slot]; + m0 = item_meta[5 * slot + 1]; mend = item_meta[5 * slot + 2]; adj = item_meta[5 * slot + 3]; + g = pk >> 8; nt = (pk >> 4) & 15; nm = pk & 15; dn = t >= NGU; + } + __syncwarp(); + if (elect_one()) mbar_arrive(it_empty + 8 * slot); + if (!MALT && t < total) { meta_glob(t, dn, g, nt, nm, m0, mend); adj = padj(g); } + return t; + }; + + // WG1 = converters (4..7): 128; WG2 / WG3 = epilogue column set 0 / 1 (8..11 / 12..15): 112 + // (128 x (56 + 72 + 128 + 2 x 112) = 61440 = 640 x 96 at launch) + if (warp == 0 || warp == 1 || (MALT && warp < 4)) { + if constexpr (MALT) asm volatile("setmaxnreg.dec.sync.aligned.u32 56;\n" ::: "memory"); + if (warp == 0) { + { + // ---------------- queue fetch + raw fp32 weight producer (whole warp loops; lane 0 fetches + broadcasts + // the queue item, one elect.sync lane publishes it and issues expect_tx + TMA) + // expert weights are a read-once stream: L2 EVICT_FIRST so they do not evict act / xn16 / out lines + const uint64_t wpol = l2_policy_evict_first(); + RawRingT ring; + // experts whose gate/up rows were fully pre-converted to e5m2 (counter 1536) by the attention + // kernel's idle warps: 64-bit mask (pcap <= 64), gate/up items TMA-load 8 KB e5m2 instead of 32 KB fp32 + uint64_t pmask = 0ull; + if (MALT && pcnt != nullptr) { + const bool p0 = lane < pcap && __ldcg(pcnt + lane) >= 2 * INTER; + const bool p1 = lane + 32 < pcap && __ldcg(pcnt + lane + 32) >= 2 * INTER; + pmask = (uint64_t)__ballot_sync(0xffffffffu, p0) | ((uint64_t)__ballot_sync(0xffffffffu, p1) << 32); + asm volatile("fence.proxy.async.global;" ::: "memory"); // generic e5m2 scratch writes -> TMA reads + } + // split first wave by blockIdx parity. The first ~2 x grid + // gate/up items were L2-prefetched (attention / o_proj phases). Even CTAs statically take L2-resident items + // [0, H); odd CTAs statically take DRAM-streamed items [P, P + O) with P = 2 x grid (beyond the prefetched + // range), so the DRAM stream runs at full rate from MoE t = 0 while L2 hits are consumed concurrently. The + // dynamic queue (position j) then walks the remaining items in ascending order: [H, P), then [P + O, total). + // The map is monotone and the static items are all gate/up items (P + O <= NGU), grabbed at kernel start by + // co-resident CTAs -> every down-item dependency is still on an item grabbed earlier (no deadlock). + const int Gd = (int)gridDim.x, Hs = (Gd + 1) >> 1, Os = Gd >> 1, Ps = 2 * Gd; + const bool split = F8 == 0 && SELF && Ps + Os <= NGU; + for (int ic = 0;; ic++) { + int t0 = 0; + const bool pre0 = !(F8 == 0 && SELF) && ic == 0; // ticket fetched pre-wait + const bool nsst = F8 == 0 && SELF && !split; + if (!((split || nsst) && ic == 0) && !pre0 && elect_one()) t0 = atomicAdd(qctr, 1); + int t = pre0 ? t_pre : __shfl_sync(0xffffffffu, t0, 0); + if (nsst) t = ic == 0 ? (int)blockIdx.x : Gd + t; + if (split) { + if (ic == 0) t = (blockIdx.x & 1) ? Ps + ((int)blockIdx.x >> 1) : ((int)blockIdx.x >> 1); + else t = t < Ps - Hs ? Hs + t : Ps + Os + (t - (Ps - Hs)); + } + const int slot = ic & 3; + bool pdn = false; int pg = 0, pnt = 0, pnm = 0, pm0 = 0, pme = 0, pad = 0, pe = 0; + if (MALT && t < total) { meta_glob(t, pdn, pg, pnt, pnm, pm0, pme); pad = padj(pg); pe = grp[pg]; } + const bool prei = MALT && !pdn && pe < pcap && ((pmask >> (pe & 63)) & 1ull) != 0; + mbar_wait_tf(it_empty + 8 * slot, ((ic >> 2) & 1) ^ 1); + __syncwarp(); + if (elect_one()) { + item_slot[slot] = t; + if (MALT && t < total) { + item_meta[5 * slot] = (pg << 8) | (pnt << 4) | pnm; + item_meta[5 * slot + 1] = pm0; item_meta[5 * slot + 2] = pme; + item_meta[5 * slot + 3] = pad; item_meta[5 * slot + 4] = pe | (prei ? (1 << 16) : 0); + } + mbar_arrive(it_full + 8 * slot); + } + __syncwarp(); + // speculative pre-wait stages always landed before reuse / CTA exit + if (PREW && ic == 0) for (int s = 0; s < pre_n; s++) mbar_wait_tf(pre_full + 8 * s, 0); // sleep (energy) instead of hot spin + if (t >= total) break; + bool dn; int g, nt; + if (MALT) { dn = pdn; g = pg; nt = pnt; } else decode(t, dn, g, nt); + const int ex = MALT ? pe : grp[g]; + const int r0 = dn ? ex * HID + nt * 128 : ex * INTER + nt * 64; + const int pre_ok = (PREW && ic == 0 && !dn && t == pre_t && r0 == pre_r0) ? pre_n : 0; + if (F8 == 0 && SELF && dn) { + // down item whose group's gate/up items are not all done yet -> the raw + // ring (RS stages) fills and stalls until the act acquire; L2-prefetch the item's WHOLE Wd tile + // (128 rows x 768 fp32 = 24 boxes of 32 cols, one per lane) so DRAM keeps streaming across the + // gate/up -> down transition. Weights are inputs; prefetch only, numerics unchanged. + int rv = 0; + if (lane == 0) asm volatile("ld.relaxed.gpu.global.b32 %0, [%1];" : "=r"(rv) : "l"(ready + g) : "memory"); + rv = __shfl_sync(0xffffffffu, rv, 0); + if (rv < MF16_READY && lane < INTER / 64) + asm volatile("cp.async.bulk.prefetch.tensor.3d.L2.global.tile.L2::cache_hint [%0, {%1, %2, %3}], %4;" ::"l"((uint64_t)&tD), + "r"(0), "r"(r0), "r"(2 * lane), "l"(wpol) : "memory"); // Wd read once -> EVICT_FIRST + __syncwarp(); + } + const int KB = dn ? INTER / 64 : HID / 64; + const int rot = mf1_rot(t, KB, krot); // rotated k-block order per item (see mf1_rot) + for (int kb = 0; kb < KB; kb++) { + const int kr = kb + rot < KB ? kb + rot : kb + rot - KB; // rotated k-block + int s; uint32_t ph; + ring.next(dn, s, ph); + MFPW(0, { if constexpr (MALT) mbar_wait_tf(raw_empty + 8 * s, ph ^ 1); else mbar_wait_hint(raw_empty + 8 * s, ph ^ 1); }); // MALT producer test-first + suspend-hinted wait (energy: no hot polling, T>=6000 clock-bound) + const uint32_t fb = raw_full + 8 * s, dst = sbase + (MfCfg::RAW_OFF) + s * GU_RAW; + __syncwarp(); + if (kb < pre_ok) { // stage already landed (pre-wait TMA, verified item): forward it + if (elect_one()) mbar_arrive(fb); + __syncwarp(); + continue; + } + if (elect_one()) { + mbar_expect_tx(fb, prei ? 8192u : (uint32_t)GU_RAW); + if (prei) { + // e5m2 gate rows (64 x 64 B, 64B swizzle) at +0, up rows at +4 KB (row r at 64 r) + tma_load_2d_hint(dst, &tE, kr * 64, r0, fb, wpol); + tma_load_2d_hint(dst + 4096, &tE, kr * 64, pcap * INTER + r0, fb, wpol); + } else if (dn) { + // Wd rows r0..r0+127 (128-row box): box 0 = k 0..31, box 1 = k 32..63 + // ONE 3D box per k-block: 128 Wd rows x 64 fp32 K (half h at +16 KB h) + tma_load_3d_hint(dst, &tD, 0, r0, 2 * kr, fb, wpol); + } else { + // gate box (64 rows x 64 K, half h at +8 KB h) at +0, up box at +16 KB + tma_load_3d_hint(dst, &tG, 0, r0, 2 * kr, fb, wpol); + tma_load_3d_hint(dst + 16384, &tU, 0, r0, 2 * kr, fb, wpol); + } + } // elect_one + __syncwarp(); + } + } + } + } else if (warp == 1) { + { + // ---------------- MMA issuer (swap-AB, TS form; whole warp loops, elect.sync lane issues MMA + commit): A = converted WEIGHT tile read from TMEM A stage + // it % 4 (M = 128 weight rows, 32 cols = 64 K), B = token tile j from smem (N = 128). Accumulator D^T: + // TMEM lane = weight row, column r of unit (uc + j) % 3 = token row r of token tile j. + // Accumulator units form a 3-entry ring (uc = running count of unit uses); each unit is waited for + // lazily right before its first MMA (kb = 0), so the next item's MMAs overlap this item's epilogue as + // soon as units drain. + int it = 0, uc = 0; + // incremental ring state: token-tile stage as (it % 3) + its parity aph, TMEM A stage tas (it % 4) + taph + int as = 0, tas = 0; + uint32_t aph = 0, taph = 0; + int cps = 0; uint32_t cpph = 0; // TCP staging ring stage + parity + const uint64_t bdesc0 = make_sdesc(sbase); // stage s descriptor = bdesc0 + s * (stage bytes >> 4) + const uint64_t bdesc8 = make_sdesc64(sbase); // FP8 gate/up token tiles: 64 B rows, 64B swizzle + const uint64_t adesc8 = make_sdesc64(sbase + (MfCfg::ASM_OFF)); // ASM: smem A ring + // AMIX (ASM, TAS = 3): A stages 0, 1 = the two 64 B K halves of ONE SWIZZLE_128B K-major buffer + // (128 rows x 128 B at ASM_OFF, chunk c of row r at c ^ (r & 7); stage P starts at +64 P, the in-atom K + // advance), stage 2 = the former 64B-swizzle 8 KB layout at ASM_OFF + 16 KB + const uint64_t adesc128 = make_sdesc(sbase + (MfCfg::ASM_OFF)); + const uint64_t adesc64b = make_sdesc64(sbase + (MfCfg::ASM_OFF) + 16384u); + for (int ic = 0;; ic++) { + const int slot = ic & 3; + mbar_wait_tf(it_full + 8 * slot, (ic >> 2) & 1); + const int t = item_slot[slot]; + int mpk = 0, mm0 = 0, mme = 0; + if (MALT && t < total) { mpk = item_meta[5 * slot]; mm0 = item_meta[5 * slot + 1]; mme = item_meta[5 * slot + 2]; } + __syncwarp(); + if (elect_one()) mbar_arrive(it_empty + 8 * slot); + if (t >= total) break; + bool dn; int g, nt; + if (MALT) { dn = t >= NGU; g = mpk >> 8; nt = (mpk >> 4) & 15; } else decode(t, dn, g, nt); + const int nm = MALT ? (mpk & 15) : grp[2 * max_groups + g]; + // TMEM accumulator unit alignment. Token tiles j, j+1 fuse into one N=256 MMA set only + // if their units are TMEM-adjacent (un < 3); an nm = 4 item starting on an odd unit (or nm = 2 on unit 3) + // needs 3 (2) MMA sets -> the converted weight A stage is re-read from smem once more per set and N=128 + // singles run. Such items skip one unit (dummy use: acc_full committed with no MMAs, drained by the + // epilogue without reading -> per-unit phase parity unchanged), so their tiles form 2 (1) N=256 pairs. + if (MALT && ((nm == 4 && (uc & 1)) || (nm == 2 && (uc & 3) == 3))) { + const int un = uc % NU; + mbar_wait_hint(acc_empty(un), ((uc / NU) & 1) ^ 1); + tc_fence_after(); + __syncwarp(); + if (elect_one()) mma_commit(acc_full(un)); + __syncwarp(); + uc++; + } + const int KB = dn ? INTER / 64 : HID / 64; + const bool f8i = (F8 != 0 && !dn) || (F8 == 2 && dn); + const uint32_t idsc = IDESC | (dn ? ((1u << 7) | (1u << 10)) : (f8i ? (1u << 7) : 0u)); + const uint32_t tbytes = f8i ? 8192u : 16384u; // token tile bytes in a stage + int ns = 0; + uint32_t dcol[3], sid[3], boff[3]; // <= 3 sets (nm = 4 over a 4-unit ring) + int wu[3], wu2[3]; + // N trimming: the last token tile of the group only has mend - (m0 + 128 j) valid rows -> its MMA N + // = valid rows rounded up to 16 (accumulator columns beyond are never read for stores) + const int mendi = MALT ? mme : grp[5 * max_groups + 2 + g], m0i = MALT ? mm0 : grp[max_groups + g]; // precomputed group row end + // SASS audit: statically indexed fill (the former `ns++`-indexed writes forced these 5 arrays + // into a 64 B local stack frame, re-read by every k-block of this serial issuer loop). Same sets. + { + int j = 0; +#pragma unroll + for (int i = 0; i < 3; i++) { + const bool act = j < nm; + const int u = uc + j, un = u % NU; + const bool pair = (j + 1 < nm) && un < NU - 1; + dcol[i] = tbase + un * 128; + const int jl = pair ? j + 1 : j; + int vr = mendi - (m0i + 128 * jl); + vr = vr > 128 ? 128 : (vr < 16 ? 16 : vr); + const uint32_t nN = (uint32_t)((pair ? 128 : 0) + ((vr + 15) & ~15)); + sid[i] = (idsc & ~(0x3Fu << 17)) | ((nN >> 3) << 17); + boff[i] = (uint32_t)(j * tbytes) >> 4; + wu[i] = u; + wu2[i] = pair ? u + 1 : -1; + if (act) { ns = i + 1; j += pair ? 2 : 1; } + } + } + // k-block body. kb = 0 is peeled (FIRST = true: waits for the accumulator units right before their + // first MMA and clears the accumulate flag), so the steady-state body has no branches: only waits on + // ta_full / a_full (try_wait + suspend hint), 4 (or 8) TS MMAs whose TMEM A / smem B descriptors + // advance by immediates, and two commits. Ring indices advance incrementally (no it % 3 division). + auto kbody = [&](auto first_tag) { + constexpr bool FIRST = decltype(first_tag)::value; + if constexpr (TCP) { + // converted weights staged in smem stage cps -> TMEM A stage tas (free once the MMAs of k-block + // it - TAS completed); tcgen05.cp and the following tcgen05.mma of this thread run in order + mbar_wait_tf(cp_full + 8 * cps, cpph); + mbar_wait_tf(ta_empty + 8 * tas, taph ^ 1u); + tc_fence_after(); + __syncwarp(); + if (elect_one()) { + const uint32_t sa = tcp0 + 128u + (uint32_t)cps * 8192u; +#pragma unroll + for (int h = 0; h < 2; h++) { + // no-swizzle K-major: core matrix (8 rows x 16 B) contiguous, LBO 128 (K), SBO 256 (rows) + const uint64_t cd = (uint64_t)(((sa + 4096u * h) & 0x3FFFF) >> 4) | ((uint64_t)(128 >> 4) << 16) | + ((uint64_t)(256 >> 4) << 32) | ((uint64_t)1 << 46); + asm volatile("tcgen05.cp.cta_group::1.128x256b [%0], %1;" ::"r"(tbase + MF16_TA + tas * TAW + 8u * h), "l"(cd) : "memory"); + } + } + __syncwarp(); + } else + MFPW(1, mbar_wait_tf(ta_full + 8 * tas, taph)); + MFPW(2, mbar_wait_tf(a_full + 8 * as, aph)); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // cp.async-gathered B -> MMA + tc_fence_after(); + // B descriptor of this stage's first token tile; + boff (tile) + 2k (16 K = 32 B per k step) + const uint64_t bd0 = (f8i ? bdesc8 : bdesc0) + (uint64_t)(as * ((MfCfg::A_STAGE) >> 4)); + const uint32_t at = tbase + MF16_TA + tas * TAW; +#pragma unroll + for (int i = 0; i < 3; i++) { + if (i >= ns) break; + if (FIRST) { // first use of this unit (pair) by the item: epilogue must have drained it + const int u = wu[i]; + MFPW(3, mbar_wait_hint(acc_empty(u % NU), ((u / NU) & 1) ^ 1)); + if (wu2[i] >= 0) mbar_wait_hint(acc_empty((u + 1) % NU), (((u + 1) / NU) & 1) ^ 1); + tc_fence_after(); + } + const uint64_t bd = bd0 + boff[i]; + __syncwarp(); + if (ASM) { + // SS: A = converted weight stage tas in smem (64 B rows, 64B swizzle), K = 32 per MMA + const uint64_t ad = (TAS == 3) ? (tas < 2 ? adesc128 + (uint64_t)(4 * tas) : adesc64b) + : adesc8 + (uint64_t)(tas * (8192 >> 4)); + if (elect_one()) { + mma_f8_ss(dcol[i], ad, bd, sid[i], FIRST ? 0u : 1u); + mma_f8_ss(dcol[i], ad + 2, bd + 2, sid[i], 1u); + } + } else if (f8i) { + // 64 K = 2 x (K = 32: 8 TMEM columns of 4 e5m2 each, 32 B of the 64 B token row) + if (elect_one()) { + mma_f8_ts(dcol[i], at, bd, sid[i], FIRST ? 0u : 1u); + mma_f8_ts(dcol[i], at + 8, bd + 2, sid[i], 1u); + } + } else if (elect_one()) { + mma_f16_ts(dcol[i], at, bd, sid[i], FIRST ? 0u : 1u); + mma_f16_ts(dcol[i], at + 8, bd + 2, sid[i], 1u); + mma_f16_ts(dcol[i], at + 16, bd + 4, sid[i], 1u); + mma_f16_ts(dcol[i], at + 24, bd + 6, sid[i], 1u); + } + } + __syncwarp(); + if (elect_one()) { + mma_commit(ta_empty + 8 * tas); + if (!AEM) mma_commit(a_empty + 8 * as); // AEM: as == tas, released by the ta_empty commit + if (TCP) mma_commit(cp_empty + 8 * cps); // staging stage free once its tcgen05.cp completed + } + __syncwarp(); + if (TCP) { if (++cps == MF_TCP_NS) { cps = 0; cpph ^= 1u; } } + // advance rings: TMEM A ring (4 stages), token-tile ring (3 stages) + if (++tas == TAS) { tas = 0; taph ^= 1u; } + if (++as == AS) { as = 0; aph ^= 1u; } + }; + kbody(std::integral_constant{}); +#pragma unroll 1 + for (int kb = 1; kb < KB; kb++) kbody(std::integral_constant{}); + it += KB; + __syncwarp(); + if (elect_one()) for (int j = 0; j < nm; j++) mma_commit(acc_full((uc + j) % NU)); + __syncwarp(); + uc += nm; + } + } + } + } else if (MALT ? warp >= 16 : (warp == 10 || warp == 15)) { + if constexpr (MALT) asm volatile("setmaxnreg.dec.sync.aligned.u32 72;\n" ::: "memory"); + // ---------------- fp16 A producers (64 threads) + // gate/up items: GATHER the group's nm*128 A rows straight from xn16[token] (fp16 xn2, written once per token, + // L2-resident) with cp.async 16 B per (row, 16 B chunk), into the 128B-swizzled K-major layout TMA would + // produce: row R at R*128 B, logical chunk c at physical chunk c ^ (R & 7). Rows past the expert's end are + // zero-filled (src-size 0). Lane L of warp w (w = 0/1) owns chunk c = L & 7 of rows R = 8i + 4w + (L >> 3), + // so R & 7 is constant per lane and each warp instruction moves 4 full 128 B row segments. The rows' tokens + // are loaded once per item into tokr[m] (warp-local row k = lane + 32m <-> R = 8(k>>2) + 4w + (k&3)) and + // fetched per copy with a shuffle. Completion: every thread cp.async.mbarrier.arrive.noinc's a_full (+1 plain + // arrive from warp 10 lane 0); the MMA thread issues fence.proxy.async after the wait. + // down items: warp 10 lane 0 TMA-loads the fp16 act tiles (expect_tx + 1 arrive, then +64 on behalf of the + // gather threads) after acquiring the group's ready counter. + const int w = MALT ? warp - 16 : (warp == 15 ? 1 : 0); // gather warp index 0 .. NGW-1 + const int c = lane & 7, rsub = lane >> 3; + const uint32_t lane_off = (uint32_t)((4 * w + rsub) * 128 + ((c ^ (4 * w + rsub)) << 4)); + int it = 0; + const uint64_t keep = l2_policy_evict_last(); // xn16 rows are re-gathered by every n-tile item: keep in L2 + for (int ic = 0;; ic++) { + bool dn = false; int g = 0, nt = 0, nm = 0, m0 = 0, mend_m = 0, adj_m = 0; + const int t = get_item_m(ic, dn, g, nt, nm, m0, mend_m, adj_m); + if (t >= total) break; + const int KB = dn ? INTER / 64 : HID / 64; + const int rot = mf1_rot(t, KB, krot); // rotated k-block order per item (see mf1_rot) + if (dn) { + if (warp == MGL) { + // whole warp 10: lane 0 acquires (all 12 gate/up n-tiles of group g stored their act columns), + // the warp loops over the a_empty waits, one elect.sync lane issues expect_tx + TMA + arrivals + if (elect_one()) { + const int* rp = ready + g; + unsigned bo = (F8 == 0 && SELF) ? 512u : 256u; // T<2048 band longer first sleep (fewer polls) + while (true) { + int v; + asm volatile("ld.acquire.gpu.global.b32 %0, [%1];" : "=r"(v) : "l"(rp) : "memory"); + if (v >= MF16_READY) break; + // exponential nanosleep backoff on the act-ready + // spin to cut polling issue / power while the group's gate/up items finish (sync only) + __nanosleep(bo); + if (bo < 2048u) bo <<= 1; // backoff for every variant (fewer polls while gate/up drains) + } + } + __syncwarp(); + asm volatile("fence.proxy.async.global;" ::: "memory"); // generic act writes -> TMA reads + for (int kb = 0; kb < KB; kb++) { + const int kr = kb + rot < KB ? kb + rot : kb + rot - KB; // rotated k-block + const int s = (it + kb) % AS; + MFPW(4, { if constexpr (MALT) mbar_wait_tf(a_empty + 8 * s, (((it + kb) / AS) & 1) ^ 1); else if constexpr (F8 == 2 && SELF) mbar_wait(a_empty + 8 * s, (((it + kb) / AS) & 1) ^ 1); else mbar_wait_hint(a_empty + 8 * s, (((it + kb) / AS) & 1) ^ 1); }); // MALT plain spin + const uint32_t fb = a_full + 8 * s, dst = sbase + s * (MfCfg::A_STAGE); + __syncwarp(); + if (elect_one()) { + constexpr uint32_t atb = F8 == 2 ? 8192u : 16384u; + mbar_expect_tx(fb, (uint32_t)nm * atb); + // act tiles re-read by all 16 down n-tile items -> L2 EVICT_LAST + for (int j = 0; j < nm; j++) { + if (MALT) tma_load_2d_hint(dst + j * atb, &tX, kr * 64, m0 + j * 128, fb, keep); + else tma_load_2d(dst + j * atb, &tX, kr * 64, m0 + j * 128, fb); + } + mbar_arrive_cnt(fb, GARR - 1u); + } + __syncwarp(); + } + } + it += KB; + continue; + } + const int mend = mend_m; // precomputed offsets[e] + counts[e] (scatter) + if constexpr (F8 != 0) { + // FP8 gate/up: B = e4m3 token rows (xn8 [T, 2048] bytes, written by the router), 64 B per row per + // 64-K block, 64B-swizzled K-major: row R at R*64, 16 B chunk c at physical c ^ ((R >> 1) & 3); + // token tiles of a stage are contiguous (tile j at j * 8 KB). Lane L of warp w owns chunk c8 = L & 3 + // of rows R = 16i + 8w + (L >> 2) (i = 0 .. 8nm-1): (R >> 1) & 3 = ((L >> 2) >> 1) & 3 per lane. + // Warp-local row k = 8i + (L >> 2) <-> R = 16(k >> 3) + 8w + (k & 7); its token in tokr[k >> 5]. + // NGW = 4: rows R = 32i + 8w + (L >> 2) (i = 0.. 4nm-1), k = 8i + (L >> 2) <-> R = 32(k >> 3) + 8w + (k & 7) + // ((R >> 1) & 3 unchanged per lane); each warp gathers a quarter of the rows + constexpr int RSTEP = 8 * NGW; // rows between a lane's consecutive copies + constexpr int NM8 = 2 * GM * 2 / NGW; // token registers per lane (GM tiles x 128 rows / (32 NGW)) + const int c8 = lane & 3, rs8 = lane >> 2; + const uint32_t lo8 = (uint32_t)((8 * w + rs8) * 64 + ((c8 ^ ((rs8 >> 1) & 3)) << 4)); + const uint8_t* xn8 = reinterpret_cast(xn16); + int tokr8[NM8]; +#pragma unroll + for (int m = 0; m < NM8; m++) { + const int kk = lane + 32 * m; + const int pos = m0 + RSTEP * (kk >> 3) + 8 * w + (kk & 7); + tokr8[m] = (m < NM8 * nm / GM && pos < mend) ? __ldg(perm_tok + pos + adj_m) : -1; + } + // per-copy token shuffles are k-block invariant -> resolved ONCE per item into tsel[] (keeps the 24 + // shfl per k-block off the MIO pipe shared with the epilogue's shuffle transposes) + int tsel[4 * NM8]; +#pragma unroll + for (int m = 0; m < NM8; m++) +#pragma unroll + for (int ii = 0; ii < 4; ii++) tsel[4 * m + ii] = __shfl_sync(0xffffffff, tokr8[m], 8 * ii + rs8); + for (int kb = 0; kb < KB; kb++, it++) { + const int kr = kb + rot < KB ? kb + rot : kb + rot - KB; // rotated k-block + const int s = it % AS; + MFPW(4, { if constexpr (MALT) mbar_wait_tf(a_empty + 8 * s, ((it / AS) & 1) ^ 1); else if constexpr (F8 == 2 && SELF) mbar_wait(a_empty + 8 * s, ((it / AS) & 1) ^ 1); else mbar_wait_hint(a_empty + 8 * s, ((it / AS) & 1) ^ 1); }); // MALT gather plain try_wait spin (critical role, no HW-suspend wake latency) + const uint32_t fb = a_full + 8 * s; + const uint32_t dst0 = sbase + s * (MfCfg::A_STAGE) + lo8; + const uint8_t* srck = xn8 + kr * 64 + c8 * 16; +#pragma unroll + for (int m = 0; m < NM8; m++) { + if (m < NM8 * nm / GM) { +#pragma unroll + for (int ii = 0; ii < 4; ii++) { + const int tok = tsel[4 * m + ii]; + const int i = 4 * m + ii; + if (tok >= 0) + cp_async16_hint(dst0 + (uint32_t)(i * RSTEP * 64), srck + (size_t)tok * HID, 16u, keep); + } + } + } + cp_async_mbar_arrive_noinc(fb); + } + continue; + } + int tokr[8]; +#pragma unroll + for (int m = 0; m < 8; m++) { + const int k = lane + 32 * m; + const int pos = m0 + 8 * (k >> 2) + 4 * w + (k & 3); + tokr[m] = (m < 2 * nm && pos < mend) ? __ldg(perm_tok + pos + adj_m) : -1; + } + // the per-copy token shuffles are k-block + // invariant -> resolved ONCE per item into tsel16[] (32 regs), so each k-block issues only the cp.async + // stream (was 8 shfl per 4 copies per k-block on the MIO pipe). Same tokens / bytes / addresses. + constexpr int NM16 = GM <= 2 ? 2 * GM : 1; + int tsel16[NM16 * 8]; + if constexpr (GM <= 2) { +#pragma unroll + for (int m = 0; m < NM16; m++) +#pragma unroll + for (int ii = 0; ii < 8; ii++) tsel16[8 * m + ii] = __shfl_sync(0xffffffff, tokr[m], 4 * ii + rsub); + } + for (int kb = 0; kb < KB; kb++, it++) { + const int kr = kb + rot < KB ? kb + rot : kb + rot - KB; // rotated k-block + const int s = it % AS; + MFPW(4, { if constexpr (MALT) mbar_wait_tf(a_empty + 8 * s, ((it / AS) & 1) ^ 1); else if constexpr (F8 == 2 && SELF) mbar_wait(a_empty + 8 * s, ((it / AS) & 1) ^ 1); else mbar_wait_hint(a_empty + 8 * s, ((it / AS) & 1) ^ 1); }); // MALT gather plain try_wait spin (critical role, no HW-suspend wake latency) + const uint32_t fb = a_full + 8 * s; + const uint32_t dst0 = sbase + s * (MfCfg::A_STAGE) + lane_off; + const __half* srck = xn16 + kr * 64 + c * 8; + if constexpr (GM <= 2) { +#pragma unroll + for (int m = 0; m < NM16; m++) { + if (m < 2 * nm) { +#pragma unroll + for (int ii = 0; ii < 8; ii++) { + const int tok = tsel16[8 * m + ii]; + if (tok >= 0) + cp_async16_hint(dst0 + (uint32_t)(8 * m + ii) * 1024u, srck + (size_t)tok * HID, 16u, keep); + } + } + } + cp_async_mbar_arrive_noinc(fb); + continue; + } +#pragma unroll + for (int m = 0; m < 8; m++) { + if (m < 2 * nm) { +#pragma unroll + for (int ii = 0; ii < 8; ii++) { + const int tok = __shfl_sync(0xffffffff, tokr[m], 4 * ii + rsub); + const int i = 8 * m + ii; // R = 8i + 4w + rsub + // rows past the expert's end are NOT written (no zero-fill): a B row n only feeds + // accumulator column n (= that padded token), which is never stored, and the MMA N is + // trimmed to the valid rows (rounded up to 16) anyway + if (tok >= 0) + cp_async16_hint(dst0 + (uint32_t)i * 1024u, srck + (size_t)tok * HID, 16u, keep); + } + } + } + cp_async_mbar_arrive_noinc(fb); + } + } + } else if (MALT ? (warp >= 4 && warp <= 7) : ((warp >= 2 && warp <= 5) || (CV8 && warp >= 16))) { + if constexpr (MALT) asm volatile("setmaxnreg.inc.sync.aligned.u32 128;\n" ::: "memory"); + static_assert(!CV8 || (!ASM && TAS >= 4 && (F8 == 2 || (F8 == 0 && TAS == 4))), "CV8: all-FP8 or fp16 TMEM-A variants only"); + const int cs = (CV8 && warp >= 16) ? 1 : 0; // CV8: raw box / TMEM A column half of this warp + // ---------------- converters: warp w owns TMEM lane quadrant q = w % 4; thread = TMEM lane L = 32q + lane. + // gate/up items: lanes are PERMUTED so every quadrant q holds gate rows 16q..16q+15 (lanes 0-15) and the + // matching up rows (lanes 16-31): lane l < 16 <- raw row r = 16q + l (gate), l >= 16 <- r = 64 + 16q + l - 16 + // (up). down items: lane L <- raw Wd row L. The thread reads raw row r (both 32-K boxes, 128B swizzle r & 7), + // releases the raw smem stage, converts to fp16 (unscaled, gate/up) or bf16 (down) and writes 32 TMEM columns + // (column c = K elements 2c, 2c+1 of the 64-K block) of A stage it % 4 with tcgen05.st. + const int q = warp & 3; + RawRingT ring; + int it = 0; // running k-block count (TMEM A ring index, matches the MMA issuer) + const uint32_t tl = tbase + ((uint32_t)(q * 32) << 16) + MF16_TA; + // smem A ring (ASM) store addresses hoisted out of the item / k-block loops: row L = 32q + lane is fixed + // per thread, so its 4 swizzled 16 B chunk addresses (chunk j at j ^ ((L >> 1) & 3)) are computed ONCE; the stage + // offset tas * 8192 and the ta parity advance incrementally (no it % TAS / it / TAS per k-block) + uint32_t aadr[4]; + { + const int L = 32 * q + lane; + const uint32_t ab = sbase + (uint32_t)(MfCfg::ASM_OFF) + (uint32_t)L * 64u; +#pragma unroll + for (int jj = 0; jj < 4; jj++) aadr[jj] = ab + (uint32_t)(16 * (jj ^ ((L >> 1) & 3))); + } + // AMIX (TAS = 3): stage 2 keeps the 64B-swizzle rows at +16 KB; stages 0, 1 = halves of a 128B-swizzle + // buffer: row L at L * 128, logical chunk 4 P + j at physical (4 P + j) ^ (L & 7) (a quarter warp = 8 + // consecutive rows hits 8 distinct 16 B bank groups: conflict-free full 128 B rows) + uint32_t a128[8]; + { + const int L = 32 * q + lane; + const uint32_t ab = sbase + (uint32_t)(MfCfg::ASM_OFF) + (uint32_t)L * 128u; +#pragma unroll + for (int jj = 0; jj < 8; jj++) a128[jj] = ab + (uint32_t)(16 * (jj ^ (L & 7))); + if (TAS == 3) { +#pragma unroll + for (int jj = 0; jj < 4; jj++) aadr[jj] += 16384u; // stage 2 base + } + } + int tas_i = 0; + uint32_t taph_i = 0; + int c8p = 0; uint32_t c8rph = 0, c8tph = 0; + int cpsc = 0; uint32_t cpphc = 0; // TCP staging ring (persists across items) // CV8 FP8: it % TAS, raw / TMEM-A phase bits + int m3p = 0; // MALT: ring stage (it % 3) + uint32_t m3c = 0; // MALT: phase bit ((it / 3) & 1) + for (int ic = 0;; ic++) { + int prei = 0; + int t; + if constexpr (MALT) { // + pre-converted flag published by the producer (item_meta slot 4 bit 16) + const int slot = ic & 3; + mbar_wait_tf(it_full + 8 * slot, (ic >> 2) & 1); + t = item_slot[slot]; + if (t < total) prei = (item_meta[5 * slot + 4] >> 16) & 1; + __syncwarp(); + if (elect_one()) mbar_arrive(it_empty + 8 * slot); + } else t = get_item(ic); + if (t >= total) break; + const int KB = t >= NGU ? INTER / 64 : HID / 64; + const bool dn = t >= NGU; + const int r = dn ? 32 * q + lane : (lane < 16 ? 16 * q + lane : 64 + 16 * q + (lane - 16)); + // raw stage = 3D TMA box(es) {32 K, rows, 2 halves}: down item row r half h at 128 r + 16 KB h; + // gate/up item: gate box rows 0..63 at +0, up box rows 64..127 at +16 KB, half h at +8 KB h inside each box + // -> row r half h at 128 r + 8 KB (r >= 64) + 8 KB h. Swizzle phase r & 7 (as before). + const int sw = r & 7; + const uint32_t h1off = dn ? 16384u : 8192u; // K half 1 offset + const uint32_t rboff = (uint32_t)r * 128u + (dn ? (uint32_t)cs * 16384u : (uint32_t)((r >> 6) + cs) * 8192u); + (void)h1off; + if constexpr (MALT && RS == 3 && TAS == 3) { + // MALT converter, compile-time ring stages: the raw fp32 ring (RS = 3) and the smem A ring + // (TAS = 3) advance in lockstep with the running k-block count, so both use stage P = it % 3 and the + // same phase bit (raw_full parity m3c, ta_empty parity m3c ^ 1). The k-block loop is unrolled by 3 + // with P a template constant: every LDS.128 / STS.128 uses a per-item precomputed register address + // + an IMMEDIATE stage offset, all mbarrier addresses are immediates, and there is no per-k-block + // ring-index / parity-mask arithmetic or stage branch. Per k-block per thread: 16 LDS.128, + // 32 cvt.e5m2x2 (+16 merges), 4 STS.128, 1 proxy fence, 3 mbarrier ops. Same bytes as the general path. + uint32_t cb; + { + cb = sbase + (MfCfg::RAW_OFF) + rboff; + } + uint32_t ca3[8]; // half 1 at + h1off +#pragma unroll + for (int j = 0; j < 8; j++) ca3[j] = cb + (uint32_t)(16 * (j ^ sw)); + // pre-converted item: e5m2 row r at raw stage + 64 r, 16 B chunk j at j ^ ((r >> 1) & 3) + uint32_t pca[4]; + { + const uint32_t pb = sbase + (MfCfg::RAW_OFF) + (uint32_t)r * 64u; +#pragma unroll + for (int j = 0; j < 4; j++) pca[j] = pb + (uint32_t)(16 * (j ^ ((r >> 1) & 3))); + } + auto step = [&](auto ptag) { + constexpr int P = decltype(ptag)::value; + mbar_wait_tf(raw_full + 8 * P, m3c); + if (prei) { + uint4 c4[4]; +#pragma unroll + for (int j = 0; j < 4; j++) c4[j] = lds128

(pca[j]); + __syncwarp(); + if (elect_one()) mbar_arrive(raw_empty + 8 * P); + mbar_wait_tf(ta_empty + 8 * P, m3c ^ 1u); +#pragma unroll + for (int j = 0; j < 4; j++) { + const uint32_t sa = P < 2 ? a128[4 * (P & 1) + j] : aadr[j]; + sts128(sa, c4[j].x, c4[j].y, c4[j].z, c4[j].w); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + if (elect_one()) mbar_arrive(ta_full + 8 * P); + if (P == 2) m3c ^= 1u; + return; + } + uint4 v3[16]; +#pragma unroll + // conflict-free swizzled LDS.128 issued box by box (box 0 = K 0..31 first): box 0's + // e5m2 conversion overlaps box 1's smem reads (same bytes, same STS.128 x4 output) + for (int j = 0; j < 8; j++) v3[j] = lds128

(ca3[j]); +#pragma unroll + for (int j = 0; j < 8; j++) v3[8 + j] = lds128

(ca3[j] + h1off); + uint32_t pw[16]; +#pragma unroll + for (int c = 0; c < 8; c++) pw[c] = cvt_e5m2x4p(v3[c].x, v3[c].y, v3[c].z, v3[c].w); + __syncwarp(); + if (elect_one()) mbar_arrive(raw_empty + 8 * P); // raw stage consumed (values in registers) +#pragma unroll + for (int c = 8; c < 16; c++) pw[c] = cvt_e5m2x4p(v3[c].x, v3[c].y, v3[c].z, v3[c].w); + mbar_wait_tf(ta_empty + 8 * P, m3c ^ 1u); // MMAs of k-block it - 3 done reading stage P +#pragma unroll + for (int j = 0; j < 4; j++) { + const uint32_t sa = P < 2 ? a128[4 * (P & 1) + j] : aadr[j]; + sts128(sa, pw[4 * j], pw[4 * j + 1], pw[4 * j + 2], pw[4 * j + 3]); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // generic writes -> tcgen05.mma + __syncwarp(); + if (elect_one()) mbar_arrive(ta_full + 8 * P); + if (P == 2) m3c ^= 1u; + }; + int kb = 0; + while (kb < KB) { + if (m3p == 0) { step(std::integral_constant{}); m3p = 1; if (++kb == KB) break; } + if (m3p == 1) { step(std::integral_constant{}); m3p = 2; if (++kb == KB) break; } + step(std::integral_constant{}); m3p = 0; ++kb; + } + continue; + } + if constexpr (CV8 && F8 == 0 && !ASM && TAS % RS == 0 && TAS <= 8) { + // CV8 fp16 converter (T < 2048 self-table fused MoE), compile-time ring stages (as the CV8 FP8 path + // below): raw fp32 ring stage P % RS and TMEM A stage P = it % TAS are template constants, so every + // LDS.128 is a per-item precomputed register address + an IMMEDIATE stage offset, every mbarrier address + // and the TMEM column offset are immediates, and the phase bits flip at compile-time-known positions (no + // per-k-block ring-index / parity-mask arithmetic or runtime 4-way stage dispatch). The item kind (gate/up + // fp16 vs down bf16) is a template tag per item (no per-k-block predicate). Same loads, conversions, + // TMEM stores and barrier order as the general path -> bit-identical. + uint32_t cb8[8]; + { + const uint32_t rb = sbase + (MfCfg::RAW_OFF) + rboff; +#pragma unroll + for (int j = 0; j < 8; j++) cb8[j] = rb + (uint32_t)(16 * (j ^ sw)); + } + const uint32_t tlc = tl + 16u * (uint32_t)cs; + auto runk = [&](auto dtag) { + constexpr bool DN = decltype(dtag)::value; + auto step16 = [&](auto ptag) { + constexpr int P = decltype(ptag)::value; + constexpr int RP = P % RS; + mbar_wait_hint(raw_full + 8 * RP, c8rph); + uint4 v8[8]; +#pragma unroll + for (int j = 0; j < 8; j++) v8[j] = lds128(cb8[j]); + __syncwarp(); + if (elect_one()) mbar_arrive(raw_empty + 8 * RP); // raw stage consumed (values in registers) + float pk16[16]; +#pragma unroll + for (int c = 0; c < 8; c++) { + if (DN) { + pk16[2 * c] = __uint_as_float(cvt_bf2(v8[c].x, v8[c].y)); + pk16[2 * c + 1] = __uint_as_float(cvt_bf2(v8[c].z, v8[c].w)); + } else { + const uint2 hh = cvt_h2x4p(v8[c]); + pk16[2 * c] = __uint_as_float(hh.x); + pk16[2 * c + 1] = __uint_as_float(hh.y); + } + } + mbar_wait_hint(ta_empty + 8 * P, c8tph ^ 1u); // MMAs of k-block it - TAS done reading stage P + tc_fence_after(); + tmem_st16(tlc + (uint32_t)(P * TAW), pk16); + asm volatile("tcgen05.wait::st.sync.aligned;" ::: "memory"); + tc_fence_before(); + __syncwarp(); + if (elect_one()) mbar_arrive(ta_full + 8 * P); + if (RP == RS - 1) c8rph ^= 1u; + if (P == TAS - 1) c8tph ^= 1u; + }; + int kb = 0; + while (kb < KB) { +#define C16STEP(PP) if constexpr (PP < TAS) { if (c8p == PP) { step16(std::integral_constant{}); c8p = (PP + 1) % TAS; if (++kb == KB) break; } } + C16STEP(0) C16STEP(1) C16STEP(2) C16STEP(3) C16STEP(4) C16STEP(5) C16STEP(6) C16STEP(7) +#undef C16STEP + } + }; + if (dn) runk(std::true_type{}); else runk(std::false_type{}); + continue; + } + if constexpr (CV8 && F8 == 2 && !ASM && TAS % RS == 0 && TAS <= 8) { + // CV8 all-FP8 converter (2048 <= T < 6000 self-table variants), compile-time ring stages: the raw + // fp32 ring (RS stages, stage it % RS) and the TMEM A ring (TAS stages, stage it % TAS) both advance + // once per k-block from the same running count, and RS divides TAS, so the k-block loop is unrolled by + // TAS with P = it % TAS a template constant: raw stage P % RS (immediate LDS / mbarrier offsets), TMEM + // A column offset P * TAW immediate, phase bits flipped at compile-time-known positions. Same + // per-k-block sequence / bytes as the general path below (8 LDS.128, 8 cvt e5m2x4, 1 tcgen05.st x8). + uint32_t cb8[8]; + { + const uint32_t rb = sbase + (MfCfg::RAW_OFF) + rboff; +#pragma unroll + for (int j = 0; j < 8; j++) cb8[j] = rb + (uint32_t)(16 * (j ^ sw)); + } + const uint32_t tlc = tl + 8u * (uint32_t)cs; + (void)tlc; + const uint32_t cpdst = tcp0 + 128u + 4096u * (uint32_t)cs + (uint32_t)((32 * q + lane) >> 3) * 256u + + (uint32_t)((32 * q + lane) & 7) * 16u; + (void)cpdst; + auto step8 = [&](auto ptag) { + constexpr int P = decltype(ptag)::value; + constexpr int RP = P % RS; + mbar_wait_hint(raw_full + 8 * RP, c8rph); + uint4 v8[8]; +#pragma unroll + for (int j = 0; j < 8; j++) v8[j] = lds128(cb8[j]); + // first half of the box converted before the raw-stage release (overlaps the remaining + // LDS.128 completions), second half after; same bytes + float pk8[8]; +#pragma unroll + for (int c = 0; c < 4; c++) pk8[c] = __uint_as_float(cvt_e5m2x4p(v8[c].x, v8[c].y, v8[c].z, v8[c].w)); + __syncwarp(); + if (elect_one()) mbar_arrive(raw_empty + 8 * RP); // raw stage consumed (values in registers) +#pragma unroll + for (int c = 4; c < 8; c++) pk8[c] = __uint_as_float(cvt_e5m2x4p(v8[c].x, v8[c].y, v8[c].z, v8[c].w)); + if constexpr (TCP) { + // 32 B (8 TMEM columns) of row L = 32q + lane into smem staging stage cpsc (core-matrix + // layout: rows 8g..8g+7 x 16 B contiguous, K chunk j at +128 j, row group at +256); the MMA + // thread copies it into TMEM A stage it % TAS with tcgen05.cp + mbar_wait_hint(cp_empty + 8 * cpsc, cpphc ^ 1u); + const uint32_t sd = cpdst + (uint32_t)cpsc * 8192u; + const uint32_t* pu = reinterpret_cast(pk8); + sts128(sd, pu[0], pu[1], pu[2], pu[3]); + sts128(sd + 128u, pu[4], pu[5], pu[6], pu[7]); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // generic writes -> tcgen05.cp + __syncwarp(); + if (elect_one()) mbar_arrive(cp_full + 8 * cpsc); + if (++cpsc == MF_TCP_NS) { cpsc = 0; cpphc ^= 1u; } + } else { + mbar_wait_hint(ta_empty + 8 * P, c8tph ^ 1u); // MMAs of k-block it - TAS done reading stage P + tc_fence_after(); + tmem_st8_e(tlc + (uint32_t)(P * TAW), pk8); + asm volatile("tcgen05.wait::st.sync.aligned;" ::: "memory"); + tc_fence_before(); + __syncwarp(); + if (elect_one()) mbar_arrive(ta_full + 8 * P); + } + if (RP == RS - 1) c8rph ^= 1u; + if (P == TAS - 1) c8tph ^= 1u; + }; + int kb = 0; + while (kb < KB) { +#define C8STEP(PP) if constexpr (PP < TAS) { if (c8p == PP) { step8(std::integral_constant{}); c8p = (PP + 1) % TAS; if (++kb == KB) break; } } + C8STEP(0) C8STEP(1) C8STEP(2) C8STEP(3) C8STEP(4) C8STEP(5) C8STEP(6) C8STEP(7) +#undef C8STEP + } + continue; + } + // Software-pipelined: the 16 LDS.128 of k-block kb+1 are issued BEFORE the tcgen05.st / wait::st of + // k-block kb whenever raw stage kb+1 has already landed (non-blocking test by lane 0, broadcast so the + // branch is warp-uniform), so their smem latency overlaps the TMEM store instead of serializing the + // per-k-block converter chain. If kb+1 has not landed, kb's TMEM store goes first (ta_full(kb) is never + // delayed by the weight stream) and kb+1 is waited for afterwards. + uint4 v[16]; + int s; + uint32_t ph; + // Per-item precomputed shared addresses of this row's 8 swizzled 16 B chunks in raw stage 0 + // (chunk j at physical j ^ (r & 7)); box 1 (+16 KB) and stage 1 (+32 KB) are IMMEDIATE offsets of the + // LDS (stage-uniform branch), so the per-k-block load sequence is 16 LDS.128 with no address math. + uint32_t ca[8]; + { + const uint32_t rb = sbase + (MfCfg::RAW_OFF) + rboff; +#pragma unroll + for (int j = 0; j < 8; j++) ca[j] = rb + (uint32_t)(16 * (j ^ sw)); + } + // code size: only the RS ring stages that exist are instantiated (the former 6-way stage dispatch + // carried dead LDS blocks for stages >= RS); same loads, same order + auto load_raw = [&](int stg) { + auto ldst = [&](auto ptag) { + constexpr int P = decltype(ptag)::value; + // box-by-box LDS issue (box 0 = K 0..31 first, as the MALT path): same bytes +#pragma unroll + for (int j = 0; j < 8; j++) v[j] = lds128

(ca[j]); + if (!CV8) { +#pragma unroll + for (int j = 0; j < 8; j++) v[8 + j] = lds128

(ca[j] + h1off); // (cs == 0 here) + } + }; + if (RS == 1 || stg == 0) ldst(std::integral_constant{}); + else if (RS == 2 || stg == 1) ldst(std::integral_constant{}); + else if (RS == 3 || stg == 2) ldst(std::integral_constant 2 ? 2 : 0)>{}); + else if (RS == 4 || stg == 3) ldst(std::integral_constant 3 ? 3 : 0)>{}); + else if (RS == 5 || stg == 4) ldst(std::integral_constant 4 ? 4 : 0)>{}); + else ldst(std::integral_constant 5 ? 5 : 0)>{}); + }; + ring.next(dn, s, ph); + MFPW(5, mbar_wait_hint(raw_full + 8 * s, ph)); + load_raw(s); + for (int kb = 0; kb < KB; kb++, it++) { + float pk[32]; + // raw stage released right after its 16 LDS.128 (release + // semantics of the arrive order the shared loads), BEFORE the e5m2 conversion -> the weight producer + // refills the stage one conversion earlier. Each raw 16 B chunk is still read exactly once. + { // all converter variants release the raw stage before conversion + __syncwarp(); + if (elect_one()) mbar_arrive(raw_empty + 8 * s); + } + if ((F8 != 0 && !dn) || (F8 == 2 && dn)) { + // FP8: TMEM column c = K elements 4c..4c+3 (= raw chunk c) as e5m2 (unscaled, satfinite) +#pragma unroll + for (int c = 0; c < (CV8 ? 8 : 16); c++) { + const uint4 a = v[c]; + pk[c] = __uint_as_float(cvt_e5m2x4p(a.x, a.y, a.z, a.w)); + } + } else if (dn) { +#pragma unroll + for (int c = 0; c < (CV8 ? 8 : 16); c++) { + const uint4 a = v[c]; + pk[2 * c] = __uint_as_float(cvt_bf2(a.x, a.y)); + pk[2 * c + 1] = __uint_as_float(cvt_bf2(a.z, a.w)); + } + } else { +#pragma unroll + for (int c = 0; c < (CV8 ? 8 : 16); c++) { // one asm block (2 packed cvt) per 4 elements + const uint2 h = cvt_h2x4p(v[c]); + pk[2 * c] = __uint_as_float(h.x); + pk[2 * c + 1] = __uint_as_float(h.y); + } + } + const bool more = kb + 1 < KB; + bool pre = false; + if (more) { + ring.next(dn, s, ph); + // next-stage LDS are no longer issued ahead of this k-block's A store + proxy fence + // (MF_LDS_AHEAD = 0). 1x8192 per-CTA clock64 probe of the seed: issuing the 16 look-ahead LDS.128 + // cost ~500 clk per k-block (MIO / SRAM saturated by the token gather, raw TMA writes and MMA + // operand reads), delaying ta_full for the MMA warp (which waited 483 kcyc of 1149 on ta_full). + pre = MF_LDS_AHEAD && __shfl_sync(0xffffffffu, (int)mbar_test(raw_full + 8 * s, ph), 0) != 0; + if (pre) load_raw(s); // stage kb+1 already landed: issue its LDS ahead of the TMEM store + } + const int tas = tas_i; // == it % TAS (incremental) + MFPW(6, mbar_wait_hint(ta_empty + 8 * tas, taph_i ^ 1u)); // MMAs of k-block it-TAS done reading + if (++tas_i == TAS) { tas_i = 0; taph_i ^= 1u; } + if (ASM) { + // A row L = 32q + lane (= the TMEM lane in the TS layout): 4 x 16 B chunks, chunk j at j ^ ((L>>1)&3) + // (addresses hoisted: aadr[j] + stage offset; 4 st.shared.v4) + const uint32_t* pu = reinterpret_cast(pk); + const uint32_t so = (uint32_t)tas * 8192u; +#pragma unroll + for (int j = 0; j < 4; j++) { + const uint32_t sa = TAS == 3 ? (tas == 0 ? a128[j] : (tas == 1 ? a128[4 + j] : aadr[j])) : aadr[j] + so; + sts128(sa, pu[4 * j], pu[4 * j + 1], pu[4 * j + 2], pu[4 * j + 3]); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // generic writes -> tcgen05.mma + } else { + tc_fence_after(); + if (CV8) { + if ((F8 != 0 && !dn) || (F8 == 2 && dn)) tmem_st8_e(tl + tas * TAW + 8 * cs, pk); // K half: 8 e5m2x4 cols + else tmem_st16(tl + tas * TAW + 16 * cs, pk); // K half: 16 fp16 / bf16 pair cols + } + else if ((F8 != 0 && !dn) || (F8 == 2 && dn)) tmem_st16(tl + tas * TAW, pk); // 16 columns of e5m2x4 + else tmem_st32(tl + tas * TAW, pk); + asm volatile("tcgen05.wait::st.sync.aligned;" ::: "memory"); + tc_fence_before(); + } + __syncwarp(); + if (elect_one()) mbar_arrive(ta_full + 8 * tas); + if (more && !pre) { + MFPW(5, mbar_wait_hint(raw_full + 8 * s, ph)); + load_raw(s); + } + } + } + } else { + if constexpr (MALT) asm volatile("setmaxnreg.inc.sync.aligned.u32 112;\n" ::: "memory"); // (MALT: warps 8..15) + // ---------------- epilogue warps 6..9 / 11..14: TMEM lane quadrant q = warp % 4, column set c + const int q = warp & 3; + const int row = q * 32 + lane; + const int c = (MALT ? warp >= 12 : warp >= 11) ? 1 : 0; + const int ew = MALT ? warp - 8 : (warp >= 11 ? warp - 7 : warp - 6); // 0..7: staging slab index (down) + using MCf = MfCfg; + // all-FP8 CV8 self-table variants (2048 <= T < 6000: var6 / var20, non-MALT) use 8-token slabs (1 KB) so the + // upper half of each warp's 2 KB slab holds the per-tile routing metadata table (see MMETA below) + constexpr bool M8SLAB = F8 == 2 && SELF && !MALT && MCf::STG_W == 2048; + // GM4 MALT (1 KB slab per warp): 4-token staging slab (512 B) + the per-tile routing metadata table in the + // upper 512 B (one broadcast LDS.64 per red.add instead of 2 SHFLs; same values -> bit-identical) + constexpr bool M4SLAB = F8 == 2 && SELF && MALT && MCf::STG_W == 1024; + // CV8 all-FP8 self-table variants (M8SLAB, 2048 <= T < 6000) also stage 4 tokens (512 B) per round (as MALT M4SLAB); + // the routing metadata table stays at slab + 1 KB. Same products / red.adds -> bit-identical + constexpr int SLT = (M8SLAB || M4SLAB) ? 4 : MCf::STG_W / 128; // tokens per down staging slab (16 or 4) + float* stg = reinterpret_cast(smem + MCf::STG) + ew * (MCf::STG_W / 4); // SLT tokens x 32 cols + int uc = 0; // running count of TMEM accumulator unit uses (matches the MMA issuer) + // act (re-read by the down items) / out (red.add target of 8 experts per token): L2 EVICT_LAST + const uint64_t keep = l2_policy_evict_last(); + // FP8: gate/up accumulators carry the token pre-scale s8 (exact power of 2, router): undo with isx + const float isx = F8 ? __ldg(f8inv) : 1.f; + for (int ic = 0;; ic++) { + bool dn = false; int g = 0, nt = 0, nm = 0, m0 = 0, mend = 0, adj_m = 0; + const int t = get_item_m(ic, dn, g, nt, nm, m0, mend, adj_m); + if (t >= total) break; + if (MALT && ((nm == 4 && (uc & 1)) || (nm == 2 && (uc & 3) == 3))) { + // unit alignment (see MMA issuer): drain the skipped accumulator unit without reading it + const int un = uc % NU; + mbar_wait_hint(acc_full(un), (uc / NU) & 1); + tc_fence_after(); + tc_fence_before(); + __syncwarp(); + if (elect_one()) mbar_arrive(acc_empty(un)); + uc++; + } + // D^T accumulator: lane = weight row (permuted, see converters), column = token row (m0 + col). + // Warp set c handles 32-token chunks ch = 4p + c and 4p + 2 + c (p < nm): 2nm chunks per warp. + if (!dn) { + // gate/up: lane l < 16 holds gate j = 16q + l, lane l + 16 the matching up row. Lanes < 16 compute + // tokens 0..15 of a chunk, lanes >= 16 tokens 16..31 (one shfl_xor 16 per value pair). + const bool lo = lane < 16; + // act store base pointers hoisted per item (column offset nt*64 + 16q + (lane & 8) folded once) + uint8_t* const act8b = reinterpret_cast(act) + nt * 64 + 16 * q + (lane & 8); + __half* const act16b = act + nt * 64 + 16 * q + (lane & 8); + (void)act8b; (void)act16b; + for (int pp = 0; pp < nm; pp++) { + float va[32], vb[32]; + // token tile pp lives in accumulator unit un = (uc + pp) % 3, cols un*128 .. +127 + const int u = uc + pp, un = u % NU; + MFPW(7, mbar_wait_hint(acc_full(un), (u / NU) & 1)); + tc_fence_after(); + const uint32_t ta = tbase + ((uint32_t)(q * 32) << 16) + un * 128 + c * 32; + // tsilu bit 1 (host-gated T >= 6000): gate rows sit in TMEM lanes 32q + 0..15, the matching up + // rows in 32q + 16..31 (converter permutation); tcgen05.ld 16x32bx2 (split 16 cols) of the gate and up + // lanes gives each lane gate/up of its row pair directly (va/vb: [0,16) gate, [16,32) up) - same values + // as the 32x32b load + 16 shfl_xor 16 pairing below, without the shuffles + const bool gu16 = MALT || (F8 == 2 && SELF) || (tsilu & 2) != 0; // compile-time for the all-FP8 self-table variants too (host always sets bit 1) // compile-time for MALT (host always sets bit 1): no dead shuffle-pairing path + if (gu16) tmem_ld16x2_gu(ta, va, ta + 64, vb); + else tmem_ld32x2(ta, va, ta + 64, vb); + { // all TMEM reads of this unit done -> free it for the MMAs + tc_fence_before(); + __syncwarp(); + if (elect_one()) mbar_arrive(acc_empty(un)); + } +#pragma unroll + for (int h2 = 0; h2 < 2; h2++) { + const float* v = h2 ? vb : va; + const int cb = m0 + (4 * pp + c + 2 * h2) * 32 + (lo ? 0 : 16); + // act for this lane's column (16q + (lane & 15)) at tokens cb + i, i = 0..15, as fp16 bits + uint32_t hp2[8]; // packed bf16 token pairs (low = token 2k, high = token 2k + 1) + uint32_t e16[8]; + float rq[16]; + float gq[16], uq[16]; +#pragma unroll + for (int i = 0; i < 16; i++) { + if (gu16) { gq[i] = v[i]; uq[i] = v[16 + i]; } + else { + const float send = lo ? v[16 + i] : v[i]; + const float recv = __shfl_xor_sync(0xffffffff, send, 16); + gq[i] = lo ? v[i] : recv; // unscaled fp16 weights: acc = natural units + uq[i] = lo ? recv : v[16 + i]; + } + } + if (F8) { // token pre-scale undo as packed FMUL2 pairs (per-lane.rn: bit-identical) + const float2 is2 = make_float2(isx, isx); +#pragma unroll + for (int i = 0; i < 16; i += 2) { + const float2 g2 = fmul2(make_float2(gq[i], gq[i + 1]), is2); + const float2 u2 = fmul2(make_float2(uq[i], uq[i + 1]), is2); + gq[i] = g2.x; gq[i + 1] = g2.y; uq[i] = u2.x; uq[i + 1] = u2.y; + } + } +#pragma unroll + for (int i = 0; i < 16; i += 2) { // packed silu(g) * u -> bf16 act (fp32 range) + // all-FP8 path (act rounded to e5m2 below) uses the 1-MUFU tanh-form sigmoid where host-gated (tsilu) + const float2 r2 = (F8 == 2 && (tsilu & 1)) ? silu_mul2_t(make_float2(gq[i], gq[i + 1]), make_float2(uq[i], uq[i + 1])) + : silu_mul2(make_float2(gq[i], gq[i + 1]), make_float2(uq[i], uq[i + 1])); + if (F8 == 2 && SELF) { + // keep the fp32 pair; packed into 4-token words below + rq[i] = r2.x; rq[i + 1] = r2.y; + } else if (F8 == 2) { + // FP8 down: act as e5m2 (unscaled, satfinite), one byte per 16-bit transpose slot + unsigned short e2; + asm("cvt.rn.satfinite.e5m2x2.f32 %0, %1, %2;" : "=h"(e2) : "f"(r2.y), "f"(r2.x)); + e16[i >> 1] = (uint32_t)e2; // byte 0 = token i, byte 1 = token i + 1 + } else { + // ONE packed cvt.rn.bf16x2.f32 per token pair (bit-identical to 2 x __float2bfloat16_rn) + hp2[i >> 1] = cvt_bf2(__float_as_uint(r2.x), __float_as_uint(r2.y)); + } + } + if constexpr (F8 == 2) { + // BYTE-packed 8x8 butterfly transpose (same data movement as the 16-bit-slot version + // below, but each shuffle carries 4 useful bytes): 2 + 2 + 2 = 6 shuffles instead of 16. + // E[r] bytes = tokens 4r .. 4r+3 of this lane's column (16q + (lane & 15)). + const bool c0 = lane & 1, c1 = lane & 2, c2 = lane & 4; + uint32_t E[4]; +#pragma unroll + for (int r = 0; r < 4; r++) { + // self-table: ONE asm block (2 packed cvt.e5m2x2 + mov.b32 {lo, hi}) per 4 tokens, + // same bytes as the e16 pair words + zero-extend / shift / or merge + if (SELF) E[r] = cvt_e5m2x4p(__float_as_uint(rq[4 * r]), __float_as_uint(rq[4 * r + 1]), + __float_as_uint(rq[4 * r + 2]), __float_as_uint(rq[4 * r + 3])); + else E[r] = e16[2 * r] | (e16[2 * r + 1] << 16); + } + // round 1 (xor 1): unit k = token 2k + c0, 2 cols (even, odd) as bytes + uint32_t U[4]; // U[j] = units 2j, 2j+1 (16 bits each) +#pragma unroll + for (int hh = 0; hh < 2; hh++) { + const uint32_t x = E[2 * hh], y = E[2 * hh + 1]; + const uint32_t snd = __byte_perm(x, y, c0 ? 0x6420 : 0x7531); + const uint32_t kp = __byte_perm(x, y, c0 ? 0x7531 : 0x6420); + const uint32_t rv = __shfl_xor_sync(0xffffffff, snd, 1); + U[2 * hh] = c0 ? __byte_perm(kp, rv, 0x1504) : __byte_perm(kp, rv, 0x5140); + U[2 * hh + 1] = c0 ? __byte_perm(kp, rv, 0x3726) : __byte_perm(kp, rv, 0x7362); + } + // round 2 (xor 2): unit k = token 4k + 2c1 + c0, 4 cols (32 bits) + uint32_t W[4]; +#pragma unroll + for (int hh = 0; hh < 2; hh++) { + const uint32_t x = U[2 * hh], y = U[2 * hh + 1]; + const uint32_t snd = __byte_perm(x, y, c1 ? 0x5410 : 0x7632); + const uint32_t kp = __byte_perm(x, y, c1 ? 0x7632 : 0x5410); + const uint32_t rv = __shfl_xor_sync(0xffffffff, snd, 2); + const uint32_t lo_ = c1 ? rv : kp, hi_ = c1 ? kp : rv; + W[2 * hh] = __byte_perm(lo_, hi_, 0x5410); + W[2 * hh + 1] = __byte_perm(lo_, hi_, 0x7632); + } + // round 3 (xor 4): unit k = token 8k + (lane & 7), 8 cols -> one 8 B store + uint2 o8k[2]; +#pragma unroll + for (int k = 0; k < 2; k++) { + const uint32_t rv = __shfl_xor_sync(0xffffffff, c2 ? W[2 * k] : W[2 * k + 1], 4); + o8k[k] = c2 ? make_uint2(rv, W[2 * k + 1]) : make_uint2(W[2 * k], rv); + } + if constexpr (!MALT) { + // round 4 (xor 8) - lanes l, l ^ 8 hold the two 8 B column + // halves (16q..+7 / 16q+8..+15) of the same tokens; lane without bit 3 keeps token k = 0 and + // gets the partner's low/high half, lane with bit 3 token k = 1 -> ONE 16 B store per lane + // (same bytes / addresses as the two 8 B stores) + const bool c3 = lane & 8; + const uint2 snd = c3 ? o8k[0] : o8k[1]; + uint2 rcv; + rcv.x = __shfl_xor_sync(0xffffffff, snd.x, 8); + rcv.y = __shfl_xor_sync(0xffffffff, snd.y, 8); + const uint4 o16 = c3 ? make_uint4(rcv.x, rcv.y, o8k[1].x, o8k[1].y) + : make_uint4(o8k[0].x, o8k[0].y, rcv.x, rcv.y); + const int pos = cb + (c3 ? 8 : 0) + (lane & 7); + if (pos < mend) + st_u4_hint(reinterpret_cast(act8b - (lane & 8) + (size_t)pos * INTER), o16, keep); + } else { +#pragma unroll + for (int k = 0; k < 2; k++) { + const int pos = cb + 8 * k + (lane & 7); + if (pos < mend) + st_u2_pol(act8b + (size_t)pos * INTER, o8k[k], keep); + } + } + continue; + } + // 3-round butterfly transpose inside each 8-lane group (xor 1, 2, 4): every round halves the + // tokens per lane and doubles the contiguous columns, so lane ends with 8 columns + // (16q + (lane & 8) .. +7) of tokens cb + 8k + (lane & 7), k = 0,1 -> one 16 B store each. + const bool b0 = lane & 1, b1 = lane & 2, b2 = lane & 4; + uint32_t w1[8]; +#pragma unroll + for (int k = 0; k < 8; k++) { // unit k = token 2k + b0, cols (j & ~1) .. +1 + // whole packed pair word exchanged (no pre-shuffle select); b0 = 0 keeps own token 2k + // + partner's token 2k, b0 = 1 partner's token 2k + 1 + own token 2k + 1 (same values) + const uint32_t rv = __shfl_xor_sync(0xffffffff, hp2[k], 1); + w1[k] = b0 ? __byte_perm(rv, hp2[k], 0x7632) : __byte_perm(hp2[k], rv, 0x5410); + } + uint32_t w2[4][2]; +#pragma unroll + for (int k = 0; k < 4; k++) { // unit k = token 4k + 2b1 + b0, 4 cols + const uint32_t rv = __shfl_xor_sync(0xffffffff, b1 ? w1[2 * k] : w1[2 * k + 1], 2); + w2[k][0] = b1 ? rv : w1[2 * k]; + w2[k][1] = b1 ? w1[2 * k + 1] : rv; + } +#pragma unroll + for (int k = 0; k < 2; k++) { // unit k = token 8k + (lane & 7), 8 cols + const uint32_t r0 = __shfl_xor_sync(0xffffffff, b2 ? w2[2 * k][0] : w2[2 * k + 1][0], 4); + const uint32_t r1 = __shfl_xor_sync(0xffffffff, b2 ? w2[2 * k][1] : w2[2 * k + 1][1], 4); + const uint4 o = b2 ? make_uint4(r0, r1, w2[2 * k + 1][0], w2[2 * k + 1][1]) + : make_uint4(w2[2 * k][0], w2[2 * k][1], r0, r1); + const int pos = cb + 8 * k + (lane & 7); + if (pos < mend) { + if (F8 == 2) { // 8 e5m2 bytes (low byte of each 16-bit slot) -> one 8 B store + const uint2 o8 = make_uint2(__byte_perm(o.x, o.y, 0x6420), __byte_perm(o.z, o.w, 0x6420)); + st_u2_pol(act8b + (size_t)pos * INTER, o8, keep); + } else + st_u4_hint(reinterpret_cast(act16b + (size_t)pos * INTER), o, keep); + } + } + } + } + // release: this warp's act stores visible to generic + async proxy, then ready[g] += 1 + if constexpr (F8 == 0 && SELF) { + // per-lane proxy fence, warp sync, then ONE elected + // red.release.gpu (cumulative release of the whole warp's act stores; no per-lane membar.gl and + // no returning atomic). Consumer: ld.acquire.gpu spin + fence.proxy.async (unchanged). + // the 8 epilogue warps (6..9, 11..14 = 256 threads; all of them process every gate/up item) + // join named barrier 1 after their per-lane proxy fences, then ONE thread (warp 6 lane 0) issues a + // single cumulative red.release.gpu ready[g] += 8 (was 8 per-warp releases of +1; same total, the + // CTA barrier orders every epilogue thread's act stores before the release - side_signal pattern) + static_assert(!(F8 == 0 && SELF) || CV8, "v456: 8 epilogue warps (CV8 layout)"); + asm volatile("fence.proxy.async.global;" ::: "memory"); + asm volatile("bar.sync 1, 256;" ::: "memory"); + if (warp == 6 && lane == 0) + asm volatile("red.release.gpu.global.add.s32 [%0], %1;" ::"l"(ready + g), "r"(8) : "memory"); + __syncwarp(); + } else { + asm volatile("fence.proxy.async.global;" ::: "memory"); + __syncwarp(); + if (elect_one()) asm volatile("red.release.gpu.global.add.s32 [%0], %1;" ::"l"(ready + g), "r"(1) : "memory"); + __syncwarp(); + } + } else { + // down: lane l = output column nt*128 + 32q + l, register t = token of the chunk. acc/16 * routing + // weight staged per 16 tokens as [token][32 cols] in smem, then one red.global.add.v4 covers + // 4 tokens x 128 contiguous bytes. + const int n0 = nt * 128 + 32 * q; + // per-lane red.add column base (n0 + 8-lane group offset), so each red.add address is ONE add of the + // shuffled row offset (tok * HID; -1 = invalid row, which also carries the validity bit) + float* const outn = out + n0 + (lane & 7) * 4; + // routing metadata (token row offset, weight) hoisted out of the per-tile loop body: base + // pointers (incl. the bucket adjustment) computed once per item, and tile pp + 1's metadata is + // prefetched right after tile pp's TMEM loads, before its red.adds (same values -> bit-identical) + const int* const ptk = perm_tok + adj_m; + const float* const pwt = perm_w + adj_m; + const int pbase = m0 + c * 32 + lane; + int roffn[2]; float rwn[2]; + auto ldmeta = [&](int pp, int* ro_, float* rw_) { +#pragma unroll + for (int h2 = 0; h2 < 2; h2++) { + const int pos = pbase + (4 * pp + 2 * h2) * 32; // token of lane's slot + ro_[h2] = -1; rw_[h2] = 0.f; + if (pos < mend) { ro_[h2] = __ldg(ptk + pos) * HID; rw_[h2] = __ldg(pwt + pos); } // bf16 Wd: unscaled + } + }; + ldmeta(0, roffn, rwn); + // per-tile routing metadata (row offset, weight) staged + // once per tile in a per-warp 512 B smem table (after the self tables), so each red.add reads its + // token's (ro, wt) with ONE broadcast LDS.64 instead of two SHFLs. Same values -> bit-identical. + // also the all-FP8 self-table variants, with the table at slab + 1 KB (8-token slab, M8SLAB) + constexpr bool MMETA = (F8 == 0 && SELF && !MALT) || M8SLAB || M4SLAB; + int2* const mmeta = M8SLAB ? reinterpret_cast(stg + 256) : M4SLAB ? reinterpret_cast(stg + 128) + : reinterpret_cast(smem + MCf::BAR + 512 + MF_STAB_BYTES) + ew * 64; + (void)mmeta; + for (int pp = 0; pp < nm; pp++) { + float va[32], vb[32]; + int roff[2] = {roffn[0], roffn[1]}; float rw[2] = {rwn[0], rwn[1]}; + if constexpr (MMETA) { + __syncwarp(); // previous tile's metadata reads complete + mmeta[lane] = make_int2(roff[0], __float_as_int(rw[0])); + mmeta[32 + lane] = make_int2(roff[1], __float_as_int(rw[1])); + } + // token tile pp lives in accumulator unit un = (uc + pp) % 3, cols un*128 .. +127 + const int u = uc + pp, un = u % NU; + MFPW(7, mbar_wait_hint(acc_full(un), (u / NU) & 1)); + tc_fence_after(); + const uint32_t ta = tbase + ((uint32_t)(q * 32) << 16) + un * 128 + c * 32; + tmem_ld32x2(ta, va, ta + 64, vb); // both 32-col loads in flight, one wait::ld + { // all TMEM reads of this unit done -> free it for the MMAs + tc_fence_before(); + __syncwarp(); + if (elect_one()) mbar_arrive(acc_empty(un)); + } + if (pp + 1 < nm) ldmeta(pp + 1, roffn, rwn); // next tile's metadata in flight under the red.adds +#pragma unroll + for (int h2 = 0; h2 < 2; h2++) { + const float* v = h2 ? vb : va; +#pragma unroll + for (int hh = 0; hh < 32 / SLT; hh++) { + // two 512 B staging slabs per warp alternate by round (stg / stg + 128 floats; + // metadata table stays at stg + 256). The write of round r + 2 into the same slab follows this + // lane's __syncwarp after the write of round r + 1, which every lane reaches only after its + // reads of round r -> the 'previous slab fully read' barrier is not needed. Same values. + constexpr bool DBS = M8SLAB; + float* const sbf = (DBS && ((h2 * (32 / SLT) + hh) & 1)) ? stg + 128 : stg; + if (!DBS) __syncwarp(); // previous slab fully read +// UNSCALED accumulator slab -> smem; the routing weight is applied on the read side, where each + // lane needs only the weight of its ONE token per red.add (4 shuffles per 16-token slab + // instead of 16 weight broadcasts; same fp32 product rw * acc -> bit-identical result) +#pragma unroll + for (int t = 0; t < SLT; t++) sbf[t * 32 + lane] = v[hh * SLT + t]; + __syncwarp(); +#pragma unroll + for (int it = 0; it < SLT / 4; it++) { + const int t = it * 4 + (lane >> 3), g4 = lane & 7; + int ro; float wt; + if constexpr (MMETA) { + const int2 mt2 = mmeta[32 * h2 + hh * SLT + t]; // visible: slab __syncwarp above + ro = mt2.x; wt = __int_as_float(mt2.y); + } else { + ro = __shfl_sync(0xffffffff, roff[h2], hh * SLT + t); + wt = __shfl_sync(0xffffffff, rw[h2], hh * SLT + t); + } + const float4 a4 = *reinterpret_cast(sbf + t * 32 + g4 * 4); + const float2 y01 = fmul2(make_float2(a4.x, a4.y), make_float2(wt, wt)); + const float2 y23 = fmul2(make_float2(a4.z, a4.w), make_float2(wt, wt)); + // self-table non-MALT variants (T<2048 fp16, 2048<=T<6000 CV8 FP8): default L2 policy + if (ro >= 0) { + if constexpr (SELF && !MALT) red_add_v4(outn + ro, make_float4(y01.x, y01.y, y23.x, y23.y)); + else red_add_v4_hint(outn + ro, make_float4(y01.x, y01.y, y23.x, y23.y), keep); + } + } + } + } + } + } + uc += nm; + } + } + tc_fence_before(); + __syncthreads(); + CHN(13, 2); + if (warp == 1) { + __syncwarp(); + tc_fence_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tbase), "r"(512)); + } +} + +constexpr int MF16_READY_C8 = 4 * MF16_GNT; // 4 epilogue warps x gate/up n-tiles per group +__global__ void __launch_bounds__(MF16_THREADS, 1) moe_f16_fused_c8_kernel( + const __half* __restrict__ xn16, const __grid_constant__ CUtensorMap tG, + const __grid_constant__ CUtensorMap tU, const __grid_constant__ CUtensorMap tX, + const __grid_constant__ CUtensorMap tD, int* grp, int max_groups, + const int* __restrict__ offsets, const int* __restrict__ counts, __half* __restrict__ act, + float* __restrict__ out, const int* __restrict__ perm_tok, const float* __restrict__ perm_w, + int* __restrict__ qctr, const float* __restrict__ f8inv, int pf_ng, int krot, int tsilu, + const __grid_constant__ L2Discard mdl, const __grid_constant__ CUtensorMap tE, const int* __restrict__ pcnt, int pcap) { + (void)f8inv; // fp16 only + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = (uint8_t*)(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023); + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const uint32_t sbase = smem_u32(smem); + const uint32_t raw_full = sbase + MF16_BAR; // [3] TMA landed + const uint32_t raw_empty = raw_full + 24; // [3] 4 converter warps finished reading the raw stage + const uint32_t a_full = raw_full + 288; // [3] token tiles (B operand) in smem + const uint32_t a_empty = raw_full + 312; // [3] + const uint32_t accf = raw_full + 80; // [3] accumulator unit full (MMA commit) + const uint32_t acce = raw_full + 104; // [3] accumulator unit drained (8 epilogue warps) + auto acc_full = [&](int h) -> uint32_t { return accf + 8u * h; }; + auto acc_empty = [&](int h) -> uint32_t { return acce + 8u * h; }; + const uint32_t ta_full = raw_full + 216; // [4] TMEM A stage written (4 converter warps) + const uint32_t ta_empty = raw_full + 248; // [4] TMEM A stage consumed (MMA commit) + const uint32_t tslot = raw_full + 128; + const uint32_t it_full = raw_full + 136; // [4] + const uint32_t it_empty = raw_full + 168; // [4] 15 consumer warps + volatile uint32_t* tslot_ptr = (volatile uint32_t*)(smem + MF16_BAR + 128); + volatile int* item_slot = (volatile int*)(smem + MF16_BAR + 200); // int[4] + if (threadIdx.x == 0) { + for (int s = 0; s < 3; s++) { // raw stage released by the 8 converter warps + mbar_init(raw_full + 8 * s, 1); mbar_init(raw_empty + 8 * s, 8); + } + for (int s = 0; s < MF16_A_STAGES; s++) { + mbar_init(a_full + 8 * s, MF16_GATHER_ARRIVALS); mbar_init(a_empty + 8 * s, 1); + } + for (int h = 0; h < 3; h++) { mbar_init(acc_full(h), 1); mbar_init(acc_empty(h), 4); } // 4 epilogue warps + for (int s = 0; s < 4; s++) { mbar_init(ta_full + 8 * s, 8); mbar_init(ta_empty + 8 * s, 1); } // 8 converter warps + for (int i = 0; i < 4; i++) { mbar_init(it_full + 8 * i, 1); mbar_init(it_empty + 8 * i, 15); } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tG) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tU) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tX) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tD) : "memory"); + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(tslot), "r"(512)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + tc_fence_before(); + __syncthreads(); + tc_fence_after(); + const uint32_t tbase = *tslot_ptr; + pdl_wait(); + pdl_trigger(); + const int ngroups = grp[3 * max_groups]; + const int NGU = ngroups * MF16_GNT; + const int total = NGU + ngroups * MF16_DNT; + int* ready = qctr + 1; + const uint32_t IDESC = (1u << 4) | ((128u >> 3) << 17) | ((128u >> 4) << 24); // f32 acc, f16 A/B, M=N=128 + + auto decode = [&](int t, bool& dn, int& g, int& nt) { + dn = t >= NGU; + if (dn) gu_decode(grp, max_groups, MF16_DNT, t - NGU, g, nt); + else gu_decode(grp, max_groups, MF16_GNT, t, g, nt); + }; + // consumer side of the item ring: every lane waits, lane 0 releases the slot for the warp + auto get_item = [&](int ic) -> int { + const int slot = ic & 3; + mbar_wait(it_full + 8 * slot, (ic >> 2) & 1); + const int t = item_slot[slot]; + __syncwarp(); + if (elect_one()) mbar_arrive(it_empty + 8 * slot); + return t; + }; + + if (warp == 0) { + { + // ---------------- queue fetch + raw fp32 weight producer (whole warp loops; lane 0 fetches + broadcasts + // the queue item, one elect.sync lane publishes it and issues expect_tx + TMA) + // expert weights are a read-once stream: L2 EVICT_FIRST so they do not evict act / xn16 / out lines + const uint64_t wpol = l2_policy_evict_first(); + RawRing ring; + for (int ic = 0;; ic++) { + int t0 = 0; + if (elect_one()) t0 = atomicAdd(qctr, 1); + const int t = __shfl_sync(0xffffffffu, t0, 0); + const int slot = ic & 3; + mbar_wait(it_empty + 8 * slot, ((ic >> 2) & 1) ^ 1); + __syncwarp(); + if (elect_one()) { + item_slot[slot] = t; + mbar_arrive(it_full + 8 * slot); + } + __syncwarp(); + if (t >= total) break; + bool dn; int g, nt; + decode(t, dn, g, nt); + const int r0 = dn ? grp[g] * HID + nt * 128 : grp[g] * INTER + nt * 64; + const int KB = dn ? INTER / 64 : HID / 64; + for (int kb = 0; kb < KB; kb++) { + int s; uint32_t ph; + ring.next(dn, s, ph); + mbar_wait(raw_empty + 8 * s, ph ^ 1); + const uint32_t fb = raw_full + 8 * s, dst = sbase + MF16_RAW_OFF + s * GU_RAW; + __syncwarp(); + if (elect_one()) { + mbar_expect_tx(fb, GU_RAW); + if (dn) { + // Wd rows r0..r0+127 (128-row box): box 0 = k 0..31, box 1 = k 32..63 + tma_load_2d_hint(dst, &tD, kb * 64, r0, fb, wpol); + tma_load_2d_hint(dst + 16384, &tD, kb * 64 + 32, r0, fb, wpol); + } else { + tma_load_2d_hint(dst, &tG, kb * 64, r0, fb, wpol); // box 0: gate rows -> B rows 0..63 + tma_load_2d_hint(dst + 8192, &tU, kb * 64, r0, fb, wpol); // up rows -> B rows 64..127 + tma_load_2d_hint(dst + 16384, &tG, kb * 64 + 32, r0, fb, wpol); // box 1 (k 32..63) + tma_load_2d_hint(dst + 24576, &tU, kb * 64 + 32, r0, fb, wpol); + } + } // elect_one + __syncwarp(); + } + } + } + } else if (warp == 10 || warp == 15) { + // ---------------- fp16 A producers (64 threads) + // gate/up items: GATHER the group's nm*128 A rows straight from xn16[token] (fp16 xn2, written once per token, + // L2-resident) with cp.async 16 B per (row, 16 B chunk), into the 128B-swizzled K-major layout TMA would + // produce: row R at R*128 B, logical chunk c at physical chunk c ^ (R & 7). Rows past the expert's end are + // zero-filled (src-size 0). Lane L of warp w (w = 0/1) owns chunk c = L & 7 of rows R = 8i + 4w + (L >> 3), + // so R & 7 is constant per lane and each warp instruction moves 4 full 128 B row segments. The rows' tokens + // are loaded once per item into tokr[m] (warp-local row k = lane + 32m <-> R = 8(k>>2) + 4w + (k&3)) and + // fetched per copy with a shuffle. Completion: every thread cp.async.mbarrier.arrive.noinc's a_full (+1 plain + // arrive from warp 10 lane 0); the MMA thread issues fence.proxy.async after the wait. + // down items: warp 10 lane 0 TMA-loads the fp16 act tiles (expect_tx + 1 arrive, then +64 on behalf of the + // gather threads) after acquiring the group's ready counter. + const int w = warp == 15 ? 1 : 0; + const int c = lane & 7, rsub = lane >> 3; + const uint32_t lane_off = (uint32_t)((4 * w + rsub) * 128 + ((c ^ (4 * w + rsub)) << 4)); + int it = 0; + const uint64_t keep = l2_policy_evict_last(); // xn16 rows are re-gathered by every n-tile item: keep in L2 + for (int ic = 0;; ic++) { + const int t = get_item(ic); + if (t >= total) break; + bool dn; int g, nt; + decode(t, dn, g, nt); + const int m0 = grp[max_groups + g], nm = grp[2 * max_groups + g]; + const int KB = dn ? INTER / 64 : HID / 64; + if (dn) { + if (warp == 10) { + // whole warp 10: lane 0 acquires (all 12 gate/up n-tiles of group g stored their act columns), + // the warp loops over the a_empty waits, one elect.sync lane issues expect_tx + TMA + arrivals + if (elect_one()) { + const int* rp = ready + g; + while (true) { + int v; + asm volatile("ld.acquire.gpu.global.b32 %0, [%1];" : "=r"(v) : "l"(rp) : "memory"); + if (v >= MF16_READY_C8) break; + __nanosleep(64); + } + } + __syncwarp(); + asm volatile("fence.proxy.async.global;" ::: "memory"); // generic act writes -> TMA reads + for (int kb = 0; kb < KB; kb++) { + const int s = (it + kb) % MF16_A_STAGES; + mbar_wait(a_empty + 8 * s, (((it + kb) / MF16_A_STAGES) & 1) ^ 1); + const uint32_t fb = a_full + 8 * s, dst = sbase + s * MF16_A_STAGE; + __syncwarp(); + if (elect_one()) { + mbar_expect_tx(fb, (uint32_t)nm * 16384u); + for (int j = 0; j < nm; j++) tma_load_2d(dst + j * 16384, &tX, kb * 64, m0 + j * 128, fb); + mbar_arrive_cnt(fb, MF16_GATHER_ARRIVALS - 1); + } + __syncwarp(); + } + } + it += KB; + continue; + } + const int e = grp[g]; + const int mend = offsets[e] + counts[e]; + int tokr[8]; +#pragma unroll + for (int m = 0; m < 8; m++) { + const int k = lane + 32 * m; + const int pos = m0 + 8 * (k >> 2) + 4 * w + (k & 3); + tokr[m] = (m < 2 * nm && pos < mend) ? __ldg(perm_tok + pos) : -1; + } + for (int kb = 0; kb < KB; kb++, it++) { + const int s = it % MF16_A_STAGES; + mbar_wait(a_empty + 8 * s, ((it / MF16_A_STAGES) & 1) ^ 1); + const uint32_t fb = a_full + 8 * s; + const uint32_t dst0 = sbase + s * MF16_A_STAGE + lane_off; + const __half* srck = xn16 + kb * 64 + c * 8; +#pragma unroll + for (int m = 0; m < 8; m++) { + if (m < 2 * nm) { +#pragma unroll + for (int ii = 0; ii < 8; ii++) { + const int tok = __shfl_sync(0xffffffff, tokr[m], 4 * ii + rsub); + const int i = 8 * m + ii; // R = 8i + 4w + rsub + cp_async16_hint(dst0 + (uint32_t)i * 1024u, srck + (size_t)(tok < 0 ? 0 : tok) * HID, + tok < 0 ? 0u : 16u, keep); + } + } + } + cp_async_mbar_arrive_noinc(fb); + if (warp == 10 && lane == 0) mbar_arrive(fb); + } + } + } else if (warp == 1) { + { + // ---------------- MMA issuer (swap-AB, TS form; whole warp loops, elect.sync lane issues MMA + commit): A = converted WEIGHT tile read from TMEM A stage + // it % 4 (M = 128 weight rows, 32 cols = 64 K), B = token tile j from smem (N = 128). Accumulator D^T: + // TMEM lane = weight row, column r of unit (uc + j) % 3 = token row r of token tile j. + // Accumulator units form a 3-entry ring (uc = running count of unit uses); each unit is waited for + // lazily right before its first MMA (kb = 0), so the next item's MMAs overlap this item's epilogue as + // soon as units drain. + int it = 0, uc = 0; + // incremental ring state: token-tile stage as (it % 3) + its parity aph, TMEM A stage tas (it % 4) + taph + int as = 0, tas = 0; + uint32_t aph = 0, taph = 0; + const uint64_t bdesc0 = make_sdesc(sbase); // stage s descriptor = bdesc0 + s * (stage bytes >> 4) + for (int ic = 0;; ic++) { + const int slot = ic & 3; + mbar_wait(it_full + 8 * slot, (ic >> 2) & 1); + const int t = item_slot[slot]; + __syncwarp(); + if (elect_one()) mbar_arrive(it_empty + 8 * slot); + if (t >= total) break; + bool dn; int g, nt; + decode(t, dn, g, nt); + const int nm = grp[2 * max_groups + g]; + const int KB = dn ? INTER / 64 : HID / 64; + // down items: A (Wd) and B (act) are bf16 (a/b format = 1, bits 7 and 10); M = N = 128 + const uint32_t idsc = IDESC | (dn ? ((1u << 7) | (1u << 10)) : 0u); + int ns = 0; + uint32_t dcol[2], sid[2], boff[2]; + int wu[2], wu2[2]; + { + int j = 0; +#pragma unroll + for (int i = 0; i < 2; i++) { // statically indexed (no local-memory arrays) + const bool act = j < nm; + const int u = uc + j, un = u % 3; + const bool pair = (j + 1 < nm) && un < 2; + dcol[i] = tbase + un * 128; + sid[i] = pair ? ((idsc & ~(0x3Fu << 17)) | ((256u >> 3) << 17)) : idsc; + boff[i] = (uint32_t)(j * 16384) >> 4; + wu[i] = u; + wu2[i] = pair ? u + 1 : -1; + if (act) { ns = i + 1; j += pair ? 2 : 1; } + } + } + // k-block body. kb = 0 is peeled (FIRST = true: waits for the accumulator units right before their + // first MMA and clears the accumulate flag), so the steady-state body has no branches: only waits on + // ta_full / a_full (try_wait + suspend hint), 4 (or 8) TS MMAs whose TMEM A / smem B descriptors + // advance by immediates, and two commits. Ring indices advance incrementally (no it % 3 division). + auto kbody = [&](auto first_tag) { + constexpr bool FIRST = decltype(first_tag)::value; + mbar_wait_hint(ta_full + 8 * tas, taph); + mbar_wait_hint(a_full + 8 * as, aph); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // cp.async-gathered B -> MMA + tc_fence_after(); + // B descriptor of this stage's first token tile; + boff (tile) + 2k (16 K = 32 B per k step) + const uint64_t bd0 = bdesc0 + (uint64_t)(as * (MF16_A_STAGE >> 4)); + const uint32_t at = tbase + MF16_TA + tas * 32; +#pragma unroll + for (int i = 0; i < 2; i++) { + if (i >= ns) break; + if (FIRST) { // first use of this unit (pair) by the item: epilogue must have drained it + const int u = wu[i]; + mbar_wait_hint(acc_empty(u % 3), ((u / 3) & 1) ^ 1); + if (wu2[i] >= 0) mbar_wait_hint(acc_empty((u + 1) % 3), (((u + 1) / 3) & 1) ^ 1); + tc_fence_after(); + } + const uint64_t bd = bd0 + boff[i]; + __syncwarp(); + if (elect_one()) { + mma_f16_ts(dcol[i], at, bd, sid[i], FIRST ? 0u : 1u); + mma_f16_ts(dcol[i], at + 8, bd + 2, sid[i], 1u); + mma_f16_ts(dcol[i], at + 16, bd + 4, sid[i], 1u); + mma_f16_ts(dcol[i], at + 24, bd + 6, sid[i], 1u); + } + } + __syncwarp(); + if (elect_one()) { + mma_commit(ta_empty + 8 * tas); + mma_commit(a_empty + 8 * as); + } + __syncwarp(); + // advance rings: TMEM A ring (4 stages), token-tile ring (3 stages) + if (++tas == 4) { tas = 0; taph ^= 1u; } + if (++as == MF16_A_STAGES) { as = 0; aph ^= 1u; } + }; + kbody(std::integral_constant{}); +#pragma unroll 1 + for (int kb = 1; kb < KB; kb++) kbody(std::integral_constant{}); + it += KB; + __syncwarp(); + if (elect_one()) for (int j = 0; j < nm; j++) mma_commit(acc_full((uc + j) % 3)); + __syncwarp(); + uc += nm; + } + } + } else if ((warp >= 2 && warp <= 5) || (warp >= 11 && warp <= 14)) { + // 8 converter warps = 2 K-halves x 4 TMEM lane quadrants. Warp set cs (0: warps 2-5, 1: warps 11-14) + // converts K elements 32cs..32cs+31 of every 64-K block (raw box cs) into TMEM A columns 16cs..16cs+15. + // Probe (per-CTA clock64, T=2048-4096): the single 4-warp converter chain cost ~1230 cyc/kb of serial + // per-warp work (relpre ~700) and set the ~1600 cyc/kb period (MMA waited 540-800/kb on ta_full); two + // independent half-size chains per quadrant run concurrently. + // ---------------- converters: warp w owns TMEM lane quadrant q = w % 4; thread = TMEM lane L = 32q + lane. + // gate/up items: lanes are PERMUTED so every quadrant q holds gate rows 16q..16q+15 (lanes 0-15) and the + // matching up rows (lanes 16-31): lane l < 16 <- raw row r = 16q + l (gate), l >= 16 <- r = 64 + 16q + l - 16 + // (up). down items: lane L <- raw Wd row L. The thread reads raw row r (both 32-K boxes, 128B swizzle r & 7), + // releases the raw smem stage, converts to fp16 (unscaled, gate/up) or bf16 (down) and writes 32 TMEM columns + // (column c = K elements 2c, 2c+1 of the 64-K block) of A stage it % 4 with tcgen05.st. + const int q = warp & 3, cs = warp >= 11 ? 1 : 0; + RawRing ring; + int it = 0; // running k-block count (TMEM A ring index, matches the MMA issuer) + const uint32_t tl = tbase + ((uint32_t)(q * 32) << 16) + MF16_TA; + for (int ic = 0;; ic++) { + const int t = get_item(ic); + if (t >= total) break; + const int KB = t >= NGU ? INTER / 64 : HID / 64; + const bool dn = t >= NGU; + const int r = dn ? 32 * q + lane : (lane < 16 ? 16 * q + lane : 64 + 16 * q + (lane - 16)); + const int sw = r & 7; + // Software-pipelined: the 16 LDS.128 of k-block kb+1 are issued BEFORE the tcgen05.st / wait::st of + // k-block kb whenever raw stage kb+1 has already landed (non-blocking test by lane 0, broadcast so the + // branch is warp-uniform), so their smem latency overlaps the TMEM store instead of serializing the + // per-k-block converter chain. If kb+1 has not landed, kb's TMEM store goes first (ta_full(kb) is never + // delayed by the weight stream) and kb+1 is waited for afterwards. + uint4 v[8]; + int s; + uint32_t ph; + // Per-item precomputed shared addresses of this row's 8 swizzled 16 B chunks in raw stage 0 + // (chunk j at physical j ^ (r & 7)); box 1 (+16 KB) and stage 1 (+32 KB) are IMMEDIATE offsets of the + // LDS (stage-uniform branch), so the per-k-block load sequence is 16 LDS.128 with no address math. + uint32_t ca[8]; + { + const uint32_t rb = sbase + MF16_RAW_OFF + (uint32_t)cs * 16384u + (uint32_t)r * 128u; +#pragma unroll + for (int j = 0; j < 8; j++) ca[j] = rb + (uint32_t)(16 * (j ^ sw)); + } + auto load_raw = [&](int stg) { + if (stg == 0) { +#pragma unroll + for (int j = 0; j < 8; j++) v[j] = lds128<0>(ca[j]); + } else if (stg == 1) { +#pragma unroll + for (int j = 0; j < 8; j++) v[j] = lds128(ca[j]); + } else { +#pragma unroll + for (int j = 0; j < 8; j++) v[j] = lds128<2 * GU_RAW>(ca[j]); + } + }; + ring.next(dn, s, ph); + mbar_wait_hint(raw_full + 8 * s, ph); + load_raw(s); + for (int kb = 0; kb < KB; kb++, it++) { + float pk[16]; + if (dn) { +#pragma unroll + for (int c = 0; c < 8; c++) { + const uint4 a = v[c]; + pk[2 * c] = __uint_as_float(cvt_bf2(a.x, a.y)); + pk[2 * c + 1] = __uint_as_float(cvt_bf2(a.z, a.w)); + } + } else { +#pragma unroll + for (int c = 0; c < 8; c++) { + const uint4 a = v[c]; + pk[2 * c] = __uint_as_float(cvt_h2(a.x, a.y)); + pk[2 * c + 1] = __uint_as_float(cvt_h2(a.z, a.w)); + } + } + __syncwarp(); + if (elect_one()) mbar_arrive(raw_empty + 8 * s); // raw stage consumed (values in registers) + const bool more = kb + 1 < KB; + bool pre = false; + if (more) { + ring.next(dn, s, ph); + pre = __shfl_sync(0xffffffffu, (int)mbar_test(raw_full + 8 * s, ph), 0) != 0; + if (pre) load_raw(s); // stage kb+1 already landed: issue its LDS ahead of the TMEM store + } + const int tas = it & 3; + mbar_wait_hint(ta_empty + 8 * tas, ((it >> 2) & 1) ^ 1); // MMAs of k-block it-4 done reading + tc_fence_after(); + tmem_st16(tl + tas * 32 + 16 * cs, pk); // this K half's 16 columns + asm volatile("tcgen05.wait::st.sync.aligned;" ::: "memory"); + tc_fence_before(); + __syncwarp(); + if (elect_one()) mbar_arrive(ta_full + 8 * tas); + if (more && !pre) { + mbar_wait_hint(raw_full + 8 * s, ph); + load_raw(s); + } + } + } + } else { + const int q = warp & 3; + const int row = q * 32 + lane; + const int ew = warp - 6; // 0..3: staging slab index (down) + float* stg = reinterpret_cast(smem + MF16_STG) + ew * 512; // 32 rows x 16 cols + int uc = 0; // running count of TMEM accumulator unit uses (matches the MMA issuer) + // act (re-read by the down items) / out (red.add target of 8 experts per token): L2 EVICT_LAST + const uint64_t keep = l2_policy_evict_last(); + for (int ic = 0;; ic++) { + const int t = get_item(ic); + if (t >= total) break; + bool dn; int g, nt; + decode(t, dn, g, nt); + const int e = grp[g], m0 = grp[max_groups + g], nm = grp[2 * max_groups + g]; + const int mend = offsets[e] + counts[e]; + // D^T accumulator: lane = weight row (permuted, see converters), column = token row (m0 + col). + // Warp set c handles 32-token chunks ch = 4p + c and 4p + 2 + c (p < nm): 2nm chunks per warp. + if (!dn) { + // gate/up: lane l < 16 holds gate j = 16q + l, lane l + 16 the matching up row. Lanes < 16 compute + // tokens 0..15 of a chunk, lanes >= 16 tokens 16..31 (one shfl_xor 16 per value pair). + const bool lo = lane < 16; + for (int pc = 0; pc < 2 * nm; pc++) { + const int pp = pc >> 1, c = pc & 1; // token tile, column set + float va[32], vb[32]; + // token tile pp lives in accumulator unit un = (uc + pp) % 3, cols un*128 .. +127 + const int u = uc + pp, un = u % 3; + if (c == 0) mbar_wait_hint(acc_full(un), (u / 3) & 1); + tc_fence_after(); + const uint32_t ta = tbase + ((uint32_t)(q * 32) << 16) + un * 128 + c * 32; + tmem_ld32x2(ta, va, ta + 64, vb); + if (c == 1) { // all TMEM reads of this unit done -> free it for the MMAs + tc_fence_before(); + __syncwarp(); + if (elect_one()) mbar_arrive(acc_empty(un)); + } +#pragma unroll + for (int h2 = 0; h2 < 2; h2++) { + const float* v = h2 ? vb : va; + const int cb = m0 + (4 * pp + c + 2 * h2) * 32 + (lo ? 0 : 16); + // act for this lane's column (16q + (lane & 15)) at tokens cb + i, i = 0..15, as fp16 bits + uint32_t hb[16]; + float gq[16], uq[16]; +#pragma unroll + for (int i = 0; i < 16; i++) { + const float send = lo ? v[16 + i] : v[i]; + const float recv = __shfl_xor_sync(0xffffffff, send, 16); + gq[i] = lo ? v[i] : recv; // unscaled fp16 weights: acc = natural units + uq[i] = lo ? recv : v[16 + i]; + } +#pragma unroll + for (int i = 0; i < 16; i += 2) { // packed silu(g) * u -> bf16 act (fp32 range) + const float2 r2 = silu_mul2(make_float2(gq[i], gq[i + 1]), make_float2(uq[i], uq[i + 1])); + hb[i] = (uint32_t)__bfloat16_as_ushort(__float2bfloat16_rn(r2.x)); + hb[i + 1] = (uint32_t)__bfloat16_as_ushort(__float2bfloat16_rn(r2.y)); + } + // 3-round butterfly transpose inside each 8-lane group (xor 1, 2, 4): every round halves the + // tokens per lane and doubles the contiguous columns, so lane ends with 8 columns + // (16q + (lane & 8) .. +7) of tokens cb + 8k + (lane & 7), k = 0,1 -> one 16 B store each. + const bool b0 = lane & 1, b1 = lane & 2, b2 = lane & 4; + uint32_t w1[8]; +#pragma unroll + for (int k = 0; k < 8; k++) { // unit k = token 2k + b0, cols (j & ~1) .. +1 + const uint32_t rv = __shfl_xor_sync(0xffffffff, b0 ? hb[2 * k] : hb[2 * k + 1], 1); + w1[k] = b0 ? (rv | (hb[2 * k + 1] << 16)) : (hb[2 * k] | (rv << 16)); + } + uint32_t w2[4][2]; +#pragma unroll + for (int k = 0; k < 4; k++) { // unit k = token 4k + 2b1 + b0, 4 cols + const uint32_t rv = __shfl_xor_sync(0xffffffff, b1 ? w1[2 * k] : w1[2 * k + 1], 2); + w2[k][0] = b1 ? rv : w1[2 * k]; + w2[k][1] = b1 ? w1[2 * k + 1] : rv; + } +#pragma unroll + for (int k = 0; k < 2; k++) { // unit k = token 8k + (lane & 7), 8 cols + const uint32_t r0 = __shfl_xor_sync(0xffffffff, b2 ? w2[2 * k][0] : w2[2 * k + 1][0], 4); + const uint32_t r1 = __shfl_xor_sync(0xffffffff, b2 ? w2[2 * k][1] : w2[2 * k + 1][1], 4); + const uint4 o = b2 ? make_uint4(r0, r1, w2[2 * k + 1][0], w2[2 * k + 1][1]) + : make_uint4(w2[2 * k][0], w2[2 * k][1], r0, r1); + const int pos = cb + 8 * k + (lane & 7); + if (pos < mend) + st_u4_hint(reinterpret_cast(act + (size_t)pos * INTER + nt * 64 + 16 * q + (lane & 8)), o, keep); + } + } + } + // release: this warp's act stores visible to generic + async proxy, then ready[g] += 1 + asm volatile("fence.proxy.async.global;" ::: "memory"); + __syncwarp(); + if (elect_one()) asm volatile("red.release.gpu.global.add.s32 [%0], %1;" ::"l"(ready + g), "r"(1) : "memory"); + __syncwarp(); + } else { + // down: lane l = output column nt*128 + 32q + l, register t = token of the chunk. acc/16 * routing + // weight staged per 16 tokens as [token][32 cols] in smem, then one red.global.add.v4 covers + // 4 tokens x 128 contiguous bytes. + const int n0 = nt * 128 + 32 * q; + // per-lane red.add column base (n0 + 8-lane group offset), so each red.add address is ONE add of the + // shuffled row offset (tok * HID; -1 = invalid row, which also carries the validity bit) + float* const outn = out + n0 + (lane & 7) * 4; + for (int pc = 0; pc < 2 * nm; pc++) { + const int pp = pc >> 1, c = pc & 1; // token tile, column set + float va[32], vb[32]; + // routing metadata of both 32-token chunks of this tile, loaded BEFORE the accumulator wait so + // the global-load latency overlaps the MMAs instead of the epilogue + int roff[2]; float rw[2]; +#pragma unroll + for (int h2 = 0; h2 < 2; h2++) { + const int pos = m0 + (4 * pp + c + 2 * h2) * 32 + lane; // token of lane's slot + roff[h2] = -1; rw[h2] = 0.f; + if (pos < mend) { roff[h2] = __ldg(perm_tok + pos) * HID; rw[h2] = __ldg(perm_w + pos); } // bf16 Wd: unscaled + } + // token tile pp lives in accumulator unit un = (uc + pp) % 3, cols un*128 .. +127 + const int u = uc + pp, un = u % 3; + if (c == 0) mbar_wait_hint(acc_full(un), (u / 3) & 1); + tc_fence_after(); + const uint32_t ta = tbase + ((uint32_t)(q * 32) << 16) + un * 128 + c * 32; + tmem_ld32x2(ta, va, ta + 64, vb); // both 32-col loads in flight, one wait::ld + if (c == 1) { // all TMEM reads of this unit done -> free it for the MMAs + tc_fence_before(); + __syncwarp(); + if (elect_one()) mbar_arrive(acc_empty(un)); + } +#pragma unroll + for (int h2 = 0; h2 < 2; h2++) { + const float* v = h2 ? vb : va; +#pragma unroll + for (int hh = 0; hh < 2; hh++) { + __syncwarp(); // previous slab fully read +#pragma unroll + for (int t = 0; t < 16; t += 2) { // routing-weight scaling as FMUL2 + const float2 w2 = make_float2(__shfl_sync(0xffffffff, rw[h2], hh * 16 + t), + __shfl_sync(0xffffffff, rw[h2], hh * 16 + t + 1)); + const float2 y2 = fmul2(make_float2(v[hh * 16 + t], v[hh * 16 + t + 1]), w2); + stg[t * 32 + lane] = y2.x; + stg[(t + 1) * 32 + lane] = y2.y; + } + __syncwarp(); +#pragma unroll + for (int it = 0; it < 4; it++) { + const int t = it * 4 + (lane >> 3), g4 = lane & 7; + const int ro = __shfl_sync(0xffffffff, roff[h2], hh * 16 + t); + const float4 w4 = *reinterpret_cast(stg + t * 32 + g4 * 4); + if (ro >= 0) red_add_v4_hint(outn + ro, w4, keep); + } + } + } + } + } + uc += nm; + } + } + tc_fence_before(); + __syncthreads(); + if (warp == 1) { + __syncwarp(); + tc_fence_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tbase), "r"(512)); + } +} + +// ------------------------------------------------------------------ MoE bookkeeping +__global__ void moe_scan_kernel(const int* __restrict__ counts, int* __restrict__ offsets, int* __restrict__ cursor, + int* __restrict__ tile_expert, int* __restrict__ tile_mstart, + int* __restrict__ total_tiles, int* __restrict__ grp, int max_groups) { + // grp layout: [0, G) expert | [G, 2G) first sorted row | [2G, 3G) #M tiles (1..4) | [3G] total groups (G=max_groups) + // | [3G+1, 4G+1) first group of the expert * 8 + #groups of the expert + // | [4G+1] #pair groups | [4G+2 + pg] pair group pg = first M tile | (#tiles (1..2) << 24) + // (pair groups: an expert's M tiles split into consecutive pairs, used by the TF32 moe_fused_kernel) + __shared__ int s_off[NEXP], s_toff[NEXP], s_goff[NEXP], s_poff[NEXP]; + int* pg = grp + 4 * max_groups + 1; + pdl_wait(); + pdl_trigger(); + const int e = threadIdx.x; + // Parallel exclusive prefix sums over the 128 experts (4 warps): warp-level shuffle scans of the 4 per-expert + // quantities (rows, M tiles, <=3-tile groups, pair groups), then the 4 warp totals combined through smem. + // (Replaces a serial 128-iteration thread-0 loop whose dependent global loads cost ~20+ us.) + __shared__ int s_wsum[4][4]; + const int lane = e & 31, wid = e >> 5; + int v[4]; + { + const int c0 = counts[e]; + const int nt0 = (c0 + TBM - 1) / TBM; + v[0] = c0; v[1] = nt0; v[2] = (nt0 + 2) / 3; v[3] = (nt0 + 1) / 2; + } + int incl[4] = {v[0], v[1], v[2], v[3]}; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { +#pragma unroll + for (int i = 0; i < 4; i++) { + const int y = __shfl_up_sync(0xffffffff, incl[i], o); + if (lane >= o) incl[i] += y; + } + } + if (lane == 31) { +#pragma unroll + for (int i = 0; i < 4; i++) s_wsum[wid][i] = incl[i]; + } + __syncthreads(); + int base[4] = {0, 0, 0, 0}, tot[4] = {0, 0, 0, 0}; +#pragma unroll + for (int w = 0; w < 4; w++) +#pragma unroll + for (int i = 0; i < 4; i++) { + if (w < wid) base[i] += s_wsum[w][i]; + tot[i] += s_wsum[w][i]; + } + s_off[e] = base[0] + incl[0] - v[0]; + s_toff[e] = base[1] + incl[1] - v[1]; + s_goff[e] = base[2] + incl[2] - v[2]; + s_poff[e] = base[3] + incl[3] - v[3]; + if (e == 0) { + *total_tiles = tot[1]; + pg[0] = tot[3]; + grp[3 * max_groups] = tot[2]; + } + __syncthreads(); + const int c = counts[e], off = s_off[e], toff = s_toff[e]; + offsets[e] = off; cursor[e] = off; + const int ntl = (c + TBM - 1) / TBM; + for (int j = 0; j < ntl; j++) { tile_expert[toff + j] = e; tile_mstart[toff + j] = off + j * TBM; } + for (int pi = 0; 2 * pi < ntl; pi++) { + const int nn = ntl - 2 * pi < 2 ? ntl - 2 * pi : 2; + pg[1 + s_poff[e] + pi] = (toff + 2 * pi) | (nn << 24); + } + // balanced split of the expert's ntl M tiles into ng = ceil(ntl/3) groups of <= 3 tiles (4 -> 2+2, 5 -> 3+2) + const int ng = (ntl + 2) / 3; + int tstart = 0; + for (int gi = 0; gi < ng; gi++) { + const int gidx = s_goff[e] + gi; + const int nm = ntl / ng + (gi < ntl % ng ? 1 : 0); + grp[gidx] = e; + grp[max_groups + gidx] = off + tstart * TBM; + grp[2 * max_groups + gidx] = nm; + grp[3 * max_groups + 1 + gidx] = (s_goff[e] << 12) | ng; + tstart += nm; + } +} +// assign each (token, k) pair its expert-sorted slot; also record the inverse map inv_pos[t*8+k] = slot. +constexpr int SC_PER = 1024; +// the former moe_scan launch is FUSED in here. Every CTA recomputes the 128-expert exclusive prefix sums of the +// router histogram itself (threads 0..127 = 4 warps, warp shuffle scans + smem combine; 512 B of L2-resident counts), +// so scatter has no scan predecessor. CTA 0 additionally writes the tables moe_scan used to produce (offsets, +// M-tile table, <=3-tile groups, pair groups, totals) - consumed only by later kernels (PDL waits on full completion). +// Slots: pos = offsets[e] + (block's reserved range from cursor[e], which starts at 0 - zeroed by prep_qkv) + rank. +__global__ void __launch_bounds__(256) moe_scatter_kernel(int n, const int* __restrict__ topk_idx, + const float* __restrict__ topk_w, const int* __restrict__ counts, + int* __restrict__ cursor, int* __restrict__ offsets, + int* __restrict__ tile_expert, int* __restrict__ tile_mstart, + int* __restrict__ total_tiles, int* __restrict__ grp, + int max_groups, int* __restrict__ perm_tok, + float* __restrict__ perm_w, int* __restrict__ inv_pos, + int nsc, const float* __restrict__ gh, + const float* __restrict__ glnw, float geps, + const float* __restrict__ gssq, float* __restrict__ gxn2, + int gmax, int wtab, int* __restrict__ tile_mend, int lpt) { + // wtab: which MoE bookkeeping tables a consumer reads (dead-write audit): bit 0 = M-tile table + // (tile_expert / tile_mstart / total_tiles: TF32 moe_fused1 / moe_fused), bit 1 = pair groups (TF32 moe_fused). + // The fp16/FP8 fused MoE path (T >= 2048) reads only grp's <=GM-tile group sections. inv_pos == nullptr: the + // inverse map (only read by the standalone moe_norm_gather kernel, not launched in production) is not written. + // fused gather range (TF32 MoE path, T < 2048): CTAs [nsc, nsc + T) are the former moe_norm_gather launch - + // row t = blockIdx.x - nsc of xn2 = tf32(ln2w * h * rstd) written once per token. They depend only on h / ssq + // (o_proj) - not on this kernel's scatter results - so both ranges run concurrently in ONE launch (saves a PDL + // boundary + ramp); the MoE kernel's griddepcontrol.wait covers both. + if ((int)blockIdx.x >= nsc) { + CHN(12, 0); + const int t = (int)blockIdx.x - nsc, tid = threadIdx.x; + // ln2 weights (kernel input) loaded before griddepcontrol.wait; same math as rms_row_ss + const float4 w0 = __ldg(reinterpret_cast(glnw) + tid); + const float4 w1 = __ldg(reinterpret_cast(glnw) + tid + 256); + pdl_wait(); + CHN(12, 1); + pdl_trigger(); + float4 o0, o1; + { + const float4* xr = reinterpret_cast(gh + (size_t)t * HID); + const float4 v0 = xr[tid], v1 = xr[tid + 256]; + const float r = rsqrtf(gssq[t] / (float)HID + geps); + o0 = make_float4(w0.x * (v0.x * r), w0.y * (v0.y * r), w0.z * (v0.z * r), w0.w * (v0.w * r)); + o1 = make_float4(w1.x * (v1.x * r), w1.y * (v1.y * r), w1.z * (v1.z * r), w1.w * (v1.w * r)); + } + const float4 h0 = make_float4(tf32_hi(o0.x), tf32_hi(o0.y), tf32_hi(o0.z), tf32_hi(o0.w)); + const float4 h1 = make_float4(tf32_hi(o1.x), tf32_hi(o1.y), tf32_hi(o1.z), tf32_hi(o1.w)); + float4* dst = reinterpret_cast(gxn2 + (size_t)t * HID); + const uint64_t kp = keep_pol(); // xn2 gathered by the MoE kernel + st_f4_pol(dst + tid, h0, kp); + st_f4_pol(dst + tid + 256, h1, kp); + return; + } + __shared__ int sh[NEXP], sbase[NEXP]; + __shared__ int s_off[NEXP], s_toff[NEXP], s_goff[NEXP], s_poff[NEXP]; + __shared__ int s_wsum[4][4]; + __shared__ int s_ntl[NEXP], s_ngs[NEXP]; // per-expert M tiles / groups (LPT group order) + const int tid = threadIdx.x; + if (tid < NEXP) sh[tid] = 0; + CHN(12, 0); + pdl_wait(); + CHN(12, 1); + pdl_trigger(); + constexpr int PT = SC_PER / 256; + const int i0 = blockIdx.x * SC_PER + tid; + int e[PT], r[PT]; + float w[PT]; +#pragma unroll + for (int j = 0; j < PT; j++) { // all loads in flight first + const int i = i0 + j * 256; + e[j] = i < n ? __ldg(topk_idx + i) : -1; + w[j] = i < n ? __ldg(topk_w + i) : 0.f; + } + // ---- per-expert exclusive prefix sums (rows, M tiles, <=3-tile groups, pair groups); same math as moe_scan + int v[4] = {0, 0, 0, 0}, incl[4] = {0, 0, 0, 0}; + const int lane = tid & 31, wid = tid >> 5; + if (tid < NEXP) { + const int c0 = __ldg(counts + tid); + const int nt0 = (c0 + TBM - 1) / TBM; + v[0] = c0; v[1] = nt0; v[2] = (nt0 + gmax - 1) / gmax; v[3] = (nt0 + 1) / 2; + s_ntl[tid] = nt0; s_ngs[tid] = v[2]; +#pragma unroll + for (int i = 0; i < 4; i++) incl[i] = v[i]; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { +#pragma unroll + for (int i = 0; i < 4; i++) { + const int y = __shfl_up_sync(0xffffffff, incl[i], o); + if (lane >= o) incl[i] += y; + } + } + if (lane == 31) { +#pragma unroll + for (int i = 0; i < 4; i++) s_wsum[wid][i] = incl[i]; + } + } +#pragma unroll + for (int j = 0; j < PT; j++) r[j] = e[j] >= 0 ? atomicAdd(&sh[e[j]], 1) : 0; // block-local rank + __syncthreads(); + if (tid < NEXP) { + int base[4] = {0, 0, 0, 0}, tot[4] = {0, 0, 0, 0}; +#pragma unroll + for (int ww = 0; ww < 4; ww++) +#pragma unroll + for (int i = 0; i < 4; i++) { + if (ww < wid) base[i] += s_wsum[ww][i]; + tot[i] += s_wsum[ww][i]; + } + s_off[tid] = base[0] + incl[0] - v[0]; + s_toff[tid] = base[1] + incl[1] - v[1]; + s_goff[tid] = base[2] + incl[2] - v[2]; + s_poff[tid] = base[3] + incl[3] - v[3]; + const int c = sh[tid]; + sbase[tid] = s_off[tid] + (c ? atomicAdd(&cursor[tid], c) : 0); // reserve the block's range + if (blockIdx.x == 0) { + int* pg = grp + 4 * max_groups + 1; + if (tid == 0) { + if (wtab & 1) *total_tiles = tot[1]; + if (wtab & 2) pg[0] = tot[3]; + grp[3 * max_groups] = tot[2]; + } + const int ex = tid, cc = v[0], off = s_off[ex], toff = s_toff[ex]; + offsets[ex] = off; + const int ntl = v[1]; + if (wtab & 1) + for (int j = 0; j < ntl; j++) { + tile_expert[toff + j] = ex; tile_mstart[toff + j] = off + j * TBM; + tile_mend[toff + j] = off + cc; // consumer decode needs no dependent offsets/counts load + } + if (wtab & 2) + for (int pi = 0; 2 * pi < ntl; pi++) { + const int nn = ntl - 2 * pi < 2 ? ntl - 2 * pi : 2; + pg[1 + s_poff[ex] + pi] = (toff + 2 * pi) | (nn << 24); + } + const int ng = (ntl + gmax - 1) / gmax; + int goff = s_goff[ex]; + if (lpt) { + goff = 0; + for (int e2 = 0; e2 < NEXP; e2++) { + const int n2 = s_ntl[e2]; + if (n2 > ntl || (n2 == ntl && e2 < ex)) goff += s_ngs[e2]; + } + } + int tstart = 0; + for (int gi = 0; gi < ng; gi++) { + const int gidx = goff + gi; + const int nm = ntl / ng + (gi < ntl % ng ? 1 : 0); + grp[gidx] = ex; + grp[max_groups + gidx] = off + tstart * TBM; + grp[2 * max_groups + gidx] = nm; + grp[3 * max_groups + 1 + gidx] = (goff << 12) | ng; + grp[5 * max_groups + 2 + gidx] = off + cc; // group row end (fused fp16/FP8 MoE decode) + tstart += nm; + } + } + } + __syncthreads(); +#pragma unroll + for (int j = 0; j < PT; j++) { + if (e[j] < 0) continue; + const int i = i0 + j * 256; + const int pos = sbase[e[j]] + r[j]; + perm_tok[pos] = i / TOPK; + perm_w[pos] = w[j]; + if (inv_pos) inv_pos[i] = pos; + } +} +// Fused post-attention RMSNorm (recomputed from h, bit-identical to rmsnorm_kernel<2>'s hi part) + gather: +// one block (256 threads) per token reads its h row once and writes the TF32-rounded normalized row into its +// 8 expert-sorted slots of the A operand with streaming stores (st.global.cs: written once, consumed by the +// gate/up TMA loads, so it should not evict the L2-resident expert weights). +__global__ void __launch_bounds__(256) moe_norm_gather_kernel(const float* __restrict__ h, const float* __restrict__ w, + float eps, const int* __restrict__ inv_pos, + const float* __restrict__ ssq, + float* __restrict__ aperm, int f16) { + pdl_wait(); + pdl_trigger(); + const int t = blockIdx.x, tid = threadIdx.x; + __shared__ int slots[TOPK]; + if (tid < TOPK) slots[tid] = inv_pos[t * TOPK + tid]; + float4 o0, o1; + rms_row_ss(h, w, ssq[t], eps, t, tid, o0, o1); // rstd from the o_proj-epilogue statistics (no reduction) + __syncthreads(); // slots[] visible + if (f16) { + // fp16 A operand for the fp16 gate/up GEMM (same 11-bit significand as TF32; |y| << 65504) + // written ONCE per token (row t of xn16 [T, 2048]); the fused MoE kernel gathers rows by perm_tok + // (default stores: keep it L2-resident for the gathers) + const uint2 u0 = make_uint2(pack_h2(o0.x, o0.y), pack_h2(o0.z, o0.w)); + const uint2 u1 = make_uint2(pack_h2(o1.x, o1.y), pack_h2(o1.z, o1.w)); + uint2* dst = reinterpret_cast(reinterpret_cast<__half*>(aperm) + (size_t)t * HID); + const uint64_t kp = keep_pol(); // xn16 gathered by the MoE kernel + st_u2_pol(dst + tid, u0, kp); + st_u2_pol(dst + tid + 256, u1, kp); + return; + } + const float4 h0 = make_float4(tf32_hi(o0.x), tf32_hi(o0.y), tf32_hi(o0.z), tf32_hi(o0.w)); + const float4 h1 = make_float4(tf32_hi(o1.x), tf32_hi(o1.y), tf32_hi(o1.z), tf32_hi(o1.w)); + // written ONCE per token (row t of xn2 [T, 2048]); the fused TF32 MoE kernel gathers rows by perm_tok + // (default stores: keep it L2-resident for the gathers) + float4* dst = reinterpret_cast(aperm + (size_t)t * HID); + const uint64_t kp = keep_pol(); // xn2 gathered by the MoE kernel + st_f4_pol(dst + tid, h0, kp); + st_f4_pol(dst + tid + 256, h1, kp); +} + +// ------------------------------------------------------------------ host side +int g_lpt = -1; // probe override of the self-table LPT group order (-1 auto) +int g_rks_cap = 0; // probe cap on the router K split (0 = none) +int g_pf_div = 6, g_pf1_kb = 12, g_pf2_kb = 0; // MoE weight L2 prefetch knobs (897 <= T < 2048) +const float* g_pf_wg = nullptr; const float* g_pf_wu = nullptr; +extern int g_mf16_krot; +L2Discard g_moe_dl{}; +int g_disc_mode = 2; // T in [897, 2048) self-table band: Wo16 / attn L2 discards run in the MoE pre-PDL-wait window (off the router critical path) +L2Discard g_oproj_dl{}; // discard list handed to the next launch_oproj_gemm (host data) +// side-stream completion counters: [0] mask_classify CTAs, [1] convert_w16 CTAs (device, cumulative over calls, +// raw cudaMalloc never freed - no tensor state); host-tracked cumulative targets. +static unsigned long long* side_ctrs() { + static unsigned long long* p = nullptr; + if (!p) { cudaMalloc(&p, 2 * sizeof(unsigned long long)); cudaMemset(p, 0, 2 * sizeof(unsigned long long)); cudaDeviceSynchronize(); } + return p; +} +static unsigned long long g_mask_target = 0, g_conv_target = 0; +// claim words (side_steal.cuh): [0, CONV_UNITS) convert units, [CONV_UNITS, cap) mask units. Raw cudaMalloc, +// never freed at exit (no tensor state); grown (after a device sync) only if a shape needs more mask units. +constexpr int CONV_UNITS = 2048 + 64; +#ifdef STRESS_PROBE +int g_side_skip = 0; +#define SKIPEP(e) (g_side_skip ? 0u : (e)) +void steal_read(unsigned long long* h) { cudaMemcpyFromSymbol(h, sidew::g_steal_cnt, 16); } +#else +#define SKIPEP(e) (e) +#endif +static unsigned g_epoch = 0; +static sidew::MaskJob g_mask_job{}; +static sidew::ConvJob g_conv_job{}; +static unsigned* claim_words(int nmask) { + static unsigned* p = nullptr; + static int cap = 0; + if (nmask + CONV_UNITS > cap) { + int nc = cap ? cap : CONV_UNITS + 65536; + while (nc < nmask + CONV_UNITS) nc *= 2; + if (p) { cudaDeviceSynchronize(); cudaFree(p); } + cudaMalloc(&p, (size_t)nc * 4); + cudaMemset(p, 0, (size_t)nc * 4); + cudaDeviceSynchronize(); + cap = nc; + } + return p; +} +// FP8 QK^T bounds (see prep_qkv_kernel): 4 unsigned, raw cudaMalloc never freed (no tensor state); zero at creation, +// filled by prep_qkv (atomicMax), consumed by the QKV epilogue + FA4 attention, reset to 0 by o_proj every call. +static unsigned* qk_bounds() { + static unsigned* p = nullptr; + if (!p) { cudaMalloc(&p, 4 * sizeof(unsigned)); cudaMemset(p, 0, 4 * sizeof(unsigned)); cudaDeviceSynchronize(); } + return p; +} +// upper bound on M-tile groups (<= 3 tiles of one expert): sum_e ceil(ntl_e/3) <= n/384 + 128 +int moe_max_groups(int n) { return (n + 2 * TBM - 1) / (2 * TBM) + NEXP; } // bound for groups of >= 2 tiles (GM 2 or 3) +// Launch with programmatic stream serialization (PDL); args converted to the kernel's exact parameter types. +template +static void pdl_launch(void (*kern)(KArgs...), dim3 grid, dim3 block, size_t smem, cudaStream_t s, Act&&... act) { + std::tuple...> targs(std::forward(act)...); + void* ptrs[sizeof...(KArgs) > 0 ? sizeof...(KArgs) : 1]; + std::apply([&](auto&... e) { int i = 0; ((ptrs[i++] = (void*)&e), ...); }, targs); + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = grid; cfg.blockDim = block; cfg.dynamicSmemBytes = smem; cfg.stream = s; + cudaLaunchAttribute at[1]; + at[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + at[0].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = at; cfg.numAttrs = 1; + cudaLaunchKernelExC(&cfg, (const void*)kern, ptrs); +} +// Host-side tensor-map descriptor cache (pure host data, keyed on pointer / dtype / shape / box): a descriptor is +// re-encoded only when one of those changes, so repeated forwards on the same buffers skip cuTensorMapEncodeTiled. +struct MapKey { const void* p; uint64_t rows, cols; uint32_t box; int dt; }; +struct MapEnt { MapKey k; CUtensorMap m; }; +template +static CUtensorMap cached_map(const MapKey& key, F encode) { + constexpr int CAP = 64; + static MapEnt* tab = new MapEnt[CAP]; // heap, never freed (host memory only) + static int n = 0, nxt = 0; + for (int i = 0; i < n; i++) { + const MapKey& e = tab[i].k; + if (e.p == key.p && e.rows == key.rows && e.cols == key.cols && e.box == key.box && e.dt == key.dt) + return tab[i].m; + } + const CUtensorMap m = encode(); + const int slot = n < CAP ? n++ : (nxt++ % CAP); // round-robin replacement once full + tab[slot].k = key; + tab[slot].m = m; + return m; +} +static CUtensorMap make_map_raw(const float* ptr, uint64_t rows, uint64_t cols, uint32_t box_rows) { + CUtensorMap m; + cuuint64_t dims[2] = {cols, rows}; + cuuint64_t strides[1] = {cols * 4}; + cuuint32_t box[2] = {32, box_rows}; + cuuint32_t es[2] = {1, 1}; + CUresult r = cuTensorMapEncodeTiled(&m, CU_TENSOR_MAP_DATA_TYPE_FLOAT32, 2, (void*)ptr, dims, strides, box, es, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, + CU_TENSOR_MAP_L2_PROMOTION_L2_256B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled failed %d", (int)r); + return m; +} +static CUtensorMap make_map(const float* ptr, uint64_t rows, uint64_t cols, uint32_t box_rows) { + return cached_map(MapKey{ptr, rows, cols, box_rows, 0}, [&] { return make_map_raw(ptr, rows, cols, box_rows); }); +} +// fp32 [rows, cols] viewed as 3D {32, rows, cols / 32} (strides cols * 4, 128 B), box {32, box_rows, 2}, 128B +// swizzle: ONE TMA load moves the full 64-K extent (both 128 B halves = 256 contiguous bytes) of every box row; +// smem: K half h at + box_rows * 128 h, row r at + 128 r, swizzle phase r & 7 (conflict-free converter reads) +static CUtensorMap make_map3k(const float* ptr, uint64_t rows, uint64_t cols, uint32_t box_rows) { + return cached_map(MapKey{ptr, rows, cols, box_rows, 6}, [&] { + CUtensorMap m; + cuuint64_t dims[3] = {32, rows, cols / 32}; + cuuint64_t strides[2] = {cols * 4, 128}; + cuuint32_t box[3] = {32, box_rows, 2}; + cuuint32_t es[3] = {1, 1, 1}; + CUresult r = cuTensorMapEncodeTiled(&m, CU_TENSOR_MAP_DATA_TYPE_FLOAT32, 3, (void*)ptr, dims, strides, box, es, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, + CU_TENSOR_MAP_L2_PROMOTION_L2_256B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled(f32 3d) failed %d", (int)r); + return m; + }); +} +// fp32 [rows, cols] map with a 16-col x 32-row box, 64B swizzle (o_proj TMA epilogue resid loads / h stores) +static CUtensorMap make_map16(const float* ptr, uint64_t rows, uint64_t cols) { + return cached_map(MapKey{ptr, rows, cols, 16, 4}, [&] { + CUtensorMap m; + cuuint64_t dims[2] = {cols, rows}; + cuuint64_t strides[1] = {cols * 4}; + cuuint32_t box[2] = {16, 32}; + cuuint32_t es[2] = {1, 1}; + CUresult r = cuTensorMapEncodeTiled(&m, CU_TENSOR_MAP_DATA_TYPE_FLOAT32, 2, (void*)ptr, dims, strides, box, es, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_64B, + CU_TENSOR_MAP_L2_PROMOTION_L2_256B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled(f32/16) failed %d", (int)r); + return m; + }); +} +static int num_sms() { + static int n = 0; + if (!n) { int dev; cudaGetDevice(&dev); cudaDeviceGetAttribute(&n, cudaDevAttrMultiProcessorCount, dev); } + return n; +} +template +static void launch_tc(int tiles_upper, const CUtensorMap& a, const CUtensorMap& b0, const CUtensorMap& b1, + const CUtensorMap& b2, const TcArgs& p, cudaStream_t s, const CUtensorMap* b3 = nullptr, + const CUtensorMap* b4 = nullptr) { + constexpr int smem = tc_smem_q(); + // SR = spill-reduced QKV kernel variant (tc_gemm_sr_kernel), host-gated + auto kern = [] { if constexpr (SR) return tc_gemm_sr_kernel; else return tc_gemm_kernel; }(); + { static bool done_ = false; if (!done_) { cudaFuncSetAttribute(kern, cudaFuncAttributeMaxDynamicSharedMemorySize, smem); done_ = true; } } + const int grid = tiles_upper < num_sms() ? tiles_upper : num_sms(); + if (grid <= 0) return; + pdl_launch(kern, dim3(grid), dim3(SR ? tc_threads_sr() : tc_threads()), smem, s, a, b0, b1, b2, b3 ? *b3 : b0, b4 ? *b4 : b0, + p); +} + +// max co-resident 2-CTA clusters of tc_gemm_kernel (queried once; host int only) +template +static int tc_pair_clusters() { + static int n = -1; + if (n < 0) { + cudaFuncSetAttribute(tc_gemm_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, tc_smem_q()); + cudaLaunchConfig_t qc = {}; + qc.gridDim = dim3(2); qc.blockDim = dim3(tc_threads()); qc.dynamicSmemBytes = tc_smem_q(); + cudaLaunchAttribute qa[1]; + qa[0].id = cudaLaunchAttributeClusterDimension; + qa[0].val.clusterDim.x = 2; qa[0].val.clusterDim.y = 1; qa[0].val.clusterDim.z = 1; + qc.attrs = qa; qc.numAttrs = 1; + int c = 0; + if (cudaOccupancyMaxActiveClusters(&c, tc_gemm_kernel, &qc) != cudaSuccess) { cudaGetLastError(); c = 0; } + if (c > num_sms() / 2) c = num_sms() / 2; + n = c; + } + return n; +} +// 2-CTA launch: grid = 2 x (#clusters), cluster (2,1,1), PDL attribute as in pdl_launch +template +static void launch_tc_pair(int pair_tiles, const CUtensorMap& a, const CUtensorMap& b0, const TcArgs& p, cudaStream_t s, + const CUtensorMap* b3 = nullptr, const CUtensorMap* b4 = nullptr, const CUtensorMap* b1 = nullptr) { + const int ncl = pair_tiles < tc_pair_clusters() ? pair_tiles : tc_pair_clusters(); + if (ncl <= 0) return; + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3(2 * ncl); cfg.blockDim = dim3(SR ? tc_threads_sr() : tc_threads()); cfg.dynamicSmemBytes = tc_smem_q(); cfg.stream = s; + cudaLaunchAttribute at[2]; + at[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + at[0].val.programmaticStreamSerializationAllowed = 1; + at[1].id = cudaLaunchAttributeClusterDimension; + at[1].val.clusterDim.x = 2; at[1].val.clusterDim.y = 1; at[1].val.clusterDim.z = 1; + cfg.attrs = at; cfg.numAttrs = 2; + auto kern = [] { if constexpr (SR) return tc_gemm_sr_kernel; else return tc_gemm_kernel; }(); + if constexpr (SR || CGV >= 3) { static bool done_ = false; if (!done_) { cudaFuncSetAttribute(kern, cudaFuncAttributeMaxDynamicSharedMemorySize, tc_smem_q()); done_ = true; } } + cudaLaunchKernelEx(&cfg, kern, a, b0, b1 ? *b1 : b0, b0, b3 ? *b3 : b0, b4 ? *b4 : b0, p); +} +// probe override of the 2-CTA selector: -1 auto, 0 force 1-CTA, 1 force 2-CTA +int g_tc_pair = -1; +bool qkv_use_f8(int T, int S); +bool oproj_use_f8(int T); +static int pick_bn(int T, int N, bool allow64); +template +static bool use_pair(int T, int N) { + if (tc_pair_clusters() <= 0) return false; + if (g_tc_pair >= 0) return g_tc_pair == 1; + if (EPI == EPI_OPROJ) { if (T < 897) return false; } + if (EPI == EPI_QKV && T >= 897 && T < 2048) { + const int sms = num_sms(), ncl = tc_pair_clusters(); + if (ncl <= 0 || pick_bn(T, N, false) != 256) return false; + const int mt = (T + TBM - 1) / TBM, nt = N / 256; + const long KB = HID / 64, E = 4 * 48; + const long t1 = (long)mt * nt, w1 = t1 / sms, r1 = t1 % sms; + long tail = 48; + if (r1 > 0 && 8 * r1 <= sms && r1 <= 2 * mt) tail = 20; + else if (r1 > 0 && 4 * r1 <= sms && r1 <= 2 * mt) tail = 24; + else if (r1 > 0 && 2 * r1 <= sms) tail = 32; + const long c1 = w1 * (KB * 48 + E) + (r1 ? KB * tail + E : 0); + const long t2 = (long)((mt + 1) / 2) * nt; + const long c2 = ((t2 + ncl - 1) / ncl) * (KB * 32 + E); + return c2 < c1; + } + else if (T < 2560) return false; + if (T >= 6000) { + const int sms = num_sms(), ncl = tc_pair_clusters(); + const int mt = (T + TBM - 1) / TBM, nt = N / 256; + const long KB = EPI == EPI_QKV ? (qkv_use_f8(T, g_cur_S) ? HID / 128 : HID / 64) : (oproj_use_f8(T) ? 32 : 64); + const long E = 4 * 48; // KB-equivalent fixed per-tile cost (KB units of 1 KB) + auto cost = [&](long tiles, long slots, long full_kb, long tail_kb, bool split) -> long { + const long w = tiles / slots, r = tiles % slots; + long c = w * (KB * full_kb + E); + if (r > 0) c += KB * (split ? tail_kb : full_kb) + E; + return c; + }; + const long t1 = (long)mt * nt, r1 = t1 % sms; + long c1; + if (EPI == EPI_OPROJ && r1 > 0 && 4 * r1 <= sms) c1 = cost(t1, sms, 48, 24, true); + else c1 = cost(t1, sms, 48, 32, r1 > 0 && 2 * r1 <= sms); + const long t2 = (long)((mt + 1) / 2) * nt, r2 = t2 % ncl; + const long c2 = cost(t2, ncl, 32, 20, EPI == EPI_OPROJ && t2 > ncl && r2 > 0 && 4 * r2 <= ncl); + return c2 <= c1; + } + if (EPI == EPI_QKV) return T >= 7000; + const int sms = num_sms(), mt = (T + TBM - 1) / TBM, nt = N / 256; + const int t1 = mt * nt, r = t1 % sms; + if (r == 0 || 2 * r <= sms) return false; // 1-CTA tail split already handles the last wave + const int ncl = tc_pair_clusters(), t2 = ((mt + 1) / 2) * nt; + return (t2 + ncl - 1) / ncl <= (t1 + sms - 1) / sms; +} + +static CUtensorMap make_map_h_raw(const void* ptr, uint64_t rows, uint64_t cols, uint32_t box_rows) { // fp16 + CUtensorMap m; + cuuint64_t dims[2] = {cols, rows}; + cuuint64_t strides[1] = {cols * 2}; + cuuint32_t box[2] = {64, box_rows}; + cuuint32_t es[2] = {1, 1}; + CUresult r = cuTensorMapEncodeTiled(&m, CU_TENSOR_MAP_DATA_TYPE_FLOAT16, 2, (void*)ptr, dims, strides, box, es, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, + CU_TENSOR_MAP_L2_PROMOTION_L2_256B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled(f16) failed %d", (int)r); + return m; +} +// 8-bit (e4m3 bytes) K-major map: box = 128 bytes of K x box_rows, 128B swizzle +static CUtensorMap make_map_b(const void* ptr, uint64_t rows, uint64_t cols, uint32_t box_rows) { + return cached_map(MapKey{ptr, rows, cols, box_rows, 2}, [&] { + CUtensorMap m; + cuuint64_t dims[2] = {cols, rows}; + cuuint64_t strides[1] = {cols}; + cuuint32_t box[2] = {128, box_rows}; + cuuint32_t es[2] = {1, 1}; + CUresult r = cuTensorMapEncodeTiled(&m, CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, (void*)ptr, dims, strides, box, es, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, + CU_TENSOR_MAP_L2_PROMOTION_L2_256B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled(u8) failed %d", (int)r); + return m; + }); +} +// 8-bit K-major map, box = 64 bytes of K x box_rows, 64B swizzle (FP8 MoE down act operand) +static CUtensorMap make_map_b64(const void* ptr, uint64_t rows, uint64_t cols, uint32_t box_rows) { + return cached_map(MapKey{ptr, rows, cols, box_rows, 3}, [&] { + CUtensorMap m; + cuuint64_t dims[2] = {cols, rows}; + cuuint64_t strides[1] = {cols}; + cuuint32_t box[2] = {64, box_rows}; + cuuint32_t es[2] = {1, 1}; + CUresult r = cuTensorMapEncodeTiled(&m, CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, (void*)ptr, dims, strides, box, es, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_64B, + CU_TENSOR_MAP_L2_PROMOTION_L2_256B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled(u8/64) failed %d", (int)r); + return m; + }); +} +static CUtensorMap make_map_h(const void* ptr, uint64_t rows, uint64_t cols, uint32_t box_rows) { + return cached_map(MapKey{ptr, rows, cols, box_rows, 1}, [&] { return make_map_h_raw(ptr, rows, cols, box_rows); }); +} +static int pick_bn(int T, int N, bool allow64) { + const int mt = (T + TBM - 1) / TBM, sms = num_sms(); + int best = 256; long bestc = -1; + const int cands[3] = {256, 128, 64}; + for (int i = 0; i < (allow64 ? 3 : 2); i++) { + const int bn = cands[i]; + const long tiles = (long)mt * (N / bn); + long c = ((tiles + sms - 1) / sms) * (bn + 240); + if (bn == 256) { // a final partial wave of r <= sms/2 tiles runs as 2r half (N=128) tiles + const long r = tiles % sms; + if (r > 0 && 2 * r <= sms) c = (tiles / sms) * (256 + 240) + (128 + 240); + // OPROJ also splits r <= sms/4 tail tiles into 4r quarter (N=64) tiles + if (allow64 && r > 0 && 4 * r <= sms) c = (tiles / sms) * (256 + 240) + (64 + 240); + if (r > 0 && 2 * r <= sms) c += 1; + } + if (bestc < 0 || c < bestc) { bestc = c; best = bn; } + } + return best; +} +// Host-side tile selector for the grouped MoE GEMMs (per T; the real tile count is device-side). Expected M tiles +// assume uniform routing: count_e ~ Normal(8T/128, var), E[ceil(count_e/128)] summed over the 128 experts. +// BN=256 cost includes the device-side tail split (a final wave of r <= grid/2 tiles runs as half tiles); +// per-tile cost ~ (A rows + B rows) = BN + 128. Returns 128 (split every tile) only if strictly cheaper. +static int pick_bn_grouped(int T, int NT) { + const double mu = 8.0 * T / NEXP, sd = sqrt(mu * (1.0 - 1.0 / NEXP)) + 1e-9; + double et = 0.0; + for (int k = 0; k * 128.0 < mu + 10 * sd + 128; k++) et += 0.5 * erfc((128.0 * k + 0.5 - mu) / (sd * 1.41421356)); + const long F = (long)(et * NEXP + 0.5) * NT, G = num_sms(); + const long r = F % G; + const long c256 = (F / G) * 384 + (r ? (2 * r <= G ? 256 : 384) : 0); + const long c128 = ((2 * F + G - 1) / G) * 256; + return c128 < c256 ? 128 : 256; +} +void launch_rmsnorm_hl(const float* x, const float* w, float eps, int T, float* hi, float* lo, float* ssq, + cudaStream_t s) { + pdl_launch(rmsnorm_kernel<2>, dim3(T), dim3(256), 0, s, x, w, eps, (void*)hi, lo, ssq); +} +void launch_rmsnorm_h(const float* x, const float* w, float eps, int T, __half* out, float* ssq, cudaStream_t s) { + pdl_launch(rmsnorm_kernel<1>, dim3(T), dim3(256), 0, s, x, w, eps, (void*)out, (float*)nullptr, ssq); +} +int g_prep_mode = 0; // probe only: 1 rows-only, 2 conversion-only +int g_prep_var = PREP_VAR_DEFAULT; +void launch_prep_qkv(const float* x, const float* w, float eps, int T, __half* xn, float* ssq, const float* wq, + const float* wk, const float* wv, __half* wqkv16, const float* cs, const float* sn, float* csT, + float* snT, int* zbuf, int nz, __half* vt, int S, int Spad, cudaStream_t s, const float* qnw, + const float* knw, float* winvq, float* xinv, __half* xn16s) { + int nconv = qkv_w32(T) ? 0 : (int)(((size_t)NQKV * HID / 4) / PREP_CONV4); + // when the QKV GEMM consumes fp32 Wqkv itself) + const int x3 = qkv_x3(T) ? 1 : 0; // 3-term xn / Wqkv layout (must match launch_qkv_rope_gemm and main.cpp) + if (g_prep_mode == 1) nconv = 0; + if (g_prep_mode == 2) T = 0; + const int pv = g_prep_var >= 0 ? g_prep_var : (T >= 3500 ? 1 : 0); // gate 6000 -> 3500 + auto kern = pv == 1 ? prep_qkv_kernel<1> : prep_qkv_kernel<0>; + pdl_launch(kern, dim3((T + 3) / 4 + nconv), dim3(256), 0, s, x, w, eps, T, xn, ssq, wq, wk, wv, wqkv16, cs, sn, + csT, snT, zbuf, nz, vt, S, Spad, (S > 0 && T > 0 && attn_qk_f8(T / S, S)) ? qk_bounds() : nullptr, qnw, knw, winvq, xinv, xn16s, + (S > 0 && T >= QKV_F16TAB_MIN_T && qkv_use_f8(T, S)) ? 1 : 0, x3); // tables for the SR e4m3 QKV epilogue +} +extern int g_qkv_vq; +// grid of the T < 2048 (non-QF, 1-CTA) QKV GEMM - same tiling as launch_qkv_rope_gemm (pick_bn + wave-tail split) +static int qkv_small_grid(int T) { + const int BN = pick_bn(T, NQKV, false), NT = NQKV / BN, G = num_sms(); + const int nmt = (T + TBM - 1) / TBM, nfull = nmt * NT, r = nfull % G; + int qs = (BN == 256 && r > 0 && 2 * r <= G) ? r : 0, ospl = 2; + if (g_qkv_vq && BN == 256 && NT == 20 && r > 0 && 4 * r <= G && r <= 2 * nmt) { qs = r; ospl = 4; } + if (g_qkv_vq && BN == 256 && NT == 20 && r > 0 && 8 * r <= G && r <= 2 * nmt) { qs = r; ospl = 8; } + const int tiles = nfull + qs * (ospl - 1); + return tiles < G ? tiles : G; +} +int g_qkv_csteal = 0; +int g_abl = 0; // ABL_PROBE builds only +int g_abl_sr = -1; // Wo convert units [0, g_qkv_csteal) executed inside the QKV GEMM (set per call) +extern int g_force_bn; +static int router_ks(int mt); +static int mor_max_clusters(); +// T < 2048 merged o_proj + router launch consumes fp32 Wo directly (in-smem fp16 conversion): no Wo16 copy. +// Must match the merge condition in launch_oproj_gemm (host-only decision, shape-keyed). +bool oproj_wo32(int T); +bool qkv_w32(int T) { (void)T; return false; } +bool qkv_x3(int T) { return T > 0 && T < QKV_F16TAB_MIN_T && !qkv_w32(T); } +bool oproj_wo32(int T) { + if (T <= 0 || T >= QKV_F16TAB_MIN_T || oproj_use_f8(T) || g_force_bn) return false; + if (use_pair(T, HID) || pick_bn(T, HID, true) != 128) return false; + const int mt = (T + TBM - 1) / TBM; + return mt <= 16 && router_ks(mt) == 16 && mt <= mor_max_clusters(); +} +void launch_convert_w16(const float* src, __half* dst, size_t n, const float* wr, float* wrh, float* wrl, + cudaStream_t s, int f8, float* winv, int T) { + const size_t n4 = n / 4; + const int grid = oproj_wo32(T) ? 0 : (int)((n4 + 1023) / 1024); // router Wr units only + const int nwr4 = NEXP * HID / 4, gsplit = (nwr4 + 1023) / 1024; + // fp16 Wo (T < 2048): the QKV GEMM's idle warps take <= 7 units each of [0, csteal); only the rest launched + int cst_n = 0; + if (f8 == 0 && T > 0 && T < QKV_F16TAB_MIN_T) { + const int c = 2 * qkv_small_grid(T) * 7; + cst_n = c < grid ? c : grid; + } + g_qkv_csteal = cst_n; + g_conv_target += (unsigned long long)(grid + gsplit); + unsigned* cst = claim_words(0); // convert claim region (grid + gsplit == CONV_UNITS) + g_conv_job = sidew::ConvJob{src, dst, grid, grid + gsplit, f8, wr, wrh, wrl, winv, cst, g_epoch, + side_ctrs() + 1, g_conv_target}; + pdl_launch(convert_w16_kernel, dim3(grid + gsplit - cst_n), dim3(256), 0, s, src, dst, n4, 16.f, grid, wr, wrh, wrl, + nwr4, side_ctrs() + 1, f8, winv, cst, SKIPEP(g_epoch), cst_n); +} +bool attn_qk_f8(int B, int S); +#ifndef QKV_F8_MIN_T +#define QKV_F8_MIN_T 4096 +#endif +#ifndef QKV_F8_MIN_S +#define QKV_F8_MIN_S 2048 +#endif +int g_qkv8 = -1; // probe override: -1 threshold, 0 / 1 force +bool qkv_use_f8(int T, int S) { + if (T < QKV_F16TAB_MIN_T) return false; + if (g_qkv8 >= 0) return g_qkv8 == 1; + return (T >= QKV_F8_MIN_T && S >= QKV_F8_MIN_S) || (T >= 6000 && S >= 256) || (T >= 2048 && S >= 256 && S < 384); +} +// split QKV - e4m3 operands for the Q/K output columns (n < 4608), fp16 for the V columns (separate tile class +// inside the same persistent GEMM). Only where full e4m3 QKV is not used (S-driven V error). g_qkv_vs: probe override. +int g_qkv_vs = -1; +#ifndef QKV_VS_TABLE +#define QKV_VS_TABLE(T, S) ((T) >= 2048 && (S) >= 300 && (S) < 384) +#endif +bool qkv_vsplit(int T, int S) { + if (T < QKV_F16TAB_MIN_T || qkv_use_f8(T, S)) return false; + if (g_qkv_vs >= 0) return g_qkv_vs == 1; + return QKV_VS_TABLE(T, S); +} +unsigned long long* g_probe_qkv = nullptr; unsigned long long* g_probe_o = nullptr; // debug probe (off: nullptr) +int g_qkv_vq = 1; // V-quarter QKV tail (probe knob) +int g_force_bn = 0, g_pmode = 0; unsigned long long* g_cprobe = nullptr; // TC_PROBE builds only +void launch_qkv_rope_gemm(const __half* xn, const __half* wqkv, const float* bq, const float* bk, const float* bv, + const float* cs, const float* sn, const float* qnw, const float* knw, float eps, int B, int S, + int Spad, __half* q, __half* k, __half* v, cudaStream_t s, unsigned* vmax, + const float* winvq, const float* xinv, const __half* xn16s, const float* wq32, + const float* wk32, const float* wv32, int* qbc) { + const int T = B * S; + const bool vs = qkv_vsplit(T, S); // e4m3 Q/K tiles + fp16 V tiles (xn16s = fp16 xn copy) + const bool f8q = qkv_use_f8(T, S) || vs; // e4m3 xn / Wqkv (byte maps, 128 B of K per box row) + bool qkv_sr = !vs && T >= 2048; // SR epilogue kernel also for 2048 <= T < 3500 (8x373 / 8x256 e4m3 QKV) +#ifdef ABL_PROBE + if (g_abl_sr >= 0) qkv_sr = !vs && g_abl_sr == 1; +#endif + const bool qkv_sr16 = false; + auto mapq = [&](const void* ptr, uint64_t rows, uint64_t cols, uint32_t br) { + return f8q ? make_map_b(ptr, rows, cols, br) : make_map_h(ptr, rows, cols, br); + }; + // qkv_x3: xn / Wqkv rows hold 3 K-concatenated fp16 segments (K = QKV_X3_K, see qkv_x3); same tiling + const bool x3 = !f8q && qkv_x3(T); + const int KQ = x3 ? QKV_X3_K : HID; + CUtensorMap a = mapq(xn, T, KQ, 128); + TcArgs p{}; + p.vmax = vmax; // non-null: fp8 o_proj mode (global max |V| for the attention-output scale) + p.BN = g_force_bn ? g_force_bn : pick_bn(T, NQKV, false); + const bool pair = use_pair(T, NQKV); + if (pair) p.BN = 256; + CUtensorMap mw = mapq(wqkv, NQKV, KQ, pair ? 128 : p.BN); // pair: each CTA loads a 128-row B half + p.qws = winvq; p.qxs = xinv; + p.M = T; p.KB = f8q ? HID / 128 : KQ / 64; p.NT = NQKV / p.BN; p.S = S; p.Spad = Spad; p.eps = eps; + const int nfull = ((T + TBM - 1) / TBM) * p.NT, G = num_sms(); + { + const int r = nfull % G; // nfull < G -> r = nfull (everything fits in one wave of half tiles if 2r <= G) + p.qsplit = (p.BN == 256 && r > 0 && 2 * r <= G) ? r : 0; + p.ospl = 2; + // T < 2048 (non-QF epilogue): tail tiles as V quarters if they fit (r <= #V tiles, 4r <= #SMs) + const int nmt = (T + TBM - 1) / TBM; + if (g_qkv_vq && !pair && T < QKV_F16TAB_MIN_T && p.BN == 256 && p.NT == 20 && r > 0 && 4 * r <= G && r <= 2 * nmt) { + p.qsplit = r; p.ospl = 4; + } + // V eighths (N = 32: 20 KB per k-block instead of 24 KB, twice the tail CTAs) when 8r <= #SMs + if (g_qkv_vq && !pair && T < QKV_F16TAB_MIN_T && p.BN == 256 && p.NT == 20 && r > 0 && 8 * r <= G && r <= 2 * nmt) { + p.qsplit = r; p.ospl = 8; + } + } + p.bias0 = bq; p.bias1 = bk; p.bias2 = bv; p.cs = cs; p.sn = sn; p.qnw = qnw; p.knw = knw; + p.q = q; p.k = k; p.v = v; p.probe = g_probe_qkv; + p.qbc = (T < QKV_F16TAB_MIN_T && vmax == nullptr) ? qbc : nullptr; // attention gate +#ifdef ABL_PROBE + p.abl = g_abl; +#endif + // QKV idle warps steal Wo convert units (T < 2048 non-QF epilogue, fp16 Wo16 only) + const bool w32 = qkv_w32(T) && wq32 != nullptr; + if (!w32 && T < QKV_F16TAB_MIN_T && !oproj_use_f8(T) && g_qkv_csteal > 0) { p.conv = g_conv_job; p.csteal = g_qkv_csteal; } + p.qkb = attn_qk_f8(B, S) ? qk_bounds() : nullptr; // FA4 FP8 QK^T: e4m3 q / k (QF epilogue only: S >= 2048 -> T >= 2048) + const bool qf = T >= QKV_F16TAB_MIN_T; // fp16 RoPE tables (prep_qkv) + streamed TMEM epilogue (+ e4m3 operands) + // VS maps: fp16 xn A operand and fp16 V weight rows [512][2048] (stored after the 5120 x 2048 e4m3 Wqkv bytes) + const __half* wv16 = reinterpret_cast(reinterpret_cast(wqkv) + (size_t)NQKV * HID); + if (pair) { + p.qsplit = 0; + const int pt = ((T + 2 * TBM - 1) / (2 * TBM)) * p.NT; + if (vs) { + CUtensorMap mv = make_map_h(wv16, 512, HID, 128), xh = make_map_h(xn16s, T, HID, 128); + launch_tc_pair(pt, a, mw, p, s, &mv, &xh); // tB3 = V rows, tB4 = fp16 xn + return; + } + if (qf && f8q && qkv_sr) launch_tc_pair(pt, a, mw, p, s); + else if (qf && f8q) launch_tc_pair(pt, a, mw, p, s); + else if (qf && qkv_sr16) launch_tc_pair(pt, a, mw, p, s); + else if (qf) launch_tc_pair(pt, a, mw, p, s); + else launch_tc_pair(pt, a, mw, p, s); + return; + } + CUtensorMap mw128 = mapq(wqkv, NQKV, KQ, 256 / p.ospl); // tail half tiles (one head) / V quarters + if (vs) { + CUtensorMap xh = make_map_h(xn16s, T, HID, 128); + CUtensorMap mv = make_map_h(wv16, 512, HID, p.BN), mv128 = make_map_h(wv16, 512, HID, 128); + launch_tc(nfull + p.qsplit * (p.ospl - 1), a, mw, mw128, xh, p, s, &mv, &mv128); + return; + } + if (qf && f8q && qkv_sr) launch_tc(nfull + p.qsplit * (p.ospl - 1), a, mw, mw128, mw, p, s); + else if (qf && f8q) launch_tc(nfull + p.qsplit * (p.ospl - 1), a, mw, mw128, mw, p, s); + else if (qf && qkv_sr16) launch_tc(nfull + p.qsplit * (p.ospl - 1), a, mw, mw128, mw, p, s); + else if (qf) launch_tc(nfull + p.qsplit * (p.ospl - 1), a, mw, mw128, mw, p, s); + else if (w32) { + // tB2 / tB3 / tB4 = fp32 Wq / Wk / Wv maps (box 32 floats x 64 rows, 128B swizzle) + CUtensorMap m2 = make_map(wq32, 4096, HID, 64), m3 = make_map(wk32, 512, HID, 64), m4 = make_map(wv32, 512, HID, 64); + launch_tc(nfull + p.qsplit * (p.ospl - 1), a, mw, mw128, m2, p, s, &m3, &m4); + } else launch_tc(nfull + p.qsplit * (p.ospl - 1), a, mw, mw128, mw, p, s); +} +int g_oproj_f8 = -1; +bool oproj_use_f8(int T) { + if (T < OPROJ_F8_MIN_T) return false; + if (g_oproj_f8 >= 0) return g_oproj_f8 == 1; + return true; +} +// merged o_proj + router (T < 2048): o_proj launch state stashed here, launched by launch_router +struct MorState { bool pending; CUtensorMap a, a32, mo, msub, mh, mr; TcArgs p; int* sctr; const char* wo16; const char* attn; }; +static MorState g_mor{}; +static int router_ks(int mt); +static int mor_max_clusters(); +void launch_oproj_gemm(const __half* attn, const __half* wo16, const float* bo, const float* resid, float* h, int T, + float* ssq, cudaStream_t s, const unsigned* vmax, const float* winv, int* sctr, const float* wo32, int* mtctr) { + // f8: attn = e4m3 bytes [T, 4096] (x global pow2 scale), wo16 = e4m3 Wo bytes [2048, 4096] (x per-row pow2 scale) + const bool f8 = oproj_use_f8(T); + auto mapx = [&](const void* ptr, uint64_t rows, uint64_t cols, uint32_t br) { + return f8 ? make_map_b(ptr, rows, cols, br) : make_map_h(ptr, rows, cols, br); + }; + CUtensorMap a = mapx(attn, T, 4096, 128); + TcArgs p{}; + p.BN = g_force_bn ? g_force_bn : pick_bn(T, HID, true); + p.cprobe = g_cprobe; p.pmode = g_pmode; + bool pair = use_pair(T, HID); + if (pair) p.BN = 256; + // 2-CTA cta_group::2 m256n128 pairs - each CTA loads its own + // 128 attn rows + only 64 Wo rows per k-block (24 KB instead of 32 KB per SM: the 1-CTA BN=128 mainloop is L2->SM + // feed-bound), same per-SM output tile (128 x 128). Used when it needs no more waves than the 1-CTA tiling. + if (!pair && !f8 && !g_force_bn && T >= 897 && T < 2048 && p.BN == 128 && tc_pair_clusters() > 0) { + const int mt1 = (T + TBM - 1) / TBM, ncl = tc_pair_clusters(), G1 = num_sms(); + const int t1 = mt1 * (HID / 128), t2 = ((mt1 + 1) / 2) * (HID / 128); + if ((t2 + ncl - 1) / ncl <= (t1 + G1 - 1) / G1) pair = true; + } + CUtensorMap mo = mapx(wo16, HID, 4096, pair ? p.BN / 2 : p.BN); // pair: each CTA loads a 128-row B half + p.vmax = const_cast(vmax); p.wsc = winv; + p.M = T; p.KB = f8 ? 4096 / 128 : 4096 / 64; p.NT = HID / p.BN; p.bias0 = bo; p.resid = resid; p.out = h; p.ssq = ssq; + const int nfull = ((T + TBM - 1) / TBM) * p.NT, G = num_sms(); + p.qsplit = 0; p.ospl = 2; + if (p.BN == 256) { // wave-tail split (must match pick_bn's cost model) + const int r = nfull % G; + if (r > 0 && 4 * r <= G) { p.qsplit = r; p.ospl = 4; } + else if (r > 0 && 2 * r <= G) { p.qsplit = r; p.ospl = 2; } + } + CUtensorMap msub = mapx(wo16, HID, 4096, 256 / p.ospl); + p.probe = g_probe_o; +#ifdef ABL_PROBE + p.abl = g_abl; +#endif + p.qkb_reset = qk_bounds(); + p.dl = g_oproj_dl; + p.mtctr = T >= 2048 ? mtctr : nullptr; // router M-tile handoff + if (T >= 897 && T < 2048 && g_pf2_kb > 0 && g_pf_wg != nullptr && moe_self_tables(T) && !oproj_use_f8(T)) { + const int G = num_sms(); + p.pfg = g_pf_wg; p.pfu = g_pf_wu; + p.pf_t0 = G < NEXP * 12 ? G : NEXP * 12; p.pf_t1 = 2 * G < NEXP * 12 ? 2 * G : NEXP * 12; + p.pf_kb = g_pf2_kb; p.pf_krot = g_mf16_krot; + } + // epilogue TMA maps: h store (tB3) and resid load (tB4), fp32 [T, 2048], box 16 cols x 32 rows, 64B swizzle + // (tB3 / tB4 are otherwise unused by o_proj) + CUtensorMap mh = make_map16(h, T, HID), mr = make_map16(resid, T, HID); + p.side_ctr = side_ctrs() + 1; p.side_target = g_conv_target; p.conv = g_conv_job; // tail sub-tile B box (128 or 64 rows) + p.ores = (f8 && T >= 2048 && (T < 6000 || T >= 8000)) ? 1 : 0; // + T>=8000 OP4 pairs (last-tile resid staged in dead ring); also the 2-CTA pair path (OP4, CG 2) + if (pair) { + p.qsplit = 0; p.ospl = 2; + const int pt = ((T + 2 * TBM - 1) / (2 * TBM)) * p.NT; + if (f8) { + // wave-tail split of the e4m3 pair tiling (e.g. 16x449: 232 pair tiles on 74 clusters = 3 waves + 10): + // the last r tiles run as N = 64 (4r <= #clusters) or N = 128 (2r <= #clusters) sub-tiles + const int ncl = tc_pair_clusters(); + if (ncl > 0 && pt > ncl) { + const int r = pt % ncl; + if (r > 0 && 4 * r <= ncl) { p.qsplit = r; p.ospl = 4; } + } + CUtensorMap msp = mapx(wo16, HID, 4096, (256 / p.ospl) / 2); + // 6000 <= T < 8000 (16x449 class): 64 KB double-sub-block stages (CG 4), half the pair handshakes + if (T >= 6000 && (p.KB & 1) == 0) launch_tc_pair(pt, a, mo, p, s, &mh, &mr, &msp); + else launch_tc_pair(pt, a, mo, p, s, &mh, &mr, &msp); + } + else if (p.BN == 128 && (p.KB & 1) == 0) launch_tc_pair(pt, a, mo, p, s, &mh, &mr); // 2 sub-blocks / stage + else launch_tc_pair(pt, a, mo, p, s, &mh, &mr); + return; + } + g_mor.pending = false; + { + const int mt = (T + TBM - 1) / TBM; + if (oproj_wo32(T) && wo32 != nullptr && p.BN == 128 && p.qsplit == 0 && mt <= 16) { + // tB0 = fp32 Wo map (box 32 floats x 128 rows, 128B swizzle), converted in smem by the kernel + g_mor.pending = true; g_mor.a = a; g_mor.a32 = make_map_h(attn, T, 4096, 64); g_mor.mo = make_map(wo32, HID, 4096, 128); g_mor.msub = msub; g_mor.mh = mh; g_mor.mr = mr; g_mor.p = p; + g_mor.sctr = sctr; g_mor.wo16 = nullptr; g_mor.attn = reinterpret_cast(attn); + return; + } + } + // fp16 1-CTA BN=128 (no tail split) in 897 <= T < 2048: double-K stages (half the producer/MMA handshakes) + p.kd2 = (!f8 && T >= 897 && T < 2048 && p.BN == 128 && p.qsplit == 0 && (p.KB & 1) == 0) ? 1 : 0; + // last tile's resid half-chunks k >= 2 staged in the dead operand ring (e4m3 1-CTA); also fp16 kd2 + // 1-CTA o_proj (897 <= T < 2048, 1 tile per CTA: the whole epilogue resid refill chain sat after the mainloop) + p.ores = ((f8 && T >= 2048 && T < 6000) || p.kd2) ? 1 : 0; + if (f8) launch_tc(nfull + p.qsplit * (p.ospl - 1), a, mo, msub, mo, p, s, &mh, &mr); + else launch_tc(nfull + p.qsplit * (p.ospl - 1), a, mo, msub, mo, p, s, &mh, &mr); +} +int* g_mcl_ctr = nullptr; +int* g_pre_ctr = nullptr; +// persistent e5m2 scratch for pre-converted expert gate / up weights [2][PRE_CAP * 768][2048] bytes +// (raw cudaMalloc, never freed: no tensor state). Fully rewritten (as needed) by every call's attention kernel. +static uint8_t* pre_scratch() { + static uint8_t* p = nullptr; + if (!p) { cudaMalloc(&p, (size_t)2 * PRE_CAP * INTER * HID); cudaDeviceSynchronize(); } + return p; +} +static CUtensorMap make_map_b64(const void* ptr, uint64_t rows, uint64_t cols, uint32_t box_rows); +static CUtensorMap pre_map() { return make_map_b64(pre_scratch(), (uint64_t)2 * PRE_CAP * INTER, HID, 64); } +static int moe_f16_gmax(int T); +bool moe_use_fp8_down(int T); +static CUtensorMap g_mcl_map; +bool fa4_mcl(int B, int S) { return g_mcl_ctr != nullptr && (S & 3) == 0 && S > 4096 && attn_qk_f8(B, S); } +void launch_mask_classify(const float* mask, int B, int S, uint8_t* codes, float* mtile, cudaStream_t s) { + const int nT = (S + 127) / 128; + if (fa4_mcl(B, S)) { + // no side grid - the FA4 attention kernel's idle warps classify the tiles (per-row readiness counters) + ++g_epoch; + const int nm = nT * nT * B; + g_mask_job = sidew::MaskJob{mask, S, nT, nm, codes, mtile, claim_words(nm) + CONV_UNITS, g_epoch, side_ctrs(), g_mask_target}; + g_mcl_map = cached_map(MapKey{mask, (uint64_t)B, (uint64_t)S, 128, 5}, [&] { + CUtensorMap m; + cuuint64_t dims[3] = {(cuuint64_t)S, (cuuint64_t)S, (cuuint64_t)B}; + cuuint64_t strides[2] = {(cuuint64_t)S * 4, (cuuint64_t)S * S * 4}; + cuuint32_t box[3] = {128, 128, 1}; + cuuint32_t es[3] = {1, 1, 1}; + CUresult r = cuTensorMapEncodeTiled(&m, CU_TENSOR_MAP_DATA_TYPE_FLOAT32, 3, (void*)mask, dims, strides, box, es, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, + CU_TENSOR_MAP_L2_PROMOTION_L2_256B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled(mask) failed %d", (int)r); + return m; + }); + return; + } + // plain launch on the side stream (not part of the PDL chain on the main stream) + g_mask_target += (unsigned long long)nT * nT * B; + ++g_epoch; // one epoch per forward (launch_mask_classify runs first among the side launches of a call) + const int nmask = nT * nT * B; + unsigned* cw = claim_words(nmask); + g_mask_job = sidew::MaskJob{mask, S, nT, nmask, codes, mtile, cw + CONV_UNITS, g_epoch, side_ctrs(), g_mask_target}; +#ifdef STRESS_PROBE + if (g_side_skip) { sidew::MaskJob j0 = g_mask_job; j0.ep = 0; mask_classify_kernel<<>>(j0); return; } +#endif + if ((S & 3) == 0) { // TMA tile classifier (global strides S*4, S*S*4 multiples of 16) + const CUtensorMap tm = cached_map(MapKey{mask, (uint64_t)B, (uint64_t)S, 128, 5}, [&] { + CUtensorMap m; + cuuint64_t dims[3] = {(cuuint64_t)S, (cuuint64_t)S, (cuuint64_t)B}; + cuuint64_t strides[2] = {(cuuint64_t)S * 4, (cuuint64_t)S * S * 4}; + cuuint32_t box[3] = {128, 128, 1}; + cuuint32_t es[3] = {1, 1, 1}; + CUresult r = cuTensorMapEncodeTiled(&m, CU_TENSOR_MAP_DATA_TYPE_FLOAT32, 3, (void*)mask, dims, strides, box, es, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, + CU_TENSOR_MAP_L2_PROMOTION_L2_256B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled(mask) failed %d", (int)r); + return m; + }); + static bool attrt = false; + if (!attrt) { + cudaFuncSetAttribute(mask_classify_tma_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, MASK_BULK_SMEM); + cudaFuncSetAttribute(mask_classify_tma_persist_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, MASK_BULK_SMEM); + attrt = true; + } + if (S >= 2048 && S < 8192) { + const int mg = nmask < MASK_PERSIST_CTAS ? nmask : MASK_PERSIST_CTAS; + mask_classify_tma_persist_kernel<<>>(tm, g_mask_job); + } else + mask_classify_tma_kernel<<>>(tm, g_mask_job); + return; + } + mask_classify_kernel<<>>(g_mask_job); +} +#ifndef FA_PM_DEFAULT +#define FA_PM_DEFAULT 2 // probe: 1/4 offload best or tied on 1x1024, 16x449, 8x373, 32x256, 2x512 +#endif +static bool fa4_use(int S) { return S >= 2048; } +// FP8 (e4m3) QK^T in the FA4 kernel: g_qk8 -1 = default (QK8_DEFAULT), 0 / 1 = force (probe builds) +#ifndef QK8_DEFAULT +#define QK8_DEFAULT 1 +#endif +int g_qk8 = -1; +// FA4 kernel selection (shared by launch_flash_attn and the FP8 QK^T decision): long sequences, or short sequences +// with many head-pair items (B * 16 * nT >= 6 x #SMs, ) +// many-batch mid-S threshold lowered 6 -> 2 x #SMs head-pair items with S >= 300 (8x373 class: 384 items, +// FA4 full-row softmax + FP8 QK^T instead of the half-row head-pair kernel); S < 300 keeps the 6 x #SMs rule +static bool fa4_sel(int B, int S) { + const int it = B * 16 * ((S + 127) / 128); + return fa4_use(S) || it >= 6 * num_sms() || (S >= 300 && it >= 2 * num_sms()); +} +// FP8 QK^T also for the short-S FA4 path (T >= 2048 so the QKV QF epilogue writes e4m3 q / k) +bool attn_qk_f8(int B, int S) { + if (!fa4_sel(B, S) || B * S < QKV_F16TAB_MIN_T || (S < 300 && B * S < 6000)) return false; + return g_qk8 >= 0 ? g_qk8 == 1 : QK8_DEFAULT != 0; +} +int g_fa_force = 0; // probe override (FA_PROBE builds) +int g_fa_pm = -1; // probe override of the MUFU-offload level (FA_PROBE builds) +// MUFU-offload level of the head-pair / single-head attention softmax per S range: 0 none, 1 = 1/8, 2 = 1/4 +static int fa_poly_level(int S) { (void)S; return FA_PM_DEFAULT; } +extern int g_mf16_krot; +void launch_flash_attn(const __half* q, const __half* k, const __half* vt, const float* mask, const uint8_t* codes, + __half* out, int B, int S, int Spad, int* work_ctr, cudaStream_t s, const unsigned* vmax, + const float* pfg, const float* pfu, const int* qbc) { + // first-wave MoE weight L2 prefetch (T < 2048 self-table fp16 MoE only: item order known) + const bool pf_on = pfg != nullptr && moe_self_tables(B * S) && B * S < 2048 && g_pf1_kb > 0; + g_pf_wg = pfg; g_pf_wu = pfu; + const int pf_items = num_sms() < NEXP * 6 ? num_sms() : NEXP * 6; + const int nT = (S + 127) / 128; + const bool qk8 = attn_qk_f8(B, S); // e4m3 q / k rows (128 B): one 128-byte x 128-row box per tile + CUtensorMap mq = qk8 ? make_map_b(q, (uint64_t)B * 32 * S, 128, 128) : make_map_h(q, (uint64_t)B * 32 * S, 128, 128); + CUtensorMap mk = qk8 ? make_map_b(k, (uint64_t)B * 4 * S, 128, 128) : make_map_h(k, (uint64_t)B * 4 * S, 128, 128); + CUtensorMap mv = make_map_h(vt, (uint64_t)B * 4 * 128, Spad, 128); + { static bool done_ = false; if (!done_) { + cudaFuncSetAttribute(tc_flash_attn_kernel<1, 0, 3>, cudaFuncAttributeMaxDynamicSharedMemorySize, FaCfg<1>::SMEM); + cudaFuncSetAttribute(tc_flash_attn_kernel<2, 0, 3>, cudaFuncAttributeMaxDynamicSharedMemorySize, FaCfg<2>::SMEM); + cudaFuncSetAttribute(tc_flash_attn_kernel<2, 0x0101, 3>, cudaFuncAttributeMaxDynamicSharedMemorySize, FaCfg<2>::SMEM); + cudaFuncSetAttribute(tc_flash_attn_kernel<2, 0x1111, 3>, cudaFuncAttributeMaxDynamicSharedMemorySize, FaCfg<2>::SMEM); + cudaFuncSetAttribute(tc_flash_attn_kernel<1, 0x5555, 2>, cudaFuncAttributeMaxDynamicSharedMemorySize, FaCfg<1>::SMEM); + cudaFuncSetAttribute(tc_flash_attn_kernel<1, 0x5555, 2, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, FaCfg<1>::SMEM); + done_ = true; } } + // softmax scale in log2 domain, also undoing the 2^-6 * 2^-6 fp16 pre-scaling of q and k + const float sl2 = 0.08838834764831845f * 1.4426950408889634f * 4096.f; + // Heads per item (1 or 2, picked on the host by an LPT makespan estimate). A head-pair item shares every K/V + // tile load between the 2 q heads of one GQA group and pipelines S of one head under the other head's softmax, + // so a virtual tile costs ~0.65 of a single-head tile; single-head items give twice the items (better SM fill / + // balance). Cost model (unit = one single-head kv tile): item = 1 (Q load + epilogue) + n_kv * NH * c_NH, + // n_kv = qt + 1 (causal estimate; the mask itself is only classified on the device), items greedily assigned in + // the kernel's LPT order to the earliest-free of min(#SMs, #items) CTAs; pair mode if its makespan is not larger. + auto makespan = [&](int nh) -> double { + const int per = B * 32 / nh, nitems = nT * per, g = nitems < num_sms() ? nitems : num_sms(); + const double c = nh == 1 ? 1.0 : 0.65; + std::vector fin(g, 0.0); // min-heap of CTA finish times + for (int qt = nT - 1; qt >= 0; qt--) { + const double w = 1.0 + (qt + 1) * nh * c; + for (int i = 0; i < per; i++) { + std::pop_heap(fin.begin(), fin.end(), std::greater()); + fin.back() += w; + std::push_heap(fin.begin(), fin.end(), std::greater()); + } + } + return *std::max_element(fin.begin(), fin.end()); + }; + // host-only memo of the decision per (B, nT) (the simulation costs O(#items log #SMs)) + static int memo_b = -1, memo_nt = -1; + static bool memo_single = false; + if (memo_b != B || memo_nt != nT) { memo_single = makespan(2) > makespan(1); memo_b = B; memo_nt = nT; } + bool single = memo_single; + if (B * S < 2048) single = true; + int sel = 0; // 0 = auto (current production choice), 1 = NH1, 2 = NH2, 4 = FA4 +#ifdef FA_PROBE + sel = g_fa_force; +#endif + if (sel == 0 && fa4_sel(B, S)) sel = 4; + if (sel == 0 && fa4_use(S)) sel = 4; + if (sel == 4) { + const bool mcl = fa4_mcl(B, S); + // MCL attention (1x8192 class) pre-converts expert gate/up weights for the MALT MoE in its idle warps + const int T_ = B * S; + const bool pre = mcl && g_pre_ctr != nullptr && pfg != nullptr && moe_use_fp8(T_) && moe_use_fp8_down(T_) && + moe_f16_gmax(T_) == 4; + launch_fa4_attn(mq, mk, mv, mask, codes, out, B, S, sl2, work_ctr, &g_mask_job, num_sms(), s, vmax, + qk8 ? qk_bounds() : nullptr, mcl ? &g_mcl_map : nullptr, mcl ? g_mcl_ctr : nullptr, + pfg, pfu, pre ? pre_scratch() : nullptr, g_pre_ctr, PRE_CAP); + return; + } + if (sel == 1) single = true; + if (sel == 2) single = false; + const int items = nT * (single ? 32 : 16) * B; // (q tile, batch, head [pair]) work items + const int grid = items < num_sms() ? items : num_sms(); + int pm = fa_poly_level(S); + // head-pair band T>=2048, S<300 (16x128 / 8x256: <=2 kv tiles per item, latency-bound softmax chain): + // all-MUFU exp2 (PM 0) - the FMA-pipe polynomial adds per-pair instruction latency without relieving a MUFU bound + if (!single && B * S >= 2048 && S < 300) pm = 0; +#ifdef FA_PROBE + if (g_fa_pm >= 0) pm = g_fa_pm; +#endif + using FaK = void (*)(CUtensorMap, CUtensorMap, CUtensorMap, const float*, const uint8_t*, __half*, int, int, int, + float, int, int*, sidew::MaskJob, const unsigned*, const float*, const float*, int, const int*, int, int, int); + const bool ksv = false; + FaK kern = single ? (pm == 0 ? (FaK)tc_flash_attn_kernel<1, 0, 3> + : ksv ? (FaK)tc_flash_attn_kernel<1, 0x5555, 2, true> : (FaK)tc_flash_attn_kernel<1, 0x5555, 2>) + : pm == 2 ? (FaK)tc_flash_attn_kernel<2, 0x1111, 3> + : pm == 1 ? (FaK)tc_flash_attn_kernel<2, 0x0101, 3> : (FaK)tc_flash_attn_kernel<2, 0, 3>; + pdl_launch(kern, dim3(grid), dim3(FA_THREADS), single ? FaCfg<1>::SMEM : FaCfg<2>::SMEM, s, mq, mk, mv, mask, codes, out, S, nT, + nT, sl2, B, work_ctr, g_mask_job, vmax, pf_on ? pfg : nullptr, pf_on ? pfu : nullptr, pf_items, (vmax == nullptr && B * S < 2048) ? qbc : nullptr, g_pf1_kb, g_mf16_krot, (B * S >= 897 && g_pf_div > 0) ? g_pf_div : 6); // first-wave prefetch 8 -> 12 k-blocks +} +// TF32 hi/lo split of the [128, 2048] router weight (input-only dependency -> runs on the side stream) +void launch_router_wsplit(const float* wr, float* wrh, float* wrl, cudaStream_t s) { + pdl_launch(split_hilo_kernel, dim3((NEXP * HID / 4 + 255) / 256), dim3(256), 0, s, wr, wrh, wrl, NEXP * HID / 4, + NEXP * HID / 4); +} +void launch_router(const float* h, const float* lnw, const float* ssq, float eps, const float* wrh, const float* wrl, + int T, int* topk_idx, float* topk_w, int* counts, const float* wg, const float* wu, + cudaStream_t s, __half* xn16, uint8_t* xn8, float* f8inv, const L2Discard* dl, int* btok, float* bw, int* mtctr) { + CUtensorMap ah = make_map(h, T, HID, 128); + // wrh = fp16 [Wr_hi; Wr_lo] (256 x 2048, row-scaled), wrl = per-expert power-of-2 scales (convert_w16_kernel) + CUtensorMap bh = make_map_h(wrh, 2 * NEXP, HID, 128), bl = bh; // hi rows only + const int mt = (T + 127) / 128; + const int KS = router_ks(mt); + if (!g_mor.pending && T >= 897 && T < 2048 && xn8 == nullptr) { + // small-T router (full K per CTA, mma.sync, no cluster split / DSMEM reduce) + const bool two = (T + 7) / 8 > num_sms(); + const int tpc = two ? 16 : 8, grid = (T + tpc - 1) / tpc; + static bool attr = false; + if (!attr) { + cudaFuncSetAttribute(router_small_kernel<1>, cudaFuncAttributeMaxDynamicSharedMemorySize, rs_smem<1>()); + cudaFuncSetAttribute(router_small_kernel<2>, cudaFuncAttributeMaxDynamicSharedMemorySize, rs_smem<2>()); + attr = true; + } + const L2Discard dd = dl ? *dl : L2Discard{}; + // router-phase L2 prefetch of the odd MoE CTAs' static first items [2G, 2G + G/2) (split first wave) + const int G = num_sms(), rp0 = 2 * G, rp1 = 2 * G + (G >> 1); + const bool rpf = wg != nullptr && moe_self_tables(T) && !moe_use_fp8(T) && rp1 <= NEXP * MF16_GNT; + if (two) + pdl_launch(router_small_kernel<2>, dim3(grid), dim3(256), rs_smem<2>(), s, h, lnw, ssq, eps, + reinterpret_cast(wrh), wrl, T, topk_idx, topk_w, counts, g_conv_job, xn16, dd, btok, bw, + rpf ? wg : nullptr, rpf ? wu : nullptr, rp0, rp1, 16, g_mf16_krot); // 16 rotated k-blocks + else + pdl_launch(router_small_kernel<1>, dim3(grid), dim3(256), rs_smem<1>(), s, h, lnw, ssq, eps, + reinterpret_cast(wrh), wrl, T, topk_idx, topk_w, counts, g_conv_job, xn16, dd, btok, bw, + rpf ? wg : nullptr, rpf ? wu : nullptr, rp0, rp1, 16, g_mf16_krot); // 16 rotated k-blocks + return; + } + if (g_mor.pending) { + // merged o_proj + router launch (see oproj_router_kernel); h / ssq / Wr operands identical to the 2-launch path + g_mor.pending = false; + // second-wave MoE weight prefetch (T < 2048 self-table fp16 MoE; first wave prefetched by attention) + const bool pf2 = wg != nullptr && moe_self_tables(T) && T < 2048; + const int pf_t0 = num_sms() < NEXP * 12 ? num_sms() : NEXP * 12; + const int pf_t1 = 2 * num_sms() < NEXP * 12 ? 2 * num_sms() : NEXP * 12; + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3(16, mt); cfg.blockDim = dim3(RT_THREADS); cfg.dynamicSmemBytes = MOR_SMEM; cfg.stream = s; + cudaLaunchAttribute at[2]; + at[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + at[0].val.programmaticStreamSerializationAllowed = 1; + at[1].id = cudaLaunchAttributeClusterDimension; + at[1].val.clusterDim.x = 16; at[1].val.clusterDim.y = 1; at[1].val.clusterDim.z = 1; + cfg.attrs = at; cfg.numAttrs = 2; + cudaLaunchKernelEx(&cfg, oproj_router_kernel, g_mor.a, g_mor.mo, g_mor.msub, g_mor.mh, g_mor.mr, g_mor.p, g_mor.a32, ah, bh, T, + lnw, ssq, eps, wrl, topk_idx, topk_w, counts, g_conv_job, g_mor.sctr, g_mor.wo16, g_mor.attn, xn8, f8inv, xn16, btok, bw, + pf2 ? wg : nullptr, pf2 ? wu : nullptr, pf_t0, pf_t1, 12, g_mf16_krot); // second-wave prefetch 10 -> 12 k-blocks + return; + } + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3(KS, mt); cfg.blockDim = dim3(RT_THREADS); cfg.dynamicSmemBytes = RT_SMEM; cfg.stream = s; + cudaLaunchAttribute at[2]; + at[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + at[0].val.programmaticStreamSerializationAllowed = 1; + at[1].id = cudaLaunchAttributeClusterDimension; + at[1].val.clusterDim.x = KS; at[1].val.clusterDim.y = 1; at[1].val.clusterDim.z = 1; + cfg.attrs = at; cfg.numAttrs = 2; + const bool lptb = T >= 3500 && T < 6000 && moe_self_tables(T); + // also off for T >= 6000 (MoE kernel self-prefetches its first items; router h / Wr feed not disturbed) + // 2560 <= T < 3500 (natural expert order since ): router prefetches the first 4 experts' gate + up rows + // (48 MB) instead of 2 - the first MoE wave covers ~12 experts; prefetch only, numerics identical + const uint32_t pf_ne = (T >= 2560 && T < 3500) ? 4u : 2u; + const uint32_t pf_bytes = (moe_use_f16_gateup(T) && T >= 2048 && T < 3500 && !lptb) ? pf_ne * INTER * HID * 4u : 0u; + cudaLaunchKernelEx(&cfg, router_kernel, ah, bh, bl, T, lnw, ssq, eps, wrl, topk_idx, topk_w, counts, wg, wu, pf_bytes, + g_conv_job, xn16, xn8, f8inv, dl ? *dl : L2Discard{}, btok, bw, + (const int*)(T >= 2048 ? mtctr : nullptr)); +} +// max co-resident 16-CTA clusters of the merged o_proj + router kernel (host int, queried once) +static int mor_max_clusters() { + static int n = -1; + if (n < 0) { + cudaFuncSetAttribute(oproj_router_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, MOR_SMEM); + cudaFuncSetAttribute(oproj_router_kernel, cudaFuncAttributeNonPortableClusterSizeAllowed, 1); + cudaGetLastError(); + cudaLaunchConfig_t qc = {}; + qc.gridDim = dim3(16, 1); qc.blockDim = dim3(RT_THREADS); qc.dynamicSmemBytes = MOR_SMEM; + cudaLaunchAttribute qa[1]; + qa[0].id = cudaLaunchAttributeClusterDimension; + qa[0].val.clusterDim.x = 16; qa[0].val.clusterDim.y = 1; qa[0].val.clusterDim.z = 1; + qc.attrs = qa; qc.numAttrs = 1; + int c = 0; + if (cudaOccupancyMaxActiveClusters(&c, oproj_router_kernel, &qc) != cudaSuccess) { cudaGetLastError(); c = 0; } + n = c; + } + return n; +} +static int router_ks(int mt) { + { static bool done_ = false; if (!done_) { cudaFuncSetAttribute(router_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, RT_SMEM); + // allow non-portable cluster sizes up to 16 (small T: 16-way K split -> 2x the busy SMs, half the k-chain) + cudaFuncSetAttribute(router_kernel, cudaFuncAttributeNonPortableClusterSizeAllowed, 1); cudaGetLastError(); done_ = true; } } + static int max_clusters[17] = {0}; + if (!max_clusters[1]) { + for (int ks = 1; ks <= 16; ks++) { + cudaLaunchConfig_t qc = {}; + qc.gridDim = dim3(ks, 1); qc.blockDim = dim3(RT_THREADS); qc.dynamicSmemBytes = RT_SMEM; + cudaLaunchAttribute qa[1]; + qa[0].id = cudaLaunchAttributeClusterDimension; + qa[0].val.clusterDim.x = ks; qa[0].val.clusterDim.y = 1; qa[0].val.clusterDim.z = 1; + qc.attrs = qa; qc.numAttrs = 1; + int n = 0; + if (cudaOccupancyMaxActiveClusters(&n, router_kernel, &qc) != cudaSuccess || n <= 0) { + cudaGetLastError(); + n = ks <= 8 ? num_sms() / ks : 0; // fallback: SM-count bound (non-portable sizes: unusable) + } + max_clusters[ks] = n; + } + } + int KS = 1; + for (int ks = 16; ks >= 1; ks--) + if ((g_rks_cap <= 0 || ks <= g_rks_cap) && mt <= max_clusters[ks] && mt * ks <= num_sms()) { KS = ks; break; } + // the per-CTA + // mainloop makespan is ceil(32 / KS) 64-K k-blocks; take the SMALLEST K split with the same makespan (e.g. mt = 16: + // KS 9 -> 8, both 4 k-blocks, balanced 4/4 slices instead of 3/4, fewer DSMEM partials per reduced row). The + // cross-CTA reduction stays in rank order (deterministic). + if (mt >= 16 && g_rks_cap <= 0) { + const int span = (HID / 64 + KS - 1) / KS; + for (int ks = 1; ks < KS; ks++) + if ((HID / 64 + ks - 1) / ks == span && mt <= max_clusters[ks]) { KS = ks; break; } + } + return KS; +} +int g_moe_var = -1; +#ifndef MOE_VAR_TABLE +#define MOE_VAR_TABLE(T) ((T) < 2048 ? 6 : (T) < 6000 ? 20 : 19) // T < 2048: GM 2 fp16 self-table path +#endif +static int moe_f16_var(int T) { return g_moe_var >= 0 ? g_moe_var : MOE_VAR_TABLE(T); } +constexpr int MF8_NVAR = 21; +static const int mf8_gm[MF8_NVAR] = {3, 3, 3, 2, 3, 3, 2, 2, 3, 3, 3, 2, 4, 3, 3, 4, 4, 4, 4, 4, 3}; +bool moe_use_fp8(int T); +bool moe_use_fp8_down(int T); +static int moe_f16_gmax(int T) { + const int v = moe_f16_var(T); + int gm = v < MF8_NVAR ? mf8_gm[v] : 3; + if (gm == 4 && !(moe_use_fp8(T) && moe_use_fp8_down(T))) gm = 3; // GM = 4 kernel exists only for all-FP8 + // T <= 1280 fp16 self-table MoE: every expert holds <= 128 rows (mean 8T/128 <= 80, 128 rows > 5 sigma away; + // a larger expert just forms 2 groups) -> 1-M-tile groups (16 KB token stages, 3-deep token ring) + if (g_moe_var < 0 && T > 0 && T <= 1280 && !moe_use_fp8(T)) gm = 1; + return gm; +} +void launch_moe_scan_scatter(int T, const int* topk_idx, const float* topk_w, int* counts, int* offsets, + int* cursor, int* tile_expert, int* tile_mstart, int* total_tiles, int* perm_tok, + float* perm_w, int* inv_pos, int* grp, cudaStream_t s, const float* h, + const float* lnw, float eps, const float* ssq, float* xn2) { + const int max_groups = moe_max_groups(T * TOPK); + const int n = T * TOPK; + const int nsc = (n + SC_PER - 1) / SC_PER; + const int maxt = (n + TBM - 1) / TBM + NEXP; // tile_mend[maxt] stored right after tile_mstart[maxt] + // single launch: per-CTA prefix of the histogram + block-aggregated scatter (CTA 0 also writes the MoE tables) + // + (xn2 != nullptr) T fused norm-gather CTAs + pdl_launch(moe_scatter_kernel, dim3(nsc + (xn2 ? T : 0)), dim3(256), 0, s, n, topk_idx, topk_w, + (const int*)counts, cursor, offsets, tile_expert, tile_mstart, total_tiles, grp, max_groups, perm_tok, + perm_w, inv_pos, nsc, h, lnw, eps, ssq, xn2, moe_f16_gmax(T), + moe_use_f16_gateup(T) ? 0 : (T > 2048 ? 3 : 1), tile_mstart + maxt, + (moe_use_f16_gateup(T) && T >= 3500 && T < 6000) ? 1 : 0); // LPT group order // tables read by the selected MoE kernel +} +void launch_moe_norm_gather(const float* h, const float* w, float eps, const int* inv_pos, const float* ssq, int T, + float* aperm, cudaStream_t s) { + pdl_launch(moe_norm_gather_kernel, dim3(T), dim3(256), 0, s, h, w, eps, inv_pos, ssq, aperm, + moe_use_f16_gateup(T) ? 1 : 0); +} +// fp16 TS fused path for T >= 2048 (avg >= 1 M tile per expert) +// threshold re-tested with the TS-MMA fp16 fused kernel (weights in TMEM): now also used for 2048 <= T < 4096 +bool moe_use_f16_gateup(int T) { return T > 0; } // fused FP8 MoE for every T (was T >= 2048: TF32 moe_fused1) +// FP8 gate/up (kind::f8f6f4: e5m2 weights, e4m3 bound-scaled tokens) inside the fused fp16 MoE kernel, T >= 2048. +// g_moe_fp8: -1 = table (production), 0 / 1 = force (probe builds). +#ifndef MOE_FP8_TABLE +#define MOE_FP8_TABLE(T) ((T) >= 2048) +#endif +int g_moe_fp8 = -1; +bool moe_use_fp8(int T); +static int moe_f16_var(int T); +bool moe_use_fp8_down(int T); +// self-table variants of the all-FP8 knob table (T >= 2048 production variants 6, 20, 19) +static bool mf8_self_var(int v) { return v == 6 || v == 20 || v == 19; } +bool moe_self_tables(int T) { + if (T <= 0 || !moe_use_f16_gateup(T)) return false; + const int gm = moe_f16_gmax(T), n = T * TOPK; + if ((n + 128 * gm - 1) / (128 * gm) + NEXP > MF_SCAP) return false; // group-count bound vs table capacity + if (T < 2048) return !moe_use_fp8(T) && (gm == 2 || gm == 1); + return moe_use_fp8(T) && moe_use_fp8_down(T) && mf8_self_var(moe_f16_var(T)); +} +int moe_self_ws_ints() { return num_sms() * MF_STAB_INTS; } +bool moe_use_fp8(int T) { + if (!moe_use_f16_gateup(T)) return false; + if (g_moe_fp8 >= 0) return g_moe_fp8 == 1; + return MOE_FP8_TABLE(T); +} +#ifndef MOE_FP8D_TABLE +#define MOE_FP8D_TABLE(T) ((T) >= 2048) +#endif +int g_moe_fp8d = -1; +bool moe_use_fp8_down(int T) { + if (g_moe_fp8d >= 0) return g_moe_fp8d == 1; + return MOE_FP8D_TABLE(T); +} +// TF32 pair-group MoE items only when the average expert holds > 1 M tile (8T/128 > 128 <=> T > 2048) +static bool moe_use_pair_groups(int T) { return T > 2048; } +// fp16 down GEMM (requires the fp16 gate/up path, whose epilogue then writes fp16 act) +static bool moe_use_f16_down(int T) { return moe_use_f16_gateup(T); } +#ifndef MOE_C8_TABLE +#define MOE_C8_TABLE(T) ((void)(T), false) +#endif +int g_moe_c8 = -1; +static bool moe_f16_conv8(int T) { + if (g_moe_c8 >= 0) return g_moe_c8 == 1; + return MOE_C8_TABLE(T); +} +int g_mf1_var = 0; // moe_fused1 ring config (probe knob; 0 = production (3, 5)) +int g_mf1_krot = MF1_KROT; // rotated k order multiplier (probe knob) +int g_mf16_krot = MF16_KROT; +int g_cur_S = 0; // sequence length of the current call (set by run_impl; host int) +void launch_moe_gemms(const float* aperm, const float* wg, const float* wu, const float* wd, int T, + const int* tile_expert, const int* tile_mstart, const int* total_tiles, const int* offsets, + const int* counts, const int* perm_tok, const float* perm_w, float* act, float* out, + const int* grp, int* moe_sync, cudaStream_t s) { + const int n = T * TOPK; + const int maxTiles = (n + TBM - 1) / TBM + NEXP; + TcArgs p{}; + p.tile_expert = tile_expert; p.tile_mstart = tile_mstart; p.total_tiles = total_tiles; + p.offsets = offsets; p.counts = counts; p.perm_tok = perm_tok; p.perm_w = perm_w; + if (moe_use_f16_gateup(T)) { + // T >= 4096: fused fp16 gate/up + down persistent kernel, one global work queue (see moe_f16_fused_kernel) + const int max_groups = moe_max_groups(n); + CUtensorMap mg = make_map3k(wg, (uint64_t)NEXP * INTER, HID, 64); + CUtensorMap mu = make_map3k(wu, (uint64_t)NEXP * INTER, HID, 64); + CUtensorMap x = make_map_h(act, n, INTER, 128); // bf16 act rows (2-byte elements; TMA copies bytes) + CUtensorMap md = make_map3k(wd, (uint64_t)NEXP * HID, INTER, 128); + { static bool done_ = false; if (!done_) { + cudaFuncSetAttribute(moe_f16_fused_kernel<3, 3, 2, 0>, cudaFuncAttributeMaxDynamicSharedMemorySize, MfCfg<3, 3, 2>::SMEM); + cudaFuncSetAttribute(moe_f16_fused_kernel<3, 2, 3, 0>, cudaFuncAttributeMaxDynamicSharedMemorySize, MfCfg<3, 2, 3>::SMEM); + cudaFuncSetAttribute(moe_f16_fused_kernel<2, 4, 2, 0>, cudaFuncAttributeMaxDynamicSharedMemorySize, MfCfg<2, 4, 2>::SMEM); + cudaFuncSetAttribute(moe_f16_fused_kernel<2, 3, 3, 0>, cudaFuncAttributeMaxDynamicSharedMemorySize, MfCfg<2, 3, 3>::SMEM); + cudaFuncSetAttribute(moe_f16_fused_kernel<3, 3, 2, 1>, cudaFuncAttributeMaxDynamicSharedMemorySize, MfCfg<3, 3, 2>::SMEM); + cudaFuncSetAttribute(moe_f16_fused_kernel<3, 2, 3, 1>, cudaFuncAttributeMaxDynamicSharedMemorySize, MfCfg<3, 2, 3>::SMEM); + cudaFuncSetAttribute(moe_f16_fused_kernel<2, 4, 2, 1>, cudaFuncAttributeMaxDynamicSharedMemorySize, MfCfg<2, 4, 2>::SMEM); + cudaFuncSetAttribute(moe_f16_fused_kernel<2, 3, 3, 1>, cudaFuncAttributeMaxDynamicSharedMemorySize, MfCfg<2, 3, 3>::SMEM); + cudaFuncSetAttribute(moe_f16_fused_c8_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, MF16_SMEM); done_ = true; } } + const int items = max_groups * (MF16_GNT + MF16_DNT); + const int grid = items < num_sms() ? items : num_sms(); + // aperm holds the fp16 xn2 rows [T, 2048] (one per token) in this mode + using MfK = decltype(&moe_f16_fused_c8_kernel); + const int var8 = moe_f16_var(T); + // non-all-FP8 paths only know variants 0..3: map others to the one with the same group size GM + const int var = var8 < 4 ? var8 : (var8 < MF8_NVAR && mf8_gm[var8] == 2 ? 3 : 0); + int smem8 = 0; + MfK kern = var == 1 ? moe_f16_fused_kernel<3, 2, 3, 0> : var == 2 ? moe_f16_fused_kernel<2, 4, 2, 0> + : var == 3 ? moe_f16_fused_kernel<2, 3, 3, 0> : moe_f16_fused_kernel<3, 3, 2, 0>; + const bool f8 = moe_use_fp8(T); + const bool f8d = f8 && moe_use_fp8_down(T); // FP8 down (e5m2 Wd x e5m2 act) + if (f8d) { + // all-FP8 knob table (see mf8_gm); variant must match the group size used by the scatter (moe_f16_gmax) + static MfK k8[MF8_NVAR] = { + moe_f16_fused_kernel<3, 3, 2, 2, 4>, moe_f16_fused_kernel<3, 2, 3, 2, 4>, moe_f16_fused_kernel<3, 4, 2, 2, 8>, + moe_f16_fused_kernel<2, 3, 3, 2, 4>, moe_f16_fused_kernel<3, 4, 2, 2, 4>, moe_f16_fused_kernel<3, 4, 3, 2, 4>, + moe_f16_fused_kernel<2, 4, 3, 2, 4>, moe_f16_fused_kernel<2, 5, 3, 2, 4>, moe_f16_fused_kernel<3, 3, 2, 2, 8>, + moe_f16_fused_kernel<3, 3, 3, 2, 4>, moe_f16_fused_kernel<3, 3, 3, 2, 8>, moe_f16_fused_kernel<2, 4, 3, 2, 8>, + moe_f16_fused_kernel<4, 4, 2, 2, 2>, moe_f16_fused_kernel<3, 4, 2, 2, 2>, moe_f16_fused_kernel<3, 4, 2, 2, 3>, + moe_f16_fused_kernel<4, 3, 2, 2, 3>, moe_f16_fused_kernel<4, 3, 2, 2, 2>, moe_f16_fused_kernel<4, 2, 3, 2, 3>, + moe_f16_fused_kernel<4, 3, 3, 2, 2>, moe_f16_fused_kernel<4, 3, 3, 2, 3>, + moe_f16_fused_kernel<3, 4, 3, 2, 8>}; + static const int s8[MF8_NVAR] = { + MfCfg<3, 3, 2, 2>::SMEM, MfCfg<3, 2, 3, 2>::SMEM, MfCfg<3, 4, 2, 2>::SMEM, MfCfg<2, 3, 3, 2>::SMEM, + MfCfg<3, 4, 2, 2>::SMEM, MfCfg<3, 4, 3, 2>::SMEM, MfCfg<2, 4, 3, 2>::SMEM, MfCfg<2, 5, 3, 2>::SMEM, + MfCfg<3, 3, 2, 2>::SMEM, MfCfg<3, 3, 3, 2>::SMEM, MfCfg<3, 3, 3, 2>::SMEM, MfCfg<2, 4, 3, 2>::SMEM, + MfCfg<4, 4, 2, 2, 2>::SMEM, MfCfg<3, 4, 2, 2, 2>::SMEM, MfCfg<3, 4, 2, 2, 3>::SMEM, MfCfg<4, 3, 2, 2, 3>::SMEM, MfCfg<4, 3, 2, 2, 2>::SMEM, MfCfg<4, 2, 3, 2, 3>::SMEM, MfCfg<4, 3, 3, 2, 2>::SMEM, MfCfg<4, 3, 3, 2, 3>::SMEM, MfCfg<3, 4, 3, 2>::SMEM}; + static bool a8 = false; + if (!a8) { for (int i = 0; i < MF8_NVAR; i++) cudaFuncSetAttribute(k8[i], cudaFuncAttributeMaxDynamicSharedMemorySize, s8[i]); a8 = true; } + const int v8 = var8 < MF8_NVAR ? var8 : 0; + kern = k8[v8]; + smem8 = s8[v8]; + } else if (f8) + kern = var == 1 ? moe_f16_fused_kernel<3, 2, 3, 1> : var == 2 ? moe_f16_fused_kernel<2, 4, 2, 1> + : var == 3 ? moe_f16_fused_kernel<2, 3, 3, 1> : moe_f16_fused_kernel<3, 3, 2, 1>; + // FP8 down: act = e5m2 bytes [n, 768], TMA box 64 B x 128 rows, 64B swizzle (matches make_sdesc64) + if (f8d) x = make_map_b64(act, n, INTER, 128); + // FP8: aperm = e4m3 xn8 [T, 2048] bytes, followed by the float 1/s8 (router) + const float* f8inv = reinterpret_cast(reinterpret_cast(aperm) + (size_t)T * HID); + int smem = var == 1 ? MfCfg<3, 2, 3>::SMEM : var == 2 ? MfCfg<2, 4, 2>::SMEM : var == 3 ? MfCfg<2, 3, 3>::SMEM : MfCfg<3, 3, 2>::SMEM; + if (f8d) smem = smem8; + // c8 variant is GM = 3 only (groups built with gmax 3 when var 0/1) + if (!f8 && moe_f16_conv8(T) && var < 2) { kern = moe_f16_fused_c8_kernel; smem = MF16_SMEM; } + // T < 2048 fp16 gate/up + bf16 down: deeper raw fp32 weight ring (RS 3 -> 4 x 32 KB = 128 KB of weight + // TMA in flight per SM; token ring AS 3 -> 2 to fit smem). GM = 2 matches moe_f16_gmax (variant 6 -> gmax 2). + if (!f8 && T < 2048 && moe_f16_gmax(T) == 2) { kern = moe_f16_fused_kernel<2, 4, 2, 0>; smem = MfCfg<2, 4, 2>::SMEM; } + // self-table variant (no scatter launch; perm_tok / perm_w = router buckets [128][T]) + const bool selft = moe_self_tables(T); + int mthr = MF16_THREADS; + if (selft && T >= 2048) { + static MfK ks[3] = {moe_f16_fused_kernel<2, 4, 3, 2, 4, true, true>, moe_f16_fused_kernel<3, 4, 3, 2, 8, true, true>, + moe_f16_fused_kernel<4, 3, 3, 2, 3, true>}; + static const int ss[3] = {MfCfg<2, 4, 3, 2>::SMEM, MfCfg<3, 4, 3, 2>::SMEM, MfCfg<4, 3, 3, 2, 3>::SMEM}; + int si[3]; + for (int i = 0; i < 3; i++) si[i] = ss[i] + MF_STAB_BYTES <= 232448 ? ss[i] + MF_STAB_BYTES : ss[i]; + si[0] += MF_TCP_BYTES; // TCP staging (variant 6 kernel) + static bool as8 = false; + if (!as8) { for (int i = 0; i < 3; i++) cudaFuncSetAttribute(ks[i], cudaFuncAttributeMaxDynamicSharedMemorySize, si[i]); as8 = true; } + const int vi = var8 == 6 ? 0 : var8 == 20 ? 1 : 2; + kern = ks[vi]; smem = si[vi]; mthr = vi < 2 ? 640 : MF16_THREADS; // CV8 variants + } else if (selft && moe_f16_gmax(T) == 1) { + // GM 1 groups, token ring 3 x 16 KB (was 2 x 32 KB, half empty at T <= 1280), raw ring 4 x 32 KB + static bool as1_ = false; + if (!as1_) { cudaFuncSetAttribute(moe_f16_fused_kernel<1, 4, 3, 0, 4, true, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, + MfCfg<1, 4, 3>::SMEM + MF_STAB_BYTES + 4096); as1_ = true; } + kern = moe_f16_fused_kernel<1, 4, 3, 0, 4, true, true>; smem = MfCfg<1, 4, 3>::SMEM + MF_STAB_BYTES + 4096; + mthr = 640; + } else if (selft) { + static bool as_ = false; + if (!as_) { cudaFuncSetAttribute(moe_f16_fused_kernel<2, 4, 2, 0, 4, true, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, + MfCfg<2, 4, 2>::SMEM + MF_STAB_BYTES + 4096); as_ = true; } + kern = moe_f16_fused_kernel<2, 4, 2, 0, 4, true, true>; smem = MfCfg<2, 4, 2>::SMEM + MF_STAB_BYTES + 4096; // + 8 x 512 B metadata tables + mthr = 640; // CV8 (4 extra converter warps) + } + if (f8d && moe_f16_gmax(T) == 4) mthr = 640; // GM = 4 all-FP8 MALT layout (20 warps) + int pf_ng; + { + const double mu = 8.0 * T / NEXP, sd = sqrt(mu * (1.0 - 1.0 / NEXP)) + 1e-9; + const int gmx = moe_f16_gmax(T); + double eg = 0.0; + for (int j = 0; j < 64; j++) eg += 0.5 * erfc((128.0 * gmx * j + 0.5 - mu) / (sd * 1.41421356)); + pf_ng = (int)(eg * 256.0 + 0.5); + if (pf_ng < 256) pf_ng = 256; + } + const bool malt_pre = f8d && moe_f16_gmax(T) == 4; // MALT kernel consumes pre-converted experts + pdl_launch(kern, dim3(grid), dim3(mthr), smem, s, + reinterpret_cast(aperm), mg, mu, x, md, const_cast(grp), max_groups, + offsets, counts, reinterpret_cast<__half*>(act), out, perm_tok, perm_w, moe_sync, f8inv, pf_ng, + T >= 6000 ? 0 : g_mf16_krot, + ((f8d && ((T >= 6000 && g_cur_S < 2048) || (selft && T < 2560))) ? 1 : 0) /* + T=2048 class (16x128, 8x256) CV8 self-table*/ | 2 | (selft ? (T << 8) : 0) | + ((selft && (g_lpt >= 0 ? g_lpt == 1 : (T >= 2048 && T < 8000 && !(T >= 2560 && T < 3500)))) ? 4 : 0) /* LPT off for 2560<=T<3500 (8x373): natural expert order -> router experts-0/1 + MoE pre-wait expert-major prefetch guesses hit the real first wave*/ /* LPT expert-group order also for 2048 <= T < 3500 (tail balance)*/, g_moe_dl, pre_map(), (malt_pre && g_pre_ctr) ? (const int*)(g_pre_ctr + 1) : (const int*)nullptr, PRE_CAP); + return; + } else { + // T < 4096: fused gate/up + down persistent kernel with one global work queue (see moe_fused_kernel) + CUtensorMap mg = make_map(wg, (uint64_t)NEXP * INTER, HID, 64); + CUtensorMap mu = make_map(wu, (uint64_t)NEXP * INTER, HID, 64); + CUtensorMap x = make_map(act, n, INTER, 128); + CUtensorMap x64 = make_map(act, n, INTER, 64); + CUtensorMap md = make_map(wd, (uint64_t)NEXP * HID, INTER, 128); + MoeArgs m{}; + m.xn = aperm; // fp32 xn2 [T, 2048] + m.tile_expert = tile_expert; m.tile_mstart = tile_mstart; m.total_tiles = total_tiles; + m.offsets = offsets; m.counts = counts; m.perm_tok = perm_tok; m.perm_w = perm_w; + m.act = act; m.out = out; m.qctr = moe_sync; + m.pgrp = grp + 4 * moe_max_groups(n) + 1; // pair-group section of grp + m.bn_g = pick_bn_grouped(T, INTER / 128); + m.bn_d = pick_bn_grouped(T, HID / TBN); + m.krot = g_mf1_krot; + m.tile_mend = tile_mstart + maxTiles; // (written by the scatter CTA 0) + const long items = (long)maxTiles * (2 * MF_GNT + 2 * MF_DNT); + const int grid = items < num_sms() ? (int)items : num_sms(); + if (moe_use_pair_groups(T)) { + // avg rows/expert > 128: experts span >= 2 M tiles -> pair-group items share each B stage + { static bool done_ = false; if (!done_) { cudaFuncSetAttribute(moe_fused_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, MF_SMEM); done_ = true; } } + pdl_launch(moe_fused_kernel, dim3(grid), dim3(MF_THREADS), MF_SMEM, s, mg, mu, x, x64, md, m); + } else { + // <= 1 M tile per expert on average: single-tile items with the deeper 4-stage ring + // (AS, BS) = (3, 5) (g_mf1_var 0); probe alternatives 1 = (4, 4), 2 = (5, 4), 3 = (6, 3) + { static bool done_ = false; if (!done_) { + cudaFuncSetAttribute(moe_fused1_kernel<3, 5>, cudaFuncAttributeMaxDynamicSharedMemorySize, Mf1Cfg<3, 5>::SMEM); + cudaFuncSetAttribute(moe_fused1_kernel<4, 4>, cudaFuncAttributeMaxDynamicSharedMemorySize, Mf1Cfg<4, 4>::SMEM); + cudaFuncSetAttribute(moe_fused1_kernel<5, 4>, cudaFuncAttributeMaxDynamicSharedMemorySize, Mf1Cfg<5, 4>::SMEM); + cudaFuncSetAttribute(moe_fused1_kernel<6, 3>, cudaFuncAttributeMaxDynamicSharedMemorySize, Mf1Cfg<6, 3>::SMEM); + cudaFuncSetAttribute(moe_fused1_kernel<2, 2, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, Mf1Cfg<2, 2, true>::SMEM); + done_ = true; } } + // 2 CTAs / SM variant (occupancy queried once; correctness does not need co-residency: every + // dependency wait targets an item grabbed earlier by a running CTA) + static int occ2 = -1; + if (occ2 < 0) { + int nb = 0; + if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&nb, moe_fused1_kernel<2, 2, true>, MF_THREADS, Mf1Cfg<2, 2, true>::SMEM) != cudaSuccess) { cudaGetLastError(); nb = 0; } + occ2 = nb; + } + if (g_mf1_var == 0 && occ2 >= 2) { + const int grid2 = items < 2L * num_sms() ? (int)items : 2 * num_sms(); + pdl_launch(moe_fused1_kernel<2, 2, true>, dim3(grid2), dim3(MF_THREADS), Mf1Cfg<2, 2, true>::SMEM, s, mg, mu, x, x64, md, m); + return; + } + if (g_mf1_var == 1) pdl_launch(moe_fused1_kernel<4, 4>, dim3(grid), dim3(MF_THREADS), Mf1Cfg<4, 4>::SMEM, s, mg, mu, x, x64, md, m); + else if (g_mf1_var == 2) pdl_launch(moe_fused1_kernel<5, 4>, dim3(grid), dim3(MF_THREADS), Mf1Cfg<5, 4>::SMEM, s, mg, mu, x, x64, md, m); + else if (g_mf1_var == 3) pdl_launch(moe_fused1_kernel<6, 3>, dim3(grid), dim3(MF_THREADS), Mf1Cfg<6, 3>::SMEM, s, mg, mu, x, x64, md, m); + else pdl_launch(moe_fused1_kernel<3, 5>, dim3(grid), dim3(MF_THREADS), Mf1Cfg<3, 5>::SMEM, s, mg, mu, x, x64, md, m); + } + return; + } + if (moe_use_f16_down(T)) { + // fp16 down GEMM with amortized in-kernel Wd conversion (DOWN instantiation of moe_gateup_f16_kernel) + const int max_groups = moe_max_groups(n); + CUtensorMap a = make_map_h(act, n, INTER, 128); // fp16 act rows (written by the fp16 gate/up epilogue) + CUtensorMap md = make_map(wd, (uint64_t)NEXP * HID, INTER, 128); + { static bool done_ = false; if (!done_) { cudaFuncSetAttribute(moe_gateup_f16_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, + GuCfg::SMEM); done_ = true; } } + const int items = max_groups * GuCfg::NT; + const int grid = items < num_sms() ? items : num_sms(); + pdl_launch(moe_gateup_f16_kernel, dim3(grid), dim3(GU_THREADS), GuCfg::SMEM, s, a, md, md, grp, + max_groups, offsets, counts, out, 0, perm_tok, perm_w); + } else { + CUtensorMap a = make_map(act, n, INTER, 128); + CUtensorMap md = make_map(wd, (uint64_t)NEXP * HID, INTER, 128); + TcArgs p2 = p; + p2.BN = pick_bn_grouped(T, HID / TBN); + p2.KB = INTER / TBK; p2.NT = HID / TBN; p2.out = out; + CUtensorMap a64 = make_map(act, n, INTER, 64); + launch_tc(maxTiles * p2.NT, a, md, md, a64, p2, s); + } +} + +#ifdef FA_PROBE +// ------------------------------------------------------------------ isolated causal attention probe +#include +__global__ void probe_fill_h(__half* p, size_t n, float scale, uint32_t seed) { + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) { + uint32_t x = (uint32_t)i * 2654435761u ^ seed; + x ^= x >> 13; x *= 0x5bd1e995u; x ^= x >> 15; + p[i] = __float2half_rn(((x & 0xFFFFFF) / 16777216.f * 2.f - 1.f) * scale); + } +} +__global__ void probe_causal(float* m, int S, size_t n) { + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) { + const size_t j = i % ((size_t)S * S); + const int r = (int)(j / S), c = (int)(j % S); + m[i] = c > r ? -INFINITY : 0.f; + } +} +std::string fa_probe() { + std::string res = "FA_PROBE (event us avg of 4; MMA-warp kcyc/CTA: item Q KV Sfree Pready Siss PViss - total) |"; + const int shapes[5][2] = {{1, 1024}, {16, 449}, {8, 373}, {32, 256}, {2, 512}}; + for (int si = 0; si < 5; si++) { + const int B = shapes[si][0], S = shapes[si][1], nT = (S + 127) / 128, Spad = nT * 128; + __half *q, *k, *vt, *o; float *mask, *mt; uint8_t* codes; int* ctr; + cudaMalloc(&q, (size_t)B * 32 * S * 128 * 2); cudaMalloc(&k, (size_t)B * 4 * S * 128 * 2); + cudaMalloc(&vt, (size_t)B * 4 * 128 * Spad * 2); cudaMalloc(&o, (size_t)B * S * 4096 * 2); + cudaMalloc(&mask, (size_t)B * S * S * 4); cudaMalloc(&mt, (size_t)B * nT * nT * 16384 * 4); + cudaMalloc(&codes, (size_t)B * nT * nT); cudaMalloc(&ctr, 4); + probe_fill_h<<<1024, 256>>>(q, (size_t)B * 32 * S * 128, 1.73f / 64.f, 1u); + probe_fill_h<<<1024, 256>>>(k, (size_t)B * 4 * S * 128, 1.73f / 64.f, 2u); + probe_fill_h<<<1024, 256>>>(vt, (size_t)B * 4 * 128 * Spad, 1.f / 1024.f, 3u); + probe_causal<<<2048, 256>>>(mask, S, (size_t)B * S * S); + cudaStream_t st; cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking); + cudaDeviceSynchronize(); + launch_mask_classify(mask, B, S, codes, mt, st); + cudaStreamSynchronize(st); + cudaEvent_t e0, e1; cudaEventCreate(&e0); cudaEventCreate(&e1); + char hb[64]; snprintf(hb, sizeof(hb), " [%dx%d]", B, S); res += hb; + struct Cfg { int force, mode, pm; const char* name; }; + const Cfg cfgs[] = {{0, 0, 0, "pm0"}, {0, 0, 1, "pm1/8"}, {0, 0, 2, "pm1/4"}, {0, 0, 0, "pm0b"}, {0, 0, 1, "pm1/8b"}, {0, 0, 2, "pm1/4b"}}; + for (const Cfg& c : cfgs) { + g_fa_force = c.force; g_fa_pm = c.pm; + cudaMemcpyToSymbol(g_fa_mode, &c.mode, 4); + unsigned long long z[16] = {0}; + float tot = 0.f; + const int reps = 10; + for (int r = 0; r <= reps; r++) { + if (r == 1) cudaMemcpyToSymbol(g_fa_clk, z, sizeof(z)); + cudaMemsetAsync(ctr, 0, 4, st); + cudaEventRecord(e0, st); + launch_flash_attn(q, k, vt, mt, codes, o, B, S, Spad, ctr, st); + cudaEventRecord(e1, st); + cudaStreamSynchronize(st); + float ms; cudaEventElapsedTime(&ms, e0, e1); + if (r > 0) tot += ms; + } + unsigned long long h[16]; + cudaMemcpyFromSymbol(h, g_fa_clk, sizeof(h)); + char buf[512]; + const double nc = h[9] ? (double)h[9] : 1.0; + if (1) + snprintf(buf, sizeof(buf), " %s: %.1f err=%d |", c.name, 1000.f * tot / reps, (int)cudaGetLastError()); + else + snprintf(buf, sizeof(buf), " %s: %.1f [%.0f %.0f %.0f %.0f %.0f %.0f %.0f - %.0f] err=%d |", c.name, + 1000.f * tot / reps, h[0] / nc / 1e3, h[1] / nc / 1e3, h[2] / nc / 1e3, h[3] / nc / 1e3, + h[4] / nc / 1e3, h[5] / nc / 1e3, h[6] / nc / 1e3, h[8] / nc / 1e3, + (int)cudaGetLastError()); + res += buf; + } + int zero = 0; cudaMemcpyToSymbol(g_fa_mode, &zero, 4); + g_fa_force = 0; g_fa_pm = -1; + cudaFree(q); cudaFree(k); cudaFree(vt); cudaFree(o); cudaFree(mask); cudaFree(mt); cudaFree(codes); cudaFree(ctr); + } + return res; +} +#endif + +#ifdef FA_PROBE +extern int g_fa4_qpt_override; extern int g_fa4_thr; +void fa4_spread(double* spread, double* span); +__global__ void probe_fill_b(uint8_t* p, size_t n, uint32_t seed) { + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) { + uint32_t x = (uint32_t)i * 2654435761u ^ seed; + x ^= x >> 13; x *= 0x5bd1e995u; x ^= x >> 15; + p[i] = (uint8_t)((x & 0x37u) | ((x >> 8) & 0x80u)); + } +} +std::string fa4_probe() { + std::string res = "FA4_PROBE us(avg10) spread/span |"; + const int shapes[3][2] = {{2, 2048}, {1, 4096}, {1, 8192}}; + unsigned* vm; cudaMalloc(&vm, 4); + { float one = 1.f; cudaMemcpy(vm, &one, 4, cudaMemcpyHostToDevice); } + for (int si = 0; si < 3; si++) { + const int B = shapes[si][0], S = shapes[si][1], nT = (S + 127) / 128, Spad = nT * 128, nQP = (nT + 1) / 2; + __half *q, *k, *vt, *o; float *mask, *mt; uint8_t* codes; int* ctr; + cudaMalloc(&q, (size_t)B * 32 * S * 128 * 2); cudaMalloc(&k, (size_t)B * 4 * S * 128 * 2); + cudaMalloc(&vt, (size_t)B * 4 * 128 * Spad * 2); cudaMalloc(&o, (size_t)B * S * 4096 * 2); + cudaMalloc(&mask, (size_t)B * S * S * 4); cudaMalloc(&mt, (size_t)B * nT * nT * 16384 * 4); + cudaMalloc(&codes, (size_t)B * nT * nT); cudaMalloc(&ctr, 4); + probe_fill_b<<<1024, 256>>>((uint8_t*)q, (size_t)B * 32 * S * 128, 1u); + probe_fill_b<<<1024, 256>>>((uint8_t*)k, (size_t)B * 4 * S * 128, 2u); + probe_fill_h<<<1024, 256>>>(vt, (size_t)B * 4 * 128 * Spad, 1.f / 1024.f, 3u); + probe_causal<<<2048, 256>>>(mask, S, (size_t)B * S * S); + cudaStream_t st; cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking); + cudaDeviceSynchronize(); + launch_mask_classify(mask, B, S, codes, mt, st); + cudaStreamSynchronize(st); + cudaEvent_t e0, e1; cudaEventCreate(&e0); cudaEventCreate(&e1); + char hb[64]; snprintf(hb, sizeof(hb), " [%dx%d]", B, S); res += hb; + const int ov[9] = {3, 6, 12, 3, 6, 12, 3, 6, 12}; + (void)nQP; + for (int ci = 0; ci < 9; ci++) { + g_fa4_thr = ov[ci]; + float tot = 0.f; double sp = 0, sn = 0; + const int reps = 20; + for (int r = 0; r <= reps; r++) { + cudaMemsetAsync(ctr, 0, 4, st); + cudaEventRecord(e0, st); + launch_flash_attn(q, k, vt, mt, codes, o, B, S, Spad, ctr, st, vm); + cudaEventRecord(e1, st); + cudaStreamSynchronize(st); + float ms; cudaEventElapsedTime(&ms, e0, e1); + if (r > 0) { tot += ms; double a, b2; fa4_spread(&a, &b2); sp += a; sn += b2; } + } + char buf[160]; + snprintf(buf, sizeof(buf), " t%d: %.1f %.1f/%.1f e%d |", ov[ci], 1000.f * tot / reps, sp / reps, sn / reps, + (int)cudaGetLastError()); + res += buf; + } + g_fa4_thr = 6; + cudaFree(q); cudaFree(k); cudaFree(vt); cudaFree(o); cudaFree(mask); cudaFree(mt); cudaFree(codes); cudaFree(ctr); + } + return res; +} +#endif + +#ifdef RS_PROBE +#include +__global__ void rsp_fill(float* p, size_t n, uint32_t seed) { + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) { + uint32_t x = (uint32_t)i * 2654435761u ^ seed; x ^= x >> 13; x *= 0x5bd1e995u; x ^= x >> 15; + p[i] = ((x & 0xFFFFFF) / 16777216.f * 2.f - 1.f) * 1.7f; + } +} +__global__ void rsp_ssq(const float* h, float* ssq) { + float s = 0.f; + for (int i = threadIdx.x; i < HID; i += 256) s += h[(size_t)blockIdx.x * HID + i] * h[(size_t)blockIdx.x * HID + i]; + for (int o = 16; o; o >>= 1) s += __shfl_xor_sync(0xffffffff, s, o); + __shared__ float r[8]; + if ((threadIdx.x & 31) == 0) r[threadIdx.x >> 5] = s; + __syncthreads(); + if (threadIdx.x == 0) { float t = 0; for (int i = 0; i < 8; i++) t += r[i]; ssq[blockIdx.x] = t; } +} +std::string rs_probe(const float* lnw, float eps, const float* wrh, const float* wrl, const float* wg, const float* wu) { + std::string res = "RS_PROBE (isolated event us, avg of 5)"; + const int Ts[2] = {8192, 7184}; + cudaStream_t st; cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking); + cudaEvent_t e0, e1; cudaEventCreate(&e0); cudaEventCreate(&e1); + for (int ti = 0; ti < 2; ti++) { + const int T = Ts[ti], n = T * TOPK, maxTiles = (n + 127) / 128 + 128, mg = moe_max_groups(n); + float *h, *ssq, *tw, *pw, *ap; int *ti_, *cnt, *off, *cur, *te, *tm, *tt, *pt, *ip, *grp; + unsigned long long* pr; + cudaMalloc(&h, (size_t)T * HID * 4); cudaMalloc(&ssq, T * 4); cudaMalloc(&tw, n * 4); cudaMalloc(&pw, n * 4); + cudaMalloc(&ap, (size_t)T * HID * 4); cudaMalloc(&ti_, n * 4); cudaMalloc(&cnt, 512); cudaMalloc(&off, 512); + cudaMalloc(&cur, 512); cudaMalloc(&te, maxTiles * 4); cudaMalloc(&tm, maxTiles * 4); cudaMalloc(&tt, 4); + cudaMalloc(&pt, n * 4); cudaMalloc(&ip, n * 4); cudaMalloc(&grp, (4 * mg + 2 + (n + 255) / 256 + 128) * 4); + cudaMalloc(&pr, 148 * 8 * 8); + uint8_t* x8; cudaMalloc(&x8, (size_t)T * HID + 16); + rsp_fill<<<1024, 256, 0, st>>>(h, (size_t)T * HID, 7u + ti); + rsp_ssq<<>>(h, ssq); + cudaStreamSynchronize(st); + float tr = 0, tsc = 0, tsa = 0, tg = 0; + const int R = 5; + for (int r = 0; r <= R; r++) { + cudaMemsetAsync(cnt, 0, 512, st); + cudaMemsetAsync(pr, 0, 148 * 64, st); + unsigned long long* pp = r == R ? pr : nullptr; + cudaMemcpyToSymbolAsync(g_rt_probe, &pp, sizeof(pp), 0, cudaMemcpyHostToDevice, st); + float ms; + cudaEventRecord(e0, st); + launch_router(h, lnw, ssq, eps, wrh, wrl, T, ti_, tw, cnt, wg, wu, st, nullptr, x8, reinterpret_cast(x8 + (size_t)T * HID)); + cudaEventRecord(e1, st); cudaEventSynchronize(e1); cudaEventElapsedTime(&ms, e0, e1); if (r) tr += ms; + pp = nullptr; + cudaMemcpyToSymbolAsync(g_rt_probe, &pp, sizeof(pp), 0, cudaMemcpyHostToDevice, st); + cudaEventRecord(e0, st); + cudaMemsetAsync(cur, 0, 512, st); // scan fused into scatter: 'scan' slot now times the cursor reset + cudaEventRecord(e1, st); cudaEventSynchronize(e1); cudaEventElapsedTime(&ms, e0, e1); if (r) tsc += ms; + cudaEventRecord(e0, st); + pdl_launch(moe_scatter_kernel, dim3((n + SC_PER - 1) / SC_PER), dim3(256), 0, st, n, (const int*)ti_, (const float*)tw, (const int*)cnt, cur, off, te, tm, tt, grp, mg, pt, pw, ip, (n + SC_PER - 1) / SC_PER, (const float*)nullptr, (const float*)nullptr, 0.f, (const float*)nullptr, (float*)nullptr, 3, 3); + cudaEventRecord(e1, st); cudaEventSynchronize(e1); cudaEventElapsedTime(&ms, e0, e1); if (r) tsa += ms; + cudaEventRecord(e0, st); + launch_moe_norm_gather(h, lnw, eps, ip, ssq, T, ap, st); + cudaEventRecord(e1, st); cudaEventSynchronize(e1); cudaEventElapsedTime(&ms, e0, e1); if (r) tg += ms; + } + // router phase stamps (globaltimer): max over CTAs of (stamp_i - min entry) + unsigned long long hp_[148 * 8]; + cudaMemcpy(hp_, pr, sizeof(hp_), cudaMemcpyDeviceToHost); + unsigned long long t0 = ~0ull; double mx[8] = {0}, av[8] = {0}; int nc = 0; + for (int c = 0; c < 148; c++) if (hp_[c * 8] && hp_[c * 8] < t0) t0 = hp_[c * 8]; + for (int c = 0; c < 148; c++) { + if (!hp_[c * 8]) continue; + nc++; + for (int i = 0; i < 7; i++) { double d = hp_[c * 8 + i] ? (double)(hp_[c * 8 + i] - t0) / 1000.0 : 0; av[i] += d; if (d > mx[i]) mx[i] = d; } + } + char b[1024]; + snprintf(b, sizeof(b), " | T=%d router %.1f scan %.1f scatter %.1f gather %.1f | router phases (us from first entry, avg/max over %d CTAs): entry %.1f/%.1f griddep %.1f/%.1f acc %.1f/%.1f partsync %.1f/%.1f hist0 %.1f/%.1f select %.1f/%.1f end %.1f/%.1f", + T, 1000 * tr / R, 1000 * tsc / R, 1000 * tsa / R, 1000 * tg / R, nc, av[0] / nc, mx[0], av[1] / nc, mx[1], av[2] / nc, mx[2], + av[3] / nc, mx[3], av[4] / nc, mx[4], av[5] / nc, mx[5], av[6] / nc, mx[6]); + res += b; + res += " err=" + std::to_string((int)cudaGetLastError()); + cudaFree(h); cudaFree(ssq); cudaFree(tw); cudaFree(pw); cudaFree(ap); cudaFree(ti_); cudaFree(cnt); cudaFree(off); + cudaFree(cur); cudaFree(te); cudaFree(tm); cudaFree(tt); cudaFree(pt); cudaFree(ip); cudaFree(grp); cudaFree(pr); cudaFree(x8); + } + return res; +} +#endif + +#ifdef CHAIN_PROBE +// ------------------------------------------------------------------ chain probe host side +#include +#include +void chn_on(bool on) { + static ulonglong2* buf = nullptr; + if (!buf) cudaMalloc(&buf, CHN_CAP * sizeof(ulonglong2)); + ulonglong2* p = on ? buf : nullptr; + unsigned long long z = 0; + cudaMemcpyToSymbol(g_chn_log, &p, sizeof(p)); + cudaMemcpyToSymbol(g_chn_n, &z, sizeof(z)); +} +std::string chn_report(int ncalls, int skip) { + unsigned long long n = 0; + cudaMemcpyFromSymbol(&n, g_chn_n, sizeof(n)); + if (n > CHN_CAP) n = CHN_CAP; + ulonglong2* d = nullptr; + cudaMemcpyFromSymbol(&d, g_chn_log, sizeof(d)); + std::vector h(n); + cudaMemcpy(h.data(), d, n * sizeof(ulonglong2), cudaMemcpyDeviceToHost); + std::map> byk; + std::map grid; + for (auto& r : h) { const int key = (int)(r.y & 0xFFFF); byk[key].push_back(r.x); grid[key] = (int)(r.y >> 16); } + // per key: chunk n = CTAs of call n (instances of one kernel id never overlap across calls) + std::map>> mm; // key -> per call (min, max) + for (auto& kv : byk) { + auto v = kv.second; std::sort(v.begin(), v.end()); + int g = grid[kv.first]; + if ((kv.first >> 2) == 12) g *= 1; // scatter: each CTA logs once per type + std::vector> c; + for (size_t i = 0; i + g <= v.size(); i += g) c.push_back({(double)v[i], (double)v[i + g - 1]}); + mm[kv.first] = c; + } + int moe = mm.count(13 * 4 + 2) ? 13 * 4 + 2 : 14 * 4 + 2; + auto& me = mm[moe]; + const char* nm[15] = {"mask", "conv", "prep", "qkv", "oproj", "rph", "moetab", "rtA", "rtB", "", "fa", "router", "scat", "moe1", "moe2"}; + std::string res; + char b[256]; + snprintf(b, sizeof(b), "[calls/key moe=%d] ", (int)me.size()); res += b; + for (auto& kv : mm) { + const int key = kv.first; auto& c = kv.second; + double smin = 0, smax = 0; int cnt = 0; + for (int i = skip; i < ncalls && i < (int)c.size() && i < (int)me.size(); i++) { + smin += (c[i].first - me[i - 1].second) / 1000.0; smax += (c[i].second - me[i - 1].second) / 1000.0; cnt++; + } + if (!cnt) continue; + snprintf(b, sizeof(b), "%s.%d(g%d)=%.1f/%.1f ", nm[key >> 2], key & 3, grid[key], smin / cnt, smax / cnt); + res += b; + } + double per = 0; int pc = 0; + for (int i = skip; i < (int)me.size(); i++) { per += (me[i].second - me[i - 1].second) / 1000.0; pc++; } + snprintf(b, sizeof(b), "| moe-end period %.2f us", pc ? per / pc : 0.0); res += b; + return res; +} +#endif + +#ifdef TMA_PROBE +#include +__global__ void tma_probe_kernel(const __grid_constant__ CUtensorMap m, int x0, uint32_t ebytes, uint16_t* out, int* flag) { + __shared__ alignas(1024) uint16_t buf[256]; + __shared__ alignas(8) uint64_t bar; + if (threadIdx.x != 0) return; + for (int i = 0; i < 256; i++) buf[i] = 0xDEAD; + const uint32_t b = smem_u32(&bar); + mbar_init(b, 1); + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + mbar_expect_tx(b, ebytes); + tma_load_2d(smem_u32(buf), &m, x0, 0, b); + int ok = 0; + for (long it = 0; it < 2000000 && !ok; it++) ok = mbar_test(b, 0) ? 1 : 0; + flag[0] = ok; + for (int i = 0; i < 256; i++) out[i] = buf[i]; +} +std::string tma_probe() { + std::string res = "TMA_PROBE:"; + float* src; uint16_t* out; int* flag; + cudaMalloc(&src, 4096 * 4); cudaMalloc(&out, 512); cudaMalloc(&flag, 4); + std::vector h(4096); + for (int i = 0; i < 4096; i++) h[i] = 1.0f + i * 0.001953125f + i * 1e-7f; + cudaMemcpy(src, h.data(), 4096 * 4, cudaMemcpyHostToDevice); + char b[512]; + // 2D bf16 view of fp32 [8 rows][256 floats]: dims {512, 8}, row stride 1024 B, box {64,1}, elementStrides {2,1} + struct PC { int es, x0; uint32_t eb; }; + const PC pcs[4] = {{2, 0, 64}, {2, 0, 128}, {2, 1, 64}, {2, 1, 128}}; + for (int E = 0; E < 4; E++) { + CUtensorMap m; + cuuint64_t dims[2] = {512, 8}; + cuuint64_t strides[1] = {1024}; + cuuint32_t box[2] = {64, 1}; + cuuint32_t es[2] = {(cuuint32_t)pcs[E].es, 1}; + CUresult r = cuTensorMapEncodeTiled(&m, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, (void*)src, dims, strides, box, es, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + snprintf(b, sizeof(b), " (es%d x0=%d enc=%d", pcs[E].es, pcs[E].x0, (int)r); res += b; + if (r == CUDA_SUCCESS) { + cudaMemset(out, 0, 512); cudaMemset(flag, 0, 4); + const uint32_t eb = pcs[E].eb; + tma_probe_kernel<<<1, 32>>>(m, pcs[E].x0, eb, out, flag); + cudaError_t ce = cudaDeviceSynchronize(); + uint16_t ho[256]; int hf = 0; + cudaMemcpy(ho, out, 512, cudaMemcpyDeviceToHost); cudaMemcpy(&hf, flag, 4, cudaMemcpyDeviceToHost); + int nhi = 0, nseq = 0; + for (int j = 0; j < 32; j++) { uint32_t u; memcpy(&u, &h[j], 4); if (ho[j] == (u >> 16)) nhi++; } + const uint16_t* hs = reinterpret_cast(h.data()); + for (int j = 0; j < 64; j++) if (ho[j] == hs[pcs[E].x0 + j]) nseq++; + snprintf(b, sizeof(b), " expect=%u done=%d err=%d hi-match32=%d seq-match64=%d first=%04x %04x %04x %04x)", eb, hf, + (int)ce, nhi, nseq, ho[0], ho[1], ho[2], ho[3]); + res += b; + if (ce != cudaSuccess) break; + } else res += ")"; + } + { + CUtensorMap m; + cuuint64_t dims[2] = {510, 8}; + cuuint64_t strides[1] = {1024}; + cuuint32_t box[2] = {64, 1}; + cuuint32_t es[2] = {2, 1}; + CUresult r = cuTensorMapEncodeTiled(&m, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, (void*)((char*)src + 2), dims, strides, box, es, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + snprintf(b, sizeof(b), " (base+2 enc=%d)", (int)r); res += b; + } + { + CUtensorMap m; + cuuint64_t dims[3] = {2, 256, 8}; + cuuint64_t strides[2] = {4, 1024}; + cuuint32_t box[3] = {1, 64, 1}; + cuuint32_t es[3] = {1, 1, 1}; + CUresult r = cuTensorMapEncodeTiled(&m, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 3, (void*)src, dims, strides, box, es, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + snprintf(b, sizeof(b), " (3D enc=%d)", (int)r); res += b; + } + return res; +} +#endif + +__global__ void clk_probe_kernel(unsigned long long* o) { + unsigned long long t0, t1; long long c0 = clock64(); + asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t0)); + do { asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t1)); } while (t1 - t0 < 200000); + long long c1 = clock64(); + o[0] = (unsigned long long)(c1 - c0); o[1] = t1 - t0; +} +float sm_clock_mhz() { + static unsigned long long* d = nullptr; + if (!d) cudaMalloc(&d, 16); + clk_probe_kernel<<<1, 1>>>(d); + unsigned long long h[2]; cudaMemcpy(h, d, 16, cudaMemcpyDeviceToHost); + return (float)h[0] * 1000.f / (float)h[1]; +}