diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_large2.cu b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_large2.cu new file mode 100644 index 0000000000000000000000000000000000000000..79292c783fba928f832573ae4e6ac1337f5059da --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_large2.cu @@ -0,0 +1,1702 @@ +// +// out[m, n] = sum_kb sx[m, kb] * sw[kb, n/128] * sum_{k in kb} A[m,k] * W[n,k] +// +// DeepGEMM-style "promotion" design (scales are arbitrary fp32, so the native +// UE8M0 block-scale MMA cannot be used). PERSISTENT kernel: grid = #SMs, each CTA +// walks WORK UNITS u = blockIdx.x, blockIdx.x + gridDim.x, ... +// +// Work decomposition (hybrid "stream-K tail", chosen on the host by fp8_bs_plan): +// * units [0, direct) : whole 128x256 tiles (tile = u), full K, +// bf16 output via TMA store. +// * units [direct, direct+tail*split) : v = u - direct, ti = v % tail, ks = v / tail; +// tile = direct + ti, K-blocks [ks*nkb/split, (ks+1)*nkb/split). +// Partials red.global.add'ed into a compact fp32 +// workspace ws[ti][128][256] (pre-zeroed), then a 2nd +// kernel converts those tiles to bf16. +// Small M (few tiles): direct = 0, all tiles split (classic split-K). +// Large M: direct = full waves of tiles, only the LAST PARTIAL WAVE is split so that +// every SM gets work in the final wave (fixes wave quantization: e.g. M=4096 has +// 896 tiles = 6 x 148 + 8; the 8 tail tiles are split 18 ways instead of leaving +// 140 SMs idle for a whole tile time). +// L2-friendly rasterization: tiles are grouped in BANDS of `group_n` 256-col +// N-blocks; inside a band the N-block index is fastest, then M. +// +// Shared memory: 4-stage TMA operand ring (4 x 48 KB) + 32 KB bf16 output staging +// (one 2 KB buffer per epilogue warp, reused for both 32-col halves of its 32x64 slab). +// +// 12 warps = 3 warpgroups. Register budget is redistributed with setmaxnreg. +// Promotion: packed FFMA2 (__ffma2_rn) + suspend-hinted mbarrier try_wait (issuer + promotion warps). +// * WG0 (warps 0..3) -> setmaxnreg.dec 56 (ptxas allocates per setmaxnreg region: 32 spilled the +// scale/TMA producers; 56/104 + x16 TMEM drain = zero local memory) +// warp 0 : TMA producer. Loads A (128x128 fp8) and W (256x128 fp8) tiles +// (128B-swizzled, BLOCK_K = 128 = one scale block) into a +// STAGES-deep smem ring guarded by full/empty mbarriers. +// warp 1 : TMEM allocator + single-thread tcgen05.mma issuer +// (kind::f8f6f4, M=128,N=256,K=32, 4 MMAs per K-block). Each +// K-block is accumulated FRESH into one of two TMEM buffers +// (double buffered, 2 x 256 fp32 columns = all 512 TMEM cols). +// warps 2,3: SCALE PRODUCER (64 threads). Per K-block of every unit they compute the +// promotion scales s[half][row] = sx[m0+row, kb] * sw[kb, nb*2+half] (256 fp32) +// into an 8-slot smem ring (sfull/sempty mbarriers), batching 4 k-blocks of +// global loads so the latency is hidden; promotion threads then read ONE +// ld.shared per k-block instead of 2 global loads + address math. +// * WG1..WG2 (warps 4..11) -> setmaxnreg.inc 224: promotion epilogue (128 cols / warpgroup). +// Warpgroup g owns output cols [g*64, g*64+64) of the tile (4 warps per +// SM sub-partition so several tcgen05.ld are in flight per SMSP). +// For every K-block: tcgen05.ld its 128x64 partial from TMEM +// (thread = one row, sub-partition = warp%4), release the TMEM +// buffer (512 arrivals), then acc[n] += partial[n] * (sx*sw) in +// fp32 regs (TMEM read in 4 x 16-col chunks; latency hidden across the 4 warps per SMSP). At unit end: +// direct unit: bf16 pack -> 64B-swizzled 2 KB smem staging -> TMA store, +// twice (one per 32-col half, waiting for the buffer read). +// split unit : red.global.add.v4.f32 of the fp32 row (64 cols) into the workspace. +#include +#include +#include +#include +#include +#include +#include "tmap_cache.h" +#include "kernel_large2.h" +#ifndef LARGE2_DYN_DEFAULT +#define LARGE2_DYN_DEFAULT 0 +#endif + +namespace { + +constexpr int BLOCK_M = 128; +constexpr int BLOCK_N = 256; +constexpr int BLOCK_K = 128; +constexpr int STAGES = 4; +constexpr int TILE_A_BYTES = BLOCK_M * BLOCK_K; // fp8, 16 KB +constexpr int TILE_B_BYTES = BLOCK_N * BLOCK_K; // 32 KB +constexpr int STAGE_BYTES = TILE_A_BYTES + TILE_B_BYTES; +constexpr int NUM_EPI_WARPS = 8; // 2 promotion warpgroups x 128 cols +constexpr int EPI_COLS = 128; // output cols per promotion warpgroup +// EPILOGUE STAGING (this version): per warp 3 KB = slot A (2 KB: 32 rows x 32 bf16 cols, 64B swizzle) + slot B +// (1 KB: 32 rows x 16 cols, 32B swizzle). A warp's 128 output cols are stored as 5 TMA boxes A|B|A|B|A +// (32+16+32+16+32 cols) instead of 8 x 16-col boxes; A and B alternate so one store is always in flight while the +// next box is packed (wait_group.read 1), the first box of a tile waits for the previous tile's last A (read 0). +constexpr int WARP_STAGE_BYTES = 3072; +constexpr int OUT_SLOTS = 3; // (legacy constant, used only by tma_store_wait_read_ring) +constexpr int OUT_STAGE_BYTES = NUM_EPI_WARPS * WARP_STAGE_BYTES; // 24 KB +constexpr int SC_SLOTS = 8; // scale ring depth (k-blocks) +constexpr int SC_BYTES = SC_SLOTS * 256 * 4; // 8 KB: [slot][half][128 rows] fp32 +constexpr int EPI_WARP0 = 4; // first epilogue warp (warpgroup 1) +constexpr int NUM_THREADS = 128 + NUM_EPI_WARPS * 32; // 12 warps = 3 warpgroups +constexpr int TMEM_COLS = 512; // 2 accumulator buffers x 256 cols +constexpr int SMEM_BYTES = STAGES * STAGE_BYTES + OUT_STAGE_BYTES + SC_BYTES + 1024 /*align*/ + 512 /*barriers + mailbox*/; +constexpr int WS_TILE_FLOATS = BLOCK_M * BLOCK_N; // compact workspace tile (fp32 128x256) +// claim mbarrier: after full/empty[STAGES], tfull/tempty[2], sfull/sempty[SC_SLOTS]; tmem slot +8, claim slot +12 +constexpr int CLAIM_BAR_OFF = STAGES * STAGE_BYTES + OUT_STAGE_BYTES + SC_BYTES + (2 * STAGES + 4 + 2 * SC_SLOTS) * 8; +// DYN unit mailbox (scale producer -> promotion warps): mfull[MB_SLOTS] @ +16, mempty[MB_SLOTS] @ +48, int4 slots @ +80 +constexpr int MB_SLOTS = 4; +constexpr int MBOX_BAR_OFF = CLAIM_BAR_OFF + 16; +constexpr int MBOX_OFF = CLAIM_BAR_OFF + 80; +static_assert(MBOX_OFF + MB_SLOTS * 16 <= STAGES * STAGE_BYTES + OUT_STAGE_BYTES + SC_BYTES + 512, "mailbox fits"); +static_assert(SMEM_BYTES <= 232448, "smem budget"); +// setmaxnreg budget: 128*56 + 256*224 = 64512 = 168 (launch regs) * 384 threads +// (224 promo regs hold acc[128] + 64 TMEM staging regs + loop state; 56 = zero-spill control WG) +constexpr int REGS_CTRL = 56; +constexpr int REGS_EPI = 224; + +// Banded tile rasterization (shared by host + all device roles). +__host__ __device__ __forceinline__ void tile_coords(int t, int num_mblk, int num_nblk, int group_n, int& mb, + int& nb) { + // group_n bit 16 = SERPENTINE band raster: odd bands walk the M-blocks in reverse, so a band starts on the A + // row-blocks the previous band just streamed (still L2-resident) instead of re-fetching them from DRAM. Bijective. + const bool serp = (group_n >> 16) & 1; + // group_n bit 17 = MIRRORED N raster (nb -> num_nblk-1-nb, bijective): used by the 2nd half-launch of the split + // M >= 12288 path so it starts on the N band the 1st launch ended on (W band still L2-resident at the seam). + const bool mir = (group_n >> 17) & 1; + group_n &= 0xFFFF; + const int per_band = group_n * num_mblk; + const int band = t / per_band; + const int r = t - band * per_band; + const int n_first = band * group_n; + const int rem = num_nblk - n_first; + const int gn = rem < group_n ? rem : group_n; + mb = r / gn; + nb = n_first + (r - mb * gn); + if (serp && (band & 1)) mb = num_mblk - 1 - mb; + if (mir) nb = num_nblk - 1 - nb; +} + +// Work unit -> (tile, K-block range [kb0, kb1), workspace tile index wsi or -1 for a direct unit). +__device__ __forceinline__ void unit_coords(int u, int direct, int tail, int split, int num_kb, int& t, int& kb0, + int& kb1, int& wsi) { + if (u < direct) { + t = u; + kb0 = 0; + kb1 = num_kb; + wsi = -1; + return; + } + const int v = u - direct; + const int ks = v / tail; + wsi = v - ks * tail; + t = direct + wsi; + kb0 = (ks * num_kb) / split; + kb1 = ((ks + 1) * num_kb) / split; +} +// SPF (split-pieces-first) variant: piece boundaries rounded to EVEN k-blocks so every piece (and hence every whole +// tile after it in the CTA's walk) starts at an even global k-block counter -> the buffer-specialised promotion pair +// path stays in use for the whole tiles. +template +__device__ __forceinline__ void unit_coords_t(int u, int direct, int tail, int split, int num_kb, int& t, int& kb0, + int& kb1, int& wsi) { + if (!EVEN || u < direct) { + unit_coords(u, direct, tail, split, num_kb, t, kb0, kb1, wsi); + return; + } + const int v = u - direct; + const int ks = v / tail; + wsi = v - ks * tail; + t = direct + wsi; + const int h = num_kb >> 1; + kb0 = 2 * ((ks * h) / split); + kb1 = (ks + 1 == split) ? num_kb : 2 * (((ks + 1) * h) / split); +} +// SPF walk of CTA b: its (single) tail piece u = direct + b FIRST (if b < tail*split), then its whole tiles +// b, b + grid, ... < direct. Returns -1 at the end. (Host guarantees direct % grid == 0 and tail*split <= grid, +// i.e. exactly the static unit -> CTA assignment of MODE 0, only the order differs.) +// OWNER PLACEMENT (rot): piece holder index pb = (b + rot) % grid; CTA b runs tail piece pb first iff pb < ts, so the +// grid - ts piece-less CTAs are b = ts - rot .. grid - 1 - rot (mod grid). rot = 0: CTAs 0..ts-1 hold the pieces. +__device__ __forceinline__ int spf_first(int b, int direct, int ts, int rot) { + const int pb = (b + rot) % (int)gridDim.x; // bijection on [0, grid) for any rot >= 0 + return pb < ts ? direct + pb : (b < direct ? b : -1); +} +__device__ __forceinline__ int spf_next(int u, int b, int direct, int grid) { + return u >= direct ? (b < direct ? b : -1) : (u + grid < direct ? u + grid : -1); +} + +// ---------------------------------------------------------------- PTX helpers +__device__ __forceinline__ uint32_t smem_u32(const void* p) { + return static_cast(__cvta_generic_to_shared(p)); +} +__device__ __forceinline__ void mbar_init(uint64_t* bar, uint32_t count) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(smem_u32(bar)), "r"(count)); +} +__device__ __forceinline__ void mbar_arrive_expect_tx(uint64_t* bar, uint32_t bytes) { + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(smem_u32(bar)), "r"(bytes) + : "memory"); +} +__device__ __forceinline__ void mbar_arrive(uint64_t* bar) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(smem_u32(bar)) : "memory"); +} +__device__ __forceinline__ void mbar_wait(uint64_t* bar, uint32_t parity) { + uint32_t addr = smem_u32(bar); + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAIT_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n" + "@!p bra WAIT_%=;\n" + "}\n" ::"r"(addr), + "r"(parity) + : "memory"); +} +// mbarrier wait with a suspend-time hint: a waiting warp is parked by the hardware (woken on phase +// completion) instead of hot-spinning, so it does not steal issue slots on its SMSP. Used by the MMA issuer +// (warp 1) and all promotion warps . +__device__ __forceinline__ void mbar_wait_sleep(uint64_t* bar, uint32_t parity) { + uint32_t addr = smem_u32(bar); + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITS_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITS_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +__device__ __forceinline__ void tma_load_2d(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1, {%2, %3}], [%4];" ::"r"( + smem_u32(dst)), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(smem_u32(bar)) + : "memory"); +} +// TMA load with an L2 cache-policy hint (policy from createpolicy): W tiles evict_last (re-read by every +// M-block of the band), A tiles evict_first (streamed; reused only within a short window). +__device__ __forceinline__ void tma_load_2d_hint(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y, + uint64_t policy) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(smem_u32(dst)), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(smem_u32(bar)), "l"(policy) + : "memory"); +} +__device__ __forceinline__ uint64_t policy_evict_last() { + uint64_t p; + asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(p)); + return p; +} +__device__ __forceinline__ uint64_t policy_evict_first() { + uint64_t p; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(p)); + return p; +} +__device__ __forceinline__ void tma_store_2d(const CUtensorMap* map, const void* src, int x, int y, uint64_t pol) { + // output store with an L2 evict_first policy (created ONCE per promotion warp, passed in): the bf16 output is + // written once and never re-read by this kernel, so its lines should not evict the W / A operand lines. + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%1, %2}], [%3], %4;" ::"l"( + reinterpret_cast(map)), + "r"(x), "r"(y), "r"(smem_u32(src)), "l"(pol) + : "memory"); +} +__device__ __forceinline__ void tma_store_commit() { asm volatile("cp.async.bulk.commit_group;" ::: "memory"); } +__device__ __forceinline__ void tma_store_wait_read() { + asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); +} +// wait until at most OUT_SLOTS-1 most recent bulk store groups still read their smem source +__device__ __forceinline__ void tma_store_wait_read_ring() { + asm volatile("cp.async.bulk.wait_group.read %0;" ::"n"(OUT_SLOTS - 1) : "memory"); +} +__device__ __forceinline__ void tma_store_wait_all() { asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); } +__device__ __forceinline__ void red_add_v4(float* p, float a, float b, float c, float d) { + asm volatile("red.global.add.v4.f32 [%0], {%1, %2, %3, %4};" ::"l"(p), "f"(a), "f"(b), "f"(c), "f"(d) + : "memory"); +} +// UMMA shared-memory descriptor: K-major, 128B swizzle, rows of 128 bytes, +// 8-row core-matrix groups 1024 B apart (SBO), sm100 descriptor version = 1. +__device__ __forceinline__ uint64_t make_sdesc(uint32_t saddr) { + uint64_t d = 0; + d |= (uint64_t)((saddr & 0x3FFFF) >> 4); + d |= (uint64_t)1 << 16; // LBO (unused for swizzled K-major) + d |= (uint64_t)(1024 >> 4) << 32; // SBO + d |= (uint64_t)1 << 46; // version + d |= (uint64_t)2 << 61; // SWIZZLE_128B + return d; +} +__device__ __forceinline__ void mma_f8(uint32_t tmem_d, uint64_t adesc, uint64_t bdesc, uint32_t idesc, + uint32_t accum) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "setp.ne.b32 p, %4, 0;\n" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %3, p;\n" + "}\n" ::"r"(tmem_d), + "l"(adesc), "l"(bdesc), "r"(idesc), "r"(accum)); +} +__device__ __forceinline__ void mma_commit(uint64_t* bar) { + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(smem_u32(bar)) + : "memory"); +} +__device__ __forceinline__ void fence_after() { asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void fence_before() { asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory"); } + +#define TMEM_LD32(taddr, r) \ + 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)) + +#define TMEM_LD16(taddr, r) \ + 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"(taddr)) + +__device__ __forceinline__ void tmem_ld_wait() { asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); } + + +__device__ __forceinline__ void tmem_ld8(uint32_t taddr, uint32_t* r) { + 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"(taddr)); +} +__device__ __forceinline__ void tmem_ld32(uint32_t taddr, uint32_t* r) { TMEM_LD32(taddr, r); } +__device__ __forceinline__ void tmem_ld64(uint32_t taddr, uint32_t* r) { + asm volatile("tcgen05.ld.sync.aligned.32x32b.x64.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,%33,%34,%35,%36,%37,%38,%39,%40,%41,%42,%43,%44,%45,%46,%47,%48,%49,%50,%51,%52,%53,%54,%55,%56,%57,%58,%59,%60,%61,%62,%63}, [%64];" + : "=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"(r[32]), "=r"(r[33]), "=r"(r[34]), "=r"(r[35]), "=r"(r[36]), "=r"(r[37]), "=r"(r[38]), "=r"(r[39]), "=r"(r[40]), "=r"(r[41]), "=r"(r[42]), "=r"(r[43]), "=r"(r[44]), "=r"(r[45]), "=r"(r[46]), "=r"(r[47]), "=r"(r[48]), "=r"(r[49]), "=r"(r[50]), "=r"(r[51]), "=r"(r[52]), "=r"(r[53]), "=r"(r[54]), "=r"(r[55]), "=r"(r[56]), "=r"(r[57]), "=r"(r[58]), "=r"(r[59]), "=r"(r[60]), "=r"(r[61]), "=r"(r[62]), "=r"(r[63]) + : "r"(taddr)); +} + + +// END-CLAIMED TAIL PIECES (MODE 31, OFF by default -- see LARGE2_DYN_DEFAULT): whole tiles u < direct stay static (u = blockIdx.x + i*grid); the K-split +// tail pieces are NOT statically assigned: when a CTA's TMA producer has issued its last whole tile it takes a +// ticket p = atomicAdd(claim_ctr, 1) (so the earliest-finishing CTAs take the pieces) and maps it to piece +// v = tail*split-1-p (contributors with the highest k first, owners kb0 == 0 last) or to none (p >= tail*split). +// Loops run u = blockIdx.x + i*grid < direct + grid (one tail slot per CTA), the tail slot is redirected to the +// claimed unit (or ends the walk): u := claimed unit, and claimed + grid >= direct + grid ends the loop +// (no extra loop-carried register: an extra one spilled the 224-reg promotion warps). +// The ticket is broadcast to the other roles through a smem slot + mbarrier (claim_bar, 1 arrival). Every CTA +// claims exactly once, so the holder of ticket gridDim.x-1 resets the counter to 0 for the next launch. +// At most one piece per CTA and every piece is claimed (tail*split <= grid, grid co-resident): the owner's wait +// for its contributors (which never wait) always completes. +__device__ __forceinline__ void mbar_arrive_u32(uint32_t a) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(a) : "memory"); +} +// MEMORY-ORDERING AUDIT: relaxed CTA-scope local arrive for the TMEM-empty hand-off (issued after tcgen05.wait::ld + +// tcgen05.fence::before_thread_sync: the TMEM reads are complete, nothing else is published by this arrive). +__device__ __forceinline__ void mbar_arrive_relaxed_u32(uint32_t addr) { + asm volatile("mbarrier.arrive.relaxed.cta.shared::cta.b64 _, [%0];" ::"r"(addr) : "memory"); +} +__device__ __forceinline__ void mbar_wait_sleep_u32(uint32_t a, uint32_t parity) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITU_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITU_%=;\n" + "}\n" ::"r"(a), + "r"(parity), "n"(0x989680) + : "memory"); +} +// 32-bit shared-window address of the 1024-aligned dynamic smem base +__device__ __forceinline__ uint32_t smem_base_u32() { + extern __shared__ uint8_t smem_raw[]; + return (smem_u32(smem_raw) + 1023u) & ~1023u; +} +template +__device__ __forceinline__ int claim_tail_unit(int direct, int tail, int split, int* claim_ctr, int u_static) { + if (!REAL) return u_static < direct + tail * split ? u_static : -1; + // claim barrier / slot live at fixed offsets of the barrier region (32-bit addresses recomputed from the + // aligned smem base: no loop-carried registers) + const uint32_t claim_bar = smem_base_u32() + CLAIM_BAR_OFF; + const uint32_t claim_slot = claim_bar + 12u; + int v; + if (CLAIMER) { + const int p = atomicAdd(claim_ctr, 1); + if (p == (int)gridDim.x - 1) atomicExch(claim_ctr, 0); // all tickets of this launch taken + const int np = tail * split; + v = p < np ? direct + (OWNERS_FIRST ? p : np - 1 - p) : -1; + asm volatile("st.shared.b32 [%0], %1;" ::"r"(claim_slot), "r"(v) : "memory"); + mbar_arrive_u32(claim_bar); // release.cta: slot visible to the waiters + } else { + mbar_wait_sleep_u32(claim_bar, 0); + asm volatile("ld.shared.b32 %0, [%1];" : "=r"(v) : "r"(claim_slot) : "memory"); + } + return v; +} + + +#ifdef LARGE2_PROF +// PROBE-ONLY instrumentation (never compiled in production): per-CTA clock64 stall statistics of the TMA producer and +// the MMA issuer. Layout per CTA (64 u64): 0 prod empty-blocked count, 1 prod empty wait clk, 2 mma full-blocked count, +// 3 mma full wait clk, 4 mma tempty-blocked count, 5 tempty wait clk, 6 kbs, 7 span clk, 8..23 hist log2(issue->full +// observed clk) for full-blocked kbs, 24..39 hist log2(issue->full observed) for ALL kbs, 40..55 hist log2(tempty wait clk) +__device__ unsigned long long* d_l2prof; +__device__ int d_l2mode; +#define PROF_SKIPP (l2mode & 1) +#define PROF_SKIPM (l2mode & 2) +#define PROF_SKIPT (l2mode & 4) +#define LEAN (l2mode & 8) +__device__ __forceinline__ bool mbar_test(uint64_t* bar, uint32_t parity) { + uint32_t ok; + asm volatile("{\n.reg .pred p;\nmbarrier.test_wait.parity.shared::cta.b64 p, [%1], %2;\nselp.u32 %0, 1, 0, p;\n}\n" + : "=r"(ok) : "r"((uint32_t)__cvta_generic_to_shared(bar)), "r"(parity) : "memory"); + return ok != 0; +} +__device__ __forceinline__ int lg2b(long long v) { int b = v <= 1 ? 0 : 63 - __clzll(v); return b > 15 ? 15 : b; } +#endif +#ifndef LARGE2_PROF +#define PROF_SKIPP 0 +#define PROF_SKIPM 0 +#define PROF_SKIPT 0 +#endif + +// ELECTED-ISSUE helpers (MODE & 128): the MMA-issuer loop is executed by the WHOLE warp 1 (warp-uniform control flow, +// loop state / descriptors are warp-uniform values), and only the tcgen05.mma / tcgen05.commit instructions are +// predicated on elect.sync (one lane issues), as in DeepGEMM / CUTLASS. +__device__ __forceinline__ void mma_f8_e(uint32_t tmem_d, uint64_t adesc, uint64_t bdesc, uint32_t idesc, + uint32_t accum) { + asm volatile( + "{\n" + ".reg .pred p, e;\n" + "elect.sync _|e, 0xffffffff;\n" + "setp.ne.b32 p, %4, 0;\n" + "@e tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %3, p;\n" + "}\n" ::"r"(tmem_d), + "l"(adesc), "l"(bdesc), "r"(idesc), "r"(accum)); +} +__device__ __forceinline__ void mma_commit_e(uint64_t* bar) { + asm volatile( + "{\n" + ".reg .pred e;\n" + "elect.sync _|e, 0xffffffff;\n" + "@e tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];\n" + "}\n" ::"r"(smem_u32(bar)) + : "memory"); +} +__device__ __forceinline__ void mma_commit_e_u32(uint32_t bar) { + asm volatile( + "{\n" + ".reg .pred e;\n" + "elect.sync _|e, 0xffffffff;\n" + "@e tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];\n" + "}\n" ::"r"(bar) + : "memory"); +} +// SHORT ISSUER LOOP helpers (EISS fast path): one asm block = elect.sync + 4 tcgen05.mma (K32 slices) + 2 commits; +// 32-bit shared addresses for every barrier; spin try_wait (no suspend hint) for the operand-full barrier. +__device__ __forceinline__ void mbar_wait_spin_u32(uint32_t addr, uint32_t parity) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITF_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n" + "@!p bra WAITF_%=;\n" + "}\n" ::"r"(addr), + "r"(parity) + : "memory"); +} +// HYBRID wait (promotion tfull): first try_wait without suspend hint (hardware-bounded poll window, minimal wake +// latency when the MMA finishes soon), then loop with a suspend-time hint so long waits park the warp instead of +// re-polling (fewer issue slots / smem barrier reads burned by 8 promotion warps under the power cap). +__device__ __forceinline__ void mbar_wait_hybrid_u32(uint32_t addr, uint32_t parity) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n" + "@p bra DONEH_%=;\n" + "WAITH_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITH_%=;\n" + "DONEH_%=:\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +__device__ __forceinline__ void mma4_commit2_e(uint32_t tmem_d, uint64_t a, uint64_t b, uint32_t idesc, + uint32_t empty_addr, uint32_t tfull_addr) { + asm volatile( + "{\n" + ".reg .pred e, p0, p1;\n" + "setp.ne.b32 p0, %11, 0;\n" + "setp.eq.b32 p1, %11, 0;\n" + "elect.sync _|e, 0xffffffff;\n" + "@e tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %10, p0;\n" + "@e tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %3, %4, %10, p1;\n" + "@e tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %5, %6, %10, p1;\n" + "@e tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %7, %8, %10, p1;\n" + "@e tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%9];\n" + "@e tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%12];\n" + "}\n" ::"r"(tmem_d), + "l"(a), "l"(b), "l"(a + 2), "l"(b + 2), "l"(a + 4), "l"(b + 4), "l"(a + 6), "l"(b + 6), "r"(empty_addr), + "r"(idesc), "r"(0u), "r"(tfull_addr) + : "memory"); +} + +// ISSUER STUDY (MODE & 512): the 4 K32 MMAs of a k-block and both commits in ONE asm block (one elect.sync when +// ELECT; TF_FIRST: tfull commit before the empty commit). +template +__device__ __forceinline__ void mma4_commit2(uint32_t tmem_d, uint64_t ad, uint64_t bd, uint32_t idesc, uint64_t* ebar, + uint64_t* tbar) { + const uint32_t e = smem_u32(ebar), t = smem_u32(tbar); + const uint32_t c1 = TF_FIRST ? t : e, c2 = TF_FIRST ? e : t; +#define MMA4_ASM(ELINE) \ + asm volatile( \ + "{\n" \ + ".reg .pred e, pf, pt;\n" \ + "setp.eq.u32 pt, 1, 1;\n" \ + "setp.eq.u32 pf, 1, 0;\n" ELINE \ + "@e tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %3, pf;\n" \ + "@e tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %4, %5, %3, pt;\n" \ + "@e tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %6, %7, %3, pt;\n" \ + "@e tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %8, %9, %3, pt;\n" \ + "@e tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%10];\n" \ + "@e tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%11];\n" \ + "}\n" ::"r"(tmem_d), \ + "l"(ad), "l"(bd), "r"(idesc), "l"(ad + 2), "l"(bd + 2), "l"(ad + 4), "l"(bd + 4), "l"(ad + 6), "l"(bd + 6), \ + "r"(c1), "r"(c2) \ + : "memory") + if constexpr (ELECT) MMA4_ASM("elect.sync _|e, 0xffffffff;\n"); + else MMA4_ASM("setp.eq.u32 e, 1, 1;\n"); +#undef MMA4_ASM +} +// HEAD L2 PREFETCH helpers (pure hints: no smem / barrier / visible state) +__device__ __forceinline__ void l2_prefetch_tile_hint(const CUtensorMap* map, int x, int y, uint64_t pol) { + asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile.L2::cache_hint [%0, {%1, %2}], %3;" ::"l"( + reinterpret_cast(map)), + "r"(x), "r"(y), "l"(pol) + : "memory"); +} +// ---------------------------------------------------------------- kernel +#define PROMO_FMA32(A_, R_) do { \ + float* a_ = (A_); \ +_Pragma("unroll") \ + for (int j = 0; j < 32; j += 2) { \ + const float2 d = __ffma2_rn(make_float2(__uint_as_float(R_[j]), __uint_as_float(R_[j + 1])), ss, \ + make_float2(a_[j], a_[j + 1])); \ + a_[j] = d.x; a_[j + 1] = d.y; \ + } \ +} while (0) +// acc[0..16) += r[0..16) * ss (8 packed FFMA2) +#define PROMO_FMA16(A_, R_) do { \ + float* a_ = (A_); \ + const uint32_t* r_ = (R_); \ +_Pragma("unroll") \ + for (int j = 0; j < 16; j += 2) { \ + const float2 d = __ffma2_rn(make_float2(__uint_as_float(r_[j]), __uint_as_float(r_[j + 1])), ss, \ + make_float2(a_[j], a_[j + 1])); \ + a_[j] = d.x; a_[j + 1] = d.y; \ + } \ +} while (0) +// SASS AUDIT: 32-bit shared offsets of the promotion barriers from the (warp-uniform) barrier-region base bar_u, +// so the per-kb waits / arrives use one uniform register + immediates instead of re-deriving generic pointers +// (S2UR SR_SWINHI + 1024-align + cvta) every k-block pair. +constexpr uint32_t TFULL_OFF = (2 * STAGES) * 8, TEMPTY_OFF = TFULL_OFF + 16; +constexpr uint32_t SFULL_OFF = TEMPTY_OFF + 16, SEMPTY_OFF = SFULL_OFF + SC_SLOTS * 8; +#define PROMO_STEP(B_) PROMO_STEPX(B_, (it % SC_SLOTS)) +// PROMO_STEPX: SLOT_ = scale-ring slot of this k-block (aligned pair loop: even slot (it & 6) and +1, so the 2nd step's +// barrier / scale addresses are the 1st step's plus immediates) +#define PROMO_STEPX(B_, SLOT_) PROMO_STEPW(B_, SLOT_, SLOT_, 1) +#define PROMO_STEPW(B_, SLOT_, WSLOT_, DOW_) do { \ + const uint32_t slot = (SLOT_); \ + if (DOW_) mbar_wait_sleep_u32(bar_u + SFULL_OFF + (uint32_t)(WSLOT_) * 8u, (UNI & 8) ? spar_ : ((it / SC_SLOTS) & 1)); \ + float s; \ + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(s) : "r"(sc_u + slot * 1024u + (uint32_t)threadIdx.x * 4u) : "memory"); \ + __syncwarp(); \ + if (lane == 0) mbar_arrive_u32(bar_u + SEMPTY_OFF + slot * 8u); \ + mbar_wait_hybrid_u32(bar_u + TFULL_OFF + (uint32_t)(B_) * 8u, (UNI & 8) ? tpar_ : ((it >> 1) & 1)); /* HYBRID tfull wait: one un-hinted try_wait (fast wake for short waits), then suspend-hinted (parks long waits: less spin energy under the power cap) */ \ + fence_after(); \ + const uint32_t taddr = taddr_b0 + (uint32_t)(B_ * BLOCK_N); \ + const float2 ss = make_float2(s, s); \ +if (PROF_SKIPP) { fence_before(); __syncwarp(); if (lane == 0) mbar_arrive_relaxed_u32(bar_u + TEMPTY_OFF + (uint32_t)(B_) * 8u); } else \ +if constexpr (LDN == 16) { \ +_Pragma("unroll") \ + for (int p = 0; p < 2; ++p) { \ + uint32_t r0[16], r1[16], r2[16], r3[16]; \ + const uint32_t ta = taddr + p * 64; \ + TMEM_LD16(ta + 0, r0); \ + TMEM_LD16(ta + 16, r1); \ + TMEM_LD16(ta + 32, r2); \ + TMEM_LD16(ta + 48, r3); \ + tmem_ld_wait(); \ + if (p == 1) { \ + fence_before(); \ + __syncwarp(); \ + if (lane == 0) mbar_arrive_relaxed_u32(bar_u + TEMPTY_OFF + (uint32_t)(B_) * 8u); \ + } \ + float* a = acc + p * 64; \ +_Pragma("unroll") \ + for (int j = 0; j < 16; j += 2) { \ + float2 d; \ + d = __ffma2_rn(make_float2(__uint_as_float(r0[j]), __uint_as_float(r0[j + 1])), ss, make_float2(a[j], a[j + 1])); \ + a[j] = d.x; a[j + 1] = d.y; \ + d = __ffma2_rn(make_float2(__uint_as_float(r1[j]), __uint_as_float(r1[j + 1])), ss, \ + make_float2(a[16 + j], a[16 + j + 1])); \ + a[16 + j] = d.x; a[16 + j + 1] = d.y; \ + d = __ffma2_rn(make_float2(__uint_as_float(r2[j]), __uint_as_float(r2[j + 1])), ss, \ + make_float2(a[32 + j], a[32 + j + 1])); \ + a[32 + j] = d.x; a[32 + j + 1] = d.y; \ + d = __ffma2_rn(make_float2(__uint_as_float(r3[j]), __uint_as_float(r3[j + 1])), ss, \ + make_float2(a[48 + j], a[48 + j + 1])); \ + a[48 + j] = d.x; a[48 + j + 1] = d.y; \ + } \ + } \ + } else if constexpr (LDN == 32) { \ + /* PIPELINED DRAIN: wait placement moved so the loads of cols 64..95 / 96..127 are in flight while the \ + FFMA2s of cols 0..31 / 32..63 run (staging stays 64 regs); one more wait::ld, then the TMEM buffer \ + is released before the last 32 FFMA2s. */ \ + uint32_t ra[32], rb[32]; \ + tmem_ld32(taddr + 0, ra); \ + tmem_ld32(taddr + 32, rb); \ + tmem_ld_wait(); \ + PROMO_FMA32(acc + 0, ra); \ + uint32_t rc[32]; \ + tmem_ld32(taddr + 64, rc); \ + PROMO_FMA32(acc + 32, rb); \ + uint32_t rd[32]; \ + tmem_ld32(taddr + 96, rd); \ + tmem_ld_wait(); \ + fence_before(); \ + __syncwarp(); \ + if (lane == 0) mbar_arrive_relaxed_u32(bar_u + TEMPTY_OFF + (uint32_t)(B_) * 8u); \ + PROMO_FMA32(acc + 64, rc); \ + PROMO_FMA32(acc + 96, rd); \ + } else if constexpr (LDN == 33) { \ + /* EARLY-RELEASE DRAIN (80 staging regs): cols 0..79 in flight first; after the 1st wait::ld the FFMA2s \ + of cols 0..31 free ra -> cols 80..111 loaded into it; after cols 32..47 rb[0..16) -> cols 112..127. \ + The last TMEM load is issued after 48 promoted cols (was 64), so the 2nd wait::ld and the tempty \ + release come earlier; the remaining 80 cols are promoted after the release. */ \ + /* WIDE-LOAD DRAIN (this version): cols 0..63 as ONE tcgen05.ld 32x32b.x64 + cols 64..79 x16, one wait; \ + after cols 0..47 are promoted, ra[0..48) receives cols 80..111 (x32) and 112..127 (x16). 4 TMEM loads \ + per k-block instead of 5, same 80 staging regs, same per-element FFMA2 order (bit-identical). */ \ + uint32_t ra[64], rc[16]; \ + /* WAIT HOIST: wait only on the x64 load; the x16 load of cols 64..79 is in flight \ + during the FFMA2s of cols 0..47 (covered by the 2nd wait). */ \ + tmem_ld64(taddr + 0, ra); \ + tmem_ld_wait(); \ + TMEM_LD16(taddr + 64, rc); \ + PROMO_FMA32(acc + 0, ra); \ + PROMO_FMA16(acc + 32, (ra + 32)); \ + tmem_ld32(taddr + 80, ra); \ + TMEM_LD16(taddr + 112, (ra + 32)); \ + PROMO_FMA16(acc + 48, (ra + 48)); \ + tmem_ld_wait(); \ + fence_before(); \ + __syncwarp(); \ + if (lane == 0) mbar_arrive_relaxed_u32(bar_u + TEMPTY_OFF + (uint32_t)(B_) * 8u); \ + PROMO_FMA16(acc + 64, rc); \ + PROMO_FMA32(acc + 80, ra); \ + PROMO_FMA16(acc + 112, (ra + 32)); \ + } else { \ +_Pragma("unroll") \ + for (int p = 0; p < 2; ++p) { \ + uint32_t r[64]; \ + const uint32_t ta = taddr + p * 64; \ +_Pragma("unroll") \ + for (int q = 0; q < 64 / LDN; ++q) { \ + if constexpr (LDN == 8) tmem_ld8(ta + q * 8, r + q * 8); \ + else tmem_ld32(ta + q * 32, r + q * 32); \ + } \ + tmem_ld_wait(); \ + if (p == 1) { \ + fence_before(); \ + __syncwarp(); \ + if (lane == 0) mbar_arrive_relaxed_u32(bar_u + TEMPTY_OFF + (uint32_t)(B_) * 8u); \ + } \ + float* a = acc + p * 64; \ +_Pragma("unroll") \ + for (int j = 0; j < 64; j += 2) { \ + const float2 d = __ffma2_rn(make_float2(__uint_as_float(r[j]), __uint_as_float(r[j + 1])), ss, \ + make_float2(a[j], a[j + 1])); \ + a[j] = d.x; a[j + 1] = d.y; \ + } \ + } \ + } \ +} while (0) + +template +__global__ void __launch_bounds__(NUM_THREADS, 1) + fp8_bs_gemm_large2_kernel(const __grid_constant__ CUtensorMap tmap_a, const __grid_constant__ CUtensorMap tmap_b, + const __grid_constant__ CUtensorMap tmap_out, const __grid_constant__ CUtensorMap tmap_out16, + const float* __restrict__ scale_x, + const float* __restrict__ scale_w, float* __restrict__ ws, int* __restrict__ cnt, int M, int N, int K, int group_n, + int direct, int tail, int split, + int* __restrict__ claim_ctr, unsigned long long* __restrict__ dbg, int spf_rot) { + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(smem_raw) + 1023) & ~uintptr_t(1023)); + uint8_t* out_stage = smem + STAGES * STAGE_BYTES; // 32 KB, 1024-aligned + float* sc_ring = reinterpret_cast(out_stage + OUT_STAGE_BYTES); // 8 KB scale ring + uint64_t* full_bar = reinterpret_cast(out_stage + OUT_STAGE_BYTES + SC_BYTES); + uint64_t* empty_bar = full_bar + STAGES; + uint64_t* tfull_bar = empty_bar + STAGES; // [2] + uint64_t* tempty_bar = tfull_bar + 2; // [2] + uint64_t* sfull_bar = tempty_bar + 2; // [SC_SLOTS] + uint64_t* sempty_bar = sfull_bar + SC_SLOTS; // [SC_SLOTS] + uint64_t* claim_bar = sempty_bar + SC_SLOTS; // tail-piece claim broadcast (DYN), smem offset CLAIM_BAR_OFF + uint32_t* tmem_slot = reinterpret_cast(claim_bar + 1); + uint64_t* mfull_bar = reinterpret_cast(smem + MBOX_BAR_OFF); // [MB_SLOTS] unit written (DYN) + uint64_t* mempty_bar = mfull_bar + MB_SLOTS; // [MB_SLOTS] unit consumed + int4* mbox = reinterpret_cast(smem + MBOX_OFF); + + // UNI: warp index / TMEM base broadcast with __shfl_sync so the compiler treats them as warp-uniform + const int warp = (UNI & 1) ? __shfl_sync(0xffffffffu, (int)(threadIdx.x / 32), 0) : (int)(threadIdx.x / 32); + const int lane = threadIdx.x % 32; + const int num_kb = K / BLOCK_K; + const int num_nblk = N / BLOCK_N; // 256-wide output column blocks + const int num_sblk = N / 128; // scale_w column blocks (128 wide) + const int num_mblk = (M + BLOCK_M - 1) / BLOCK_M; + const int num_units = direct + tail * split; + // WBOX1: group_n bit 19 = W tensor map encoded with a single 256-row box (one W TMA per stage) + const bool wbox1 = (group_n >> 19) & 1; + // MODE bits (A/B probing; production = 0 static or 31 end-claimed): 1/2/4 TMA/MMA/scale walk through the + // claim slot, 8 promotion units via the mailbox, 16 real atomic claim (else the claim returns the static unit). + // MODE 64 = SPF (split pieces first): each CTA's K-split tail piece runs BEFORE its whole tiles (all pieces start + // together at kernel begin) instead of last; the piece fixup code is unchanged (contributors red.add + publish, + // owner kb0 == 0 waits for them -- they run concurrently and never wait -- adds the ws partial, re-zeroes, stores + // bf16). Removes the end-of-kernel contributor -> owner chain; piece boundaries are kept even (unit_coords_t). + constexpr bool SPF = (MODE & 64) != 0; + constexpr bool EISS = (MODE & 128) != 0; // whole-warp issuer loop, elect.sync-predicated MMA / commit + constexpr bool ISPIN = (MODE & 256) != 0; // issuer waits without suspend hint + constexpr bool ASM4 = (MODE & 512) != 0; // ISSUER STUDY: 4 MMAs + 2 commits in ONE elected asm block + constexpr bool ORD = (MODE & 1024) != 0; // ISSUER STUDY: tempty wait before full wait, tfull commit first + constexpr bool DUAL = (MODE & 2048) != 0; + constexpr bool FAST = (MODE & 4096) != 0; + constexpr bool DYN = (MODE & 63) != 0; + constexpr bool REAL = (MODE & 16) != 0; + constexpr bool MBOX = false; + // DYN: one tail slot per CTA after its whole tiles (redirected to the claimed piece) + const int num_units_loop = DYN ? (tail > 0 ? direct + (int)gridDim.x : direct) : num_units; + const int nul_tma = (MODE & 1) ? num_units_loop : num_units; + const int nul_mma = (MODE & 2) ? num_units_loop : num_units; + const int nul_sc = (MODE & 4) ? num_units_loop : num_units; + + if (threadIdx.x == 0) { + for (int i = 0; i < STAGES; ++i) { + mbar_init(&full_bar[i], 1); + mbar_init(&empty_bar[i], 1); + } + for (int i = 0; i < 2; ++i) { + mbar_init(&tfull_bar[i], 1); + mbar_init(&tempty_bar[i], NUM_EPI_WARPS); // one elected arrive per promotion warp + } + for (int i = 0; i < SC_SLOTS; ++i) { + mbar_init(&sfull_bar[i], 64); // 64 scale-producer threads + mbar_init(&sempty_bar[i], NUM_EPI_WARPS); // one arrive per promotion warp + } + mbar_init(claim_bar, 1); + for (int i = 0; i < MB_SLOTS; ++i) { + mbar_init(mfull_bar + i, 1); + mbar_init(mempty_bar + i, NUM_EPI_WARPS); + } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_a)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_b)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_out)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_out16)) : "memory"); + } + // HEAD L2 PREFETCH of this CTA's FIRST unit (first 2 k-blocks): W (read-only weight, never written by a preceding + // grid) by thread 0 BEFORE griddepcontrol.wait; A by the idle warp 0 lane 2 right AFTER the wait (A may be produced + // by the previous grid). Pure L2 hints (no smem / barrier / visible state). Static walk only (not the DYN claim). + int pf_m0 = -1, pf_n0 = 0, pf_kb0 = 0, pf_kb1 = 0; + if (!DYN && (threadIdx.x == 0 || threadIdx.x == 2)) { + const int u0 = SPF ? spf_first(blockIdx.x, direct, tail * split, spf_rot) : (int)blockIdx.x; + if (u0 >= 0 && u0 < num_units) { + int t, kb0, kb1, wsi, mbk, nbk; + unit_coords_t(u0, direct, tail, split, num_kb, t, kb0, kb1, wsi); + tile_coords(t, num_mblk, num_nblk, group_n, mbk, nbk); + pf_m0 = mbk * BLOCK_M; + pf_n0 = nbk * BLOCK_N; + pf_kb0 = kb0; + pf_kb1 = (kb1 < kb0 + 2) ? kb1 : kb0 + 2; + } + } + if (threadIdx.x == 0 && pf_m0 >= 0) { + const uint64_t pol_pf = policy_evict_last(); // same policy as the W TMA loads + for (int kb = pf_kb0; kb < pf_kb1; ++kb) { + l2_prefetch_tile_hint(&tmap_b, kb * BLOCK_K, pf_n0, pol_pf); + if (!wbox1) l2_prefetch_tile_hint(&tmap_b, kb * BLOCK_K, pf_n0 + BLOCK_N / 2, pol_pf); + } + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(smem_u32(tmem_slot)), + "r"(TMEM_COLS)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + fence_before(); + __syncthreads(); + // PDL: barrier init / TMEM alloc / tensormap prefetch above overlap the previous grid's tail; no global + // memory (inputs, workspace, counters, output) is touched before the previous grid completed and flushed. + asm volatile("griddepcontrol.wait;" ::: "memory"); + // EARLY PDL TRIGGER (cross-call / split-half overlap): every CTA of this persistent grid is resident (grid <= #SMs, + // 1 CTA/SM), so the dependent grid's CTAs can take SMs as soon as ours exit and run their prologue + pre-wait W L2 + // prefetch while our tail still runs. The dependent still griddepcontrol.wait's for our full completion before + // touching ws / counters / A / output, so this is memory-safe (the end-of-kernel trigger below is now a no-op). + asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); + if (threadIdx.x == 2 && pf_m0 >= 0) { + const uint64_t pol_pf = policy_evict_first(); // same policy as the A TMA loads + for (int kb = pf_kb0; kb < pf_kb1; ++kb) l2_prefetch_tile_hint(&tmap_a, kb * BLOCK_K, pf_m0, pol_pf); + } +#ifdef LARGE2_PROF + __shared__ unsigned long long pst[64]; + __shared__ long long piss[STAGES]; + __shared__ unsigned int phist[48]; + if (threadIdx.x < 64) pst[threadIdx.x] = 0; + if (threadIdx.x < 48) phist[threadIdx.x] = 0; + __syncthreads(); + const long long pt_start = clock64(); + unsigned long long pg_start; + asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(pg_start)); + const int l2mode = d_l2mode; +#endif + if (dbg && threadIdx.x == 0) { + unsigned long long t0; + asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t0)); + dbg[blockIdx.x * 2] = t0; + } + fence_after(); + const uint32_t tmem_base = (UNI & 2) ? __shfl_sync(0xffffffffu, *tmem_slot, 0) : *tmem_slot; + + if (warp < EPI_WARP0) { + // WG0: control warpgroup gives registers away (all 128 threads execute this). + asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;" ::"n"(REGS_CTRL)); + if (warp == 0 && !(DUAL && lane == 1)) { + // ------------------------------------------------ TMA producer + if (lane == 0) { + const uint64_t pol_a = policy_evict_first(); + const uint64_t pol_w = policy_evict_last(); +#ifdef LARGE2_PROF + long long p_eb = 0, p_ebc = 0, p_is = 0; +#endif + uint32_t it = 0; // global K-block counter across units + for (int u = SPF ? spf_first(blockIdx.x, direct, tail * split, spf_rot) : (int)blockIdx.x; SPF ? (u >= 0) : (u < nul_tma); + u = SPF ? spf_next(u, blockIdx.x, direct, gridDim.x) : u + (int)gridDim.x) { + int t, kb0, kb1, wsi, mbk, nbk; + if (((MODE >> 0) & 1) && u >= direct) { + u = claim_tail_unit(direct, tail, split, claim_ctr, u); + if (u < 0) break; + } + unit_coords_t(u, direct, tail, split, num_kb, t, kb0, kb1, wsi); + tile_coords(t, num_mblk, num_nblk, group_n, mbk, nbk); + const int m0 = mbk * BLOCK_M; + const int n0 = nbk * BLOCK_N; + for (int kb = kb0; kb < kb1; ++kb, ++it) { + const int s = it % STAGES; + const uint32_t ph = (it / STAGES) & 1; +#ifdef LARGE2_PROF + if (!LEAN && !mbar_test(&empty_bar[s], ph ^ 1)) { + const long long w0 = clock64(); + mbar_wait_sleep(&empty_bar[s], ph ^ 1); + ++p_eb; p_ebc += clock64() - w0; + } + piss[s] = clock64(); +#endif + mbar_wait_sleep(&empty_bar[s], ph ^ 1); + uint8_t* sa = smem + s * STAGE_BYTES; + uint8_t* sb = sa + TILE_A_BYTES; + if (PROF_SKIPT) { mbar_arrive(&full_bar[s]); } else { + mbar_arrive_expect_tx(&full_bar[s], STAGE_BYTES); + tma_load_2d_hint(sa, &tmap_a, &full_bar[s], kb * BLOCK_K, m0, pol_a); + // W slab as TWO 128-row boxes (16 KB each, contiguous -> same 128B-swizzled layout as one 256-row + // box) on the SAME full barrier (single expect_tx of STAGE_BYTES above) + tma_load_2d_hint(sb, &tmap_b, &full_bar[s], kb * BLOCK_K, n0, pol_w); + // WBOX1 (group_n bit 19, M>=12288 halves): tmap_b box is 256 rows -> the whole W slab in ONE TMA + if (!wbox1) tma_load_2d_hint(sb + TILE_B_BYTES / 2, &tmap_b, &full_bar[s], kb * BLOCK_K, n0 + BLOCK_N / 2, pol_w); + } +#ifdef LARGE2_PROF + p_is += clock64() - piss[s]; +#endif + } + } +#ifdef LARGE2_PROF + pst[0] = p_eb; pst[1] = p_ebc; pst[60] = p_is; +#endif + } + } else if (warp == 1 || (DUAL && warp == 0 && lane == 1)) { + // ------------------------------------------------ MMA issuer (single thread, or whole warp with EISS) + // DUAL: warp 1 issues the even k-blocks (TMEM buffer 0), warp 0 lane 1 the odd ones (buffer 1). + auto issuer = [&](auto elect_tag, const int sel) __attribute__((always_inline)) { + constexpr bool ELECT = decltype(elect_tag)::value; + // instr descriptor: D=f32, A=B=e4m3, K-major both, N>>3 @17, M>>4 @24 + const uint32_t idesc = (1u << 4) | ((uint32_t)(BLOCK_N >> 3) << 17) | ((uint32_t)(BLOCK_M >> 4) << 24); +#ifdef LARGE2_PROF + long long r_fb = 0, r_fbc = 0, r_tb = 0, r_tbc = 0, r_w = 0, r_m = 0, r_g = 0, r_last = 0, r_kb = 0; +#endif + uint32_t it = 0; + // LEAN EISS issuer (SASS audit trim): 32-bit barrier addresses + A descriptor base hoisted out of the + // k-loop, running stage / phase counters (no per-kb generic->shared conversions or descriptor rebuild). + // Same suspend-hinted waits, same elect.sync-predicated MMA / commit sequence as EISS. + constexpr bool LEANI = ELECT && !ASM4 && !ORD && !ISPIN && !DUAL && !FAST; + const uint32_t lfull0 = smem_u32(full_bar), lempty0 = smem_u32(empty_bar); + const uint32_t ltfull0 = smem_u32(tfull_bar), ltempty0 = smem_u32(tempty_bar); + const uint64_t ladesc0 = make_sdesc(smem_u32(smem)); + uint32_t ls = 0, lph = 0; + for (int u = SPF ? spf_first(blockIdx.x, direct, tail * split, spf_rot) : (int)blockIdx.x; SPF ? (u >= 0) : (u < nul_mma); + u = SPF ? spf_next(u, blockIdx.x, direct, gridDim.x) : u + (int)gridDim.x) { + int t, kb0, kb1, wsi; + if (((MODE >> 1) & 1) && u >= direct) { + u = claim_tail_unit(direct, tail, split, claim_ctr, u); + if (u < 0) break; + } + unit_coords_t(u, direct, tail, split, num_kb, t, kb0, kb1, wsi); + for (int kb = kb0; kb < kb1; ++kb, ++it) { +#ifndef LARGE2_PROF + if constexpr (LEANI) { + constexpr uint64_t BOFF = TILE_A_BYTES >> 4, SOFF = STAGE_BYTES >> 4; + const uint32_t b = it & 1; + const uint64_t ad = ladesc0 + (uint64_t)ls * SOFF, bd = ad + BOFF; + mbar_wait_sleep_u32(lfull0 + ls * 8, lph); // operands landed + mbar_wait_sleep_u32(ltempty0 + b * 8, ((it >> 1) & 1) ^ 1); // TMEM buffer drained + fence_after(); + const uint32_t tmem_d = tmem_base + b * BLOCK_N; +#pragma unroll + for (int k = 0; k < BLOCK_K / 32; ++k) mma_f8_e(tmem_d, ad + 2 * k, bd + 2 * k, idesc, k > 0 ? 1u : 0u); + mma_commit_e_u32(lempty0 + ls * 8); + mma_commit_e_u32(ltfull0 + b * 8); + if (++ls == STAGES) { ls = 0; lph ^= 1; } + continue; + } +#endif + const int s = it % STAGES; + const uint32_t ph = (it / STAGES) & 1; + const int b = it & 1; + if (DUAL && b != sel) continue; // other issuer's k-block + // Operands (TMA, 4 stages ahead) are almost always ready long before the TMEM buffer is released, + // so wait for them and build the descriptors FIRST; the tempty wait (the critical MMA <-> promotion + // hand-off, clock64 trace M=8192: ~96 clk from tempty observed to first MMA with the old order) is + // then followed directly by the fence + MMA issue. +#ifdef LARGE2_PROF + const long long q0 = clock64(); + if (LEAN) { + mbar_wait_sleep(&full_bar[s], ph); + const long long qa = clock64(); + r_fbc += qa - q0; + mbar_wait_sleep(&tempty_bar[b], ((it >> 1) & 1) ^ 1); + r_tbc += clock64() - qa; + } else { + const bool rdy = mbar_test(&full_bar[s], ph); + if (!rdy) { mbar_wait_sleep(&full_bar[s], ph); ++r_fb; r_fbc += clock64() - q0; } + const long long lat = clock64() - piss[s]; + phist[(rdy ? 16 : 0) + lg2b(lat)] += 1; + const long long w0 = clock64(); + if (!mbar_test(&tempty_bar[b], ((it >> 1) & 1) ^ 1)) { + mbar_wait_sleep(&tempty_bar[b], ((it >> 1) & 1) ^ 1); + const long long d = clock64() - w0; + ++r_tb; r_tbc += d; phist[32 + lg2b(d)] += 1; + } + } +#endif + if (ORD) mbar_wait_sleep(&tempty_bar[b], ((it >> 1) & 1) ^ 1); + if (ISPIN) mbar_wait(&full_bar[s], ph); + else mbar_wait_sleep(&full_bar[s], ph); // operands landed + const uint32_t sa = smem_u32(smem + s * STAGE_BYTES); + const uint32_t sb = sa + TILE_A_BYTES; + const uint64_t adesc = make_sdesc(sa); + const uint64_t bdesc = make_sdesc(sb); + const uint32_t tmem_d = tmem_base + b * BLOCK_N; + if (ORD) {} + else if (ISPIN) mbar_wait(&tempty_bar[b], ((it >> 1) & 1) ^ 1); + else mbar_wait_sleep(&tempty_bar[b], ((it >> 1) & 1) ^ 1); // epilogue drained this TMEM buffer +#ifdef LARGE2_PROF + const long long q1 = clock64(); + r_w += q1 - q0; +#endif + fence_after(); + if (ASM4 && !PROF_SKIPM) { + mma4_commit2(tmem_d, adesc, bdesc, idesc, &empty_bar[s], &tfull_bar[b]); + } else { +#pragma unroll + for (int k = 0; k < BLOCK_K / 32; ++k) { + // advance 32 fp8 = 32 bytes inside the 128B swizzle atom: +2 in addr>>4 units + if (!PROF_SKIPM) { + if (ELECT) mma_f8_e(tmem_d, adesc + 2 * k, bdesc + 2 * k, idesc, k > 0 ? 1u : 0u); + else mma_f8(tmem_d, adesc + 2 * k, bdesc + 2 * k, idesc, k > 0 ? 1u : 0u); + } + } + if (ELECT) { + mma_commit_e(&empty_bar[s]); + mma_commit_e(&tfull_bar[b]); + } else { + mma_commit(&empty_bar[s]); // smem stage free once MMAs complete + mma_commit(&tfull_bar[b]); // partial accumulator ready + } + } // !ASM4 +#ifdef LARGE2_PROF + { + const long long q2 = clock64(); + r_m += q2 - q1; + if (r_last) r_g += q0 - r_last; + r_last = q2; + ++r_kb; + } +#endif + } + } +#ifdef LARGE2_PROF + if (warp == 1) { pst[2] = r_fb; pst[3] = r_fbc; pst[4] = r_tb; pst[5] = r_tbc; pst[6] = r_kb; pst[56] = r_w; pst[57] = r_m; pst[58] = r_g; } +#endif + }; + if constexpr (FAST) { + if (warp == 1) { + const uint32_t idesc = (1u << 4) | ((uint32_t)(BLOCK_N >> 3) << 17) | ((uint32_t)(BLOCK_M >> 4) << 24); + const uint32_t full0 = smem_u32(full_bar), empty0 = smem_u32(empty_bar); + const uint32_t tfull0 = smem_u32(tfull_bar), tempty0 = smem_u32(tempty_bar); + const uint64_t adesc0 = make_sdesc(smem_u32(smem)); // stage s: + s * (STAGE_BYTES >> 4) + constexpr uint64_t BOFF = TILE_A_BYTES >> 4, SOFF = STAGE_BYTES >> 4; + uint32_t it = 0, s = 0, ph = 0; + for (int u = SPF ? spf_first(blockIdx.x, direct, tail * split, spf_rot) : (int)blockIdx.x; SPF ? (u >= 0) : (u < nul_mma); + u = SPF ? spf_next(u, blockIdx.x, direct, gridDim.x) : u + (int)gridDim.x) { + int t, kb0, kb1, wsi; + if (((MODE >> 1) & 1) && u >= direct) { + u = claim_tail_unit(direct, tail, split, claim_ctr, u); + if (u < 0) break; + } + unit_coords_t(u, direct, tail, split, num_kb, t, kb0, kb1, wsi); + for (int kb = kb0; kb < kb1; ++kb, ++it) { + const uint32_t b = it & 1; + const uint64_t ad = adesc0 + (uint64_t)s * SOFF; + mbar_wait_spin_u32(full0 + s * 8, ph); // operands landed + mbar_wait_sleep_u32(tempty0 + b * 8, ((it >> 1) & 1) ^ 1); // TMEM buffer drained + fence_after(); + mma4_commit2_e(tmem_base + b * BLOCK_N, ad, ad + BOFF, idesc, empty0 + s * 8, tfull0 + b * 8); + if (++s == STAGES) { s = 0; ph ^= 1; } + } + } + } + } else if (warp == 1) { + if (EISS || lane == 0) issuer(std::integral_constant{}, 0); + } else { + issuer(std::false_type{}, 1); + } + } + else { + // ------------------------------------------------ scale producer (warps 2,3; 64 threads) + // thread lt owns rows lt and lt+64 of the tile, both 128-col scale halves. + const int lt = threadIdx.x - 64; + uint32_t it = 0; + uint32_t ui = 0; // unit counter (DYN mailbox ring position) + for (int u = SPF ? spf_first(blockIdx.x, direct, tail * split, spf_rot) : (int)blockIdx.x; SPF ? (u >= 0) : (u < nul_sc); + u = SPF ? spf_next(u, blockIdx.x, direct, gridDim.x) : u + (int)gridDim.x) { + int t, kb0, kb1, wsi, mbk, nbk; + if (((MODE >> 2) & 1) && u >= direct) { + u = claim_tail_unit(direct, tail, split, claim_ctr, u); + if (u < 0) break; + } + unit_coords_t(u, direct, tail, split, num_kb, t, kb0, kb1, wsi); + tile_coords(t, num_mblk, num_nblk, group_n, mbk, nbk); + if (MBOX && lt == 0) { // publish the decoded unit to the promotion warps (unit mailbox) + const int ms = ui % MB_SLOTS; + mbar_wait_sleep(&mempty_bar[ms], ((ui / MB_SLOTS) & 1) ^ 1); + mbox[ms] = make_int4(mbk, nbk, kb0 | (kb1 << 16), wsi); + mbar_arrive(&mfull_bar[ms]); // release.cta: mailbox st.shared visible to the waiters + } + ++ui; + const int ra = mbk * BLOCK_M + lt, rb = ra + 64; + // NEXT-UNIT SCALE-STRIP L2 PREFETCH (group_n bit 22, M>=12288 split halves only): while this unit's scales + // are produced, prefetch the NEXT unit's sx rows (lt, lt+64: 4 x 128 B lines each over 128 k-blocks) and its + // sw column pair (one 128 B line per k-block row, 2 per thread) into L2, so the next unit's first scale batches + // do not wait for DRAM after the M-block switch. Pure hint (prefetch.global.L2): no visible state, bit-identical. + if (!DYN && ((group_n >> 22) & 1)) { + const int un = SPF ? spf_next(u, blockIdx.x, direct, gridDim.x) : u + (int)gridDim.x; + if (un >= 0 && un < num_units) { + int tn, k0n, k1n, wn, mbn, nbn; + unit_coords_t(un, direct, tail, split, num_kb, tn, k0n, k1n, wn); + tile_coords(tn, num_mblk, num_nblk, group_n, mbn, nbn); + const int rna = mbn * BLOCK_M + lt, rnb = rna + 64; + for (int kb = k0n; kb < k1n; kb += 32) { + if (rna < M) asm volatile("prefetch.global.L2 [%0];" ::"l"(scale_x + (size_t)rna * num_kb + kb)); + if (rnb < M) asm volatile("prefetch.global.L2 [%0];" ::"l"(scale_x + (size_t)rnb * num_kb + kb)); + } + for (int kb = k0n + lt; kb < k1n; kb += 64) + asm volatile("prefetch.global.L2 [%0];" ::"l"(scale_w + (size_t)kb * num_sblk + 2 * nbn)); + } + } + const float* pa = scale_x + (size_t)(ra < M ? ra : 0) * num_kb; // rows >= M: value unused + const float* pb = scale_x + (size_t)(rb < M ? rb : 0) * num_kb; + for (int kb = kb0; kb < kb1; kb += 4) { + const int nq = (kb1 - kb) < 4 ? (kb1 - kb) : 4; + float xa[4], xb[4]; + float2 w[4]; + if (nq == 4 && ((kb | num_kb) & 3) == 0) { + // POWER: one 16 B load per row per 4 k-blocks (row base 16B-aligned since num_kb % 4 == 0) + const float4 va = __ldg(reinterpret_cast(pa + kb)); + const float4 vb = __ldg(reinterpret_cast(pb + kb)); + xa[0] = va.x; xa[1] = va.y; xa[2] = va.z; xa[3] = va.w; + xb[0] = vb.x; xb[1] = vb.y; xb[2] = vb.z; xb[3] = vb.w; +#pragma unroll + for (int q = 0; q < 4; ++q) + w[q] = __ldg(reinterpret_cast(scale_w + (size_t)(kb + q) * num_sblk) + nbk); + } else { +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + xa[q] = __ldg(pa + kb + q); + xb[q] = __ldg(pb + kb + q); + w[q] = __ldg(reinterpret_cast(scale_w + (size_t)(kb + q) * num_sblk) + nbk); + } + } + } +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + const uint32_t ii = it + q; + const int slot = ii % SC_SLOTS; + mbar_wait_sleep(&sempty_bar[slot], ((ii / SC_SLOTS) & 1) ^ 1); + float* d = sc_ring + slot * 256; + d[lt] = xa[q] * w[q].x; + d[lt + 64] = xb[q] * w[q].x; + d[128 + lt] = xa[q] * w[q].y; + d[128 + lt + 64] = xb[q] * w[q].y; + mbar_arrive(&sfull_bar[slot]); + } + } + it += nq; + } + } + if (MBOX && lt == 0) { // end-of-work marker + const int ms = ui % MB_SLOTS; + mbar_wait_sleep(&mempty_bar[ms], ((ui / MB_SLOTS) & 1) ^ 1); + mbox[ms] = make_int4(0, 0, 0, -2); + mbar_arrive(&mfull_bar[ms]); + } + } + } else { + // ------------------------------------------------ epilogue (warps 4..11, 2 warpgroups) + asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;" ::"n"(REGS_EPI)); + const int g = (warp - EPI_WARP0) >> 2; // warpgroup -> 64-col quarter of the tile + const int sub = warp & 3; // TMEM sub-partition this warp may access + const int row = sub * 32 + lane; // row within tile == TMEM lane + // this warp's 1 KB staging buffer: 32 rows x 16 bf16 cols (32 B, 32B-swizzled); reused for 4 quarters + uint8_t* wstage0 = out_stage + (g * 4 + sub) * WARP_STAGE_BYTES; // 3072-B (512-aligned) per-warp area + // output-store L2 evict_first policy, created once per warp (was one createpolicy per TMA store box) + // group_n bit 21 (OUTN, M=2048 class): bf16 output stores with an evict_normal L2 policy instead of evict_first + uint64_t pol_out; + if ((group_n >> 21) & 1) asm volatile("createpolicy.fractional.L2::evict_normal.b64 %0, 1.0;" : "=l"(pol_out)); + else pol_out = policy_evict_first(); + // store one 32-row x 128-col bf16 tile slab as 5 boxes A(32)|B(16)|A(32)|B(16)|A(32); pkf(v) = packed uint4 of + // 8-col chunk v. Slot A = wstage0 (64B swizzle: chunk j of row lane at j ^ ((lane>>1)&3)), slot B = +2048 + // (32B swizzle: chunk j at j ^ ((lane>>2)&1)). + auto store_tile = [&](auto&& pkf, const int xn, const int ym) __attribute__((always_inline)) { +#pragma unroll + for (int bx = 0; bx < 5; ++bx) { + const bool isA = (bx & 1) == 0; + const int c0 = (bx >> 1) * 48 + (isA ? 0 : 32); // first col of this box + if (lane == 0) { + if (bx == 0) asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); + else asm volatile("cp.async.bulk.wait_group.read 1;" ::: "memory"); + } + __syncwarp(); + uint8_t* wst = wstage0 + (isA ? 0 : 2048); + if (isA) { +#pragma unroll + for (int j = 0; j < 4; ++j) + *reinterpret_cast(wst + lane * 64 + ((j ^ ((lane >> 1) & 3)) << 4)) = pkf(c0 / 8 + j); + } else { +#pragma unroll + for (int j = 0; j < 2; ++j) + *reinterpret_cast(wst + lane * 32 + ((j ^ ((lane >> 2) & 1)) << 4)) = pkf(c0 / 8 + j); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // st.shared visible to the TMA engine + __syncwarp(); + if (lane == 0) { + tma_store_2d(isA ? &tmap_out : &tmap_out16, wst, xn + c0, ym, pol_out); + tma_store_commit(); + } + } + }; + // precomputed TMEM addresses of both accumulator buffers for this warp's lanes / cols + uint32_t taddr_b0 = tmem_base + ((uint32_t)(sub * 32) << 16) + g * EPI_COLS; + if (UNI & 4) taddr_b0 = __shfl_sync(0xffffffffu, taddr_b0, 0); + // my scale within a ring slot (warpgroup g = 128-col scale half g), as a 32-bit shared-window address + const uint32_t sc_mine = smem_u32(sc_ring + g * 128 + row); + // warp-uniform 32-bit base of the mbarrier region (full_bar[0]); see TFULL_OFF / SFULL_OFF + const uint32_t bar_u = __shfl_sync(0xffffffffu, smem_u32(full_bar), 0); + // my scale address = sc_u + slot*1024 + threadIdx.x*4 (g*128 + row == threadIdx.x - 128 -> the -512 B is folded + // into the warp-uniform sc_u), so re-materialising it costs S2R + shift instead of ~12 ops of generic-pointer math + const uint32_t sc_u = __shfl_sync(0xffffffffu, smem_u32(sc_ring), 0) - 512u; + uint32_t it = 0; + constexpr bool DEFER = (MODE & 8192) != 0; + uint32_t dpk[DEFER ? 64 : 1]; + int pend = 0, pend_m0 = 0, pend_n0 = 0; + auto flush_pending = [&]() __attribute__((always_inline)) { + if constexpr (DEFER) { + if (pend) { + store_tile([&](int v) __attribute__((always_inline)) { + return make_uint4(dpk[v * 4 + 0], dpk[v * 4 + 1], dpk[v * 4 + 2], dpk[v * 4 + 3]); + }, pend_n0, pend_m0 + sub * 32); + pend = 0; + } + } + }; + auto unit_body = [&](const int u, const uint32_t mslot) __attribute__((always_inline)) { + int kb0, kb1; + if constexpr (MBOX) { + int kbp; + asm volatile("ld.shared.b32 %0, [%1];" : "=r"(kbp) : "r"(mslot + 8u) : "memory"); + kb0 = kbp & 0xFFFF; + kb1 = kbp >> 16; + } else { + int t_, w_; + unit_coords_t(u, direct, tail, split, num_kb, t_, kb0, kb1, w_); + } + float acc[EPI_COLS]; + // DEFER early drain applies to an aligned (it even, even count >= 2) unit following a deferred epilogue + const bool early = DEFER && pend && !(it & 1) && (kb1 - kb0) >= 2 && !((kb1 - kb0) & 1); + if (DEFER && pend && !early) flush_pending(); + if (!early) { +#pragma unroll + for (int j = 0; j < EPI_COLS; ++j) acc[j] = 0.f; + } + + // BUFFER-SPECIALISED promotion step (PROMO_STEP macro): b (TMEM buffer / barrier index) is a compile-time constant, so the + // tcgen05.ld addresses are fixed offsets of one uniform base and &tfull/&tempty are constants (no per-kb + // runtime buffer select / address math between the tfull wait and the first LDTM). + // kb loop unrolled by 2 so buffer b = it & 1 is a compile-time constant in every step (direct units start at an + // even `it` and have an even k-block count; odd prologue / epilogue steps handle tail pieces). + { + int kb = kb0; + if (DEFER && early) { + // k-block kb0 (it even -> TMEM buffer 0): drain the 128 cols straight into registers, release the buffer, + // THEN issue the previous unit's deferred bf16 stores, then acc = partial * s (FMUL == 0 + partial*s). + const uint32_t slot = it % SC_SLOTS; + mbar_wait_sleep(&sfull_bar[slot], (it / SC_SLOTS) & 1); + float s; + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(s) : "r"(sc_mine + slot * 1024u) : "memory"); + __syncwarp(); + if (lane == 0) mbar_arrive(&sempty_bar[slot]); + mbar_wait_sleep(&tfull_bar[0], (it >> 1) & 1); + fence_after(); + uint32_t r0[32], r1[32], r2[32], r3[32]; + tmem_ld32(taddr_b0 + 0, r0); + tmem_ld32(taddr_b0 + 32, r1); + tmem_ld32(taddr_b0 + 64, r2); + tmem_ld32(taddr_b0 + 96, r3); + tmem_ld_wait(); + fence_before(); + __syncwarp(); + if (lane == 0) mbar_arrive(&tempty_bar[0]); + flush_pending(); + const float2 ss = make_float2(s, s); +#pragma unroll + for (int j = 0; j < 32; j += 2) { + float2 d; + d = __fmul2_rn(make_float2(__uint_as_float(r0[j]), __uint_as_float(r0[j + 1])), ss); acc[j] = d.x; acc[j + 1] = d.y; + d = __fmul2_rn(make_float2(__uint_as_float(r1[j]), __uint_as_float(r1[j + 1])), ss); acc[32 + j] = d.x; acc[33 + j] = d.y; + d = __fmul2_rn(make_float2(__uint_as_float(r2[j]), __uint_as_float(r2[j + 1])), ss); acc[64 + j] = d.x; acc[65 + j] = d.y; + d = __fmul2_rn(make_float2(__uint_as_float(r3[j]), __uint_as_float(r3[j + 1])), ss); acc[96 + j] = d.x; acc[97 + j] = d.y; + } + ++it; + ++kb; + { + const uint32_t tpar_ = (it >> 1) & 1, spar_ = (it / SC_SLOTS) & 1; + PROMO_STEP(1); // k-block kb0+1 (it odd -> buffer 1) + } + ++it; + ++kb; + } + if (!(it & 1) && !((kb1 - kb) & 1)) { + for (; kb < kb1; kb += 2, it += 2) { // aligned pairs (all direct whole tiles) + // it even: k-blocks it and it+1 share both mbarrier phases (same TMEM-buffer round it>>1 and, + // since SC_SLOTS is even, the same scale-ring round it/SC_SLOTS) -> computed once per pair + const uint32_t tpar_ = (it >> 1) & 1, spar_ = (it / SC_SLOTS) & 1; + const uint32_t sl0_ = it & (uint32_t)(SC_SLOTS - 2); // it even -> it % SC_SLOTS, bit 0 known zero + PROMO_STEPW(0, sl0_, sl0_ + 1u, 1); // one sfull wait (slot sl0_+1) covers both k-blocks + PROMO_STEPW(1, sl0_ + 1u, 0u, 0); + } + } else { + for (; kb < kb1; ++kb, ++it) { // generic (odd-aligned tail pieces): runtime buffer index + const int bb = it & 1; + const uint32_t tpar_ = (it >> 1) & 1, spar_ = (it / SC_SLOTS) & 1; + PROMO_STEP(bb); + } + } + } + int mbk, nb, wsi; + if constexpr (MBOX) { + int kbp; + asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4];" + : "=r"(mbk), "=r"(nb), "=r"(kbp), "=r"(wsi) + : "r"(mslot) + : "memory"); + kb0 = kbp & 0xFFFF; + kb1 = kbp >> 16; + } else { + int t; + unit_coords_t(u, direct, tail, split, num_kb, t, kb0, kb1, wsi); + tile_coords(t, num_mblk, num_nblk, group_n, mbk, nb); + } + const int m0 = mbk * BLOCK_M; + const int n0 = nb * BLOCK_N + g * EPI_COLS; + const int m = m0 + row; + if (wsi >= 0) { + // Tail piece (K-split tile wsi; each CTA has at most one, always its LAST unit). Fused stream-K + // fixup, no zero-fill / convert launches: + // * contributor (kb0 > 0): red.add fp32 partial into the persistent zeroed ws tile (thread-ownership + // float4 layout: chunk v of row r of warpgroup g at float4 index (g*16+v)*128 + r -> coalesced), + // bar.sync, then one thread publishes the k-block count (fence.acq_rel + red) in cnt[wsi]. + // * owner (kb0 == 0): spins until the contributors' counts reach num_kb - kb1, adds the ws partial + // into its registers, re-zeroes ws + counter (self-cleaning) and falls through to the bf16 TMA store. + // All CTAs are co-resident (grid <= #SMs, 1 CTA/SM), so the owner's wait always completes. + const int etid = threadIdx.x - EPI_WARP0 * 32; // 0..255 + float4* wrow = reinterpret_cast(ws + (size_t)wsi * WS_TILE_FLOATS) + (g * (EPI_COLS / 4)) * BLOCK_M + row; + if (kb0 > 0) { + if (m < M) { +#pragma unroll + for (int v = 0; v < EPI_COLS / 4; ++v) + red_add_v4(reinterpret_cast(wrow + v * BLOCK_M), acc[v * 4 + 0], acc[v * 4 + 1], acc[v * 4 + 2], + acc[v * 4 + 3]); + } + asm volatile("bar.sync 1, 256;" ::: "memory"); + if (etid == 0) { + asm volatile("fence.acq_rel.gpu;" ::: "memory"); + asm volatile("red.relaxed.gpu.global.add.s32 [%0], %1;" ::"l"(cnt + wsi), "r"(kb1 - kb0) : "memory"); + } + if constexpr (DEFER) { + // (pend == 0 here) kill dpk's liveness across the k-loop on this path: every path through a unit's + // k-loop now writes dpk before the next flush could read it, so dpk is never live during promotion. +#pragma unroll + for (int i = 0; i < 64; ++i) dpk[i] = 0u; + } + return; + } + if (etid == 0) { + const int need = num_kb - kb1; + int c; + while (true) { + asm volatile("ld.acquire.gpu.global.b32 %0, [%1];" : "=r"(c) : "l"(cnt + wsi) : "memory"); + if (c >= need) break; + __nanosleep(32); + } + cnt[wsi] = 0; // all contributions arrived: reset for the next call + } + asm volatile("bar.sync 1, 256;" ::: "memory"); + if (m < M) { +#pragma unroll + for (int v0 = 0; v0 < EPI_COLS / 4; v0 += 8) { // 4 batches of 8 ld.global.cg.v4 issued before the adds (more MLP) + float4 p[8]; +#pragma unroll + for (int v = 0; v < 8; ++v) p[v] = __ldcg(wrow + (v0 + v) * BLOCK_M); +#pragma unroll + for (int v = 0; v < 8; ++v) { + __stcg(wrow + (v0 + v) * BLOCK_M, make_float4(0.f, 0.f, 0.f, 0.f)); + acc[(v0 + v) * 4 + 0] += p[v].x; + acc[(v0 + v) * 4 + 1] += p[v].y; + acc[(v0 + v) * 4 + 2] += p[v].z; + acc[(v0 + v) * 4 + 3] += p[v].w; + } + } + } + } + if constexpr (DEFER) { + // pack to bf16 now (acc dies here); stores issued after the next unit's first TMEM drain +#pragma unroll + for (int v = 0; v < EPI_COLS / 8; ++v) { + __nv_bfloat162 h0 = __floats2bfloat162_rn(acc[v * 8 + 0], acc[v * 8 + 1]); + __nv_bfloat162 h1 = __floats2bfloat162_rn(acc[v * 8 + 2], acc[v * 8 + 3]); + __nv_bfloat162 h2 = __floats2bfloat162_rn(acc[v * 8 + 4], acc[v * 8 + 5]); + __nv_bfloat162 h3 = __floats2bfloat162_rn(acc[v * 8 + 6], acc[v * 8 + 7]); + dpk[v * 4 + 0] = *reinterpret_cast(&h0); + dpk[v * 4 + 1] = *reinterpret_cast(&h1); + dpk[v * 4 + 2] = *reinterpret_cast(&h2); + dpk[v * 4 + 3] = *reinterpret_cast(&h3); + } + pend = 1; + pend_m0 = m0; + pend_n0 = n0; + return; + } + store_tile([&](int v) __attribute__((always_inline)) { + __nv_bfloat162 h0 = __floats2bfloat162_rn(acc[v * 8 + 0], acc[v * 8 + 1]); + __nv_bfloat162 h1 = __floats2bfloat162_rn(acc[v * 8 + 2], acc[v * 8 + 3]); + __nv_bfloat162 h2 = __floats2bfloat162_rn(acc[v * 8 + 4], acc[v * 8 + 5]); + __nv_bfloat162 h3 = __floats2bfloat162_rn(acc[v * 8 + 6], acc[v * 8 + 7]); + uint4 pk; + pk.x = *reinterpret_cast(&h0); + pk.y = *reinterpret_cast(&h1); + pk.z = *reinterpret_cast(&h2); + pk.w = *reinterpret_cast(&h3); + return pk; + }, n0, m0 + sub * 32); + }; + // tail slot (MODE & 8): u := claimed unit (32-bit claim helpers, nothing else loop-carried); claimed + grid + // >= direct + grid ends the loop. + for (int u = SPF ? spf_first(blockIdx.x, direct, tail * split, spf_rot) : (int)blockIdx.x; + SPF ? (u >= 0) : (u < ((MODE & 8) ? num_units_loop : num_units)); + u = SPF ? spf_next(u, blockIdx.x, direct, gridDim.x) : u + (int)gridDim.x) { + if ((MODE & 8) && u >= direct) { + u = claim_tail_unit(direct, tail, split, claim_ctr, u); + if (u < 0) break; + } + unit_body(u, 0u); + } + flush_pending(); + // only the smem READ of in-flight output stores must finish before exit (CUTLASS tma_store_wait): + // the global writes complete asynchronously and are flushed at grid completion. + if (lane == 0) tma_store_wait_read(); + __syncwarp(); + } + + fence_before(); + __syncthreads(); +#ifdef LARGE2_PROF + if (threadIdx.x == 0) { + pst[7] = clock64() - pt_start; + unsigned long long g1; + asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(g1)); + pst[61] = g1 - pg_start; + } + __syncthreads(); + if (threadIdx.x < 48) pst[8 + threadIdx.x] = phist[threadIdx.x]; + __syncthreads(); + if (d_l2prof && threadIdx.x < 64) d_l2prof[blockIdx.x * 64 + threadIdx.x] = pst[threadIdx.x]; +#endif + if (dbg && threadIdx.x == 0) { + unsigned long long t1; + asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t1)); + dbg[blockIdx.x * 2 + 1] = t1; + } + // PDL: all of this CTA's work is issued/complete -> let the next grid start its prologue (it still + // griddepcontrol.wait's for this grid's full completion before touching global memory). + asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); + if (warp == 1) { + fence_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tmem_base), "r"(TMEM_COLS)); + } +} + +// split-K finish: compact fp32 workspace tiles -> bf16 output at each tile's (m0, n0). +// 8 elements (32 B in, 16 B out) per thread; ws tile ti <-> output tile (direct + ti). +__global__ void ws_to_bf16_kernel(const float4* __restrict__ ws, __nv_bfloat16* __restrict__ out, int M, int N, + int num_mblk, int num_nblk, int group_n, int direct, size_t n8) { + constexpr int PER_TILE8 = WS_TILE_FLOATS / 8; // 4096 8-element chunks per tile + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n8; i += (size_t)gridDim.x * blockDim.x) { + const int ti = (int)(i / PER_TILE8); + const int rem = (int)(i - (size_t)ti * PER_TILE8); + const int r = rem / (BLOCK_N / 8); + const int c = (rem - r * (BLOCK_N / 8)) * 8; + int mb, nb; + tile_coords(direct + ti, num_mblk, num_nblk, group_n, mb, nb); + const int m = mb * BLOCK_M + r; + if (m >= M) continue; + const float4 a = __ldcs(ws + 2 * i); + const float4 b = __ldcs(ws + 2 * i + 1); + __nv_bfloat162 h0 = __floats2bfloat162_rn(a.x, a.y); + __nv_bfloat162 h1 = __floats2bfloat162_rn(a.z, a.w); + __nv_bfloat162 h2 = __floats2bfloat162_rn(b.x, b.y); + __nv_bfloat162 h3 = __floats2bfloat162_rn(b.z, b.w); + uint4 pk; + pk.x = *reinterpret_cast(&h0); + pk.y = *reinterpret_cast(&h1); + pk.z = *reinterpret_cast(&h2); + pk.w = *reinterpret_cast(&h3); + *reinterpret_cast(out + (size_t)m * N + nb * BLOCK_N + c) = pk; + } +} + +// 2D K-major fp8 tensor map: dims {K, rows}, box {128, box_rows}, 128B swizzle. +// promo: L2 sector promotion of the TMA loads (256B default; 128B for the M=4096-class W map, plan group_n bit 18) +static void make_tmap(CUtensorMap* map, const void* ptr, uint64_t rows, uint64_t K, uint32_t box_rows, + CUtensorMapL2promotion promo = CU_TENSOR_MAP_L2_PROMOTION_L2_256B) { + cuuint64_t dims[2] = {K, rows}; + cuuint64_t strides[1] = {K}; + cuuint32_t box[2] = {BLOCK_K, box_rows}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(map, CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, const_cast(ptr), dims, strides, + box, estr, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, + promo, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) { + fprintf(stderr, "cuTensorMapEncodeTiled failed: %d\n", (int)r); + } +} +// bf16 output maps: dims {N, M}, box {cols, 32 rows}: 32 cols (64 B) -> 64B swizzle, 16 cols (32 B) -> 32B swizzle. +static void make_tmap_out(CUtensorMap* map, void* ptr, uint64_t M, uint64_t N, uint32_t cols = 16) { + cuuint64_t dims[2] = {N, M}; + cuuint64_t strides[1] = {N * 2}; + cuuint32_t box[2] = {cols, 32}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, ptr, dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, + cols == 32 ? CU_TENSOR_MAP_SWIZZLE_64B : CU_TENSOR_MAP_SWIZZLE_32B, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) { + fprintf(stderr, "cuTensorMapEncodeTiled(out) failed: %d\n", (int)r); + } +} + +// Choose the band width (in 256-col N-blocks) per M: simulate the first wave of +// `grid` concurrently-resident tiles and count the unique A + W tiles it touches. +static int choose_group_n(int num_mblk, int num_nblk, int grid) { + int best_g = num_nblk; + long best_cost = -1; + const int total = num_mblk * num_nblk; + const int wave = grid < total ? grid : total; + for (int g = num_nblk; g >= 1; --g) { + if (g != num_nblk && g < 2) continue; + static unsigned char seen_m[4096], seen_n[1024]; + if (num_mblk > 4096 || num_nblk > 1024) return num_nblk; + for (int i = 0; i < num_mblk; ++i) seen_m[i] = 0; + for (int i = 0; i < num_nblk; ++i) seen_n[i] = 0; + long um = 0, un = 0; + for (int t = 0; t < wave; ++t) { + int mb, nb; + tile_coords(t, num_mblk, num_nblk, g, mb, nb); + if (!seen_m[mb]) { seen_m[mb] = 1; ++um; } + if (!seen_n[nb]) { seen_n[nb] = 1; ++un; } + } + const long cost = um * TILE_A_BYTES + un * TILE_B_BYTES; + if (best_cost < 0 || cost < best_cost) { best_cost = cost; best_g = g; } + } + return best_g; +} + +static int get_num_sms() { + static int num_sms = 0; + if (num_sms == 0) { + int dev; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&num_sms, cudaDevAttrMultiProcessorCount, dev); + cudaFuncSetAttribute(fp8_bs_gemm_large2_kernel<33, 0>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaFuncSetAttribute(fp8_bs_gemm_large2_kernel<33, 31>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaFuncSetAttribute(fp8_bs_gemm_large2_kernel<33, 64>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaFuncSetAttribute(fp8_bs_gemm_large2_kernel<33, 128>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaFuncSetAttribute(fp8_bs_gemm_large2_kernel<33, 192>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaFuncSetAttribute(fp8_bs_gemm_large2_kernel<33, 384>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaFuncSetAttribute(fp8_bs_gemm_large2_kernel<33, 448>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + } + return num_sms; +} + +// Classic split-K chooser for small M: model the time of the busiest CTA = +// ceil(units / SMs) * K-blocks-per-unit, plus a fixed penalty (in K-block units) +// for the workspace zero + atomics + convert pass. Only for <= 2 waves of tiles. +static int choose_split_small(int num_tiles, int num_kb, int sms) { + if (num_tiles <= 0 || num_tiles > 2 * sms || num_kb < 2) return 1; + const double penalty = 6.0; + int best_s = 1; + double best = (double)((num_tiles + sms - 1) / sms) * num_kb; + for (int s = 2; s <= 8 && s <= num_kb; ++s) { + const long units = (long)num_tiles * s; + const double c = (double)((units + sms - 1) / sms) * (double)((num_kb + s - 1) / s) + penalty; + if (c < best) { best = c; best_s = s; } + } + return best_s; +} + +} // namespace + +// Work plan: small M -> classic split-K of every tile; otherwise full waves of whole tiles plus a +// K-split of only the last partial wave ("stream-K tail") so it occupies (nearly) all SMs. +Fp8PlanL2 fp8_large2_plan(int M, int N, int K) { + const int sms = get_num_sms(); + const int num_kb = K / BLOCK_K; + const int num_tiles = (N / BLOCK_N) * ((M + BLOCK_M - 1) / BLOCK_M); + Fp8PlanL2 p{num_tiles, 0, 1, 0}; + const int s_small = choose_split_small(num_tiles, num_kb, sms); + if (s_small > 1) { + p.direct = 0; + p.tail = num_tiles; + p.split = s_small; + } else if (num_tiles > sms && num_tiles % sms != 0) { + const int full = (num_tiles / sms) * sms; + const int tail = num_tiles - full; + int s = sms / tail; // tail*s <= sms: one tail piece per CTA at most + if (s > num_kb / 4) s = num_kb / 4; // keep >= 4 K-blocks per piece + if (s >= 2) { + p.direct = full; + p.tail = tail; + p.split = s; + } + } + if (p.tail > 0) p.ws_floats = (size_t)p.tail * WS_TILE_FLOATS; + { + const int nmb = (M + BLOCK_M - 1) / BLOCK_M; + p.group_n = nmb <= 16 ? 4 : (nmb >= 128 && (N / BLOCK_N) % 4 == 0 ? 4 : 8); + // M >= 16384 class: band 4 + SERPENTINE raster (bit 16): A re-read 7x from DRAM -> band-switch A reuse in L2. + if (nmb >= 128 && (N / BLOCK_N) % 4 == 0) p.group_n |= 1 << 16; + // M=4096 class (24 < M-blocks < 48): serpentine band-8 raster (bijective; A row-block reuse at band switches) + if (nmb > 24 && nmb < 48) p.group_n |= 1 << 16; + // M=2048 class (13..16 M-blocks, band 4): SERPENTINE band-4 raster (bijective; only band-2 serpentine was tried) + if (nmb > 12 && nmb <= 16) p.group_n |= 1 << 16; + if (nmb >= 48 && nmb < 96 && sms == 148) p.spf_rot = 40; + if (nmb > 12 && nmb <= 24) p.spf_rot = 32; + // M=4096 class (24 < M-blocks < 48, SPF14 pieces): piece holders rotated by 40 (any rot is a bijection). + if (nmb > 24 && nmb < 48 && sms == 148) p.spf_rot = 40; + // M=4096 class: W tensor-map L2 sector promotion 128B (bit 18; host-side only, pure hint, bit-identical) + if (nmb > 24 && nmb < 48) p.group_n |= 1 << 18; + } + return p; +} + +void launch_fp8_large2(const void* a, const void* w, const float* sx, const float* sw, void* out, float* ws, + const Fp8PlanL2& plan_in, int M, int N, int K, cudaStream_t stream) { + launch_fp8_large2_ex(a, w, sx, sw, out, ws, plan_in, M, N, K, stream, LARGE2_DYN_DEFAULT, nullptr); +} +void launch_fp8_large2_ex(const void* a, const void* w, const float* sx, const float* sw, void* out, float* ws, + const Fp8PlanL2& plan_in, int M, int N, int K, cudaStream_t stream, int dyn, + unsigned long long* dbg) { + CUtensorMap ta, tb, to; + make_tmap(&ta, a, (uint64_t)M, (uint64_t)K, BLOCK_M); + // 128-row W boxes (2 per stage), or ONE 256-row box per stage when group_n bit 19 (WBOX1) is set + // group_n bit 18 (host-only flag, masked off in tile_coords): W map L2 promotion 128B instead of 256B + make_tmap(&tb, w, (uint64_t)N, (uint64_t)K, ((plan_in.group_n >> 19) & 1) ? BLOCK_N : BLOCK_N / 2, + ((plan_in.group_n >> 20) & 1) ? CU_TENSOR_MAP_L2_PROMOTION_NONE + : (((plan_in.group_n >> 18) & 1) ? CU_TENSOR_MAP_L2_PROMOTION_L2_128B : CU_TENSOR_MAP_L2_PROMOTION_L2_256B)); + // group_n bit 20 (host-only flag): W map L2 promotion NONE (M=8192 class) + CUtensorMap to16; + make_tmap_out(&to, out, (uint64_t)M, (uint64_t)N, 32); + make_tmap_out(&to16, out, (uint64_t)M, (uint64_t)N, 16); + const int num_sms = get_num_sms(); + const int num_nblk = N / BLOCK_N; + const int num_mblk = (M + BLOCK_M - 1) / BLOCK_M; + const int num_tiles = num_nblk * num_mblk; + Fp8PlanL2 plan = plan_in; + // VALIDITY HARDENING: the tail owner piece spins on contributor pieces of OTHER CTAs, so the whole grid + // must be co-resident. Verify it with the occupancy API (as kernel_large/kernel_sk do); if it cannot be + // guaranteed (e.g. reduced SM availability), fall back to whole tiles only (no cross-CTA waits). + static int max_per_sm = 0; + if (max_per_sm == 0) { + if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&max_per_sm, fp8_bs_gemm_large2_kernel<33, 0>, NUM_THREADS, + SMEM_BYTES) != cudaSuccess || max_per_sm <= 0) + max_per_sm = 1; + } + if (plan.tail > 0) { + const int nu = plan.direct + plan.tail * plan.split; + const int g = nu < num_sms ? nu : num_sms; + if (g > max_per_sm * num_sms || plan.tail * plan.split > g) { + plan.direct = num_tiles; + plan.tail = 0; + plan.split = 1; + plan.ws_floats = 0; + } + } + // Persistent self-cleaning tail workspace + per-tail-tile counters (heap-held raw device memory, never + // freed -> no static CUDA-object destructor). Zeroed once on (re)allocation; every call leaves both zero. + // The `ws` argument is ignored. + (void)ws; + struct L2Ws { float* ws = nullptr; int* cnt = nullptr; int* claim = nullptr; size_t floats = 0, cnts = 0; }; + static L2Ws& S = *new L2Ws(); + if (!S.claim) { // tail-piece claim ticket counter (DYN), self-resetting each launch + cudaMalloc(&S.claim, sizeof(int)); + cudaMemsetAsync(S.claim, 0, sizeof(int), stream); + } + if (plan.tail > 0) { + const size_t need = (size_t)plan.tail * WS_TILE_FLOATS; + if (need > S.floats || (size_t)plan.tail > S.cnts) { + if (S.ws) { + cudaStreamSynchronize(stream); + cudaFree(S.ws); + cudaFree(S.cnt); + } + S.floats = need > S.floats ? need : S.floats; + S.cnts = (size_t)plan.tail > S.cnts ? (size_t)plan.tail : S.cnts; + cudaMalloc(&S.ws, S.floats * sizeof(float)); + cudaMalloc(&S.cnt, S.cnts * sizeof(int)); + cudaMemsetAsync(S.ws, 0, S.floats * sizeof(float), stream); + cudaMemsetAsync(S.cnt, 0, S.cnts * sizeof(int), stream); + } + } + const int num_units = plan.direct + plan.tail * plan.split; + int grid = num_units < num_sms ? num_units : num_sms; + const int gflags = plan.group_n & ~0xFFFF; // raster flag bits (serpentine) + const int gsel = (plan.group_n & 0xFFFF) > 0 ? (plan.group_n & 0xFFFF) : 8; + const int group_n = (num_nblk < gsel ? num_nblk : gsel) | gflags; + (void)choose_group_n; + (void)num_tiles; + (void)num_mblk; + { + // programmatic dependent launch: launch processing / prologue overlaps the preceding grid + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3(grid, 1, 1); + cfg.blockDim = dim3(NUM_THREADS, 1, 1); + cfg.dynamicSmemBytes = SMEM_BYTES; + cfg.stream = stream; + cudaLaunchAttribute pattr[1]; + pattr[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + pattr[0].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = pattr; + cfg.numAttrs = 1; + // SPF (dyn == 64) needs exactly the static one-piece-per-CTA assignment: direct % grid == 0, tail*split <= grid. + // dyn bits: 64 = SPF, 1..63 = end-claimed tail (DYN), 128 = elected whole-warp MMA issuer, 256 = spin waits + const int dm = dyn & 127; + const int iss = ((dyn & 0x1F80) ? (dyn & 0x1F80) : 128) | (dyn & 8192); // 8192: deferred epilogue (EISS) // default: elected whole-warp issuer (see top) + const bool spf = dm == 64 && plan.tail > 0 && plan.direct % grid == 0 && plan.tail * plan.split <= grid; + auto kfn = spf ? fp8_bs_gemm_large2_kernel<33, 64> + : ((dm && dm != 64) ? fp8_bs_gemm_large2_kernel<33, 31> : fp8_bs_gemm_large2_kernel<33, 0>); +#define L2K(I) kfn = spf ? fp8_bs_gemm_large2_kernel<33, 64 | (I)> : fp8_bs_gemm_large2_kernel<33, (I)>; break; + switch (iss) { + case 128: L2K(128) + case 384: L2K(384) + case 128 | 512: L2K(128 | 512) + case 128 | 4096: L2K(128 | 4096) + case 128 | 8192: L2K(128 | 8192) + default: break; + } +#undef L2K + { + // smem attribute set once per kernel instantiation (host-side memo, no per-call driver call) + static const void* done[16] = {}; + const void* kp = reinterpret_cast(kfn); + int i = 0; + while (i < 16 && done[i] && done[i] != kp) ++i; + if (i < 16 && !done[i]) { cudaFuncSetAttribute(kfn, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); done[i] = kp; } + } + cudaLaunchKernelEx(&cfg, kfn, ta, tb, to, to16, sx, sw, S.ws, S.cnt, M, N, K, group_n, plan.direct, plan.tail, plan.split, + S.claim, dbg, plan.spf_rot); + } +} + +#ifdef LARGE2_PROF +void large2_set_prof(unsigned long long* p) { cudaMemcpyToSymbol(d_l2prof, &p, sizeof(p)); } +void large2_set_mode(int m) { cudaMemcpyToSymbol(d_l2mode, &m, sizeof(m)); } +#endif diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_large2.h b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_large2.h new file mode 100644 index 0000000000000000000000000000000000000000..7de3fa445e3802afb3efdfa17e44ef7dfba9cfe9 --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_large2.h @@ -0,0 +1,25 @@ +#pragma once +#include +#include +// Work decomposition plan for the persistent FP8 blockwise GEMM. +// tiles [0, direct) : one unit each, full K, bf16 TMA store +// tiles [direct, direct+tail) : split into `split` K-pieces each; partials red.add'ed into a +// compact fp32 workspace [tail][128][256] (pre-zeroed), then +// converted to bf16 by a second kernel. +struct Fp8PlanL2 { + int direct; + int tail; + int split; + size_t ws_floats; // 0 if no workspace needed + int group_n = 0; // L2 band width in 256-col N-blocks (0 -> 8); set by the static dispatch table + int spf_rot = 0; // SPF owner placement: CTA b holds tail piece (b + spf_rot) % grid (if < tail*split) +}; +Fp8PlanL2 fp8_large2_plan(int M, int N, int K); +// out[M,N] (bf16) = A[M,K] (e4m3, scales sx[M,K/128]) x W[N,K]^T (e4m3, scales sw[K/128, N/128]). +void launch_fp8_large2(const void* a, const void* w, const float* sx, const float* sw, void* out, float* ws, + const Fp8PlanL2& plan, int M, int N, int K, cudaStream_t stream); +// dyn: 1 = tail pieces claimed at the end via a global ticket counter; dbg: optional per-CTA globaltimer +// {start, end} stamps (2 x grid u64), nullptr in production. +void launch_fp8_large2_ex(const void* a, const void* w, const float* sx, const float* sw, void* out, float* ws, + const Fp8PlanL2& plan_in, int M, int N, int K, cudaStream_t stream, int dyn, + unsigned long long* dbg); diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_largev.cu b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_largev.cu new file mode 100644 index 0000000000000000000000000000000000000000..9609263d0c8c89bde8b23e020f0be9e3b814bf98 --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_largev.cu @@ -0,0 +1,524 @@ +// LARGE-M VARIABLE-WIDTH PERSISTENT KERNEL (kernel_largev.cu): tile-width study vs kernel_large2's 128x256 tiles. +// +// out[m, n] = sum_kb sx[m, kb] * sw[kb, n/128] * sum_{k in kb} A[m,k] * W[n,k] +// +// The N range is cut into T tiles of 16*q or 16*(q+1) columns (rr = C - q*T wide tiles, C = N/16), e.g. N=7168, +// T=37 -> 4 x 208 + 33 x 192 cols, so that (M/128) * T is an exact multiple of #SMs (M=16384: 128 x 37 = 4736 = +// 32 x 148 -> no partial last wave, no K-split tail / fixup). Persistent grid = #SMs, CTA b walks tiles +// t = b, b + grid, ... (full K each, no cross-CTA dependencies); banded raster (group_n N-tiles per band, +// N-tile index fastest) for L2 reuse of A / W. +// Roles (12 warps, setmaxnreg 56 / 224): +// warp 0 : TMA producer, 4-stage ring of {A 128x128 fp8 (16 KB), W 16c x 128 fp8 (<= 28 KB)}, 128B swizzle. +// W box from one of two tensor maps (16q / 16(q+1) rows). +// warp 1 : TMEM alloc (512 cols) + single-thread tcgen05.mma kind::f8f6f4 M128 N=16c K32 (4 per k-block), +// each k-block accumulated FRESH into TMEM buffer it&1 (cols 0 / 256). +// warps 2,3 : scale producer: per k-block sx[128 rows] + per-warpgroup sw pair {A, B} into an 8-slot smem ring. +// warps 4-11: promotion: warpgroup 0 owns the first ceil(c/2) 16-col chunks, warpgroup 1 the remaining floor(c/2) +// (<= 112 cols each, so at most one 128-col scale boundary: chunk j uses sw B iff j >= cb). +// Per k-block: early-release pipelined tcgen05.ld drain (64 staging regs), packed FFMA2 promotion. +// Tile end: bf16 pack -> 3-slot per-warp ring of 1 KB 32B-swizzled boxes (32 rows x 16 cols) -> +// TMA store (rows >= M clipped). +#include +#include +#include +#include +#include +#include "tmap_cache.h" +#include "kernel_largev.h" + +namespace { + +constexpr int BLOCK_M = 128; +constexpr int BLOCK_K = 128; +constexpr int MAXW = 224; // widest tile (14 chunks) +constexpr int STAGES = 4; +constexpr int TILE_A_BYTES = BLOCK_M * BLOCK_K; // 16 KB +constexpr int STAGE_BYTES = TILE_A_BYTES + MAXW * BLOCK_K; // 44 KB (1024-multiple) +constexpr int NUM_EPI_WARPS = 8; +constexpr int EPI_WARP0 = 4; +constexpr int NUM_THREADS = 128 + NUM_EPI_WARPS * 32; +constexpr int TMEM_COLS = 512; +constexpr int WARP_STAGE_BYTES = 32 * 32; // 32 rows x 16 bf16 (one TMA box) +constexpr int OUT_SLOTS = 3; +constexpr int OUT_STAGE_BYTES = NUM_EPI_WARPS * OUT_SLOTS * WARP_STAGE_BYTES; // 24 KB +constexpr int SC_SLOTS = 8; +constexpr int SC_SLOT_FLOATS = 136; // 128 sx + 4 sw (+pad) +constexpr int SC_BYTES = SC_SLOTS * SC_SLOT_FLOATS * 4; +constexpr int SMEM_BYTES = STAGES * STAGE_BYTES + OUT_STAGE_BYTES + SC_BYTES + 1024 + 256; +static_assert(SMEM_BYTES <= 232448, "smem budget"); +static_assert(STAGE_BYTES % 1024 == 0, "swizzle alignment"); +constexpr int REGS_CTRL = 56; +constexpr int REGS_EPI = 224; + +__host__ __device__ __forceinline__ void tile_coords(int t, int num_mblk, int num_nt, int group_n, int& mb, int& nt) { + const int per_band = group_n * num_mblk; + const int band = t / per_band; + const int r = t - band * per_band; + const int n_first = band * group_n; + const int rem = num_nt - n_first; + const int gn = rem < group_n ? rem : group_n; + mb = r / gn; + nt = n_first + (r - mb * gn); +} + +__device__ __forceinline__ uint32_t smem_u32(const void* p) { return static_cast(__cvta_generic_to_shared(p)); } +__device__ __forceinline__ void mbar_init(uint64_t* bar, uint32_t count) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(smem_u32(bar)), "r"(count)); +} +__device__ __forceinline__ void mbar_arrive_expect_tx(uint64_t* bar, uint32_t bytes) { + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(smem_u32(bar)), "r"(bytes) : "memory"); +} +__device__ __forceinline__ void mbar_arrive(uint64_t* bar) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(smem_u32(bar)) : "memory"); +} +__device__ __forceinline__ void mbar_wait_sleep(uint64_t* bar, uint32_t parity) { + uint32_t addr = smem_u32(bar); + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITS_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITS_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +__device__ __forceinline__ void tma_load_2d_hint(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y, + uint64_t policy) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(smem_u32(dst)), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(smem_u32(bar)), "l"(policy) + : "memory"); +} +__device__ __forceinline__ void tma_store_2d(const CUtensorMap* map, uint32_t src, int x, int y) { + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%1, %2}], [%3], %4;" ::"l"( + reinterpret_cast(map)), + "r"(x), "r"(y), "r"(src), "l"(pol) + : "memory"); +} +__device__ __forceinline__ uint64_t make_sdesc(uint32_t saddr) { + uint64_t d = 0; + d |= (uint64_t)((saddr & 0x3FFFF) >> 4); + d |= (uint64_t)1 << 16; + d |= (uint64_t)(1024 >> 4) << 32; // SBO: 8 rows x 128 B + d |= (uint64_t)1 << 46; // sm100 descriptor version + d |= (uint64_t)2 << 61; // SWIZZLE_128B + return d; +} +__device__ __forceinline__ void mma_f8(uint32_t tmem_d, uint64_t adesc, uint64_t bdesc, uint32_t idesc, uint32_t accum) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "setp.ne.b32 p, %4, 0;\n" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %3, p;\n" + "}\n" ::"r"(tmem_d), + "l"(adesc), "l"(bdesc), "r"(idesc), "r"(accum)); +} +__device__ __forceinline__ void mma_commit(uint64_t* bar) { + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(smem_u32(bar)) + : "memory"); +} +__device__ __forceinline__ void fence_after() { asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void fence_before() { asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void ffma2(float& a0, float& a1, uint32_t x0, uint32_t x1, float2 ss) { + const float2 d = __ffma2_rn(make_float2(__uint_as_float(x0), __uint_as_float(x1)), ss, make_float2(a0, a1)); + a0 = d.x; + a1 = d.y; +} + +#define TMEM_LD32(taddr, r) \ + 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)) +#define TMEM_LD16(taddr, r) \ + 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"(taddr)) +__device__ __forceinline__ void tmem_ld_wait() { asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); } + +__device__ __forceinline__ void promo_chunk(float* a, const uint32_t* r, float s) { + const float2 ss = make_float2(s, s); +#pragma unroll + for (int j = 0; j < 16; j += 2) ffma2(a[j], a[j + 1], r[j], r[j + 1], ss); +} + +// Promotion of one whole tile (all K) for a warpgroup owning NC 16-col chunks + bf16 TMA-store epilogue. +template +__device__ __forceinline__ void promo_tile(uint32_t taddr_b0, uint32_t sc_base, uint64_t* sfull_bar, + uint64_t* sempty_bar, uint64_t* tfull_bar, uint64_t* tempty_bar, int g, + int lane, int row, int cb, int num_kb, uint32_t& it, uint32_t& ob, + uint32_t wstage0, const CUtensorMap* tmap_out, int xcol, int yrow) { + static_assert(NC >= 5 && NC <= 7, "chunks"); + constexpr int NCOL = NC * 16; + float acc[NCOL]; +#pragma unroll + for (int j = 0; j < NCOL; ++j) acc[j] = 0.f; + for (int kb = 0; kb < num_kb; ++kb, ++it) { + const int b = it & 1; + const uint32_t slot = it % SC_SLOTS; + mbar_wait_sleep(&sfull_bar[slot], (it / SC_SLOTS) & 1); + const uint32_t sp = sc_base + slot * (SC_SLOT_FLOATS * 4); + float sxr, wA, wB; + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(sxr) : "r"(sp + row * 4) : "memory"); + asm volatile("ld.shared.v2.f32 {%0, %1}, [%2];" : "=f"(wA), "=f"(wB) : "r"(sp + 512 + g * 8) : "memory"); + const float sA = sxr * wA, sB = sxr * wB; + __syncwarp(); + if (lane == 0) mbar_arrive(&sempty_bar[slot]); + float sc[NC]; +#pragma unroll + for (int c = 0; c < NC; ++c) sc[c] = c >= cb ? sB : sA; + mbar_wait_sleep(&tfull_bar[b], (it >> 1) & 1); + fence_after(); + const uint32_t taddr = taddr_b0 + ((uint32_t)b << 8); + // early-release drain: chunks 0..3 loaded up front, later chunks into the freed staging registers + uint32_t ra[32], rb[32]; + TMEM_LD32(taddr + 0, ra); + TMEM_LD32(taddr + 32, rb); + tmem_ld_wait(); + promo_chunk(acc + 0, ra, sc[0]); + promo_chunk(acc + 16, ra + 16, sc[1]); + if constexpr (NC == 7) { + TMEM_LD32(taddr + 64, ra); + promo_chunk(acc + 32, rb, sc[2]); + TMEM_LD16(taddr + 96, rb); + promo_chunk(acc + 48, rb + 16, sc[3]); + } else if constexpr (NC == 6) { + TMEM_LD32(taddr + 64, ra); + promo_chunk(acc + 32, rb, sc[2]); + promo_chunk(acc + 48, rb + 16, sc[3]); + } else { + TMEM_LD16(taddr + 64, ra); + promo_chunk(acc + 32, rb, sc[2]); + promo_chunk(acc + 48, rb + 16, sc[3]); + } + tmem_ld_wait(); + fence_before(); + __syncwarp(); + if (lane == 0) mbar_arrive(&tempty_bar[b]); // TMEM buffer free + promo_chunk(acc + 64, ra, sc[4]); + if constexpr (NC >= 6) promo_chunk(acc + 80, ra + 16, sc[5]); + if constexpr (NC == 7) promo_chunk(acc + 96, rb, sc[6]); + } + // bf16 epilogue: one 32 rows x 16 cols box per chunk through the 3-slot per-warp staging ring (32B swizzle: + // 16 B chunk j of row lane at j ^ ((lane >> 2) & 1)); the box using a slot waits for the store 3 boxes back. +#pragma unroll + for (int h = 0; h < NC; ++h) { + if (lane == 0) asm volatile("cp.async.bulk.wait_group.read %0;" ::"n"(OUT_SLOTS - 1) : "memory"); + __syncwarp(); + const uint32_t wst = wstage0 + (ob % OUT_SLOTS) * WARP_STAGE_BYTES; + ++ob; +#pragma unroll + for (int j = 0; j < 2; ++j) { + const int v = h * 2 + j; + __nv_bfloat162 h0 = __floats2bfloat162_rn(acc[v * 8 + 0], acc[v * 8 + 1]); + __nv_bfloat162 h1 = __floats2bfloat162_rn(acc[v * 8 + 2], acc[v * 8 + 3]); + __nv_bfloat162 h2 = __floats2bfloat162_rn(acc[v * 8 + 4], acc[v * 8 + 5]); + __nv_bfloat162 h3 = __floats2bfloat162_rn(acc[v * 8 + 6], acc[v * 8 + 7]); + const uint32_t addr = wst + lane * 32 + ((j ^ ((lane >> 2) & 1)) << 4); + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(addr), "r"(*reinterpret_cast(&h0)), + "r"(*reinterpret_cast(&h1)), "r"(*reinterpret_cast(&h2)), + "r"(*reinterpret_cast(&h3)) + : "memory"); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + if (lane == 0) { + tma_store_2d(tmap_out, wst, xcol + h * 16, yrow); + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + } + } +} + +__global__ void __launch_bounds__(NUM_THREADS, 1) + fp8_largev_kernel(const __grid_constant__ CUtensorMap tmap_a, const __grid_constant__ CUtensorMap tmap_b_lo, + const __grid_constant__ CUtensorMap tmap_b_hi, const __grid_constant__ CUtensorMap tmap_out, + const float* __restrict__ scale_x, const float* __restrict__ scale_w, int M, int N, int K, + int T, int qch, int rr, int group_n) { + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(smem_raw) + 1023) & ~uintptr_t(1023)); + uint8_t* out_stage = smem + STAGES * STAGE_BYTES; + float* sc_ring = reinterpret_cast(out_stage + OUT_STAGE_BYTES); + uint64_t* full_bar = reinterpret_cast(out_stage + OUT_STAGE_BYTES + SC_BYTES); + uint64_t* empty_bar = full_bar + STAGES; + uint64_t* tfull_bar = empty_bar + STAGES; + uint64_t* tempty_bar = tfull_bar + 2; + uint64_t* sfull_bar = tempty_bar + 2; + uint64_t* sempty_bar = sfull_bar + SC_SLOTS; + uint32_t* tmem_slot = reinterpret_cast(sempty_bar + SC_SLOTS); + + const int warp = __shfl_sync(0xffffffffu, (int)(threadIdx.x / 32), 0); + const int lane = threadIdx.x % 32; + const int num_kb = K / BLOCK_K; + const int num_sblk = N / 128; + const int num_mblk = (M + BLOCK_M - 1) / BLOCK_M; + const int num_tiles = num_mblk * T; + + if (threadIdx.x == 0) { + for (int i = 0; i < STAGES; ++i) { + mbar_init(&full_bar[i], 1); + mbar_init(&empty_bar[i], 1); + } + for (int i = 0; i < 2; ++i) { + mbar_init(&tfull_bar[i], 1); + mbar_init(&tempty_bar[i], NUM_EPI_WARPS); + } + for (int i = 0; i < SC_SLOTS; ++i) { + mbar_init(&sfull_bar[i], 64); + mbar_init(&sempty_bar[i], NUM_EPI_WARPS); + } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_a)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_b_lo)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_b_hi)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_out)) : "memory"); + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(smem_u32(tmem_slot)), + "r"(TMEM_COLS)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + fence_before(); + __syncthreads(); + asm volatile("griddepcontrol.wait;" ::: "memory"); // PDL: no global memory touched before this + fence_after(); + const uint32_t tmem_base = __shfl_sync(0xffffffffu, *tmem_slot, 0); + + if (warp < EPI_WARP0) { + asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;" ::"n"(REGS_CTRL)); + if (warp == 0 && lane == 0) { + // ------------------------------------------------ TMA producer + uint64_t pol_a, pol_w; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_a)); + asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol_w)); + uint32_t it = 0; + for (int t = blockIdx.x; t < num_tiles; t += gridDim.x) { + int mb, nt; + tile_coords(t, num_mblk, T, group_n, mb, nt); + const bool wide = nt < rr; + const int c = qch + (wide ? 1 : 0); + const int n0 = 16 * (nt * qch + (nt < rr ? nt : rr)); + const CUtensorMap* tmb = wide ? &tmap_b_hi : &tmap_b_lo; + const uint32_t tx = (uint32_t)(TILE_A_BYTES + 16 * c * BLOCK_K); + for (int kb = 0; kb < num_kb; ++kb, ++it) { + const int s = it % STAGES; + const uint32_t ph = (it / STAGES) & 1; + mbar_wait_sleep(&empty_bar[s], ph ^ 1); + uint8_t* sa = smem + s * STAGE_BYTES; + mbar_arrive_expect_tx(&full_bar[s], tx); // OOB A rows zero-filled, still counted + tma_load_2d_hint(sa, &tmap_a, &full_bar[s], kb * BLOCK_K, mb * BLOCK_M, pol_a); + tma_load_2d_hint(sa + TILE_A_BYTES, tmb, &full_bar[s], kb * BLOCK_K, n0, pol_w); + } + } + } else if (warp == 1 && lane == 0) { + // ------------------------------------------------ MMA issuer + uint32_t it = 0; + for (int t = blockIdx.x; t < num_tiles; t += gridDim.x) { + int mb, nt; + tile_coords(t, num_mblk, T, group_n, mb, nt); + const int c = qch + (nt < rr ? 1 : 0); + const uint32_t idesc = (1u << 4) | ((uint32_t)((16 * c) >> 3) << 17) | ((uint32_t)(BLOCK_M >> 4) << 24); + for (int kb = 0; kb < num_kb; ++kb, ++it) { + const int s = it % STAGES; + const uint32_t ph = (it / STAGES) & 1; + const int b = it & 1; + mbar_wait_sleep(&full_bar[s], ph); + const uint32_t sa = smem_u32(smem + s * STAGE_BYTES); + const uint64_t adesc = make_sdesc(sa); + const uint64_t bdesc = make_sdesc(sa + TILE_A_BYTES); + const uint32_t tmem_d = tmem_base + b * 256; + mbar_wait_sleep(&tempty_bar[b], ((it >> 1) & 1) ^ 1); + fence_after(); +#pragma unroll + for (int k = 0; k < BLOCK_K / 32; ++k) mma_f8(tmem_d, adesc + 2 * k, bdesc + 2 * k, idesc, k > 0 ? 1u : 0u); + mma_commit(&empty_bar[s]); + mma_commit(&tfull_bar[b]); + } + } + } else if (warp >= 2) { + // ------------------------------------------------ scale producer (warps 2,3; rows lt, lt+64) + // slot: [0,128) = sx[m0+row, kb], [128,132) = sw[kb, blk] for {g0 A, g0 B, g1 A, g1 B} + const int lt = threadIdx.x - 64; + uint32_t it = 0; + for (int t = blockIdx.x; t < num_tiles; t += gridDim.x) { + int mb, nt; + tile_coords(t, num_mblk, T, group_n, mb, nt); + const int c = qch + (nt < rr ? 1 : 0); + const int c0 = (c + 1) >> 1; + const int n0 = 16 * (nt * qch + (nt < rr ? nt : rr)); + const int ra = mb * BLOCK_M + lt, rb = ra + 64; + const float* pa = scale_x + (size_t)(ra < M ? ra : 0) * num_kb; // rows >= M: value unused + const float* pb = scale_x + (size_t)(rb < M ? rb : 0) * num_kb; + const int gg = (lt >> 1) & 1; + const int blk = ((n0 + gg * 16 * c0) >> 7) + (lt & 1); + const int wj = blk < num_sblk ? blk : num_sblk - 1; + for (int kb = 0; kb < num_kb; kb += 4) { + const int nq = (num_kb - kb) < 4 ? (num_kb - kb) : 4; + float xa[4], xb[4], wv[4]; + if (nq == 4 && ((kb | num_kb) & 3) == 0) { + const float4 va = __ldg(reinterpret_cast(pa + kb)); + const float4 vb = __ldg(reinterpret_cast(pb + kb)); + xa[0] = va.x; xa[1] = va.y; xa[2] = va.z; xa[3] = va.w; + xb[0] = vb.x; xb[1] = vb.y; xb[2] = vb.z; xb[3] = vb.w; +#pragma unroll + for (int q = 0; q < 4; ++q) wv[q] = __ldg(scale_w + (size_t)(kb + q) * num_sblk + wj); + } else { +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + xa[q] = __ldg(pa + kb + q); + xb[q] = __ldg(pb + kb + q); + wv[q] = __ldg(scale_w + (size_t)(kb + q) * num_sblk + wj); + } + } + } +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + const uint32_t ii = it + q; + const int slot = ii % SC_SLOTS; + mbar_wait_sleep(&sempty_bar[slot], ((ii / SC_SLOTS) & 1) ^ 1); + float* d = sc_ring + slot * SC_SLOT_FLOATS; + d[lt] = xa[q]; + d[lt + 64] = xb[q]; + if (lt < 4) d[128 + lt] = wv[q]; + mbar_arrive(&sfull_bar[slot]); + } + } + it += nq; + } + } + } + } else { + // ------------------------------------------------ promotion + epilogue (warps 4..11) + asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;" ::"n"(REGS_EPI)); + const int g = (warp - EPI_WARP0) >> 2; + const int sub = warp & 3; + const int row = sub * 32 + lane; + const uint32_t sc_base = smem_u32(sc_ring); + const uint32_t wstage0 = smem_u32(out_stage) + (uint32_t)((g * 4 + sub) * OUT_SLOTS * WARP_STAGE_BYTES); + uint32_t it = 0, ob = 0; + for (int t = blockIdx.x; t < num_tiles; t += gridDim.x) { + int mb, nt; + tile_coords(t, num_mblk, T, group_n, mb, nt); + const int c = qch + (nt < rr ? 1 : 0); + const int c0 = (c + 1) >> 1; + const int ncg = g ? (c >> 1) : c0; // warp-uniform chunk count of this warpgroup + const int coff = g * 16 * c0; + const int n0 = 16 * (nt * qch + (nt < rr ? nt : rr)); + const int cbase = n0 + coff; + const int cb = (((cbase >> 7) + 1) * 128 - cbase) >> 4; // first chunk past the 128-col scale boundary + const uint32_t taddr_b0 = tmem_base + ((uint32_t)(sub * 32) << 16) + coff; + const int yrow = mb * BLOCK_M + sub * 32; + if (ncg == 7) + promo_tile<7>(taddr_b0, sc_base, sfull_bar, sempty_bar, tfull_bar, tempty_bar, g, lane, row, cb, num_kb, it, + ob, wstage0, &tmap_out, cbase, yrow); + else if (ncg == 6) + promo_tile<6>(taddr_b0, sc_base, sfull_bar, sempty_bar, tfull_bar, tempty_bar, g, lane, row, cb, num_kb, it, + ob, wstage0, &tmap_out, cbase, yrow); + else + promo_tile<5>(taddr_b0, sc_base, sfull_bar, sempty_bar, tfull_bar, tempty_bar, g, lane, row, cb, num_kb, it, + ob, wstage0, &tmap_out, cbase, yrow); + } + if (lane == 0) asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); + __syncwarp(); + } + fence_before(); + __syncthreads(); + asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); + if (warp == 1) { + fence_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tmem_base), "r"(TMEM_COLS)); + } +} + +static void make_tmap(CUtensorMap* map, const void* ptr, uint64_t rows, uint64_t K, uint32_t box_rows) { + cuuint64_t dims[2] = {K, rows}; + cuuint64_t strides[1] = {K}; + cuuint32_t box[2] = {BLOCK_K, box_rows}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(map, CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, const_cast(ptr), dims, strides, + box, estr, 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\n", (int)r); +} + +static int largev_sms() { + static int sms = 0; + if (sms == 0) { + int dev; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev); + cudaFuncSetAttribute(fp8_largev_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + } + return sms; +} + +} // namespace + +// T = 0: auto (smallest max-per-CTA work: ceil(tiles/sms) * widest tile chunks, ties -> fewer tiles). +int fp8_largev_auto_T(int M, int N) { + const int sms = largev_sms(); + const int C = N / 16, nmb = (M + BLOCK_M - 1) / BLOCK_M; + int best = 0; + long bestc = -1; + for (int T = (C + 13) / 14; T <= C / 10; ++T) { + const int q = C / T, rr = C - q * T; + const long waves = ((long)nmb * T + sms - 1) / sms; + const long cost = waves * (q + (rr > 0 ? 1 : 0)); + if (bestc < 0 || cost < bestc) { bestc = cost; best = T; } + } + return best; +} + +bool fp8_largev_supported(int M, int N, int K, int T) { + if (!(M >= 1 && N % 128 == 0 && K % BLOCK_K == 0 && K >= BLOCK_K)) return false; + const int C = N / 16; + if (T <= 0 || T > C) return false; + const int q = C / T, rr = C - q * T; + return q >= 10 && q + (rr > 0 ? 1 : 0) <= 14; +} + +void launch_fp8_largev(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, int K, + int T, int group_n, cudaStream_t stream) { + const int sms = largev_sms(); + const int C = N / 16, q = C / T, rr = C - q * T; + CUtensorMap ta, tbl, tbh, to; + make_tmap(&ta, a, (uint64_t)M, (uint64_t)K, BLOCK_M); + make_tmap(&tbl, w, (uint64_t)N, (uint64_t)K, 16 * q); + make_tmap(&tbh, w, (uint64_t)N, (uint64_t)K, 16 * (q + 1) <= MAXW ? 16 * (q + 1) : 16 * q); + { + // bf16 output map: dims {N, M}, box {16 cols (32 B), 32 rows}, 32B swizzle + cuuint64_t dims[2] = {(cuuint64_t)N, (cuuint64_t)M}; + cuuint64_t strides[1] = {(cuuint64_t)N * 2}; + cuuint32_t box[2] = {16, 32}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(&to, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, out, dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_32B, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled(out) failed: %d\n", (int)r); + } + const int tiles = ((M + BLOCK_M - 1) / BLOCK_M) * T; + const int grid = tiles < sms ? tiles : sms; + const int gn = group_n <= 0 || group_n > T ? T : group_n; + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3(grid, 1, 1); + cfg.blockDim = dim3(NUM_THREADS, 1, 1); + cfg.dynamicSmemBytes = SMEM_BYTES; + cfg.stream = stream; + cudaLaunchAttribute attr[1]; + attr[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attr[0].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = attr; + cfg.numAttrs = 1; + cudaLaunchKernelEx(&cfg, fp8_largev_kernel, ta, tbl, tbh, to, sx, sw, M, N, K, T, q, rr, gn); +} diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_largev.h b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_largev.h new file mode 100644 index 0000000000000000000000000000000000000000..3c15dc855936e7da60f7724c37aba1d14342d29f --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_largev.h @@ -0,0 +1,7 @@ +#pragma once +#include +// Large M: persistent 128 x (16q | 16(q+1)) variable-width tiles, T N-tiles (kernel_largev.cu). +int fp8_largev_auto_T(int M, int N); +bool fp8_largev_supported(int M, int N, int K, int T); +void launch_fp8_largev(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, int K, + int T, int group_n, cudaStream_t stream); diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128c.cu b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128c.cu new file mode 100644 index 0000000000000000000000000000000000000000..e4068363fb16a64aca8e0247ba82a63d42cd848f --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128c.cu @@ -0,0 +1,956 @@ +// REDUCE-SCATTER (this version, 32-col chunks 32/32/16): split-K partials reduced per chunk; chunk c of promotion warp q is owned by +// rank (q+c)%3, so all 3 ranks own ~1/3 of the tile and all warps both push and store (see the reduction section). +// POWER (this version): idle-role mbarrier waits (TMA empty, scale sempty, pusher ready) suspend-hinted; +// scale producer loads sx as one float4 per row per 4 aligned k-blocks. +// M <= 128 (single 128-row M block) KERNEL v2: 128 x 160 tiles, THREE TMEM partial buffers, split-K 3 as a +// 3-CTA CLUSTER along K, split-K partials reduced through DSMEM (FP24 push, no global workspace, single launch). +// +// out[m, n] = sum_kb sx[m, kb] * sw[kb, n/128] * sum_{k in kb} A[m,k] * W[n,k] +// +// Why: with 2 TMEM buffers the mainloop was gated by the promotion hand-off (TMEM release) in most k-blocks. +// 160-col tiles let 3 accumulator buffers (3 x 160 = 480 of 512 TMEM cols) be in flight, so the MMA can run up +// to 2 k-blocks ahead of the promotion warps. +// Work decomposition: N = 7168 -> ceil(N/160) = 45 N-tiles (the last has 128 valid cols: W rows >= N are TMA +// zero-filled, the bf16 TMA store clips cols >= N). Cluster c owns cols [c*160, +160) of all (<=128) rows; CTA +// rank r streams K-blocks [r*nkb/3, (r+1)*nkb/3) (42/43/43 for K=16384). grid = 45*3 = 135 CTAs. +// Roles (12 warps, setmaxnreg 56 / 224): +// warp 0 : TMA producer, 6-stage ring of {A 128x128 fp8 (16 KB), W 160x128 fp8 (20 KB)}, 128B swizzle. +// warp 1 : TMEM alloc (512 cols) + single-thread tcgen05.mma kind::f8f6f4 M128 N160 K32 (4 per k-block); +// k-block `it` accumulated FRESH into TMEM buffer b = it % 3 (cols b*160 .. +160). +// warps 2,3 : scale producer: per k-block sx[128 rows] + per-warpgroup sw pair into an 8-slot smem ring. +// warps 4-11: promotion. Warpgroup g owns tile cols [g*80, +80), thread = tile row = TMEM lane. Per k-block: +// 5 x16 tcgen05.ld, ONE wait::ld, release the buffer (one elected arrive per warp), then +// acc += part * s with s = sx*sw[A or B] per 16-col chunk (a chunk never straddles a 128-col +// scale block: n0 and g*80 are multiples of 16). +// DSMEM split-K reduction by ASYNC PUSH: the 8 promotion-warp slots q = sub*2 + g (32 rows x 80 cols each) are +// owned by rank q % 3. A pusher warp packs its slice as FP24 (top 24 bits of fp32 per value, fp24_push.h) in its idle ring, waits +// for the owner's 'ready' (owner ring idle), then one cp.async.bulk smem -> owner smem (complete_tx on the +// owner's recv mbarrier). The owner adds the 2 received slices, packs bf16 and TMA-stores one 32x80 box. +// A single end-of-kernel cluster barrier keeps source/destination smem alive until all copies completed. +#include +#include +#include +#include +#include +#include "tmap_cache.h" +#include "kernel_m128c.h" +#include "raw_push.h" // EXACT fp32 split-K push (was fp24) +#include "fp24_push.h" // fp24 push + +// M128C_FUSED_ISSUE: 1 = fused single-asm MMA issue loop (shipped), 0 = previous per-MMA issuer +#ifndef M128C_FUSED_ISSUE +#define M128C_FUSED_ISSUE 1 +#endif +namespace { + +constexpr int BLOCK_M = 128; +constexpr int TILE_N = 160; +constexpr int BLOCK_K = 128; +constexpr int CL = 3; // cluster size = split-K factor +constexpr int NBUF = 3; // TMEM accumulator buffers +constexpr int STAGES = 6; +constexpr int TILE_A_BYTES = BLOCK_M * BLOCK_K; // 16 KB +constexpr int TILE_B_BYTES = TILE_N * BLOCK_K; // 20 KB +constexpr int STAGE_BYTES = TILE_A_BYTES + TILE_B_BYTES; // 36 KB (1024-multiple) +constexpr int W_NBOX = 4; // W loaded as 4 x 40-row TMA boxes per stage +constexpr int W_BOX_ROWS = TILE_N / W_NBOX; +constexpr int W_HALF_BYTES = W_BOX_ROWS * BLOCK_K; // 5 KB per box (5 swizzle atoms) +static_assert(W_HALF_BYTES % 1024 == 0, "W half box swizzle alignment"); +constexpr int NUM_EPI_WARPS = 8; +constexpr int EPI_COLS = TILE_N / 2; // 80 per promotion warpgroup +constexpr int NCHUNK = EPI_COLS / 16; // 5 +constexpr int EPI_WARP0 = 4; +constexpr int NUM_THREADS = 128 + NUM_EPI_WARPS * 32; // 384 +constexpr int TMEM_COLS = 512; // 3 buffers at cols 0, 160, 320 +constexpr int SC_SLOTS = 8; +constexpr int SC_SLOT_FLOATS = 136; // 128 sx (per row) + 4 sw (+pad) +constexpr int SC_BYTES = SC_SLOTS * SC_SLOT_FLOATS * 4; +constexpr int SMEM_BYTES = STAGES * STAGE_BYTES + SC_BYTES + 1024 /*align*/ + 1024 /*barriers*/; +// N-CHUNKED MAINLOOP END: the last TAIL_KB k-blocks of every CTA are loaded / MMA'd in two N halves (warpgroup 0's +// cols [0,80) for all tail k-blocks first, then warpgroup 1's [80,160)), so warpgroup 0 finishes its K range early +// and its split-K DSMEM reduce-scatter overlaps warpgroup 1's last loads / MMAs / promotion. +constexpr int TAIL_KB = 3; +constexpr uint32_t WH_BYTES = 2 * W_HALF_BYTES; // 80 W rows = one warpgroup's half of the W slab (10 KB) +static_assert(STAGES == 2 * TAIL_KB, "per-warpgroup reduce regions = 3 ring stages each"); +// post-mainloop ring layout (raw fp32 push, 10 KB slices): [0, 6*PSLOT) recv slots ((q/3)*2 + j: an owner rank +// owns slots q = rank, rank+3, rank+6 -> q/3 distinct), [6*PSLOT, 14*PSLOT) outgoing fp32 staging (q); +// bf16 output staging of owner warp q reuses its consumed recv slots q*2, q*2+1 +constexpr uint32_t PSL_BYTES = rawpush::slice_bytes(EPI_COLS); // raw fp32 slice (raw_push.h) +constexpr uint32_t PSLOT = (PSL_BYTES + 127u) & ~127u; +constexpr uint32_t OUT_OFF = 6 * PSLOT; +constexpr uint32_t BF_OFF = 0; // bf16 box of owner warp q reuses its recv slot pair (q*2, q*2+1) +constexpr uint32_t BF_BOX = 32 * EPI_COLS * 2; // 5120 B +static_assert(SMEM_BYTES <= 232448, "smem budget"); +static_assert(14 * PSLOT <= (uint32_t)(STAGES * STAGE_BYTES) && BF_BOX <= 2 * PSLOT && PSLOT % 128 == 0, "recv + staging fit in ring"); +static_assert(STAGE_BYTES % 1024 == 0 && TILE_A_BYTES % 1024 == 0, "swizzle alignment"); +static_assert(NBUF * TILE_N <= TMEM_COLS, "tmem"); +constexpr int REGS_CTRL = 56; +constexpr int REGS_EPI = 224; + +__device__ __forceinline__ uint32_t smem_u32(const void* p) { + return static_cast(__cvta_generic_to_shared(p)); +} +__device__ __forceinline__ uint32_t cluster_ctarank() { + uint32_t r; + asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(r)); + return r; +} +__device__ __forceinline__ void cluster_sync() { + asm volatile("barrier.cluster.arrive.release.aligned;\n\tbarrier.cluster.wait.acquire.aligned;" ::: "memory"); +} +__device__ __forceinline__ void mbar_init(uint64_t* bar, uint32_t count) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(smem_u32(bar)), "r"(count)); +} +__device__ __forceinline__ void mbar_arrive_expect_tx(uint64_t* bar, uint32_t bytes) { + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(smem_u32(bar)), "r"(bytes) + : "memory"); +} +__device__ __forceinline__ void mbar_arrive(uint64_t* bar) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(smem_u32(bar)) : "memory"); +} +__device__ __forceinline__ void mbar_wait(uint64_t* bar, uint32_t parity) { + uint32_t addr = smem_u32(bar); + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAIT_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n" + "@!p bra WAIT_%=;\n" + "}\n" ::"r"(addr), + "r"(parity) + : "memory"); +} +__device__ __forceinline__ void mbar_wait_sleep(uint64_t* bar, uint32_t parity) { + uint32_t addr = smem_u32(bar); + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITS_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITS_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +__device__ __forceinline__ void tma_load_2d_hint(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y, + uint64_t policy) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(smem_u32(dst)), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(smem_u32(bar)), "l"(policy) + : "memory"); +} +__device__ __forceinline__ uint64_t make_sdesc(uint32_t saddr) { + uint64_t d = 0; + d |= (uint64_t)((saddr & 0x3FFFF) >> 4); + d |= (uint64_t)1 << 16; + d |= (uint64_t)(1024 >> 4) << 32; // SBO: 8 rows x 128 B + d |= (uint64_t)1 << 46; // sm100 descriptor version + d |= (uint64_t)2 << 61; // SWIZZLE_128B + return d; +} +__device__ __forceinline__ void mma_f8(uint32_t tmem_d, uint64_t adesc, uint64_t bdesc, uint32_t idesc, + uint32_t accum) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "setp.ne.b32 p, %4, 0;\n" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %3, p;\n" + "}\n" ::"r"(tmem_d), + "l"(adesc), "l"(bdesc), "r"(idesc), "r"(accum)); +} +__device__ __forceinline__ void mma_commit(uint64_t* bar) { + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(smem_u32(bar)) + : "memory"); +} +__device__ __forceinline__ void fence_after() { asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void fence_before() { asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void ffma2(float& a0, float& a1, uint32_t x0, uint32_t x1, float2 ss) { + const float2 d = __ffma2_rn(make_float2(__uint_as_float(x0), __uint_as_float(x1)), ss, make_float2(a0, a1)); + a0 = d.x; + a1 = d.y; +} +__device__ __forceinline__ void sts_v4f(uint32_t a, float x, float y, float z, float w) { + asm volatile("st.shared.v4.f32 [%0], {%1, %2, %3, %4};" ::"r"(a), "f"(x), "f"(y), "f"(z), "f"(w) : "memory"); +} +__device__ __forceinline__ uint32_t mapa_rank(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; +} +__device__ __forceinline__ void st_dsmem_v4(uint32_t a, float x, float y, float z, float w) { + asm volatile("st.shared::cluster.v4.f32 [%0], {%1, %2, %3, %4};" ::"r"(a), "f"(x), "f"(y), "f"(z), "f"(w) : "memory"); +} +__device__ __forceinline__ float4 lds_v4f(uint32_t a) { + float4 v; + asm volatile("ld.shared.v4.f32 {%0, %1, %2, %3}, [%4];" : "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w) : "r"(a) : "memory"); + return v; +} +__device__ __forceinline__ float4 ld_dsmem_v4(uint32_t a) { + 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"(a) + : "memory"); + return v; +} + +__device__ __forceinline__ void cluster_arrive() { asm volatile("barrier.cluster.arrive.release.aligned;" ::: "memory"); } +__device__ __forceinline__ void cluster_wait() { asm volatile("barrier.cluster.wait.acquire.aligned;" ::: "memory"); } +// RELAXED TAIL (as kernel_m256c): the end barrier #2 arrive and the owner's 'ready' remote arrives publish no +// generic-proxy data (pushed slices are ordered by the recv mbarrier complete_tx, the output by the owner's bulk +// wait_group; the owner ring's last readers were MMAs whose completion was observed via tfull), so relaxed suffices. +__device__ __forceinline__ void cluster_arrive_relaxed() { asm volatile("barrier.cluster.arrive.relaxed.aligned;" ::: "memory"); } +__device__ __forceinline__ void mbar_arrive_remote_relaxed(uint32_t cluster_addr) { + asm volatile("mbarrier.arrive.relaxed.cluster.shared::cluster.b64 _, [%0];" ::"r"(cluster_addr) : "memory"); +} +// remote (DSMEM) mbarrier arrive with cluster-scope release +__device__ __forceinline__ void mbar_arrive_remote(uint32_t cluster_addr) { + asm volatile("mbarrier.arrive.release.cluster.shared::cluster.b64 _, [%0];" ::"r"(cluster_addr) : "memory"); +} +__device__ __forceinline__ void mbar_wait_cluster(uint32_t addr, uint32_t parity) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITC_%=:\n" + "mbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITC_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +// local smem -> peer CTA smem bulk copy, completion (complete_tx) on the peer's mbarrier +__device__ __forceinline__ void bulk_s2dsmem(uint32_t dst_cl, uint32_t src, uint32_t bytes, uint32_t mbar_cl) { + asm volatile("cp.async.bulk.shared::cluster.shared::cta.mbarrier::complete_tx::bytes [%0], [%1], %2, [%3];" ::"r"( + dst_cl), + "r"(src), "r"(bytes), "r"(mbar_cl) + : "memory"); +} +__device__ __forceinline__ void tma_store_2d_u32(const CUtensorMap* map, uint32_t src, int x, int y) { + // output store with an L2 evict_first policy: the bf16 output is written once and never re-read by this + // kernel, so its lines should not evict the W / A operand lines the tile raster reuses from L2. + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%1, %2}], [%3], %4;" ::"l"( + reinterpret_cast(map)), + "r"(x), "r"(y), "r"(src), "l"(pol) + : "memory"); +} + +#define TMEM_LD16(taddr, r) \ + 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"(taddr)) + +// HEAD W L2 PREFETCH helper: L2-only bulk-tensor prefetch of one W box (pure hint, no smem / barrier involvement). +__device__ __forceinline__ void tma_prefetch_l2(const CUtensorMap* map, int x, int y) { + asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile [%0, {%1, %2}];" ::"l"(reinterpret_cast(map)), + "r"(x), "r"(y) + : "memory"); +} +__device__ __forceinline__ void tma_prefetch_l2_hint(const CUtensorMap* map, int x, int y, uint64_t pol) { + asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile.L2::cache_hint [%0, {%1, %2}], %3;" ::"l"( + reinterpret_cast(map)), + "r"(x), "r"(y), "l"(pol) + : "memory"); +} +__device__ __forceinline__ void mbar_wait_sleep_u32(uint32_t addr, uint32_t parity) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITU_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITU_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +__device__ __forceinline__ void mbar_arrive_u32(uint32_t addr) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(addr) : "memory"); +} +// MEMORY-ORDERING AUDIT: relaxed CTA-scope local arrive for the TMEM-empty hand-off (issued after tcgen05.wait::ld + +// tcgen05.fence::before_thread_sync: the TMEM reads are complete, nothing else is published by this arrive). +__device__ __forceinline__ void mbar_arrive_relaxed_u32(uint32_t addr) { + asm volatile("mbarrier.arrive.relaxed.cta.shared::cta.b64 _, [%0];" ::"r"(addr) : "memory"); +} +__device__ __forceinline__ void tmem_ld_wait() { asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); } + +// SKEWED REDUCE-SCATTER OWNERSHIP (this version): rank 0 has the shortest K range and finishes +// its mainloop first, so it should own the FEWEST columns (its inbound slices all come from the late ranks 1,2, while +// the late ranks' inbound include rank 0's early push). 16-col units per rank 12/14/14 (was 13/14/13): max late +// DSMEM ingress 26 -> 24 units, max late egress 27 -> 26 units. Warp q's 3 chunks (32|32|16 cols) still go to 3 +// distinct ranks: chunk 2 (16 cols) owned by o2(q) = {0,0,0,0,1,1,2,2}[q], chunk 0 by (o2+1)%3, chunk 1 by (o2+2)%3. +__device__ __forceinline__ int rs_o2(int q) { return q < 4 ? 0 : (q < 6 ? 1 : 2); } +__device__ __forceinline__ int rs_owner(int q, int c) { + const int o2 = rs_o2(q); + return c == 2 ? o2 : (c == 0 ? (o2 + 1) % 3 : (o2 + 2) % 3); +} +__device__ __forceinline__ int rs_chunk(int q, int r) { // chunk of warp q owned by rank r + const int o2 = rs_o2(q); + return r == o2 ? 2 : (r == (o2 + 1) % 3 ? 0 : 1); +} + +// VARIANT bits V: 1 = FP24 st.async split-K push (instead of exact fp32), 2 = EARLY READY (warpgroup 0 owner warps +// signal their reduce region idle right after the last pre-tail k-block's tfull), 4 = W160, 8 = W2X80 (two 80-row W TMA boxes, one per column half, per +// full-width k-block; also 80-row boxes in the tail). W160: (one 160-row W TMA box per +// full-width k-block, 80-row boxes for the tail halves, instead of 4 x 40-row boxes). +template +__global__ void __launch_bounds__(NUM_THREADS, 1) + fp8_m128c_kernel(const __grid_constant__ CUtensorMap tmap_a, const __grid_constant__ CUtensorMap tmap_b, + const __grid_constant__ CUtensorMap tmap_bw, const __grid_constant__ CUtensorMap tmap_bh, + const __grid_constant__ CUtensorMap tmap_out, + const __grid_constant__ CUtensorMap tmap_out16, + const float* __restrict__ scale_x, const float* __restrict__ scale_w, + __nv_bfloat16* __restrict__ out, int M, int N, int K, int pro) { + constexpr bool FP24 = (V & 1) != 0, EARLY = (V & 2) != 0, W160 = (V & 4) != 0, W2X80 = (V & 8) != 0; + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(smem_raw) + 1023) & ~uintptr_t(1023)); + float* sc_ring = reinterpret_cast(smem + STAGES * STAGE_BYTES); // scale ring (after the operand ring) + // full_bar[s]: A + W rows [0,80) landed; full1_bar[s]: W rows [80,160) landed + uint64_t* full_bar = reinterpret_cast(smem + STAGES * STAGE_BYTES + SC_BYTES); + uint64_t* full1_bar = full_bar + STAGES; + uint64_t* empty_bar = full1_bar + STAGES; + uint64_t* tfull_bar = empty_bar + STAGES; // [NBUF*2]: (buffer b, column half g) at b*2+g + uint64_t* tempty_bar = tfull_bar + 2 * NBUF; // [NBUF*2] + // REDUCE-SCATTER: ready_bar[q*3 + o] (local, pusher side): owner rank o's warp q ring idle -> may push to it; + // recv_bar[q] (owner side): all chunk slices of warp q owned by this rank landed (complete_tx, both sources) + uint64_t* ready_bar = tempty_bar + 2 * NBUF; // [24] + uint64_t* recv_bar = ready_bar + 24; // [8] + uint64_t* sfull_bar = recv_bar + 8; // [SC_SLOTS] scale slot written (64 producer threads) + uint64_t* sempty_bar = sfull_bar + SC_SLOTS; // [SC_SLOTS] scale slot consumed (1 arrive per promo warp) + uint32_t* tmem_slot = reinterpret_cast(sempty_bar + SC_SLOTS); + + const int warp = __shfl_sync(0xffffffffu, (int)(threadIdx.x / 32), 0); // warp-uniform + const int lane = threadIdx.x % 32; + const int num_kb = K / BLOCK_K; + const int num_sblk = N / 128; + const int rank = (int)cluster_ctarank(); + const int n0 = (blockIdx.x / CL) * TILE_N; // cluster's output column base + const int kb0 = (rank * num_kb) / CL; // this CTA's K-block range + const int kb1 = ((rank + 1) * num_kb) / CL; + + // LANE-PARALLEL MBARRIER INIT (this version): the 78 barriers are contiguous in smem (full[6] | full1[6] | + // empty[6] | tfull[6] | tempty[6] | ready[24] | recv[8] | sfull[8] | sempty[8]); warp 0's 32 lanes init them in + // parallel (<= 3 each, was 78 serial inits by thread 0 ahead of the head W L2 prefetch). Every lane fences its own + // inits (fence.mbarrier_init applies to the executing thread's prior inits); __syncthreads / the cluster barrier + // below publish them exactly as before. + if (threadIdx.x < 32) { + constexpr int NBAR = 3 * STAGES + 4 * NBUF + 24 + 8 + 2 * SC_SLOTS; + static_assert(NBAR == 78, "barrier count"); + for (int i = threadIdx.x; i < NBAR; i += 32) { + uint32_t c = 1; + if (i >= 3 * STAGES + 2 * NBUF && i < 3 * STAGES + 4 * NBUF) c = NUM_EPI_WARPS / 2; // tempty + else if (i >= NBAR - 2 * SC_SLOTS && i < NBAR - SC_SLOTS) c = 64; // sfull + else if (i >= NBAR - SC_SLOTS) c = NUM_EPI_WARPS; // sempty + mbar_init(full_bar + i, c); + } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + } + if (threadIdx.x == 0) { + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_a)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_b)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_out)) : "memory"); + // HEAD W L2 PREFETCH (pro k-blocks): thread 0 waits for the previous grid itself (PDL) and starts the DRAM + // fetch of this CTA's first W k-slabs into L2 before TMEM alloc / __syncthreads / cluster barrier / role + // dispatch, so the first ring stages (DRAM-latency + startup-queueing bound) land sooner. Pure hint. + // (this version) issued BEFORE griddepcontrol.wait: W is a read-only input never written by a preceding grid, + // and an L2 prefetch is a pure hint (no smem / barrier / visible state) -> safe to overlap the previous grid's tail. + // Prefetched with an L2 evict_first policy (W is streamed once per call, same policy as its TMA loads). + if ((pro & 0xff) > 0) { + uint64_t pol_pf; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_pf)); + for (int kb = kb0; kb < kb1 && kb < kb0 + (pro & 0xff); ++kb) { +#pragma unroll + for (int wb = 0; wb < W_NBOX; ++wb) tma_prefetch_l2_hint(&tmap_b, kb * BLOCK_K, n0 + wb * W_BOX_ROWS, pol_pf); + } + } + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(smem_u32(tmem_slot)), + "r"(TMEM_COLS)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + fence_before(); + __syncthreads(); + // PDL: everything above overlaps the previous grid's tail; no global memory touched before this wait. + asm volatile("griddepcontrol.wait;" ::: "memory"); + // EARLY PDL TRIGGER (cross-call overlap): the whole grid is resident (1 CTA/SM), so the dependent grid (next call) + // may start its prologue + pre-wait W L2 prefetch on SMs as soon as they free up; it still griddepcontrol.wait's + // for this grid's full completion (and memory flush) before touching any global state. + asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); + // HEAD A L2 PREFETCH: right after the PDL wait (A may be produced by the preceding grid), the otherwise idle + // warp 2 lane 0 issues L2-only bulk-tensor prefetches of this CTA's first 3 A k-blocks (evict_last: the same + // A k-slab is read by all 45 clusters' CTAs of this rank). Pure hint: no smem / barrier / visible state. + if (threadIdx.x == 64) { + uint64_t pol_ap; + asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol_ap)); + for (int kb = kb0; kb < kb1 && kb < kb0 + 3; ++kb) tma_prefetch_l2_hint(&tmap_a, kb * BLOCK_K, 0, pol_ap); + } + cluster_arrive_relaxed(); // #1 arrive (RELAXED: inits published by fence.mbarrier_init.release.cluster): barriers initialised (waited on only before the first remote op) + fence_after(); + const uint32_t tmem_base = __shfl_sync(0xffffffffu, *tmem_slot, 0); + + if (warp < EPI_WARP0) { + asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;" ::"n"(REGS_CTRL)); + if (warp == 0 && lane == 0) { + // ------------------------------------------------ TMA producer + uint64_t pol_a, pol_w; + // pro bits 8-9: A L2 policy (0 evict_last, 1 evict_first, 2 evict_normal) + const int apol = (pro >> 8) & 3; + if (apol == 1) asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_a)); + else if (apol == 2) asm volatile("createpolicy.fractional.L2::evict_normal.b64 %0, 1.0;" : "=l"(pol_a)); + else asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol_a)); + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_w)); + // LEAN PRODUCER: hoisted 32-bit full/empty barrier + ring bases, running stage / phase counters + // (no per-kb % / div or generic->shared conversions). Same loads, same barriers (bit-identical). + const uint32_t full0 = smem_u32(full_bar), empty0 = smem_u32(empty_bar), ring0 = smem_u32(smem); + const uint64_t mb_a = reinterpret_cast(&tmap_a), mb_b = reinterpret_cast(&tmap_b); + const uint32_t f1b0 = smem_u32(full1_bar); + const int ntail = (kb1 - kb0) < TAIL_KB ? (kb1 - kb0) : TAIL_KB; + const int kbt = kb1 - ntail; // first tail k-block + // TMA of W box wb (40 rows) of k-block kx into stage sa, completion on barrier fb + auto load_w = [&](uint32_t sa, int kx, int wb, uint32_t fb) __attribute__((always_inline)) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(sa + (uint32_t)(TILE_A_BYTES + wb * W_HALF_BYTES)), + "l"(mb_b), "r"(kx), "r"(n0 + wb * W_BOX_ROWS), "r"(fb), "l"(pol_w) + : "memory"); + }; + // W160: box of `rows` rows (map = tmap_bw 160 rows / tmap_bh 80 rows) at W row offset r0 into stage sa + auto load_wb = [&](uint32_t sa, uint64_t mp, int kx, int r0, uint32_t fb) __attribute__((always_inline)) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(sa + (uint32_t)(TILE_A_BYTES + r0 * BLOCK_K)), + "l"(mp), "r"(kx), "r"(n0 + r0), "r"(fb), "l"(pol_w) + : "memory"); + }; + const uint64_t mb_bw = reinterpret_cast(&tmap_bw), mb_bh = reinterpret_cast(&tmap_bh); + auto load_a = [&](uint32_t sa, int kx, uint32_t fb) __attribute__((always_inline)) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(sa), + "l"(mb_a), "r"(kx), "r"(0), "r"(fb), "l"(pol_a) + : "memory"); + }; + auto expect = [&](uint32_t fb, uint32_t bytes) __attribute__((always_inline)) { + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(fb), "r"(bytes) : "memory"); + }; + uint32_t s = 0, ph = 0; + // OOB A rows (>= M) / W rows (>= N, last tile) zero-filled, still counted in the tx bytes + for (int kb = kb0; kb < kbt; ++kb) { + const uint32_t fb = full0 + s * 8u, fb1 = f1b0 + s * 8u; + mbar_wait_sleep_u32(empty0 + s * 8u, ph ^ 1); + const uint32_t sa = ring0 + s * (uint32_t)STAGE_BYTES; + const int kx = kb * BLOCK_K; + if constexpr (W160) { + // whole 160-row W slab as ONE box + A on full; full1 completed by a plain arrive (full covers all bytes) + expect(fb, (uint32_t)TILE_A_BYTES + 2 * WH_BYTES); + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(fb1) : "memory"); + load_wb(sa, mb_bw, kx, 0, fb); + load_a(sa, kx, fb); + } else if constexpr (W2X80) { + // W2X80: W slab as TWO 80-row boxes (10 KB each), one per column half: rows [0,80) (+A) on full, + // rows [80,160) on full1 (same barrier split / bytes as the 4 x 40 layout, half the TMA box count) + expect(fb, (uint32_t)TILE_A_BYTES + WH_BYTES); + expect(fb1, WH_BYTES); + load_wb(sa, mb_bh, kx, 0, fb); + load_wb(sa, mb_bh, kx, EPI_COLS, fb1); + load_a(sa, kx, fb); + } else { + expect(fb, (uint32_t)TILE_A_BYTES + WH_BYTES); + expect(fb1, WH_BYTES); + // W slab as FOUR 40-row boxes (5 KB each, 1024-aligned): boxes 0,1 (+A) on full, boxes 2,3 on full1 + load_w(sa, kx, 0, fb); + load_w(sa, kx, 1, fb); + load_w(sa, kx, 2, fb1); + load_w(sa, kx, 3, fb1); + load_a(sa, kx, fb); + } + if (++s == STAGES) { s = 0; ph ^= 1; } + } + // N-chunked tail: warpgroup 0's operands (A + W rows [0,80)) of ALL tail k-blocks first ... + const uint32_t st0 = s; + for (int kb = kbt; kb < kb1; ++kb) { + const uint32_t fb = full0 + s * 8u; + mbar_wait_sleep_u32(empty0 + s * 8u, ph ^ 1); + const uint32_t sa = ring0 + s * (uint32_t)STAGE_BYTES; + const int kx = kb * BLOCK_K; + expect(fb, (uint32_t)TILE_A_BYTES + WH_BYTES); + if constexpr (W160 || W2X80) load_wb(sa, mb_bh, kx, 0, fb); + else { + load_w(sa, kx, 0, fb); + load_w(sa, kx, 1, fb); + } + load_a(sa, kx, fb); + if (++s == STAGES) { s = 0; ph ^= 1; } + } + // ... then warpgroup 1's W rows [80,160) into the same (still held) stages + s = st0; + for (int kb = kbt; kb < kb1; ++kb) { + const uint32_t fb1 = f1b0 + s * 8u; + const uint32_t sa = ring0 + s * (uint32_t)STAGE_BYTES; + const int kx = kb * BLOCK_K; + expect(fb1, WH_BYTES); + if constexpr (W160 || W2X80) load_wb(sa, mb_bh, kx, EPI_COLS, fb1); + else { + load_w(sa, kx, 2, fb1); + load_w(sa, kx, 3, fb1); + } + if (++s == STAGES) s = 0; + } + } else if (warp == 1) { + // ------------------------------------------------ MMA issuer (whole warp 1, elect.sync-predicated MMA / commit) + // instr descriptor: D=f32, A=B=e4m3, K-major both, N>>3 @17, M>>4 @24 + const uint32_t idesc = (1u << 4) | ((uint32_t)(TILE_N >> 3) << 17) | ((uint32_t)(BLOCK_M >> 4) << 24); +#if 1 // (N-chunked tail requires the fused issuer) + // FUSED ISSUE (M128C_FUSED_ISSUE=1, as kernel_m256v): barrier / descriptor addresses hoisted as 32-bit values, + // running stage/phase/buffer counters (no % / div), spin wait on operands-full (normally already resident), + // suspend-hinted wait on the TMEM hand-off, and the 4 K32 MMAs + both commits issued as ONE asm block. + const uint32_t full0 = smem_u32(full_bar), full10 = smem_u32(full1_bar), empty0 = smem_u32(empty_bar); + const uint32_t tfull0 = smem_u32(tfull_bar), tempty0 = smem_u32(tempty_bar); + const uint64_t adesc0 = make_sdesc(smem_u32(smem)); + constexpr uint64_t BOFF = TILE_A_BYTES >> 4, SOFF = STAGE_BYTES >> 4, HOFF = WH_BYTES >> 4; + const uint32_t idesc_h = (1u << 4) | ((uint32_t)(EPI_COLS >> 3) << 17) | ((uint32_t)(BLOCK_M >> 4) << 24); + auto wspin = [&](uint32_t a, uint32_t p) __attribute__((always_inline)) { + asm volatile( + "{\n.reg .pred p;\nWF_%=:\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n@!p bra WF_%=;\n}\n" + ::"r"(a), "r"(p) : "memory"); + }; + auto wsleep = [&](uint32_t a, uint32_t p) __attribute__((always_inline)) { + asm volatile( + "{\n.reg .pred p;\nWT_%=:\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n@!p bra WT_%=;\n}\n" + ::"r"(a), "r"(p), "n"(0x989680) : "memory"); + }; + // 4 K32 MMAs (accumulate from 0) + up to 3 commits (c1, c2 used iff nc >= 2 / 3), one elected thread + auto mma4 = [&](uint32_t d, uint64_t ad, uint64_t bd, uint32_t id, uint32_t c0, uint32_t c1, uint32_t c2, + uint32_t nc) __attribute__((always_inline)) { + asm volatile( + "{\n" + ".reg .pred pf, pt, e, q1, q2;\n" + "setp.eq.u32 pt, 1, 1;\n" + "setp.eq.u32 pf, 1, 0;\n" + "elect.sync _|e, 0xffffffff;\n" + "setp.ge.and.u32 q1, %13, 2, e;\n" + "setp.ge.and.u32 q2, %13, 3, e;\n" + "@e tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %3, pf;\n" + "@e tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %4, %5, %3, pt;\n" + "@e tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %6, %7, %3, pt;\n" + "@e tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %8, %9, %3, pt;\n" + "@e tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%10];\n" + "@q1 tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%11];\n" + "@q2 tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%12];\n" + "}\n" ::"r"(d), + "l"(ad), "l"(bd), "r"(id), "l"(ad + 2), "l"(bd + 2), "l"(ad + 4), "l"(bd + 4), "l"(ad + 6), "l"(bd + 6), + "r"(c0), "r"(c1), "r"(c2), "r"(nc) + : "memory"); + }; + const int ntail = (kb1 - kb0) < TAIL_KB ? (kb1 - kb0) : TAIL_KB; + const int kbt = kb1 - ntail; + uint32_t s = 0, ph = 0, b = 0, bph = 0; + for (int kb = kb0; kb < kbt; ++kb) { + // full-width k-block: both column halves of TMEM buffer b, both operand halves + const uint64_t ad = adesc0 + (uint64_t)s * SOFF, bd = ad + BOFF; + wspin(full0 + s * 8, ph); + wspin(full10 + s * 8, ph); + wsleep(tempty0 + (b * 2) * 8, bph ^ 1); + wsleep(tempty0 + (b * 2 + 1) * 8, bph ^ 1); + fence_after(); + // TFULL-FIRST commit order: promotion hand-offs before the stage release + mma4(tmem_base + b * (uint32_t)TILE_N, ad, bd, idesc, tfull0 + (b * 2) * 8, tfull0 + (b * 2 + 1) * 8, + empty0 + s * 8, 3u); + if (++s == STAGES) { s = 0; ph ^= 1; } + if (++b == NBUF) { b = 0; bph ^= 1; } + } + // N-chunked tail, phase 1: column half 0 (W rows [0,80), N=80) of every tail k-block + const uint32_t s_t = s, ph_t = ph, b_t = b, bph_t = bph; + for (int kb = kbt; kb < kb1; ++kb) { + const uint64_t ad = adesc0 + (uint64_t)s * SOFF, bd = ad + BOFF; + wspin(full0 + s * 8, ph); + wsleep(tempty0 + (b * 2) * 8, bph ^ 1); + fence_after(); + mma4(tmem_base + b * (uint32_t)TILE_N, ad, bd, idesc_h, tfull0 + (b * 2) * 8, 0u, 0u, 1u); + if (++s == STAGES) { s = 0; ph ^= 1; } + if (++b == NBUF) { b = 0; bph ^= 1; } + } + // phase 2: column half 1 (W rows [80,160)) of the same k-blocks, then release the stages + s = s_t; ph = ph_t; b = b_t; bph = bph_t; + for (int kb = kbt; kb < kb1; ++kb) { + const uint64_t ad = adesc0 + (uint64_t)s * SOFF, bd = ad + BOFF + HOFF; + wspin(full10 + s * 8, ph); + wsleep(tempty0 + (b * 2 + 1) * 8, bph ^ 1); + fence_after(); + mma4(tmem_base + b * (uint32_t)TILE_N + EPI_COLS, ad, bd, idesc_h, tfull0 + (b * 2 + 1) * 8, empty0 + s * 8, + 0u, 2u); + if (++s == STAGES) { s = 0; ph ^= 1; } + if (++b == NBUF) { b = 0; bph ^= 1; } + } +#else + uint32_t it = 0; + int b = 0; + uint32_t bph = 0; // phase of buffer use round (it / NBUF) & 1 + for (int kb = kb0; kb < kb1; ++kb, ++it) { + const int s = it % STAGES; + const uint32_t ph = (it / STAGES) & 1; + mbar_wait_sleep(&full_bar[s], ph); + const uint32_t sa = smem_u32(smem + s * STAGE_BYTES); + const uint64_t adesc = make_sdesc(sa); + const uint64_t bdesc = make_sdesc(sa + TILE_A_BYTES); + const uint32_t tmem_d = tmem_base + b * TILE_N; + mbar_wait_sleep(&tempty_bar[b], bph ^ 1); + fence_after(); +#pragma unroll + for (int k = 0; k < BLOCK_K / 32; ++k) mma_f8(tmem_d, adesc + 2 * k, bdesc + 2 * k, idesc, k > 0 ? 1u : 0u); + mma_commit(&empty_bar[s]); + mma_commit(&tfull_bar[b]); + if (++b == NBUF) { b = 0; bph ^= 1; } + } +#endif + } else if (warp >= 2) { + // ------------------------------------------------ scale producer (warps 2,3; 64 threads) + // slot: [0,128) = sx[row, kb] (0 for rows >= M), [128,132) = sw[kb, blk] for {g0 A, g0 B, g1 A, g1 B} + const int lt = threadIdx.x - 64; + const int ra = lt, rb = lt + 64; + const float* pa = scale_x + (size_t)(ra < M ? ra : 0) * num_kb; + const float* pb = scale_x + (size_t)(rb < M ? rb : 0) * num_kb; + const int gg = (lt >> 1) & 1; + const int blk = ((n0 + gg * EPI_COLS) >> 7) + (lt & 1); + const int wj = blk < num_sblk ? blk : num_sblk - 1; // cols >= N (last tile) are zero: any valid block + uint32_t it = 0; + for (int kb = kb0; kb < kb1; kb += 4) { + const int nq = (kb1 - kb) < 4 ? (kb1 - kb) : 4; + float xa[4], xb[4], wv[4]; + if (nq == 4 && ((kb | num_kb) & 3) == 0) { + // POWER: one 16 B sx load per row per 4 k-blocks (row base 16B-aligned since num_kb % 4 == 0) + const float4 va = ra < M ? __ldg(reinterpret_cast(pa + kb)) : make_float4(0.f, 0.f, 0.f, 0.f); + const float4 vb = rb < M ? __ldg(reinterpret_cast(pb + kb)) : make_float4(0.f, 0.f, 0.f, 0.f); + xa[0] = va.x; xa[1] = va.y; xa[2] = va.z; xa[3] = va.w; + xb[0] = vb.x; xb[1] = vb.y; xb[2] = vb.z; xb[3] = vb.w; +#pragma unroll + for (int q = 0; q < 4; ++q) wv[q] = __ldg(scale_w + (size_t)(kb + q) * num_sblk + wj); + } else { +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + xa[q] = ra < M ? __ldg(pa + kb + q) : 0.f; + xb[q] = rb < M ? __ldg(pb + kb + q) : 0.f; + wv[q] = __ldg(scale_w + (size_t)(kb + q) * num_sblk + wj); + } + } + } +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + const uint32_t ii = it + q; + const int slot = ii % SC_SLOTS; + mbar_wait_sleep(&sempty_bar[slot], ((ii / SC_SLOTS) & 1) ^ 1); + float* d = sc_ring + slot * SC_SLOT_FLOATS; + d[lt] = xa[q]; + d[lt + 64] = xb[q]; + if (lt < 4) d[128 + lt] = wv[q]; + mbar_arrive(&sfull_bar[slot]); + } + } + it += nq; + } + } + __syncwarp(); + cluster_wait(); // #1 + cluster_arrive_relaxed(); // #2 (end): no CTA exits while peers may still copy from / into its smem + cluster_wait(); + } else { + // ------------------------------------------------ promotion (warps 4..11) + asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;" ::"n"(REGS_EPI)); + const int g = (warp - EPI_WARP0) >> 2; + const int sub = warp & 3; + const int row = sub * 32 + lane; + // warp-uniform TMEM base (shfl broadcast -> uniform register, no per-kb rematerialisation) + const uint32_t taddr_b0 = __shfl_sync(0xffffffffu, tmem_base + ((uint32_t)(sub * 32) << 16) + g * EPI_COLS, 0); + // chunk c (16 cols) uses scale block B iff c >= cb (precomputed per tile/warpgroup, warp-uniform) + const int cbase = n0 + g * EPI_COLS; + const int cb = (((cbase >> 7) + 1) * 128 - cbase) >> 4; + // SASS AUDIT: warp-uniform 32-bit bases (barrier region / scale ring) + immediates in the k-loop instead of + // per-kb generic-pointer math (&bar[i] -> cvta). Barrier offsets from full_bar: tfull 2*STAGES*8, tempty +NBUF*8, + // ready +NBUF*8, recv +8*8, sfull +16*8, sempty +SC_SLOTS*8. + const uint32_t bar_u = __shfl_sync(0xffffffffu, smem_u32(full_bar), 0); + constexpr uint32_t TFULL_OFF = 3 * STAGES * 8, TEMPTY_OFF = TFULL_OFF + 2 * NBUF * 8; + constexpr uint32_t SFULL_OFF = TEMPTY_OFF + 2 * NBUF * 8 + 24 * 8 + 8 * 8, SEMPTY_OFF = SFULL_OFF + SC_SLOTS * 8; + const uint32_t sc_u = __shfl_sync(0xffffffffu, smem_u32(sc_ring), 0); + const uint32_t sc_row = sc_u + (uint32_t)row * 4u; // my sx within a slot + const uint32_t sc_w = sc_u + 512u + (uint32_t)g * 8u; // my warpgroup's sw pair within a slot (uniform) + float acc[EPI_COLS]; +#pragma unroll + for (int j = 0; j < EPI_COLS; ++j) acc[j] = 0.f; + uint32_t it = 0; + int b = 0; + uint32_t bph = 0; + // EARLY READY: warpgroup 0's reduce region = ring stages of local k-blocks n-6..n-4 (pre-tail). Once the tfull of + // local k-block n-4 (= kb1 - TAIL_KB - 1) is observed, every MMA reading those stages completed and no later TMA + // load targets them, so the owner warp may arm its receive barrier and signal 'ready' to the pushers right there. + const int qe = sub * 2 + g; + const int cown_e = rs_chunk(qe, rank); + const uint32_t own_bytes_e = FP24 ? pushfmt::slice_bytes(cown_e < 2 ? 32 : 16) : rawpush::slice_bytes(cown_e < 2 ? 32 : 16); + const bool early_ok = EARLY && g == 0 && (kb1 - kb0) >= STAGES; + const int kb_early = kb1 - TAIL_KB - 1; + auto signal_ready = [&]() __attribute__((always_inline)) { + cluster_wait(); // #1: peers' barriers initialised + if (lane == 0) { + mbar_arrive_expect_tx(&recv_bar[qe], 2u * own_bytes_e); + for (int d = 1; d < CL; ++d) + mbar_arrive_remote_relaxed(mapa_rank(smem_u32(&ready_bar[qe * 3 + rank]), (uint32_t)((rank + d) % CL))); + } + __syncwarp(); + }; + for (int kb = kb0; kb < kb1; ++kb, ++it) { + const uint32_t slot = it % SC_SLOTS; + mbar_wait_sleep_u32(bar_u + SFULL_OFF + slot * 8u, (it / SC_SLOTS) & 1); + const uint32_t soff = slot * (uint32_t)(SC_SLOT_FLOATS * 4); + float sxv, wA, wB; + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(sxv) : "r"(sc_row + soff) : "memory"); + asm volatile("ld.shared.v2.f32 {%0, %1}, [%2];" : "=f"(wA), "=f"(wB) : "r"(sc_w + soff) : "memory"); + __syncwarp(); + if (lane == 0) mbar_arrive_u32(bar_u + SEMPTY_OFF + slot * 8u); + const float sA = sxv * wA, sB = sxv * wB; + mbar_wait_sleep_u32(bar_u + TFULL_OFF + (uint32_t)(b * 2 + g) * 8u, bph); + fence_after(); + if (early_ok && kb == kb_early) signal_ready(); + const uint32_t taddr = taddr_b0 + (uint32_t)(b * TILE_N); + uint32_t r[NCHUNK][16]; +#pragma unroll + for (int c = 0; c < NCHUNK; ++c) TMEM_LD16(taddr + c * 16, r[c]); + tmem_ld_wait(); + fence_before(); + __syncwarp(); + if (lane == 0) mbar_arrive_relaxed_u32(bar_u + TEMPTY_OFF + (uint32_t)(b * 2 + g) * 8u); // TMEM buffer free for the MMA 3 k-blocks ahead +#pragma unroll + for (int c = 0; c < NCHUNK; ++c) { + const float sc = c >= cb ? sB : sA; + const float2 ss = make_float2(sc, sc); +#pragma unroll + for (int j = 0; j < 16; j += 2) ffma2(acc[c * 16 + j], acc[c * 16 + j + 1], r[c][j], r[c][j + 1], ss); + } + if (++b == NBUF) { b = 0; bph ^= 1; } + } + // ---- split-K REDUCE-SCATTER by ASYNC DSMEM PUSH (32-col chunk granularity). Warp q = sub*2 + g holds 32 rows x + // 80 cols = 3 chunks c: cols [0,32), [32,64), [64,80) (widths 32/32/16). Chunk c of warp q is OWNED by rank + // o = rs_owner(q, c) (skewed, see rs_owner), so each warp owns exactly ONE chunk on each rank (rank totals 192/224/224) and + // every warp pushes its 2 non-owned chunks (exact fp32, 4 KB / 2 KB bulk copies) -- one push per peer instead of + // 1-2 x 2 KB -- adds the 2 received copies of its owned chunk and TMA-stores it as 32x16 bf16 boxes. + // Ring layout (idle after the last tfull): recv [q*8K + j*4K) (j = source index), push staging + // [64K + q*10K + c*4K), bf16 staging [144K + q*2K + h*1K) (h = 16-col sub-box). + static_assert(144 * 1024 + 16 * 1024 <= STAGES * STAGE_BYTES, "reduce-scatter areas fit in ring"); + constexpr int NCH32 = 3; + const uint32_t ring = smem_u32(smem); + const int q = sub * 2 + g; + const int cown = rs_chunk(q, rank); // my owned chunk (0..2) + (void)cown; + // Per-warpgroup reduce regions: 3 ring stages each. Stage of local k-block i is i % STAGES; with n local k-blocks + // the tail occupies stages (n-3..n-1) % 6 = (n+3..n+5) % 6 (warpgroup 1's region, idle once warpgroup 1 is done) + // and stages (n..n+2) % 6 were last used by pre-tail k-blocks (warpgroup 0's region, idle once warpgroup 0 is done). + auto rstage = [&](int o, int i) -> uint32_t { + const int no = ((o + 1) * num_kb) / CL - (o * num_kb) / CL; + return ring + (uint32_t)((no + 3 * g + i) % STAGES) * (uint32_t)STAGE_BYTES; + }; + const uint32_t recv_me = rstage(rank, 0) + (uint32_t)sub * 8192u; + const uint32_t push_me = sub < 3 ? rstage(rank, 1) + (uint32_t)sub * 10240u : rstage(rank, 2); + const uint32_t bf_me = rstage(rank, 2) + 10240u + (uint32_t)sub * 2048u; + if (!early_ok) signal_ready(); + (void)push_me; +#pragma unroll + for (int c = 0; c < NCH32; ++c) { + if (rs_owner(q, c) == rank) continue; + const int o = rs_owner(q, c); + mbar_wait_cluster(smem_u32(&ready_bar[q * 3 + o]), 0); // owner o's ring idle (every lane acquires) + const uint32_t j = (uint32_t)((rank - o + CL - 1) % CL); // my source index at owner o + const uint32_t mb = mapa_rank(smem_u32(&recv_bar[q]), (uint32_t)o); + const uint32_t dst = + mapa_rank(rstage(o, 0) + (uint32_t)sub * 8192u + j * 4096u, (uint32_t)o) + (uint32_t)lane * 16u; + const int nv = c < 2 ? 8 : 4; + if constexpr (FP24) { + // FP24 push (fp24_push.h layout): 16-col group gg -> 12 packed words -> 3 x 16 B st.async at + // ((gg*3 + cc)*32 + lane)*16 +#pragma unroll + for (int gg = 0; gg < 2; ++gg) { + if (gg >= nv / 4) continue; + uint32_t wv[12]; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const float* a = acc + c * 32 + gg * 16 + 4 * i; + const uint32_t t0 = pushfmt::rnd24(a[0]), t1 = pushfmt::rnd24(a[1]); + const uint32_t t2 = pushfmt::rnd24(a[2]), t3 = pushfmt::rnd24(a[3]); + wv[3 * i + 0] = __byte_perm(t0, t1, 0x5321); + wv[3 * i + 1] = __byte_perm(t1, t2, 0x6532); + wv[3 * i + 2] = __byte_perm(t2, t3, 0x7653); + } +#pragma unroll + for (int cc = 0; cc < 3; ++cc) + asm volatile("st.async.shared::cluster.mbarrier::complete_tx::bytes.v4.b32 [%0], {%1, %2, %3, %4}, [%5];" + ::"r"(dst + (uint32_t)((gg * 3 + cc) * 512)), "r"(wv[4 * cc]), "r"(wv[4 * cc + 1]), + "r"(wv[4 * cc + 2]), "r"(wv[4 * cc + 3]), "r"(mb) + : "memory"); + } + continue; + } +#pragma unroll + for (int v = 0; v < 8; ++v) { + if (v >= nv) continue; + const float* a = acc + c * 32 + 4 * v; + asm volatile("st.async.shared::cluster.mbarrier::complete_tx::bytes.v4.f32 [%0], {%1, %2, %3, %4}, [%5];" + ::"r"(dst + (uint32_t)v * 512u), "f"(a[0]), "f"(a[1]), "f"(a[2]), "f"(a[3]), "r"(mb) + : "memory"); + } + } + __syncwarp(); + mbar_wait_sleep(&recv_bar[q], 0); +#pragma unroll + for (int c = 0; c < NCH32; ++c) { + if (rs_owner(q, c) != rank) continue; + const uint32_t src = recv_me; + if constexpr (FP24) { + if (c < 2) { + pushfmt::add<32>(acc + c * 32, src, lane); + pushfmt::add<32>(acc + c * 32, src + 4096u, lane); + } else { + pushfmt::add<16>(acc + 64, src, lane); + pushfmt::add<16>(acc + 64, src + 4096u, lane); + } + } else if (c < 2) { + rawpush::add<32>(acc + c * 32, src, lane); + rawpush::add<32>(acc + c * 32, src + 4096u, lane); + } else { + rawpush::add<16>(acc + 64, src, lane); + rawpush::add<16>(acc + 64, src + 4096u, lane); + } + } + fence_before(); + cluster_arrive_relaxed(); // #2: all data received by this warp consumed (its inbound copies complete) +#pragma unroll + for (int c = 0; c < NCH32; ++c) { + if (rs_owner(q, c) != rank) continue; + const int nsb = c < 2 ? 2 : 1; // 16-col sub-boxes +#pragma unroll + for (int sb = 0; sb < 2; ++sb) { + if (sb >= nsb) continue; + const uint32_t bst = bf_me + (uint32_t)sb * 1024u; +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int e = c * 32 + sb * 16 + h * 8; + __nv_bfloat162 h0 = __floats2bfloat162_rn(acc[e + 0], acc[e + 1]); + __nv_bfloat162 h1 = __floats2bfloat162_rn(acc[e + 2], acc[e + 3]); + __nv_bfloat162 h2 = __floats2bfloat162_rn(acc[e + 4], acc[e + 5]); + __nv_bfloat162 h3 = __floats2bfloat162_rn(acc[e + 6], acc[e + 7]); + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(bst + lane * 32 + h * 16), + "r"(*reinterpret_cast(&h0)), "r"(*reinterpret_cast(&h1)), + "r"(*reinterpret_cast(&h2)), "r"(*reinterpret_cast(&h3)) + : "memory"); + } + } + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + if (lane == 0) { + const int nsb = cown < 2 ? 2 : 1; + for (int sb = 0; sb < nsb; ++sb) { + // 32 rows x 16 cols box; rows >= M / cols >= N clipped by the TMA unit + tma_store_2d_u32(&tmap_out16, bf_me + (uint32_t)sb * 1024u, + n0 + g * EPI_COLS + cown * 32 + sb * 16, sub * 32); + } + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); + } + __syncwarp(); + cluster_wait(); + } + // (end cluster barrier #2 passed by every warp: no DSMEM traffic remains) + if (warp == 1) { + fence_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tmem_base), "r"(TMEM_COLS)); + } +} + +static void make_tmap(CUtensorMap* map, const void* ptr, uint64_t rows, uint64_t K, uint32_t box_rows, + CUtensorMapL2promotion promo = CU_TENSOR_MAP_L2_PROMOTION_L2_256B) { + cuuint64_t dims[2] = {K, rows}; + cuuint64_t strides[1] = {K}; + cuuint32_t box[2] = {BLOCK_K, box_rows}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(map, CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, const_cast(ptr), dims, strides, + box, estr, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, + promo, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled failed: %d\n", (int)r); +} + +} // namespace + +bool fp8_m128c_supported(int M, int N, int K) { + return M >= 1 && M <= BLOCK_M && N % 128 == 0 && K % BLOCK_K == 0 && K / BLOCK_K >= CL; +} + +void launch_fp8_m128c(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, int K, + cudaStream_t stream, int pro, int var) { + static bool attr = false; + if (!attr) { + cudaFuncSetAttribute(fp8_m128c_kernel<0>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaFuncSetAttribute(fp8_m128c_kernel<1>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaFuncSetAttribute(fp8_m128c_kernel<2>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaFuncSetAttribute(fp8_m128c_kernel<3>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaFuncSetAttribute(fp8_m128c_kernel<4>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaFuncSetAttribute(fp8_m128c_kernel<9>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + attr = true; + } + CUtensorMap tbw, tbh; + CUtensorMap ta, tb, to, to16; + make_tmap(&ta, a, (uint64_t)M, (uint64_t)K, BLOCK_M); + { + // bf16 output map for the reduce-scatter chunk stores: box {16 cols (32 B), 32 rows}, no swizzle + cuuint64_t dims[2] = {(cuuint64_t)N, (cuuint64_t)M}; + cuuint64_t strides[1] = {(cuuint64_t)N * 2}; + cuuint32_t box[2] = {16, 32}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(&to16, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, out, dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled(out16) failed: %d\n", (int)r); + } + { + // bf16 output map: dims {N, M}, box {80 cols (160 B), 32 rows}, no swizzle + cuuint64_t dims[2] = {(cuuint64_t)N, (cuuint64_t)M}; + cuuint64_t strides[1] = {(cuuint64_t)N * 2}; + cuuint32_t box[2] = {(cuuint32_t)EPI_COLS, 32}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(&to, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, out, dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled(out) failed: %d\n", (int)r); + } + // pro bits 10-11: W tensor-map L2 promotion (0 256B, 1 none, 2 128B) + const int wpr = (pro >> 10) & 3; + make_tmap(&tb, w, (uint64_t)N, (uint64_t)K, W_BOX_ROWS, + wpr == 1 ? CU_TENSOR_MAP_L2_PROMOTION_NONE + : (wpr == 2 ? CU_TENSOR_MAP_L2_PROMOTION_L2_128B : CU_TENSOR_MAP_L2_PROMOTION_L2_256B)); + { + const CUtensorMapL2promotion wp = wpr == 1 ? CU_TENSOR_MAP_L2_PROMOTION_NONE + : (wpr == 2 ? CU_TENSOR_MAP_L2_PROMOTION_L2_128B : CU_TENSOR_MAP_L2_PROMOTION_L2_256B); + make_tmap(&tbw, w, (uint64_t)N, (uint64_t)K, TILE_N, wp); + make_tmap(&tbh, w, (uint64_t)N, (uint64_t)K, EPI_COLS, wp); + } + const int ntiles = (N + TILE_N - 1) / TILE_N; + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3(ntiles * CL, 1, 1); + cfg.blockDim = dim3(NUM_THREADS, 1, 1); + cfg.dynamicSmemBytes = SMEM_BYTES; + cfg.stream = stream; + cudaLaunchAttribute attr_l[2]; + attr_l[0].id = cudaLaunchAttributeClusterDimension; + attr_l[0].val.clusterDim.x = CL; + attr_l[0].val.clusterDim.y = 1; + attr_l[0].val.clusterDim.z = 1; + cfg.attrs = attr_l; + attr_l[1].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attr_l[1].val.programmaticStreamSerializationAllowed = 1; + cfg.numAttrs = 2; + auto kfn = var == 1 ? fp8_m128c_kernel<1> : var == 2 ? fp8_m128c_kernel<2> : var == 3 ? fp8_m128c_kernel<3> + : var == 4 ? fp8_m128c_kernel<4> : var == 9 ? fp8_m128c_kernel<9> : fp8_m128c_kernel<0>; + cudaLaunchKernelEx(&cfg, kfn, ta, tb, tbw, tbh, to, to16, sx, sw, reinterpret_cast<__nv_bfloat16*>(out), M, N, K, pro); +} diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128c.h b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128c.h new file mode 100644 index 0000000000000000000000000000000000000000..d321472035c5c2ed6edbe085d985689e1b0aebda --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128c.h @@ -0,0 +1,13 @@ +#pragma once +#include +// pro = number of head W k-slabs L2-prefetched by thread 0 before the CTA prologue (0 = off) +#ifndef M128C_PRO_DEFAULT +#define M128C_PRO_DEFAULT (5 | (1 << 8) | (1 << 10)) /* W map L2 promotion NONE */ // head W prefetch depth 8 (pre-PDL-wait, evict_first) +#endif +#ifndef M128C_VAR_DEFAULT +#define M128C_VAR_DEFAULT 9 /* FP24 push + W2X80 (2 x 80-row W boxes per kb; untried point between 1-box W160 and 4x40)*/ // // FP24 push; kernel variant bits (1 FP24 push, 2 early ready, 4 W160 boxes) +#endif +// M <= 128: 128x160 tiles (3 TMEM buffers), split-K 3 as a 3-CTA cluster, DSMEM partial reduction (kernel_m128c.cu). +bool fp8_m128c_supported(int M, int N, int K); +void launch_fp8_m128c(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, int K, + cudaStream_t stream, int pro = M128C_PRO_DEFAULT, int var = M128C_VAR_DEFAULT); diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128x2.cu b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128x2.cu new file mode 100644 index 0000000000000000000000000000000000000000..899efa6fcbd930e30af32bf0041881852b54a7e8 --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128x2.cu @@ -0,0 +1,530 @@ +// M <= 128 KERNEL "x2": TWO co-resident CTAs per SM so the tensor core interleaves two independent +// TMA -> MMA -> TMEM -> promotion pipelines (hides each CTA's TMEM hand-off latency). +// +// out[m, n] = sum_kb sx[m, kb] * sw[kb, n/128] * sum_{k in kb} A[m,k] * W[n,k] +// +// Work decomposition: tile = 128 rows (all M <= 128 tokens) x 128 cols (exactly one 128-col scale block). +// N/128 = 56 N-tiles, each split-K CL = 5 ways as a 5-CTA CLUSTER along K -> 280 CTAs (~2 per SM). +// Rank r streams k-blocks [r*nkb/5, (r+1)*nkb/5). +// Per-CTA resources sized for 2 CTAs/SM: 256 threads, smem ~102 KB (3-stage ring of A 16 KB + W 16 KB), +// TMEM 256 cols (2 partial buffers x 128 cols), setmaxnreg 56 (control WG) / 200 (promotion WG). +// Roles (8 warps): +// warp 0 : TMA producer (A 128x128 fp8 + W 128x128 fp8, 128B swizzle, OOB A rows zero-filled). +// warp 1 : TMEM alloc + single-thread tcgen05.mma kind::f8f6f4 M128 N128 K32 (4 per k-block), each k-block +// accumulated FRESH into TMEM buffer it&1. +// warps 2,3 : scale producer: per k-block s[row] = sx[row,kb] * sw[kb, nt] into an 8-slot smem ring. +// warps 4-7 : promotion (1 warpgroup, thread = tile row = TMEM lane, 128 fp32 acc regs): per k-block +// 8 x16 tcgen05.ld in a 2-deep software pipeline (4 wait::ld), acc += part * s (packed FFMA2), +// TMEM buffer released (one elected arrive per warp) after the last wait::ld. +// Split-K reduction by ASYNC DSMEM PUSH (FP24 = top 24 bits of fp32 per value, fp24_push.h): slot q = promotion warp sub (32 rows x +// 128 cols) is owned by cluster rank q (rank 4 owns none). Every non-owner warp packs its slice into its idle +// ring, waits the owner's 'ready' (owner ring idle), and issues one cp.async.bulk smem -> owner smem +// (complete_tx on the owner's recv mbarrier for that source). The owner adds the 4 slices, packs bf16 and +// TMA-stores one 32x128 box. One end-of-kernel cluster barrier keeps smem alive until all copies completed. +#include +#include +#include +#include +#include +#include "tmap_cache.h" +#include "kernel_m128x2.h" +#include "fp24_push.h" // fp24 push + +namespace { + +constexpr int BLOCK_M = 128; +constexpr int TILE_N = 128; +constexpr int BLOCK_K = 128; +constexpr int CL = 5; // cluster size = split-K factor +constexpr int STAGES = 3; +constexpr int TILE_A_BYTES = BLOCK_M * BLOCK_K; // 16 KB +constexpr int TILE_B_BYTES = TILE_N * BLOCK_K; // 16 KB +constexpr int STAGE_BYTES = TILE_A_BYTES + TILE_B_BYTES; +constexpr int NUM_EPI_WARPS = 4; +constexpr int EPI_WARP0 = 4; +constexpr int NUM_THREADS = 128 + NUM_EPI_WARPS * 32; // 256 +constexpr int TMEM_COLS = 256; // 2 buffers x 128 cols (two CTAs share the 512 cols) +constexpr int SC_SLOTS = 8; +constexpr int SC_BYTES = SC_SLOTS * BLOCK_M * 4; // 4 KB +constexpr int SMEM_BYTES = STAGES * STAGE_BYTES + SC_BYTES + 1024 /*align*/ + 512 /*barriers*/; +// post-mainloop ring layout: [0, 4*PSLOT) recv slots (source j), [4*PSLOT, 8*PSLOT) outgoing FP24 staging (q); +// bf16 output staging (owner warp, 8 KB) reuses recv slot 0 after the 4 received slices were added +constexpr uint32_t PSL_BYTES = pushfmt::slice_bytes(TILE_N); // FP24 slice (fp24_push.h) +constexpr uint32_t PSLOT = (PSL_BYTES + 127u) & ~127u; +constexpr uint32_t OUT_OFF = 4 * PSLOT; +constexpr uint32_t BF_OFF = 0; // bf16 staging reuses recv slot 0 once all 4 received slices were consumed +constexpr uint32_t BF_BOX = 32 * TILE_N * 2; // 8 KB +static_assert(8 * PSLOT <= (uint32_t)(STAGES * STAGE_BYTES) && BF_BOX <= PSLOT, "push areas fit in ring"); +static_assert(2 * (SMEM_BYTES + 1024) <= 233472, "two CTAs per SM"); +constexpr int REGS_CTRL = 56; +constexpr int REGS_EPI = 200; // 128*56 + 128*200 = 32768 = 128 regs x 256 threads (launch bound for 2 CTAs/SM) + +__device__ __forceinline__ uint32_t smem_u32(const void* p) { + return static_cast(__cvta_generic_to_shared(p)); +} +__device__ __forceinline__ uint32_t cluster_ctarank() { + uint32_t r; + asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(r)); + return r; +} +__device__ __forceinline__ void mbar_init(uint64_t* bar, uint32_t count) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(smem_u32(bar)), "r"(count)); +} +__device__ __forceinline__ void mbar_arrive_expect_tx(uint64_t* bar, uint32_t bytes) { + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(smem_u32(bar)), "r"(bytes) + : "memory"); +} +__device__ __forceinline__ void mbar_arrive(uint64_t* bar) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(smem_u32(bar)) : "memory"); +} +__device__ __forceinline__ void mbar_wait_sleep(uint64_t* bar, uint32_t parity) { + uint32_t addr = smem_u32(bar); + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITS_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITS_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +__device__ __forceinline__ void tma_load_2d_hint(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y, + uint64_t policy) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(smem_u32(dst)), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(smem_u32(bar)), "l"(policy) + : "memory"); +} +__device__ __forceinline__ uint64_t make_sdesc(uint32_t saddr) { + uint64_t d = 0; + d |= (uint64_t)((saddr & 0x3FFFF) >> 4); + d |= (uint64_t)1 << 16; + d |= (uint64_t)(1024 >> 4) << 32; // SBO: 8 rows x 128 B + d |= (uint64_t)1 << 46; // sm100 descriptor version + d |= (uint64_t)2 << 61; // SWIZZLE_128B + return d; +} +__device__ __forceinline__ void mma_f8(uint32_t tmem_d, uint64_t adesc, uint64_t bdesc, uint32_t idesc, + uint32_t accum) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "setp.ne.b32 p, %4, 0;\n" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %3, p;\n" + "}\n" ::"r"(tmem_d), + "l"(adesc), "l"(bdesc), "r"(idesc), "r"(accum)); +} +__device__ __forceinline__ void mma_commit(uint64_t* bar) { + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(smem_u32(bar)) + : "memory"); +} +__device__ __forceinline__ void fence_after() { asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void fence_before() { asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void ffma2(float& a0, float& a1, uint32_t x0, uint32_t x1, float2 ss) { + const float2 d = __ffma2_rn(make_float2(__uint_as_float(x0), __uint_as_float(x1)), ss, make_float2(a0, a1)); + a0 = d.x; + a1 = d.y; +} +__device__ __forceinline__ uint32_t mapa_rank(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; +} +__device__ __forceinline__ void cluster_arrive() { asm volatile("barrier.cluster.arrive.release.aligned;" ::: "memory"); } +__device__ __forceinline__ void cluster_wait() { asm volatile("barrier.cluster.wait.acquire.aligned;" ::: "memory"); } +// RELAXED TAIL (as kernel_m256c): the end barrier #2 arrive and the owner's 'ready' remote arrives publish no +// generic-proxy data (pushed slices are ordered by the recv mbarrier complete_tx, the output by the owner's bulk +// wait_group; the owner ring's last readers were MMAs whose completion was observed via tfull), so relaxed suffices. +__device__ __forceinline__ void cluster_arrive_relaxed() { asm volatile("barrier.cluster.arrive.relaxed.aligned;" ::: "memory"); } +__device__ __forceinline__ void mbar_arrive_remote_relaxed(uint32_t cluster_addr) { + asm volatile("mbarrier.arrive.relaxed.cluster.shared::cluster.b64 _, [%0];" ::"r"(cluster_addr) : "memory"); +} +__device__ __forceinline__ void mbar_arrive_remote(uint32_t cluster_addr) { + asm volatile("mbarrier.arrive.release.cluster.shared::cluster.b64 _, [%0];" ::"r"(cluster_addr) : "memory"); +} +__device__ __forceinline__ void mbar_wait_cluster(uint32_t addr, uint32_t parity) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITC_%=:\n" + "mbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITC_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +__device__ __forceinline__ void bulk_s2dsmem(uint32_t dst_cl, uint32_t src, uint32_t bytes, uint32_t mbar_cl) { + asm volatile("cp.async.bulk.shared::cluster.shared::cta.mbarrier::complete_tx::bytes [%0], [%1], %2, [%3];" ::"r"( + dst_cl), + "r"(src), "r"(bytes), "r"(mbar_cl) + : "memory"); +} +__device__ __forceinline__ void tma_store_2d_u32(const CUtensorMap* map, uint32_t src, int x, int y) { + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%1, %2}], [%3], %4;" ::"l"( + reinterpret_cast(map)), + "r"(x), "r"(y), "r"(src), "l"(pol) + : "memory"); +} + +#define TMEM_LD16(taddr, r) \ + 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"(taddr)) +__device__ __forceinline__ void tmem_ld_wait() { asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); } + +__device__ __forceinline__ void promo16(float* a, const uint32_t* r, float2 ss) { +#pragma unroll + for (int j = 0; j < 16; j += 2) ffma2(a[j], a[j + 1], r[j], r[j + 1], ss); +} + +__global__ void __launch_bounds__(NUM_THREADS, 2) + fp8_m128x2_kernel(const __grid_constant__ CUtensorMap tmap_a, const __grid_constant__ CUtensorMap tmap_b, + const __grid_constant__ CUtensorMap tmap_out, const float* __restrict__ scale_x, + const float* __restrict__ scale_w, __nv_bfloat16* __restrict__ out, int M, int N, int K) { + (void)out; // output written via tmap_out + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(smem_raw) + 1023) & ~uintptr_t(1023)); + float* sc_ring = reinterpret_cast(smem + STAGES * STAGE_BYTES); + uint64_t* full_bar = reinterpret_cast(smem + STAGES * STAGE_BYTES + SC_BYTES); + uint64_t* empty_bar = full_bar + STAGES; + uint64_t* tfull_bar = empty_bar + STAGES; // [2] + uint64_t* tempty_bar = tfull_bar + 2; // [2] + uint64_t* ready_bar = tempty_bar + 2; // [4 slots q]: owner rank q's ring idle -> may push slot q + uint64_t* recv_bar = ready_bar + 4; // [4 sources]: (owner only) slice from source j landed + uint64_t* sfull_bar = recv_bar + 4; // [SC_SLOTS] + uint64_t* sempty_bar = sfull_bar + SC_SLOTS; + uint32_t* tmem_slot = reinterpret_cast(sempty_bar + SC_SLOTS); + + const int warp = __shfl_sync(0xffffffffu, (int)(threadIdx.x / 32), 0); + const int lane = threadIdx.x % 32; + const int num_kb = K / BLOCK_K; + const int num_sblk = N / 128; + const int rank = (int)cluster_ctarank(); + const int nt = blockIdx.x / CL; + const int n0 = nt * TILE_N; + const int kb0 = (rank * num_kb) / CL; + const int kb1 = ((rank + 1) * num_kb) / CL; + + if (threadIdx.x == 0) { + for (int i = 0; i < STAGES; ++i) { + mbar_init(&full_bar[i], 1); + mbar_init(&empty_bar[i], 1); + } + for (int i = 0; i < 2; ++i) { + mbar_init(&tfull_bar[i], 1); + mbar_init(&tempty_bar[i], NUM_EPI_WARPS); + } + for (int i = 0; i < 4; ++i) { + mbar_init(&ready_bar[i], 1); + mbar_init(&recv_bar[i], 1); + } + for (int i = 0; i < SC_SLOTS; ++i) { + mbar_init(&sfull_bar[i], 64); + mbar_init(&sempty_bar[i], NUM_EPI_WARPS); + } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_a)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_b)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_out)) : "memory"); + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(smem_u32(tmem_slot)), + "r"(TMEM_COLS)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + fence_before(); + __syncthreads(); + asm volatile("griddepcontrol.wait;" ::: "memory"); // PDL: no global memory touched before this + cluster_arrive_relaxed(); // #1 arrive: barriers initialised (waited on before the first remote op) + fence_after(); + const uint32_t tmem_base = __shfl_sync(0xffffffffu, *tmem_slot, 0); + + if (warp < EPI_WARP0) { + asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;" ::"n"(REGS_CTRL)); + if (warp == 0 && lane == 0) { + // ------------------------------------------------ TMA producer + uint64_t pol_a, pol_w; + asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol_a)); + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_w)); + uint32_t it = 0; + for (int kb = kb0; kb < kb1; ++kb, ++it) { + const int s = it % STAGES; + const uint32_t ph = (it / STAGES) & 1; + mbar_wait_sleep(&empty_bar[s], ph ^ 1); + uint8_t* sa = smem + s * STAGE_BYTES; + mbar_arrive_expect_tx(&full_bar[s], STAGE_BYTES); // OOB A rows zero-filled, still counted + tma_load_2d_hint(sa + TILE_A_BYTES, &tmap_b, &full_bar[s], kb * BLOCK_K, n0, pol_w); + tma_load_2d_hint(sa, &tmap_a, &full_bar[s], kb * BLOCK_K, 0, pol_a); + } + } else if (warp == 1 && lane == 0) { + // ------------------------------------------------ MMA issuer (single thread) + const uint32_t idesc = (1u << 4) | ((uint32_t)(TILE_N >> 3) << 17) | ((uint32_t)(BLOCK_M >> 4) << 24); + uint32_t it = 0; + for (int kb = kb0; kb < kb1; ++kb, ++it) { + const int s = it % STAGES; + const uint32_t ph = (it / STAGES) & 1; + const int b = it & 1; + mbar_wait_sleep(&full_bar[s], ph); + const uint32_t sa = smem_u32(smem + s * STAGE_BYTES); + const uint64_t adesc = make_sdesc(sa); + const uint64_t bdesc = make_sdesc(sa + TILE_A_BYTES); + const uint32_t tmem_d = tmem_base + b * TILE_N; + mbar_wait_sleep(&tempty_bar[b], ((it >> 1) & 1) ^ 1); + fence_after(); +#pragma unroll + for (int k = 0; k < BLOCK_K / 32; ++k) mma_f8(tmem_d, adesc + 2 * k, bdesc + 2 * k, idesc, k > 0 ? 1u : 0u); + mma_commit(&empty_bar[s]); + mma_commit(&tfull_bar[b]); + } + } else if (warp >= 2) { + // ------------------------------------------------ scale producer (warps 2,3; 64 threads, rows lt, lt+64) + const int lt = threadIdx.x - 64; + const int ra = lt, rb = lt + 64; + const float* pa = scale_x + (size_t)(ra < M ? ra : 0) * num_kb; + const float* pb = scale_x + (size_t)(rb < M ? rb : 0) * num_kb; + const int wj = nt < num_sblk ? nt : num_sblk - 1; + uint32_t it = 0; + // POWER: batches aligned to 4 k-blocks (head batch up to the next multiple of 4), so full batches load sx + // as ONE float4 per row (row base 16B-aligned when num_kb % 4 == 0). + for (int kb = kb0, nq = 0; kb < kb1; kb += nq) { + nq = 4 - (kb & 3); + if (kb1 - kb < nq) nq = kb1 - kb; + float xa[4], xb[4], wv[4]; + if (nq == 4 && (num_kb & 3) == 0) { + const float4 va = ra < M ? __ldg(reinterpret_cast(pa + kb)) : make_float4(0.f, 0.f, 0.f, 0.f); + const float4 vb = rb < M ? __ldg(reinterpret_cast(pb + kb)) : make_float4(0.f, 0.f, 0.f, 0.f); + xa[0] = va.x; xa[1] = va.y; xa[2] = va.z; xa[3] = va.w; + xb[0] = vb.x; xb[1] = vb.y; xb[2] = vb.z; xb[3] = vb.w; +#pragma unroll + for (int q = 0; q < 4; ++q) wv[q] = __ldg(scale_w + (size_t)(kb + q) * num_sblk + wj); + } else { +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + xa[q] = ra < M ? __ldg(pa + kb + q) : 0.f; + xb[q] = rb < M ? __ldg(pb + kb + q) : 0.f; + wv[q] = __ldg(scale_w + (size_t)(kb + q) * num_sblk + wj); + } + } + } +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + const uint32_t ii = it + q; + const int slot = ii % SC_SLOTS; + mbar_wait_sleep(&sempty_bar[slot], ((ii / SC_SLOTS) & 1) ^ 1); + float* d = sc_ring + slot * BLOCK_M; + d[lt] = xa[q] * wv[q]; + d[lt + 64] = xb[q] * wv[q]; + mbar_arrive(&sfull_bar[slot]); + } + } + it += nq; + } + } + __syncwarp(); + cluster_wait(); // #1 + cluster_arrive_relaxed(); // #2 (end): no CTA exits while peers may still copy from / into its smem + cluster_wait(); + } else { + // ------------------------------------------------ promotion (warps 4..7) + asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;" ::"n"(REGS_EPI)); + const int sub = warp & 3; + const int row = sub * 32 + lane; + const uint32_t taddr_b0 = tmem_base + ((uint32_t)(sub * 32) << 16); + const uint32_t sc_mine = smem_u32(sc_ring) + row * 4; + float acc[TILE_N]; +#pragma unroll + for (int j = 0; j < TILE_N; ++j) acc[j] = 0.f; + uint32_t it = 0; + for (int kb = kb0; kb < kb1; ++kb, ++it) { + const int b = it & 1; + const uint32_t slot = it % SC_SLOTS; + mbar_wait_sleep(&sfull_bar[slot], (it / SC_SLOTS) & 1); + float s; + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(s) : "r"(sc_mine + slot * (BLOCK_M * 4)) : "memory"); + __syncwarp(); + if (lane == 0) mbar_arrive(&sempty_bar[slot]); + const float2 ss = make_float2(s, s); + mbar_wait_sleep(&tfull_bar[b], (it >> 1) & 1); + fence_after(); + const uint32_t taddr = taddr_b0 + (uint32_t)(b * TILE_N); + // 2-deep pipelined drain: chunk c+2 is loaded into the register set freed by chunk c's FFMA2s while + // chunk c+1's FFMA2s run; 4 wait::ld per k-block, 32 staging regs. + uint32_t ra[16], rb[16]; + TMEM_LD16(taddr + 0, ra); + TMEM_LD16(taddr + 16, rb); + tmem_ld_wait(); + promo16(acc + 0, ra, ss); + TMEM_LD16(taddr + 32, ra); + promo16(acc + 16, rb, ss); + TMEM_LD16(taddr + 48, rb); + tmem_ld_wait(); + promo16(acc + 32, ra, ss); + TMEM_LD16(taddr + 64, ra); + promo16(acc + 48, rb, ss); + TMEM_LD16(taddr + 80, rb); + tmem_ld_wait(); + promo16(acc + 64, ra, ss); + TMEM_LD16(taddr + 96, ra); + promo16(acc + 80, rb, ss); + TMEM_LD16(taddr + 112, rb); + tmem_ld_wait(); + fence_before(); + __syncwarp(); + if (lane == 0) mbar_arrive(&tempty_bar[b]); // TMEM buffer free + promo16(acc + 96, ra, ss); + promo16(acc + 112, rb, ss); + } + // ---- split-K reduction by async DSMEM push. Slot q = sub, owner rank q (ranks 0..3; rank 4 only pushes). + // The operand ring is idle once the last tfull was observed (all MMAs, hence all TMA loads, completed). + static_assert(pushfmt::slice_bytes(TILE_N) == PSL_BYTES, "push slice size"); + const uint32_t ring = smem_u32(smem); + const int q = sub; + const int owner = q; + cluster_wait(); // #1: peers' barriers initialised + if (owner != rank) { + const uint32_t stg = ring + OUT_OFF + (uint32_t)q * PSLOT; + pushfmt::pack(acc, stg, lane); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + if (lane == 0) { + mbar_wait_cluster(smem_u32(&ready_bar[q]), 0); // owner's ring idle + const uint32_t j = (uint32_t)(rank < owner ? rank : rank - 1); // my source index (0..3) at the owner + const uint32_t dst = mapa_rank(ring + j * PSLOT, (uint32_t)owner); + const uint32_t mb = mapa_rank(smem_u32(&recv_bar[j]), (uint32_t)owner); + bulk_s2dsmem(dst, stg, PSL_BYTES, mb); + } + __syncwarp(); + fence_before(); + cluster_arrive_relaxed(); // #2 + cluster_wait(); + } else { + if (lane == 0) { + for (int j = 0; j < CL - 1; ++j) mbar_arrive_expect_tx(&recv_bar[j], PSL_BYTES); + for (int d = 0; d < CL; ++d) + if (d != rank) mbar_arrive_remote_relaxed(mapa_rank(smem_u32(&ready_bar[q]), (uint32_t)d)); + } + __syncwarp(); +#pragma unroll 1 + for (int j = 0; j < CL - 1; ++j) { + mbar_wait_sleep(&recv_bar[j], 0); + pushfmt::add(acc, ring + (uint32_t)j * PSLOT, lane); + } + fence_before(); + cluster_arrive_relaxed(); // #2: all received data consumed + // bf16 pack into a 32 rows x 128 cols box as two 64-col 128B-swizzled halves (4 KB each), TMA store + // clips rows >= M. 16 B chunk c of row lane at (c ^ (lane & 7)). + const uint32_t bst = ring + BF_OFF; +#pragma unroll + for (int c = 0; c < TILE_N / 8; ++c) { + const int e = c * 8; + __nv_bfloat162 h0 = __floats2bfloat162_rn(acc[e + 0], acc[e + 1]); + __nv_bfloat162 h1 = __floats2bfloat162_rn(acc[e + 2], acc[e + 3]); + __nv_bfloat162 h2 = __floats2bfloat162_rn(acc[e + 4], acc[e + 5]); + __nv_bfloat162 h3 = __floats2bfloat162_rn(acc[e + 6], acc[e + 7]); + const uint32_t addr = bst + (uint32_t)(c >> 3) * 4096u + lane * 128 + (((c & 7) ^ (lane & 7)) << 4); + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(addr), + "r"(*reinterpret_cast(&h0)), "r"(*reinterpret_cast(&h1)), + "r"(*reinterpret_cast(&h2)), "r"(*reinterpret_cast(&h3)) + : "memory"); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + if (lane == 0) { + tma_store_2d_u32(&tmap_out, bst, n0, sub * 32); + tma_store_2d_u32(&tmap_out, bst + 4096u, n0 + 64, sub * 32); + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); + } + __syncwarp(); + cluster_wait(); + } + } + if (warp == 1) { + fence_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tmem_base), "r"(TMEM_COLS)); + } +} + +static void make_tmap(CUtensorMap* map, const void* ptr, uint64_t rows, uint64_t K, uint32_t box_rows) { + cuuint64_t dims[2] = {K, rows}; + cuuint64_t strides[1] = {K}; + cuuint32_t box[2] = {BLOCK_K, box_rows}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(map, CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, const_cast(ptr), dims, strides, + box, estr, 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\n", (int)r); +} + +static cudaLaunchConfig_t make_cfg(int grid, cudaStream_t stream, cudaLaunchAttribute* attr) { + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3(grid, 1, 1); + cfg.blockDim = dim3(NUM_THREADS, 1, 1); + cfg.dynamicSmemBytes = SMEM_BYTES; + cfg.stream = stream; + attr[0].id = cudaLaunchAttributeClusterDimension; + attr[0].val.clusterDim.x = CL; + attr[0].val.clusterDim.y = 1; + attr[0].val.clusterDim.z = 1; + attr[1].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attr[1].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = attr; + cfg.numAttrs = 2; + return cfg; +} + +static int max_active_clusters() { + static int v = -1; + if (v < 0) { + cudaFuncSetAttribute(fp8_m128x2_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaFuncSetAttribute(fp8_m128x2_kernel, cudaFuncAttributeNonPortableClusterSizeAllowed, 1); + cudaLaunchAttribute attr[2]; + cudaLaunchConfig_t q = make_cfg(CL * 64, 0, attr); + q.numAttrs = 1; + int n = 0; + if (cudaOccupancyMaxActiveClusters(&n, fp8_m128x2_kernel, &q) != cudaSuccess) { + cudaGetLastError(); + n = 0; + } + v = n; + } + return v; +} + +} // namespace + +bool fp8_m128x2_supported(int M, int N, int K) { + if (!(M >= 1 && M <= BLOCK_M && N % 128 == 0 && K % BLOCK_K == 0 && K / BLOCK_K >= CL)) return false; + // only worthwhile if every cluster is resident at once (2 CTAs/SM); otherwise the caller uses kernel_m128c + return max_active_clusters() >= N / TILE_N; +} + +void launch_fp8_m128x2(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, int K, + cudaStream_t stream) { + (void)max_active_clusters(); // sets the smem / cluster attributes once + CUtensorMap ta, tb, to; + make_tmap(&ta, a, (uint64_t)M, (uint64_t)K, BLOCK_M); + make_tmap(&tb, w, (uint64_t)N, (uint64_t)K, TILE_N); + { + // bf16 output map: dims {N, M}, box {64 cols (128 B), 32 rows}, 128B swizzle + cuuint64_t dims[2] = {(cuuint64_t)N, (cuuint64_t)M}; + cuuint64_t strides[1] = {(cuuint64_t)N * 2}; + cuuint32_t box[2] = {64, 32}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(&to, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, out, dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled(out) failed: %d\n", (int)r); + } + cudaLaunchAttribute attr[2]; + cudaLaunchConfig_t cfg = make_cfg((N / TILE_N) * CL, stream, attr); + cudaLaunchKernelEx(&cfg, fp8_m128x2_kernel, ta, tb, to, sx, sw, reinterpret_cast<__nv_bfloat16*>(out), M, N, K); +} diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128x2.h b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128x2.h new file mode 100644 index 0000000000000000000000000000000000000000..b51d3a29665406b7aa3da3aa70d5c19936e9b4e5 --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128x2.h @@ -0,0 +1,7 @@ +#pragma once +#include +// M <= 128: 128x128 tiles, split-K 5 as 5-CTA clusters, TWO co-resident CTAs per SM (kernel_m128x2.cu). +// Returns false if the shape is unsupported or the 2-CTA/SM cluster grid cannot be fully co-resident. +bool fp8_m128x2_supported(int M, int N, int K); +void launch_fp8_m128x2(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, int K, + cudaStream_t stream); diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256.cu b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256.cu new file mode 100644 index 0000000000000000000000000000000000000000..28d032c3a19eb061bd840c6da1ea925d7be9559a --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256.cu @@ -0,0 +1,863 @@ +// SMALL-M (128 < M <= 256 class) KERNEL: 2-CTA cluster along M + W TMA multicast + stream-K. +// +// out[m, n] = sum_kb sx[m, kb] * sw[kb, n/128] * sum_{k in kb} A[m,k] * W[n,k] +// +// Same DeepGEMM-style "promotion" core as kernel_large2.cu (tcgen05 kind::f8f6f4 M=128,N=256,K=32, +// each 128-wide K-block accumulated fresh into one of 2 TMEM buffers, 8 promotion warps scale it +// by sx*sw into fp32 registers). Differences: +// * Cluster of 2 CTAs along M. A cluster owns PAIR TILES = 256 rows (2 x 128-row M tiles, CTA rank r +// owns rows [mp*256 + r*128, +128)) x 256 cols. Each CTA TMA-loads its own A tile and HALF of the +// W box (rows n0 + r*128 .. +128) with .multicast::cluster (ctaMask 0b11), so W is read from +// L2/DRAM once per pair tile instead of once per M tile. full barrier: local, expects A + both W +// halves (48 KB). empty barrier: count 2, released by the tcgen05.commit (multicast) of BOTH CTAs' +// MMAs (a stage is reused only when both CTAs consumed it, since the peer writes into it). +// * Stream-K: the linear (pair tile, k-block) space T = tiles * num_kb is cut into gridDim.x/2 +// contiguous equal ranges, one per cluster (both CTAs walk the identical sequence). Every piece +// that does not start a tile is red.global.add'ed (fp32) into the persistent zeroed workspace +// ws[(t*2 + rank)] (128x256, thread-ownership float4 layout) by "contributor" pieces (kb0 > 0); the tile's "owner" piece (kb0 == 0, the +// last piece of its CTA) waits on a per-ws-tile k-block counter, adds the ws partial to its registers, +// re-zeroes ws + counter (self-cleaning) and stores bf16 directly -> single launch, no convert kernel. +// All clusters are co-resident (grid capped by cudaOccupancyMaxActiveClusters), so the wait is safe. +// * Owner bf16 output: per-warp 1 KB 32B-swizzled smem staging boxes (32 rows x 16 cols) -> TMA store. +// FIXUP / TAIL RESTRUCTURE (this version; globaltimer phase table at M=256 in the candidate notes): +// * owner LAST piece: the operand ring is idle -> the 128 KB fp32 ws tile is TMA-bulk-loaded into ring[0,128K) +// (throughput-bound instead of latency-bound ldcg batches), added from smem, and the bf16 tile is staged in +// ring[128K,192K) as 128 B-row boxes (64x32, 128B swizzle; 4x fewer TMA rows than 32 B boxes), no reuse waits. +// * ws DOUBLE-BUFFERED by call parity: the owner no longer re-zeroes (its 128 KB zero writes queued ahead of the +// bf16 store); instead one "pure" contributor per split tile (a CTA with end-of-kernel slack) bulk-stores zeros +// from an 8 KB zero smem region over that tile of the other parity (used by the next call). +// (DBG_T/DBG_V are globaltimer probes, compiled out unless M256_DBG is defined.) +// Roles (12 warps): warp0 TMA producer, warp1 TMEM alloc + MMA issuer, warps2-3 SCALE PRODUCER (setmaxnreg.dec 56; +// per k-block s[half][row] = sx*sw into an 8-slot smem ring, sfull/sempty mbarriers; promotion does 1 ld.shared), +// warps 4..11 = 2 promotion warpgroups x 128 cols (setmaxnreg.inc 224), thread = one tile row (TMEM lane); +// per k-block drain = 2 passes of (4 x16 tcgen05.ld -> 1 wait::ld -> 32 packed FFMA2), one elected tempty arrive per warp; +// suspend-hinted mbarrier try_wait for the MMA issuer + promotion warps. +#include +#include +#include +#include +#include +#include "tmap_cache.h" +#include "kernel_m256.h" + +#ifdef M256_DBG +__device__ unsigned long long* d_m256_dbg; +__device__ __forceinline__ unsigned long long gtime() { unsigned long long t; asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); return t; } +#define DBG_T(i) do { if (d_m256_dbg) d_m256_dbg[blockIdx.x * 16 + (i)] = gtime(); } while (0) +#define DBG_V(i, v) do { if (d_m256_dbg) d_m256_dbg[blockIdx.x * 16 + (i)] = (v); } while (0) +#else +#define DBG_T(i) do {} while (0) +#define DBG_V(i, v) do {} while (0) +#endif +namespace { + +constexpr int BLOCK_M = 128; +constexpr int BLOCK_N = 256; +constexpr int BLOCK_K = 128; +constexpr int STAGES = 4; +constexpr int TILE_A_BYTES = BLOCK_M * BLOCK_K; // fp8, 16 KB +constexpr int TILE_B_BYTES = BLOCK_N * BLOCK_K; // 32 KB (two 16 KB halves, one per cluster rank) +constexpr int STAGE_BYTES = TILE_A_BYTES + TILE_B_BYTES; +constexpr int NUM_EPI_WARPS = 8; // 2 promotion warpgroups x 128 cols +constexpr int EPI_COLS = 128; +constexpr int EPI_WARP0 = 4; +constexpr int NUM_THREADS = 128 + NUM_EPI_WARPS * 32; // 384 +constexpr int TMEM_COLS = 512; +constexpr int SC_SLOTS = 8; // scale ring depth (k-blocks) +constexpr int SC_BYTES = SC_SLOTS * 256 * 4; // 8 KB: [slot][half][128 rows] fp32 +constexpr int OUT_STAGE_BYTES = NUM_EPI_WARPS * 32 * 32; // 1 KB per promotion warp: 32 rows x 16 bf16 (TMA box) +constexpr int ZERO_BYTES = 8192; // all-zero smem source for the async bulk re-zeroing of the next call's ws tiles +constexpr int SMEM_BYTES = + STAGES * STAGE_BYTES + OUT_STAGE_BYTES + SC_BYTES + ZERO_BYTES + 1024 /*align*/ + 256 /*barriers*/; +constexpr int WS_TILE_FLOATS = BLOCK_M * BLOCK_N; +static_assert(SMEM_BYTES <= 232448, "smem budget"); +// setmaxnreg: 128*64 + 256*216 = 63488 <= 168*384 (probe: control WG spilled at 56; promotion fits 216, zero spills) +constexpr int REGS_CTRL = 64; +constexpr int REGS_EPI = 216; + +// ---------------------------------------------------------------- PTX helpers +__device__ __forceinline__ uint32_t smem_u32(const void* p) { + return static_cast(__cvta_generic_to_shared(p)); +} +__device__ __forceinline__ uint32_t cluster_ctarank() { + uint32_t r; + asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(r)); + return r; +} +__device__ __forceinline__ void cluster_sync() { + asm volatile("barrier.cluster.arrive.release.aligned;\n\tbarrier.cluster.wait.acquire.aligned;" ::: "memory"); +} +__device__ __forceinline__ void mbar_init(uint64_t* bar, uint32_t count) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(smem_u32(bar)), "r"(count)); +} +__device__ __forceinline__ void mbar_arrive_expect_tx(uint64_t* bar, uint32_t bytes) { + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(smem_u32(bar)), "r"(bytes) + : "memory"); +} +__device__ __forceinline__ void mbar_arrive(uint64_t* bar) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(smem_u32(bar)) : "memory"); +} +__device__ __forceinline__ void mbar_wait(uint64_t* bar, uint32_t parity) { + uint32_t addr = smem_u32(bar); + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAIT_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n" + "@!p bra WAIT_%=;\n" + "}\n" ::"r"(addr), + "r"(parity) + : "memory"); +} +// mbarrier wait with a suspend-time hint (waiting warp parked instead of hot-spinning; frees issue slots). +// Used by the MMA issuer and the promotion warps. +__device__ __forceinline__ void mbar_wait_sleep(uint64_t* bar, uint32_t parity) { + uint32_t addr = smem_u32(bar); + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITS_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITS_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +// packed promotion FMA (fma.rn.f32x2): {a0,a1} += {x0,x1} * ss +__device__ __forceinline__ void ffma2(float& a0, float& a1, uint32_t x0, uint32_t x1, float2 ss) { + const float2 d = __ffma2_rn(make_float2(__uint_as_float(x0), __uint_as_float(x1)), ss, make_float2(a0, a1)); + a0 = d.x; + a1 = d.y; +} +// packed add via fma.rn.f32x2 with 1.0 multiplier (bit-identical to two fp32 adds) +__device__ __forceinline__ void fadd2(float& a0, float& a1, float x0, float x1) { + const float2 d = __ffma2_rn(make_float2(x0, x1), make_float2(1.f, 1.f), make_float2(a0, a1)); + a0 = d.x; + a1 = d.y; +} +__device__ __forceinline__ void tma_load_2d(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1, {%2, %3}], [%4];" ::"r"( + smem_u32(dst)), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(smem_u32(bar)) + : "memory"); +} +// Multicast TMA: box lands at the same smem offset in every CTA of ctaMask and signals the +// mbarrier at the same offset in each destination CTA. +__device__ __forceinline__ void tma_load_2d_mc(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y, + uint16_t mask) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.multicast::cluster" + " [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(smem_u32(dst)), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(smem_u32(bar)), "h"(mask) + : "memory"); +} +// Multicast TMA with an L2 cache-policy hint (W slab: read exactly once per call -> evict_first, so the +// streamed 117 MB of W does not evict the re-read A tiles / fp32 workspace lines from L2). +__device__ __forceinline__ void tma_load_2d_mc_hint(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y, + uint16_t mask, uint64_t policy) { + 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"(smem_u32(dst)), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(smem_u32(bar)), "h"(mask), "l"(policy) + : "memory"); +} +__device__ __forceinline__ void tma_store_2d(const CUtensorMap* map, const void* src, int x, int y) { + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group [%0, {%1, %2}], [%3];" ::"l"( + reinterpret_cast(map)), + "r"(x), "r"(y), "r"(smem_u32(src)) + : "memory"); +} +// 32-bit shared-memory accessors (keep smem addresses as 32-bit regs in the register-tight promotion warps) +__device__ __forceinline__ float lds_f32(uint32_t a) { + float v; + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(v) : "r"(a) : "memory"); + return v; +} +__device__ __forceinline__ void sts_v4(uint32_t a, uint4 v) { + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(a), "r"(v.x), "r"(v.y), "r"(v.z), "r"(v.w) : "memory"); +} +__device__ __forceinline__ void tma_store_2d_u32(const CUtensorMap* map, uint32_t src, int x, int y) { + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group [%0, {%1, %2}], [%3];" ::"l"( + reinterpret_cast(map)), + "r"(x), "r"(y), "r"(src) + : "memory"); +} +// 1D bulk copies (async proxy) used by the owner fixup once the operand ring is idle. +__device__ __forceinline__ void bulk_load_g2s(uint32_t dst, const void* src, uint32_t bytes, uint64_t* bar) { + asm volatile("cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1], %2, [%3];" ::"r"(dst), + "l"(reinterpret_cast(src)), "r"(bytes), "r"(smem_u32(bar)) + : "memory"); +} +__device__ __forceinline__ void bulk_store_s2g(void* dst, uint32_t src, uint32_t bytes) { + asm volatile("cp.async.bulk.global.shared::cta.bulk_group [%0], [%1], %2;" ::"l"(reinterpret_cast(dst)), + "r"(src), "r"(bytes) + : "memory"); +} +__device__ __forceinline__ float4 lds_v4(uint32_t a) { + float4 v; + asm volatile("ld.shared.v4.f32 {%0, %1, %2, %3}, [%4];" : "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w) : "r"(a) : "memory"); + return v; +} +__device__ __forceinline__ void tma_store_commit() { asm volatile("cp.async.bulk.commit_group;" ::: "memory"); } +__device__ __forceinline__ void tma_store_wait_read() { + asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); +} +__device__ __forceinline__ void tma_store_wait_all() { asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); } +__device__ __forceinline__ void red_add_v4(float* p, float a, float b, float c, float d) { + asm volatile("red.global.add.v4.f32 [%0], {%1, %2, %3, %4};" ::"l"(p), "f"(a), "f"(b), "f"(c), "f"(d) + : "memory"); +} +// UMMA smem descriptor: K-major, 128B swizzle, SBO 1024 B, sm100 version 1. +__device__ __forceinline__ uint64_t make_sdesc(uint32_t saddr) { + uint64_t d = 0; + d |= (uint64_t)((saddr & 0x3FFFF) >> 4); + d |= (uint64_t)1 << 16; + d |= (uint64_t)(1024 >> 4) << 32; + d |= (uint64_t)1 << 46; + d |= (uint64_t)2 << 61; + return d; +} +__device__ __forceinline__ void mma_f8(uint32_t tmem_d, uint64_t adesc, uint64_t bdesc, uint32_t idesc, + uint32_t accum) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "setp.ne.b32 p, %4, 0;\n" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %3, p;\n" + "}\n" ::"r"(tmem_d), + "l"(adesc), "l"(bdesc), "r"(idesc), "r"(accum)); +} +__device__ __forceinline__ void mma_commit(uint64_t* bar) { + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(smem_u32(bar)) + : "memory"); +} +// Arrive (on MMA completion) on the barrier at this smem offset in every CTA of ctaMask. +__device__ __forceinline__ void mma_commit_mc(uint64_t* bar, uint16_t mask) { + asm volatile( + "tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%0], %1;" ::"r"( + smem_u32(bar)), + "h"(mask) + : "memory"); +} +__device__ __forceinline__ void fence_after() { asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void fence_before() { asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory"); } + +#define TMEM_LD32(taddr, r) \ + 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)) + +#define TMEM_LD16(taddr, r) \ + 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"(taddr)) + +__device__ __forceinline__ void tmem_ld_wait() { asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); } + +// Stream-K walker: next piece (pair tile t, k-blocks [kb0, kb1)) of the range [pos, end). +// 32-bit walker (this path: M <= 256 -> num_mpair = 1, total = N/256 * K/128 fits easily in int; 32-bit keeps +// the promotion warps' loop state small next to acc[128] + 64 TMEM staging regs). +__device__ __forceinline__ bool next_piece(int& pos, int end, int nkb, int& t, int& kb0, int& kb1) { + if (pos >= end) return false; + t = pos / nkb; + kb0 = pos - t * nkb; + const int rem = end - pos; + kb1 = (nkb - kb0) < rem ? nkb : kb0 + rem; + pos += kb1 - kb0; + return true; +} + +// ---------------------------------------------------------------- kernel (cluster dims = 2) +__global__ void __launch_bounds__(NUM_THREADS, 1) + fp8_m256_kernel(const __grid_constant__ CUtensorMap tmap_a, const __grid_constant__ CUtensorMap tmap_b, + const __grid_constant__ CUtensorMap tmap_out, const __grid_constant__ CUtensorMap tmap_out128, + const float* __restrict__ scale_x, const float* __restrict__ scale_w, float* __restrict__ ws, + float* __restrict__ ws_next, int* __restrict__ cnt, __nv_bfloat16* __restrict__ out, int M, int N, int K) { + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(smem_raw) + 1023) & ~uintptr_t(1023)); + uint8_t* out_stage = smem + STAGES * STAGE_BYTES; // 16 KB bf16 output staging + float* sc_ring = reinterpret_cast(out_stage + OUT_STAGE_BYTES); // 8 KB scale ring + uint8_t* zero_stage = out_stage + OUT_STAGE_BYTES + SC_BYTES; // 8 KB of zeros + uint64_t* full_bar = reinterpret_cast(out_stage + OUT_STAGE_BYTES + SC_BYTES + ZERO_BYTES); + uint64_t* empty_bar = full_bar + STAGES; + uint64_t* tfull_bar = empty_bar + STAGES; // [2] + uint64_t* tempty_bar = tfull_bar + 2; // [2] + uint64_t* sfull_bar = tempty_bar + 2; // [SC_SLOTS] + uint64_t* sempty_bar = sfull_bar + SC_SLOTS; // [SC_SLOTS] + uint64_t* fix_bar = sempty_bar + SC_SLOTS; // owner fixup: ws tile bulk-loaded into the idle ring + uint32_t* tmem_slot = reinterpret_cast(fix_bar + 1); + + if (threadIdx.x == 0) DBG_T(0); + const int warp = threadIdx.x / 32; + const int lane = threadIdx.x % 32; + const int num_kb = K / BLOCK_K; + const int num_nblk = N / BLOCK_N; + const int num_sblk = N / 128; + const int num_mblk = (M + BLOCK_M - 1) / BLOCK_M; + const int num_mpair = (num_mblk + 1) / 2; + const int rank = (int)cluster_ctarank(); // row-half of the pair tile owned by this CTA + const int cid = blockIdx.x >> 1; // cluster id + const int ncl = gridDim.x >> 1; + // pair tile t: mp = t % num_mpair (M-fastest), nb = t / num_mpair + const long long total = (long long)num_mpair * num_nblk * num_kb; + const int seg_begin = (int)((long long)cid * total / ncl); + const int seg_end = (int)((long long)(cid + 1) * total / ncl); + + uint32_t pre_cnt = 0; // k-blocks whose barrier arm + A load were issued in the startup prologue (thread 0) + if (threadIdx.x == 0) { + for (int i = 0; i < STAGES; ++i) { + mbar_init(&full_bar[i], 1); + mbar_init(&empty_bar[i], 2); // released by the MMA commit of both CTAs in the cluster + } + for (int i = 0; i < 2; ++i) { + mbar_init(&tfull_bar[i], 1); + mbar_init(&tempty_bar[i], NUM_EPI_WARPS); // one elected arrive per promotion warp + } + for (int i = 0; i < SC_SLOTS; ++i) { + mbar_init(&sfull_bar[i], 64); // 64 scale-producer threads + mbar_init(&sempty_bar[i], NUM_EPI_WARPS); // one arrive per promotion warp + } + mbar_init(fix_bar, 1); + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_a)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_b)) : "memory"); + // STARTUP PROLOGUE: thread 0 is also the TMA producer (warp 0 lane 0). Before the zero-fill, TMEM alloc, + // __syncthreads and cluster barrier, it arms the first STAGES full barriers (full 48 KB expect_tx) and + // issues their LOCAL A-tile loads (fresh ring: no empty wait needed). The multicast W halves need the + // peer's barriers initialised, so they are issued by the producer loop after the cluster barrier. + { + int ppos = seg_begin, pt, pkb0, pkb1; + while (pre_cnt < STAGES && next_piece(ppos, seg_end, num_kb, pt, pkb0, pkb1)) { + const int m0 = ((pt % num_mpair) * 2 + rank) * BLOCK_M; + for (int kb = pkb0; kb < pkb1 && pre_cnt < STAGES; ++kb, ++pre_cnt) { + uint8_t* sa = smem + pre_cnt * STAGE_BYTES; + mbar_arrive_expect_tx(&full_bar[pre_cnt], STAGE_BYTES); + tma_load_2d(sa, &tmap_a, &full_bar[pre_cnt], kb * BLOCK_K, m0); + } + } + } + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_out)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_out128)) : "memory"); + } + for (int i = threadIdx.x; i < ZERO_BYTES / 16; i += NUM_THREADS) + sts_v4(smem_u32(zero_stage) + i * 16, make_uint4(0u, 0u, 0u, 0u)); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // zeros visible to later bulk copies + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(smem_u32(tmem_slot)), + "r"(TMEM_COLS)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + fence_before(); + __syncthreads(); + asm volatile("barrier.cluster.arrive.relaxed.aligned;\n\tbarrier.cluster.wait.acquire.aligned;" ::: "memory"); /* RELAXED arrive: no generic data to publish */ // peer barriers initialised before any multicast TMA / remote arrive + fence_after(); + if (threadIdx.x == 0) DBG_T(1); + const uint32_t tmem_base = *tmem_slot; + + if (warp < EPI_WARP0) { + asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;" ::"n"(REGS_CTRL)); + if (warp == 0) { + // ------------------------------------------------ TMA producer + if (lane == 0) { + uint64_t pol_w; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_w)); + uint32_t it = 0; // identical K-block sequence in both CTAs of the cluster + int pos = seg_begin; + int t, kb0, kb1; + while (next_piece(pos, seg_end, num_kb, t, kb0, kb1)) { + const int mp = t % num_mpair, nb = t / num_mpair; + const int m0 = (mp * 2 + rank) * BLOCK_M; + const int n0 = nb * BLOCK_N; + for (int kb = kb0; kb < kb1; ++kb, ++it) { + const int s = it % STAGES; + const uint32_t ph = (it / STAGES) & 1; + uint8_t* sa = smem + s * STAGE_BYTES; + uint8_t* sb = sa + TILE_A_BYTES; + if (it >= pre_cnt) { // (first pre_cnt k-blocks: armed + A issued in the startup prologue) + mbar_wait(&empty_bar[s], ph ^ 1); // both CTAs' MMAs finished reading stage s + mbar_arrive_expect_tx(&full_bar[s], STAGE_BYTES); // A (local, OOB rows zero-filled) + both W halves + tma_load_2d(sa, &tmap_a, &full_bar[s], kb * BLOCK_K, m0); + } + // my 128-row half of the W box -> same offset in both CTAs + tma_load_2d_mc_hint(sb + rank * (TILE_B_BYTES / 2), &tmap_b, &full_bar[s], kb * BLOCK_K, + n0 + rank * (BLOCK_N / 2), (uint16_t)0x3, pol_w); + } + } + // drain: wait until every stage's last use was released by both CTAs, so no remote + // arrive targets this CTA's barriers after it passes the final cluster barrier. + for (int i = 0; i < STAGES; ++i, ++it) { + const int s = it % STAGES; + const uint32_t ph = (it / STAGES) & 1; + mbar_wait(&empty_bar[s], ph ^ 1); + } + } + } else if (warp == 1) { + // ------------------------------------------------ MMA issuer (single thread) + if (lane == 0) { + const uint32_t idesc = (1u << 4) | ((uint32_t)(BLOCK_N >> 3) << 17) | ((uint32_t)(BLOCK_M >> 4) << 24); + uint32_t it = 0; + int pos = seg_begin; + int t, kb0, kb1; + while (next_piece(pos, seg_end, num_kb, t, kb0, kb1)) { + for (int kb = kb0; kb < kb1; ++kb, ++it) { + const int s = it % STAGES; + const uint32_t ph = (it / STAGES) & 1; + const int b = it & 1; + // reordered: wait operands + build descriptors first, then tempty -> fence -> MMA directly + mbar_wait_sleep(&full_bar[s], ph); // A + both W halves landed + if (it == 0) DBG_T(2); + const uint32_t sa = smem_u32(smem + s * STAGE_BYTES); + const uint64_t adesc = make_sdesc(sa); + const uint64_t bdesc = make_sdesc(sa + TILE_A_BYTES); + const uint32_t tmem_d = tmem_base + b * BLOCK_N; + mbar_wait_sleep(&tempty_bar[b], ((it >> 1) & 1) ^ 1); // epilogue drained this TMEM buffer + fence_after(); +#pragma unroll + for (int k = 0; k < BLOCK_K / 32; ++k) mma_f8(tmem_d, adesc + 2 * k, bdesc + 2 * k, idesc, k > 0 ? 1u : 0u); + mma_commit_mc(&empty_bar[s], (uint16_t)0x3); // free stage s in BOTH CTAs + mma_commit(&tfull_bar[b]); // partial accumulator ready (local) + } + } + DBG_T(3); + } + } else { + // ------------------------------------------------ scale producer (warps 2,3; 64 threads) + // per k-block writes s[half][row] = sx[m0+row, kb] * sw[kb, nb*2+half] into the smem ring; + // thread lt owns rows lt, lt+64. Global loads batched 4 k-blocks at a time. + const int lt = threadIdx.x - 64; + uint32_t it = 0; + int pos = seg_begin; + int t, kb0, kb1; + while (next_piece(pos, seg_end, num_kb, t, kb0, kb1)) { + const int mp = t % num_mpair, nb = t / num_mpair; + const int ra = (mp * 2 + rank) * BLOCK_M + lt, rb = ra + 64; + const float* pa = scale_x + (size_t)(ra < M ? ra : 0) * num_kb; // rows >= M: value unused + const float* pb = scale_x + (size_t)(rb < M ? rb : 0) * num_kb; + for (int kb = kb0; kb < kb1; kb += 4) { + const int nq = (kb1 - kb) < 4 ? (kb1 - kb) : 4; + float xa[4], xb[4]; + float2 w[4]; +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + xa[q] = __ldg(pa + kb + q); + xb[q] = __ldg(pb + kb + q); + w[q] = __ldg(reinterpret_cast(scale_w + (size_t)(kb + q) * num_sblk) + nb); + } + } +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + const uint32_t ii = it + q; + const int slot = ii % SC_SLOTS; + mbar_wait(&sempty_bar[slot], ((ii / SC_SLOTS) & 1) ^ 1); + float* d = sc_ring + slot * 256; + d[lt] = xa[q] * w[q].x; + d[lt + 64] = xb[q] * w[q].x; + d[128 + lt] = xa[q] * w[q].y; + d[128 + lt + 64] = xb[q] * w[q].y; + mbar_arrive(&sfull_bar[slot]); + } + } + it += nq; + } + } + } + } else { + // ------------------------------------------------ promotion epilogue (warps 4..11) + asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;" ::"n"(REGS_EPI)); + const int g = (warp - EPI_WARP0) >> 2; // 128-col half of the tile + const int sub = warp & 3; // TMEM sub-partition + const int row = sub * 32 + lane; + // precomputed TMEM addresses of both accumulator buffers for this warp's lanes / cols + const uint32_t taddr_b0 = tmem_base + ((uint32_t)(sub * 32) << 16) + g * EPI_COLS; + const uint32_t sc_mine = smem_u32(sc_ring + g * 128 + row); // my scale within a ring slot + const uint32_t wstage = smem_u32(out_stage + (warp - EPI_WARP0) * 1024); // this warp's 1 KB output staging box + uint32_t it = 0; + int pos = seg_begin; + int t, kb0, kb1; + while (next_piece(pos, seg_end, num_kb, t, kb0, kb1)) { + const int mp = t % num_mpair, nb = t / num_mpair; + const int m0 = (mp * 2 + rank) * BLOCK_M; + const int m = m0 + row; + float acc[EPI_COLS]; +#pragma unroll + for (int j = 0; j < EPI_COLS; ++j) acc[j] = 0.f; + for (int kb = kb0; kb < kb1; ++kb, ++it) { + const int b = it & 1; + const uint32_t slot = it % SC_SLOTS; + // promotion scale from the producer's smem ring (one ld.shared), slot released per warp + mbar_wait_sleep(&sfull_bar[slot], (it / SC_SLOTS) & 1); + const float s = lds_f32(sc_mine + slot * 1024); + const float2 ss = make_float2(s, s); + __syncwarp(); + if (lane == 0) mbar_arrive(&sempty_bar[slot]); + mbar_wait_sleep(&tfull_bar[b], (it >> 1) & 1); + fence_after(); + const uint32_t taddr = taddr_b0 + (uint32_t)(b * BLOCK_N); + // TMEM drain, 2 passes of 64 cols: ALL FOUR x16 tcgen05.ld of a pass issued back-to-back (64 staging + // regs), ONE wait::ld, then 64 FMAs. After the 2nd pass's wait the buffer is released with ONE elected + // arrive per warp (tempty count = NUM_EPI_WARPS), before the last 64 FMAs. +#pragma unroll + for (int p = 0; p < 2; ++p) { + uint32_t r0[16], r1[16], r2[16], r3[16]; + const uint32_t ta = taddr + p * 64; + TMEM_LD16(ta + 0, r0); + TMEM_LD16(ta + 16, r1); + TMEM_LD16(ta + 32, r2); + TMEM_LD16(ta + 48, r3); + tmem_ld_wait(); + if (p == 1) { + fence_before(); + __syncwarp(); + if (lane == 0) mbar_arrive(&tempty_bar[b]); + } + float* a = acc + p * 64; +#pragma unroll + for (int j = 0; j < 16; j += 2) { // packed FFMA2: 32 instead of 64 FMA instructions per pass + ffma2(a[j], a[j + 1], r0[j], r0[j + 1], ss); + ffma2(a[16 + j], a[16 + j + 1], r1[j], r1[j + 1], ss); + ffma2(a[32 + j], a[32 + j + 1], r2[j], r2[j + 1], ss); + ffma2(a[48 + j], a[48 + j + 1], r3[j], r3[j + 1], ss); + } + } + } + // Stream-K fixup (fused, no convert kernel). Piece kinds (per CTA rank, ws tile wt = t*2 + rank): + // * contributor (kb0 > 0): red.add fp32 partial into the zeroed ws tile, then publish its k-block + // count in cnt[wt] (bar.sync + one release fence by a single thread). A contributor piece is + // always the FIRST piece of its CTA's segment, so it finishes early. + // * owner (kb0 == 0): always the LAST piece of its CTA. If it covers the whole K range it stores + // bf16 directly; otherwise it waits until the contributors' counts reach num_kb - kb1, adds the + // ws partial (and re-zeroes it + the counter: self-cleaning), and stores bf16 directly. + const int wt = t * 2 + rank; + const int etid = threadIdx.x - EPI_WARP0 * 32; // 0..255 + // last piece of this CTA's segment: every k-block was consumed (all TMA loads incl. the peer's multicast + // halves landed, all MMAs completed), so the 192 KB operand ring is idle and may be reused for the fixup. + const bool last_piece = pos >= seg_end; + const uint32_t ring = smem_u32(smem); + if (etid == 0) { if (kb0 > 0) { DBG_T(4); DBG_V(12, (kb0 << 16) | kb1); } else { DBG_T(5); DBG_V(13, (kb0 << 16) | kb1); } } + // ws tile layout follows thread ownership: float4 chunk v (cols g*64 + 4v..+4) of row r lives at + // float4 index (g*32 + v)*128 + r, so for each v a warp touches 512 contiguous bytes (coalesced). + float4* wrow = reinterpret_cast(ws + (size_t)wt * WS_TILE_FLOATS) + (g * (EPI_COLS / 4)) * BLOCK_M + row; + if (kb0 > 0) { + if (m < M) { +#pragma unroll + for (int v = 0; v < EPI_COLS / 4; ++v) + red_add_v4(reinterpret_cast(wrow + v * BLOCK_M), acc[v * 4 + 0], acc[v * 4 + 1], acc[v * 4 + 2], + acc[v * 4 + 3]); + } + if (etid == 0) DBG_T(11); + asm volatile("bar.sync 1, 256;" ::: "memory"); + if (etid == 0) DBG_T(14); + if (etid == 0) { + // cumulative release: orders every epilogue thread's red.adds (via bar.sync) before the count + asm volatile("fence.acq_rel.gpu;" ::: "memory"); + asm volatile("red.relaxed.gpu.global.add.s32 [%0], %1;" ::"l"(cnt + wt), "r"(kb1 - kb0) : "memory"); + DBG_T(6); + // Re-zero this ws tile in the OTHER parity's workspace (used by the next call, untouched in this one) + // with async bulk stores from the zero smem region. Exactly ONE piece per split tile does it, chosen so + // that it is a CTA with slack (a "pure" contributor = last piece of its CTA, finishing well before the + // owners' fixup), never a CTA whose next piece is an owner mainloop. Pieces of tile t in k order: + // P0 (owner) | P1 .. Pk (Pk = tile-end piece, kb1 == num_kb): + // * Pk pure (its cluster's segment ends exactly at the tile end) -> Pk zeroes; + // * Pk crossing (first piece of a CTA that continues), P(k-1) pure (k>1) -> P(k-1) zeroes; + // * Pk crossing, k == 1 (previous piece is the owner) -> Pk zeroes. + // Cluster segments are [c*total/ncl, (c+1)*total/ncl) in (pair tile, k-block) space. + const long long tstart = (long long)t * num_kb, tend = tstart + num_kb; + bool zero_mine; + if (last_piece) + zero_mine = kb1 == num_kb || (long long)(cid + 2) * total / ncl > tend; + else + zero_mine = (long long)(cid - 1) * total / ncl <= tstart; + if (zero_mine) { + // completed by this thread's final tma_store_wait_all + float* zt = ws_next + (size_t)wt * WS_TILE_FLOATS; + const uint32_t zs = smem_u32(zero_stage); + for (int q = 0; q < WS_TILE_FLOATS * 4 / ZERO_BYTES; ++q) bulk_store_s2g(zt + q * (ZERO_BYTES / 4), zs, ZERO_BYTES); + tma_store_commit(); + } + } + continue; + } + if (kb1 < num_kb && last_piece) { + // FAST OWNER FIXUP: one thread waits for the contributors, then TMA-bulk-loads the whole 128 KB fp32 ws + // tile into ring[0, 128K) (throughput-bound, instead of latency-bound per-thread L2 loads). Each thread + // adds its 32 float4 (same thread-ownership layout -> conflict-free ld.shared.v4). No re-zeroing here: + // this parity's tile is re-zeroed by the NEXT call's tile-end piece (double-buffered ws, see host). + if (etid == 0) { + const int need = num_kb - kb1; + int c; + while (true) { + asm volatile("ld.acquire.gpu.global.b32 %0, [%1];" : "=r"(c) : "l"(cnt + wt) : "memory"); + if (c >= need) break; + __nanosleep(32); + } + cnt[wt] = 0; // all contributions arrived: reset for the next call + DBG_T(7); + asm volatile("fence.proxy.async.global;" ::: "memory"); // generic-proxy red.adds -> async-proxy reads + mbar_arrive_expect_tx(fix_bar, WS_TILE_FLOATS * 4); + const float* src = ws + (size_t)wt * WS_TILE_FLOATS; +#pragma unroll + for (int q = 0; q < 4; ++q) bulk_load_g2s(ring + q * 32768, src + q * 8192, 32768, fix_bar); + } + mbar_wait_sleep(fix_bar, 0); // at most one fast fixup per CTA -> phase 0 + const uint32_t my = ring + (uint32_t)(((g * (EPI_COLS / 4)) * BLOCK_M + row) * 16); +#pragma unroll + for (int v0 = 0; v0 < EPI_COLS / 4; v0 += 8) { + float4 p[8]; +#pragma unroll + for (int v = 0; v < 8; ++v) p[v] = lds_v4(my + (v0 + v) * (BLOCK_M * 16)); +#pragma unroll + for (int v = 0; v < 8; ++v) { + fadd2(acc[(v0 + v) * 4 + 0], acc[(v0 + v) * 4 + 1], p[v].x, p[v].y); + fadd2(acc[(v0 + v) * 4 + 2], acc[(v0 + v) * 4 + 3], p[v].z, p[v].w); + } + } + if (etid == 0) DBG_T(8); + } else if (kb1 < num_kb) { + if (etid == 0) { + const int need = num_kb - kb1; + int c; + while (true) { + asm volatile("ld.acquire.gpu.global.b32 %0, [%1];" : "=r"(c) : "l"(cnt + wt) : "memory"); + if (c >= need) break; + __nanosleep(32); + } + cnt[wt] = 0; // all contributions arrived: reset for the next call + DBG_T(7); + } + asm volatile("bar.sync 1, 256;" ::: "memory"); + if (m < M) { +#pragma unroll + for (int v0 = 0; v0 < EPI_COLS / 4; v0 += 4) { // batches of 4 float4 (16 regs: no spills) + float4 p[4]; +#pragma unroll + for (int v = 0; v < 4; ++v) p[v] = __ldcg(wrow + (v0 + v) * BLOCK_M); +#pragma unroll + for (int v = 0; v < 4; ++v) { + __stcg(wrow + (v0 + v) * BLOCK_M, make_float4(0.f, 0.f, 0.f, 0.f)); + fadd2(acc[(v0 + v) * 4 + 0], acc[(v0 + v) * 4 + 1], p[v].x, p[v].y); + fadd2(acc[(v0 + v) * 4 + 2], acc[(v0 + v) * 4 + 3], p[v].z, p[v].w); + } + } + } + if (etid == 0) DBG_T(8); + } + if (last_piece) { + // LAST piece (operand ring idle): per warp 2 x (32 rows x 64 cols) bf16 boxes with 128 B rows (4x fewer + // TMA row requests than 32 B boxes), each in its own 4 KB 128B-swizzled slot at ring + 128 KB + warp*8 KB + // (16 B chunk j of row lane at j ^ (lane & 7)); both issued back-to-back, no staging reuse waits. +#pragma unroll + for (int h = 0; h < EPI_COLS / 64; ++h) { + const uint32_t stg = ring + 131072u + (uint32_t)((warp - EPI_WARP0) * 8192 + h * 4096); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int v = h * 8 + j; + __nv_bfloat162 h0 = __floats2bfloat162_rn(acc[v * 8 + 0], acc[v * 8 + 1]); + __nv_bfloat162 h1 = __floats2bfloat162_rn(acc[v * 8 + 2], acc[v * 8 + 3]); + __nv_bfloat162 h2 = __floats2bfloat162_rn(acc[v * 8 + 4], acc[v * 8 + 5]); + __nv_bfloat162 h3 = __floats2bfloat162_rn(acc[v * 8 + 6], acc[v * 8 + 7]); + uint4 pk; + pk.x = *reinterpret_cast(&h0); + pk.y = *reinterpret_cast(&h1); + pk.z = *reinterpret_cast(&h2); + pk.w = *reinterpret_cast(&h3); + sts_v4(stg + lane * 128 + ((j ^ (lane & 7)) << 4), pk); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // st.shared visible to the TMA engine + __syncwarp(); + if (lane == 0) { + tma_store_2d_u32(&tmap_out128, stg, nb * BLOCK_N + g * EPI_COLS + h * 64, m0 + sub * 32); + tma_store_commit(); + } + } + continue; + } + // bf16 output: per warp 8 x (32 rows x 16 cols) boxes, packed into its 1 KB 32B-swizzled staging + // buffer (16 B chunk j of row lane at j ^ ((lane >> 2) & 1)) and TMA-stored (rows >= M clipped). +#pragma unroll + for (int h = 0; h < EPI_COLS / 16; ++h) { + if (lane == 0) tma_store_wait_read(); // previous box finished reading the staging buffer + __syncwarp(); +#pragma unroll + for (int j = 0; j < 2; ++j) { + const int v = h * 2 + j; + __nv_bfloat162 h0 = __floats2bfloat162_rn(acc[v * 8 + 0], acc[v * 8 + 1]); + __nv_bfloat162 h1 = __floats2bfloat162_rn(acc[v * 8 + 2], acc[v * 8 + 3]); + __nv_bfloat162 h2 = __floats2bfloat162_rn(acc[v * 8 + 4], acc[v * 8 + 5]); + __nv_bfloat162 h3 = __floats2bfloat162_rn(acc[v * 8 + 6], acc[v * 8 + 7]); + uint4 pk; + pk.x = *reinterpret_cast(&h0); + pk.y = *reinterpret_cast(&h1); + pk.z = *reinterpret_cast(&h2); + pk.w = *reinterpret_cast(&h3); + sts_v4(wstage + lane * 32 + ((j ^ ((lane >> 2) & 1)) << 4), pk); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // st.shared visible to the TMA engine + __syncwarp(); + if (lane == 0) { + tma_store_2d_u32(&tmap_out, wstage, nb * BLOCK_N + g * EPI_COLS + h * 16, m0 + sub * 32); + tma_store_commit(); + } + } + } + if (threadIdx.x == EPI_WARP0 * 32) DBG_T(15); + if (lane == 0) tma_store_wait_all(); // output stores complete before exit + __syncwarp(); + if (threadIdx.x == EPI_WARP0 * 32) DBG_T(9); + } + + fence_before(); + __syncthreads(); + asm volatile("barrier.cluster.arrive.relaxed.aligned;\n\tbarrier.cluster.wait.acquire.aligned;" ::: "memory"); /* RELAXED arrive: no generic data to publish */ // no CTA exits while its peer may still multicast into / arrive on it + if (threadIdx.x == 0) DBG_T(10); + if (warp == 1) { + fence_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tmem_base), "r"(TMEM_COLS)); + } +} + +static void make_tmap(CUtensorMap* map, const void* ptr, uint64_t rows, uint64_t K, uint32_t box_rows) { + cuuint64_t dims[2] = {K, rows}; + cuuint64_t strides[1] = {K}; + cuuint32_t box[2] = {BLOCK_K, box_rows}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(map, CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, const_cast(ptr), dims, strides, + box, estr, 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\n", (int)r); +} + +// bf16 output map: dims {N, M}, box {16 cols (32 B), 32 rows}, 32B swizzle. +static void make_tmap_out(CUtensorMap* map, void* ptr, uint64_t M, uint64_t N) { + cuuint64_t dims[2] = {N, M}; + cuuint64_t strides[1] = {N * 2}; + cuuint32_t box[2] = {16, 32}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, ptr, dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_32B, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) { + fprintf(stderr, "cuTensorMapEncodeTiled(out) failed: %d\n", (int)r); + } +} + +// bf16 output map for the last-piece store: box {64 cols (128 B), 32 rows}, 128B swizzle. +static void make_tmap_out128(CUtensorMap* map, void* ptr, uint64_t M, uint64_t N) { + cuuint64_t dims[2] = {N, M}; + cuuint64_t strides[1] = {N * 2}; + cuuint32_t box[2] = {64, 32}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, ptr, dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) { + fprintf(stderr, "cuTensorMapEncodeTiled(out128) failed: %d\n", (int)r); + } +} + +struct M256Ws { + float* ws = nullptr; + int* cnt = nullptr; + size_t floats = 0; + size_t cnts = 0; +}; + +} // namespace + +size_t fp8_m256_ws_floats(int M, int N) { + const int num_mpair = ((M + BLOCK_M - 1) / BLOCK_M + 1) / 2; + return (size_t)num_mpair * (N / BLOCK_N) * 2 * WS_TILE_FLOATS; +} + +void launch_fp8_m256(const void* a, const void* w, const float* sx, const float* sw, void* out, float* ws, int M, + int N, int K, cudaStream_t stream) { + static int sms = 0; + if (sms == 0) { + int dev; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev); + cudaFuncSetAttribute(fp8_m256_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + } + // Persistent DOUBLE-BUFFERED fp32 workspace (2 parities x ws tiles) + per-ws-tile k-block counters (heap-held + // raw device memory, never freed -> no static CUDA-object destructor). Call c red.adds into parity c&1 (which + // must be all-zero on entry) and, via each split tile's tile-end piece, re-zeroes the same tiles of parity + // (c+1)&1 that call c-1 dirtied. Invariant (same plan every call): on entry, the current parity is zero. + // Counters are reset by their owner piece. Everything is re-zeroed on (re)allocation or when the plan + // signature (N, K, #clusters) changes. The `ws` argument is ignored. + (void)ws; + static M256Ws& S = *new M256Ws(); + static int parity = 0; + static long long plan_key = -1; + { + const size_t need = 2 * fp8_m256_ws_floats(M, N); + const size_t needc = need / 2 / WS_TILE_FLOATS; + if (need > S.floats || needc > S.cnts) { + if (S.ws) { + cudaStreamSynchronize(stream); + cudaFree(S.ws); + cudaFree(S.cnt); + } + S.floats = need > S.floats ? need : S.floats; + S.cnts = S.floats / 2 / WS_TILE_FLOATS; + cudaMalloc(&S.ws, S.floats * sizeof(float)); + cudaMalloc(&S.cnt, S.cnts * sizeof(int)); + plan_key = -1; // force a full zero below + } + } + CUtensorMap ta, tb; // + output map below + make_tmap(&ta, a, (uint64_t)M, (uint64_t)K, BLOCK_M); + make_tmap(&tb, w, (uint64_t)N, (uint64_t)K, BLOCK_N / 2); // each CTA loads (and multicasts) a 128-row half + CUtensorMap to; + make_tmap_out(&to, out, (uint64_t)M, (uint64_t)N); + CUtensorMap to128; + make_tmap_out128(&to128, out, (uint64_t)M, (uint64_t)N); + const int num_mpair = ((M + BLOCK_M - 1) / BLOCK_M + 1) / 2; + const long long total = (long long)num_mpair * (N / BLOCK_N) * (K / BLOCK_K); + int ncl = sms / 2; + if (total < ncl) ncl = (int)total; + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3(ncl * 2, 1, 1); + cfg.blockDim = dim3(NUM_THREADS, 1, 1); + cfg.dynamicSmemBytes = SMEM_BYTES; + cfg.stream = stream; + cudaLaunchAttribute attr[1]; + attr[0].id = cudaLaunchAttributeClusterDimension; + attr[0].val.clusterDim.x = 2; + attr[0].val.clusterDim.y = 1; + attr[0].val.clusterDim.z = 1; + cfg.attrs = attr; + cfg.numAttrs = 1; + // The owner piece spins on contributors from other clusters, so every cluster must be co-resident: + // cap the cluster count at the device's max active clusters for this kernel / config. + static int max_cl = 0; + if (max_cl == 0) { + cudaLaunchConfig_t q = cfg; + q.gridDim = dim3(sms, 1, 1); + if (cudaOccupancyMaxActiveClusters(&max_cl, fp8_m256_kernel, &q) != cudaSuccess || max_cl <= 0) max_cl = 1; + } + if (ncl > max_cl) { + ncl = max_cl; + cfg.gridDim = dim3(ncl * 2, 1, 1); + } + const long long key = ((long long)N << 40) ^ ((long long)K << 16) ^ ((long long)num_mpair << 9) ^ (long long)ncl; + if (key != plan_key) { + cudaMemsetAsync(S.ws, 0, S.floats * sizeof(float), stream); + cudaMemsetAsync(S.cnt, 0, S.cnts * sizeof(int), stream); + plan_key = key; + parity = 0; + } + const size_t half = S.floats / 2; + float* ws_cur = S.ws + (size_t)parity * half; + float* ws_nxt = S.ws + (size_t)(parity ^ 1) * half; + parity ^= 1; + cudaLaunchKernelEx(&cfg, fp8_m256_kernel, ta, tb, to, to128, sx, sw, ws_cur, ws_nxt, S.cnt, reinterpret_cast<__nv_bfloat16*>(out), M, N, K); +} diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256.h b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256.h new file mode 100644 index 0000000000000000000000000000000000000000..43812cd11d3fd3bceda65b86ceebacf4974e4084 --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256.h @@ -0,0 +1,9 @@ +#pragma once +#include +#include +// 2-CTA-cluster (along M) W-multicast stream-K FP8 blockwise GEMM, used for 128 < M <= 256. +// ws: ignored (an internal persistent self-cleaning workspace + per-tile counters is always used; +// the fp32 -> bf16 conversion is fused into the GEMM kernel). +size_t fp8_m256_ws_floats(int M, int N); +void launch_fp8_m256(const void* a, const void* w, const float* sx, const float* sw, void* out, float* ws, int M, + int N, int K, cudaStream_t stream); diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256c.cu b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256c.cu new file mode 100644 index 0000000000000000000000000000000000000000..29fc6b6f2dc67afdd2496f5e8c61c704e6e3ef64 --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256c.cu @@ -0,0 +1,666 @@ +// POWER (this version): idle-role mbarrier waits (TMA empty, scale sempty, pusher ready) suspend-hinted; +// scale producer loads sx as one float4 per row per 4 aligned k-blocks. +// UNIFORM WARP INDEX / TMEM BASE: __shfl_sync-broadcast so tcgen05.ld addresses are uniform. +// PER-WARPGROUP SCALE PAIR (this version): the scale producer stores, per k-block, sw for the (at most two) 128-col +// scale blocks of each promotion warpgroup {g0: A,B | g1: A,B}; promotion does 1 ld.shared sx + 1 ld.shared.v2 sw, +// 2 FMUL and a warp-uniform chunk-boundary select (was 4 ld.shared + 3 FMUL + 14 SEL per k-block). +// M = 256-class KERNEL v3 (kernel_m256c.cu): 4-CTA cluster, NO global split-K partials. +// +// out[m, n] = sum_kb sx[m, kb] * sw[kb, n/128] * sum_{k in kb} A[m,k] * W[n,k] +// +// Tiling: tile = 128 tokens x 224 hidden cols (N = 7168 = 32 x 224; tcgen05 kind::f8f6f4 M128 N224 K32). +// 2 M-tiles x (N/224) N-tiles, every tile split-K 2 -> grid = 4 * N/224 CTAs (128 for N = 7168). +// Cluster of 4 CTAs = one N-tile: rank r -> mh = r & 1 (M-tile: rows mh*128..+128), kh = r >> 1 (K half). +// * W multicast: the two CTAs {mh = 0, 1} of a K half share the same 224x128 W k-slab; each loads its +// 112-row half (14 KB) with .multicast::cluster to both (mask 0b11 << 2*kh) -> W read from L2/DRAM once. +// full barrier: local, expects A (16 KB) + both W halves (28 KB); empty barrier: count 2, released by +// the multicast tcgen05.commit of both CTAs' MMAs. +// * Each CTA runs nkb/2 k-blocks into a double-buffered TMEM accumulator (2 x 224 of 512 cols); 8 +// promotion warps scale each k-block's partial by sx[row]*sw[kb, col/128] (per 16-col chunk; a chunk +// never straddles a 128-col scale block since n0 % 16 == 0) into fp32 registers. +// * K-pair reduction by ASYNC DSMEM PUSH (no workspace / atomics / mid-kernel cluster barrier): CTA kh owns +// rows [kh*64, +64) of its M-tile. Owner warps arm a receive mbarrier and remote-arrive a per-warp 'ready' +// mbarrier in the K partner; the partner's pusher warp stages its fp32 slice in its idle ring and issues one +// cp.async.bulk smem -> owner smem (complete_tx). Owner adds, packs bf16, TMA-stores one 32x112 box per warp. +// Single end-of-kernel cluster barrier. +// Roles (12 warps): warp0 TMA producer, warp1 TMEM alloc + MMA issuer, warps2-3 scale producer +// (per k-block sx[128 rows] + 3 sw values into an 8-slot smem ring), warps 4..11 promotion +// (warpgroup g = cols [g*112, +112), thread = tile row = TMEM lane). +#include +#include +#include +#include +#include +#include "tmap_cache.h" +#include "kernel_m256c.h" +#include "raw_push.h" // EXACT fp32 K-pair push (was fp24) +#include "fp24_push.h" // fp24 push + +namespace { + +constexpr int BLOCK_M = 128; +constexpr int TN = 224; // tile cols (MMA N) +constexpr int HALF_N = TN / 2; // W rows loaded per CTA (multicast half) / cols per promotion warpgroup +constexpr int BLOCK_K = 128; +constexpr int STAGES = 5; // 5 x 44 KB ring (220 KB): absorbs K-pair / DRAM skew (empty barrier needs both multicast CTAs) +constexpr int TILE_A_BYTES = BLOCK_M * BLOCK_K; // 16 KB +constexpr int TILE_B_BYTES = TN * BLOCK_K; // 28 KB +constexpr int STAGE_BYTES = TILE_A_BYTES + TILE_B_BYTES; // 44 KB (1024-multiple) +constexpr int NUM_EPI_WARPS = 8; +constexpr int EPI_WARP0 = 4; +constexpr int NUM_THREADS = 128 + NUM_EPI_WARPS * 32; +constexpr int TMEM_COLS = 512; +constexpr int SC_SLOTS = 8; +constexpr int SC_SLOT_FLOATS = 136; // 128 sx (per row) + 3 sw (+pad) +constexpr int SC_BYTES = SC_SLOTS * SC_SLOT_FLOATS * 4; +constexpr int SMEM_BYTES = STAGES * STAGE_BYTES + SC_BYTES + 1024 + 512; +constexpr int NCHUNK = HALF_N / 16; // 7 x16 TMEM chunks per warpgroup +constexpr int PARK_F4 = HALF_N / 4; // 28 float4 per thread +static_assert(SMEM_BYTES <= 232448, "smem budget"); +static_assert(STAGE_BYTES % 1024 == 0 && (HALF_N * BLOCK_K) % 1024 == 0, "swizzle atom alignment"); +static_assert(2 * 64 * TN * 4 <= STAGES * STAGE_BYTES, "park area"); +// push-reduction ring layout (after the mainloop): [0, 56K) recv slots, [56K, 112K) outgoing staging, +// [112K, 140K) bf16 output staging; slot q = g*2 + (sub&1), 14 KB fp32 (32 rows x 112 cols) per warp. +constexpr uint32_t WSL = PARK_F4 * 32 * 16; // 14336 B +constexpr uint32_t OUT_OFF = 4 * WSL; +constexpr uint32_t BF_OFF = 8 * WSL; +static_assert(rawpush::slice_bytes(HALF_N) <= WSL, "raw slice fits slot"); +static_assert(BF_OFF + 4 * 32 * HALF_N * 2 <= STAGES * STAGE_BYTES, "push + bf16 staging area"); +constexpr int REGS_CTRL = 56; +constexpr int REGS_EPI = 224; + +__device__ __forceinline__ uint32_t smem_u32(const void* p) { + return static_cast(__cvta_generic_to_shared(p)); +} +__device__ __forceinline__ uint32_t cluster_ctarank() { + uint32_t r; + asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(r)); + return r; +} +__device__ __forceinline__ void cluster_sync() { + asm volatile("barrier.cluster.arrive.release.aligned;\n\tbarrier.cluster.wait.acquire.aligned;" ::: "memory"); +} +__device__ __forceinline__ void mbar_init(uint64_t* bar, uint32_t count) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(smem_u32(bar)), "r"(count)); +} +__device__ __forceinline__ void mbar_arrive_expect_tx(uint64_t* bar, uint32_t bytes) { + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(smem_u32(bar)), "r"(bytes) + : "memory"); +} +__device__ __forceinline__ void mbar_arrive(uint64_t* bar) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(smem_u32(bar)) : "memory"); +} +__device__ __forceinline__ void mbar_wait(uint64_t* bar, uint32_t parity) { + uint32_t addr = smem_u32(bar); + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAIT_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n" + "@!p bra WAIT_%=;\n" + "}\n" ::"r"(addr), + "r"(parity) + : "memory"); +} +__device__ __forceinline__ void mbar_wait_sleep(uint64_t* bar, uint32_t parity) { + uint32_t addr = smem_u32(bar); + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITS_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITS_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +__device__ __forceinline__ void ffma2(float& a0, float& a1, uint32_t x0, uint32_t x1, float2 ss) { + const float2 d = __ffma2_rn(make_float2(__uint_as_float(x0), __uint_as_float(x1)), ss, make_float2(a0, a1)); + a0 = d.x; + a1 = d.y; +} +__device__ __forceinline__ void fadd2(float& a0, float& a1, float x0, float x1) { + const float2 d = __ffma2_rn(make_float2(x0, x1), make_float2(1.f, 1.f), make_float2(a0, a1)); + a0 = d.x; + a1 = d.y; +} +__device__ __forceinline__ void tma_load_2d(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1, {%2, %3}], [%4];" ::"r"( + smem_u32(dst)), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(smem_u32(bar)) + : "memory"); +} +__device__ __forceinline__ void tma_load_2d_mc_hint(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y, + uint16_t mask, uint64_t policy) { + 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"(smem_u32(dst)), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(smem_u32(bar)), "h"(mask), "l"(policy) + : "memory"); +} +__device__ __forceinline__ float lds_f32(uint32_t a) { + float v; + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(v) : "r"(a) : "memory"); + return v; +} +__device__ __forceinline__ void sts_f4(uint32_t a, float x, float y, float z, float w) { + asm volatile("st.shared.v4.f32 [%0], {%1, %2, %3, %4};" ::"r"(a), "f"(x), "f"(y), "f"(z), "f"(w) : "memory"); +} +__device__ __forceinline__ void sts_u4(uint32_t a, uint4 v) { + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(a), "r"(v.x), "r"(v.y), "r"(v.z), "r"(v.w) : "memory"); +} +__device__ __forceinline__ void tma_store_2d(const CUtensorMap* map, uint32_t src, int x, int y) { + // output store with an L2 evict_first policy: the bf16 output is written once and never re-read by this + // kernel, so its lines should not evict the W / A operand lines the tile raster reuses from L2. + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%1, %2}], [%3], %4;" ::"l"( + reinterpret_cast(map)), + "r"(x), "r"(y), "r"(src), "l"(pol) + : "memory"); +} +__device__ __forceinline__ uint32_t mapa_shared(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; +} +__device__ __forceinline__ float4 ld_dsmem_f4(uint32_t a) { + 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"(a) + : "memory"); + return v; +} +__device__ __forceinline__ void mbar_arrive_remote(uint32_t cluster_addr) { + asm volatile("mbarrier.arrive.release.cluster.shared::cluster.b64 _, [%0];" ::"r"(cluster_addr) : "memory"); +} +__device__ __forceinline__ void mbar_arrive_remote_relaxed(uint32_t cluster_addr) { + asm volatile("mbarrier.arrive.relaxed.cluster.shared::cluster.b64 _, [%0];" ::"r"(cluster_addr) : "memory"); +} +__device__ __forceinline__ void cluster_sync_end_relaxed() { + asm volatile("barrier.cluster.arrive.relaxed.aligned;\n\tbarrier.cluster.wait.acquire.aligned;" ::: "memory"); +} +__device__ __forceinline__ void mbar_wait_cluster(uint32_t addr, uint32_t parity) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITC_%=:\n" + "mbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITC_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +// local smem -> peer CTA smem bulk copy, completion (complete_tx) on the peer's mbarrier +__device__ __forceinline__ void bulk_s2dsmem(uint32_t dst_cl, uint32_t src, uint32_t bytes, uint32_t mbar_cl) { + asm volatile("cp.async.bulk.shared::cluster.shared::cta.mbarrier::complete_tx::bytes [%0], [%1], %2, [%3];" ::"r"( + dst_cl), + "r"(src), "r"(bytes), "r"(mbar_cl) + : "memory"); +} +__device__ __forceinline__ float4 lds_f4(uint32_t a) { + float4 v; + asm volatile("ld.shared.v4.f32 {%0, %1, %2, %3}, [%4];" : "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w) : "r"(a) : "memory"); + return v; +} +__device__ __forceinline__ uint64_t make_sdesc(uint32_t saddr) { + uint64_t d = 0; + d |= (uint64_t)((saddr & 0x3FFFF) >> 4); + d |= (uint64_t)1 << 16; + d |= (uint64_t)(1024 >> 4) << 32; + d |= (uint64_t)1 << 46; + d |= (uint64_t)2 << 61; + return d; +} +__device__ __forceinline__ void mma_f8(uint32_t tmem_d, uint64_t adesc, uint64_t bdesc, uint32_t idesc, + uint32_t accum) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "setp.ne.b32 p, %4, 0;\n" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %3, p;\n" + "}\n" ::"r"(tmem_d), + "l"(adesc), "l"(bdesc), "r"(idesc), "r"(accum)); +} +__device__ __forceinline__ void mma_commit(uint64_t* bar) { + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(smem_u32(bar)) + : "memory"); +} +__device__ __forceinline__ void mma_commit_mc(uint64_t* bar, uint16_t mask) { + asm volatile( + "tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%0], %1;" ::"r"( + smem_u32(bar)), + "h"(mask) + : "memory"); +} +__device__ __forceinline__ void fence_after() { asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void fence_before() { asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory"); } + +#define TMEM_LD32(taddr, r) \ + 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)) + +#define TMEM_LD16(taddr, r) \ + 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"(taddr)) + +__device__ __forceinline__ void tmem_ld_wait() { asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); } + +// acc[c*16 .. +16) += partial chunk c * s +__device__ __forceinline__ void promo_chunk(float* a, const uint32_t* r, float s) { + const float2 ss = make_float2(s, s); +#pragma unroll + for (int j = 0; j < 16; j += 2) ffma2(a[j], a[j + 1], r[j], r[j + 1], ss); +} + +// NP = 1: 4-CTA cluster (2 M x 2 K) = one N-tile. NP = 2 (A-MULTICAST, this version): 8-CTA cluster = +// 2 N-tiles x 2 M x 2 K; rank r -> mh = r&1, kh = (r>>1)&1, nh = r>>2. Each CTA loads only a 64-row HALF of its +// A tile (rows m0 + nh*64) and multicasts it to itself and its N partner (r^4), so A L2->SM traffic halves. +// A stage is written by self, the M partner (W half) and the N partner (A half) -> empty count 3, MMA commit +// multicast to {r, r^1, r^4}. +template +__global__ void __launch_bounds__(NUM_THREADS, 1) + fp8_m256c_kernel(const __grid_constant__ CUtensorMap tmap_a, const __grid_constant__ CUtensorMap tmap_b, + const __grid_constant__ CUtensorMap tmap_out, + const float* __restrict__ scale_x, const float* __restrict__ scale_w, + __nv_bfloat16* __restrict__ out, int M, int N, int K) { + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(smem_raw) + 1023) & ~uintptr_t(1023)); + float* sc_ring = reinterpret_cast(smem + STAGES * STAGE_BYTES); + uint64_t* full_bar = reinterpret_cast(smem + STAGES * STAGE_BYTES + SC_BYTES); + uint64_t* empty_bar = full_bar + STAGES; + uint64_t* tfull_bar = empty_bar + STAGES; + uint64_t* tempty_bar = tfull_bar + 2; + uint64_t* sfull_bar = tempty_bar + 2; + uint64_t* sempty_bar = sfull_bar + SC_SLOTS; + uint64_t* ready_bar = sempty_bar + SC_SLOTS; // [4] slot q: partner's owner warp q ring idle -> may push + uint64_t* recv_bar = ready_bar + 4; // [4] slot q: partner's slice landed here (complete_tx) + uint32_t* tmem_slot = reinterpret_cast(recv_bar + 4); + + // warp-uniform warp index (shfl from lane 0): role / TMEM-address math can live in uniform registers + const int warp = __shfl_sync(0xffffffffu, (int)(threadIdx.x / 32), 0); + const int lane = threadIdx.x % 32; + const int num_kb = K / BLOCK_K; + const int num_sblk = N / 128; + const int rank = (int)cluster_ctarank(); + const int mh = rank & 1, kh = (rank >> 1) & 1; + const int nh = NP == 2 ? (rank >> 2) : 0; + const int nt = NP == 2 ? (blockIdx.x >> 3) * 2 + nh : (blockIdx.x >> 2); + const int n0 = nt * TN; + const int m0 = mh * BLOCK_M; + const int kbeg = kh * (num_kb / 2), kend = kbeg + num_kb / 2; + const uint16_t pair_mask = (uint16_t)(0x3u << (rank & 6)); // W multicast: {r, r^1} + const uint16_t a_mask = (uint16_t)((1u << rank) | (1u << (rank ^ 4))); // NP=2 A multicast: {r, r^4} + const uint16_t rel_mask = NP == 2 ? (uint16_t)(pair_mask | a_mask) : pair_mask; // stage writers to release + + if (threadIdx.x == 0) { + for (int i = 0; i < STAGES; ++i) { + mbar_init(&full_bar[i], 1); + mbar_init(&empty_bar[i], NP == 2 ? 3 : 2); // both CTAs of the multicast pair must release the stage + } + for (int i = 0; i < 2; ++i) { + mbar_init(&tfull_bar[i], 1); + mbar_init(&tempty_bar[i], NUM_EPI_WARPS); + } + for (int i = 0; i < SC_SLOTS; ++i) { + mbar_init(&sfull_bar[i], 64); + mbar_init(&sempty_bar[i], NUM_EPI_WARPS); + } + for (int i = 0; i < 4; ++i) { + mbar_init(&ready_bar[i], 1); + mbar_init(&recv_bar[i], 1); + } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_a)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_b)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_out)) : "memory"); + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(smem_u32(tmem_slot)), + "r"(TMEM_COLS)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + fence_before(); + __syncthreads(); + // PDL: everything above (barrier init, TMEM alloc, tensormap prefetch) overlaps the previous grid's tail; + // no global memory is touched before the previous grid has completed and flushed. + asm volatile("griddepcontrol.wait;" ::: "memory"); + asm volatile("barrier.cluster.arrive.relaxed.aligned;\n\tbarrier.cluster.wait.acquire.aligned;" ::: "memory"); /* RELAXED arrive: no generic data to publish */ // peer barriers initialised before any multicast / remote arrive + fence_after(); + const uint32_t tmem_base = __shfl_sync(0xffffffffu, *tmem_slot, 0); // warp-uniform TMEM base + + if (warp < EPI_WARP0) { + asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;" ::"n"(REGS_CTRL)); + if (warp == 0) { + // ------------------------------------------------ TMA producer + if (lane == 0) { + uint64_t pol_w, pol_a; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_w)); + asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol_a)); + uint32_t it = 0; + for (int kb = kbeg; kb < kend; ++kb, ++it) { + const int s = it % STAGES; + const uint32_t ph = (it / STAGES) & 1; + uint8_t* sa = smem + s * STAGE_BYTES; + uint8_t* sb = sa + TILE_A_BYTES; + mbar_wait_sleep(&empty_bar[s], ph ^ 1); // both pair CTAs' MMAs finished reading stage s + mbar_arrive_expect_tx(&full_bar[s], STAGE_BYTES); + if constexpr (NP == 2) // my 64-row A half -> same offset in me and my N partner + tma_load_2d_mc_hint(sa + nh * (64 * BLOCK_K), &tmap_a, &full_bar[s], kb * BLOCK_K, m0 + nh * 64, a_mask, + pol_a); + else + tma_load_2d(sa, &tmap_a, &full_bar[s], kb * BLOCK_K, m0); // rows >= M zero-filled + tma_load_2d_mc_hint(sb + mh * (HALF_N * BLOCK_K), &tmap_b, &full_bar[s], kb * BLOCK_K, n0 + mh * HALF_N, + pair_mask, pol_w); + } + // drain: every stage's last use released by both pair CTAs (no remote arrive after exit) + for (int i = 0; i < STAGES; ++i, ++it) { + const int s = it % STAGES; + mbar_wait_sleep(&empty_bar[s], ((it / STAGES) & 1) ^ 1); + } + } + } else if (warp == 1) { + // ------------------------------------------------ MMA issuer + if (lane == 0) { + const uint32_t idesc = (1u << 4) | ((uint32_t)(TN >> 3) << 17) | ((uint32_t)(BLOCK_M >> 4) << 24); + uint32_t it = 0; + for (int kb = kbeg; kb < kend; ++kb, ++it) { + const int s = it % STAGES; + const uint32_t ph = (it / STAGES) & 1; + const int b = it & 1; + mbar_wait_sleep(&full_bar[s], ph); + const uint32_t sa = smem_u32(smem + s * STAGE_BYTES); + const uint64_t adesc = make_sdesc(sa); + const uint64_t bdesc = make_sdesc(sa + TILE_A_BYTES); + const uint32_t tmem_d = tmem_base + b * 256; + mbar_wait_sleep(&tempty_bar[b], ((it >> 1) & 1) ^ 1); + fence_after(); +#pragma unroll + for (int k = 0; k < BLOCK_K / 32; ++k) mma_f8(tmem_d, adesc + 2 * k, bdesc + 2 * k, idesc, k > 0 ? 1u : 0u); + mma_commit_mc(&empty_bar[s], rel_mask); // free stage s in both pair CTAs + mma_commit(&tfull_bar[b]); + } + } + } else { + // ------------------------------------------------ scale producer (warps 2,3) + // slot: [0,128) = sx[m0+row, kb] (0 for rows >= M), [128,132) = sw[kb, blk] for {g0 blkA, g0 blkB, g1 blkA, g1 blkB} + const int lt = threadIdx.x - 64; + const int ra = m0 + lt, rb = ra + 64; + const float* pa = scale_x + (size_t)(ra < M ? ra : 0) * num_kb; + const float* pb = scale_x + (size_t)(rb < M ? rb : 0) * num_kb; + // lt < 4: warpgroup gg = lt >> 1, block A (lt even) = first scale block of its 112 cols, B = next (clamped) + const int gg = (lt >> 1) & 1; + const int blk = ((n0 + gg * HALF_N) >> 7) + (lt & 1); + const int wj = blk < num_sblk ? blk : num_sblk - 1; + uint32_t it = 0; + for (int kb = kbeg; kb < kend; kb += 4) { + const int nq = (kend - kb) < 4 ? (kend - kb) : 4; + float xa[4], xb[4], wv[4]; + if (nq == 4 && ((kb | num_kb) & 3) == 0) { + // POWER: one 16 B sx load per row per 4 k-blocks (row base 16B-aligned since num_kb % 4 == 0) + const float4 va = ra < M ? __ldg(reinterpret_cast(pa + kb)) : make_float4(0.f, 0.f, 0.f, 0.f); + const float4 vb = rb < M ? __ldg(reinterpret_cast(pb + kb)) : make_float4(0.f, 0.f, 0.f, 0.f); + xa[0] = va.x; xa[1] = va.y; xa[2] = va.z; xa[3] = va.w; + xb[0] = vb.x; xb[1] = vb.y; xb[2] = vb.z; xb[3] = vb.w; +#pragma unroll + for (int q = 0; q < 4; ++q) wv[q] = __ldg(scale_w + (size_t)(kb + q) * num_sblk + wj); + } else { +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + xa[q] = ra < M ? __ldg(pa + kb + q) : 0.f; + xb[q] = rb < M ? __ldg(pb + kb + q) : 0.f; + wv[q] = __ldg(scale_w + (size_t)(kb + q) * num_sblk + wj); + } + } + } +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + const uint32_t ii = it + q; + const int slot = ii % SC_SLOTS; + mbar_wait_sleep(&sempty_bar[slot], ((ii / SC_SLOTS) & 1) ^ 1); + float* d = sc_ring + slot * SC_SLOT_FLOATS; + d[lt] = xa[q]; + d[lt + 64] = xb[q]; + if (lt < 4) d[128 + lt] = wv[q]; + mbar_arrive(&sfull_bar[slot]); + } + } + it += nq; + } + } + __syncwarp(); + cluster_sync_end_relaxed(); // single end barrier (relaxed arrive): no CTA exits while DSMEM copies from / into it may be pending + } else { + // ------------------------------------------------ promotion (warps 4..11) + asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;" ::"n"(REGS_EPI)); + const int g = (warp - EPI_WARP0) >> 2; // 112-col half of the tile + const int sub = warp & 3; + const int row = sub * 32 + lane; + const uint32_t taddr_b0 = tmem_base + ((uint32_t)(sub * 32) << 16) + g * HALF_N; + const uint32_t sc_base = smem_u32(sc_ring); + // chunks c >= cb of this warpgroup use scale block B (cb = first 16-col chunk past the 128-col block boundary; + // a chunk never straddles it since n0 and g*112 are multiples of 16); warp-uniform + const int cbase = n0 + g * HALF_N; + const int cb = (((cbase >> 7) + 1) * 128 - cbase) >> 4; + float acc[HALF_N]; +#pragma unroll + for (int j = 0; j < HALF_N; ++j) acc[j] = 0.f; + uint32_t it = 0; + for (int kb = kbeg; kb < kend; ++kb, ++it) { + const int b = it & 1; + const uint32_t slot = it % SC_SLOTS; + mbar_wait_sleep(&sfull_bar[slot], (it / SC_SLOTS) & 1); + const uint32_t sp = sc_base + slot * (SC_SLOT_FLOATS * 4); + const float sxr = lds_f32(sp + row * 4); + float wA, wB; + asm volatile("ld.shared.v2.f32 {%0, %1}, [%2];" : "=f"(wA), "=f"(wB) : "r"(sp + 512 + g * 8) : "memory"); + const float sA = sxr * wA, sB = sxr * wB; + __syncwarp(); + if (lane == 0) mbar_arrive(&sempty_bar[slot]); + float sc[NCHUNK]; +#pragma unroll + for (int c = 0; c < NCHUNK; ++c) sc[c] = c >= cb ? sB : sA; + mbar_wait_sleep(&tfull_bar[b], (it >> 1) & 1); + fence_after(); + const uint32_t taddr = taddr_b0 + ((uint32_t)b << 8); + { + // EARLY-RELEASE DRAIN (ported from kernel_large2 LDN=33; 64 staging regs): cols 0..63 loaded up front + // (2 x32), one wait::ld; after promoting cols 0..31 the freed ra receives cols 64..95 (x32), after cols + // 32..47 the freed rb[0..16) receives cols 96..111 (x16). So the last tcgen05.ld is issued after 48 + // promoted cols (was 64); the 2nd wait::ld + tempty release follow cols 48..63, and the remaining + // 48 cols are promoted after the release. + uint32_t ra[32], rb[32]; + TMEM_LD32(taddr + 0, ra); + TMEM_LD32(taddr + 32, rb); + tmem_ld_wait(); + promo_chunk(acc + 0, ra, sc[0]); + promo_chunk(acc + 16, ra + 16, sc[1]); + TMEM_LD32(taddr + 64, ra); + promo_chunk(acc + 32, rb, sc[2]); + TMEM_LD16(taddr + 96, rb); + promo_chunk(acc + 48, rb + 16, sc[3]); + tmem_ld_wait(); + fence_before(); + __syncwarp(); + if (lane == 0) mbar_arrive(&tempty_bar[b]); + promo_chunk(acc + 64, ra, sc[4]); + promo_chunk(acc + 80, ra + 16, sc[5]); + promo_chunk(acc + 96, rb, sc[6]); + } + } + // ---- K-pair reduction by ASYNC DSMEM PUSH (no cluster barrier between mainloop and reduction). + // CTA kh owns tile rows [kh*64, +64) = sub-partitions {2kh, 2kh+1}. Warp slot q = g*2 + (sub&1) pairs warp + // (g, sub) here with warp (g, sub) in the K partner (rank ^ 2). The operand ring is idle once this CTA's last + // MMA completed (implied by the last tfull): every inbound A / multicast-W write targeted a k-block we consumed. + // owner warp: arms recv[q] (expect_tx 14 KB), remote-arrives the partner's ready[q], waits recv[q], adds the + // slice from LOCAL smem, then stages bf16 and TMA-stores one 32x112 box. + // pusher warp: stages its fp32 slice in local [56K + q*14K) (float4 v of lane at (v*32+lane)*16), waits + // ready[q] (partner's ring idle), and issues ONE cp.async.bulk smem -> partner smem [q*14K) with + // complete_tx on the partner's recv[q]. + // A single end-of-kernel cluster barrier keeps all source/destination smem alive until the copies finish. + const bool own = (sub >> 1) == kh; + const uint32_t q = (uint32_t)(g * 2 + (sub & 1)); + const uint32_t ring = smem_u32(smem); + const uint32_t partner = (uint32_t)(rank ^ 2); + if (!own) { + // RAW FP32 PUSH (raw_push.h): exact partial, 14336 B slice (= WSL) + rawpush::pack(acc, ring + OUT_OFF + q * WSL, lane); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // st.shared visible to the bulk copy engine + __syncwarp(); + if (lane == 0) { + mbar_wait_cluster(smem_u32(&ready_bar[q]), 0); + bulk_s2dsmem(mapa_shared(ring + q * WSL, partner), ring + OUT_OFF + q * WSL, rawpush::slice_bytes(HALF_N), + mapa_shared(smem_u32(&recv_bar[q]), partner)); + } + __syncwarp(); + } else { + if (lane == 0) { + mbar_arrive_expect_tx(&recv_bar[q], rawpush::slice_bytes(HALF_N)); + mbar_arrive_remote_relaxed(mapa_shared(smem_u32(&ready_bar[q]), partner)); + } + __syncwarp(); + mbar_wait_sleep(&recv_bar[q], 0); + rawpush::add(acc, ring + q * WSL, lane); // exact fp32 slice accumulate + const uint32_t stg = ring + BF_OFF + q * (uint32_t)(32 * HALF_N * 2); +#pragma unroll + for (int v = 0; v < HALF_N / 8; ++v) { + __nv_bfloat162 h0 = __floats2bfloat162_rn(acc[v * 8 + 0], acc[v * 8 + 1]); + __nv_bfloat162 h1 = __floats2bfloat162_rn(acc[v * 8 + 2], acc[v * 8 + 3]); + __nv_bfloat162 h2 = __floats2bfloat162_rn(acc[v * 8 + 4], acc[v * 8 + 5]); + __nv_bfloat162 h3 = __floats2bfloat162_rn(acc[v * 8 + 6], acc[v * 8 + 7]); + uint4 pk; + pk.x = *reinterpret_cast(&h0); + pk.y = *reinterpret_cast(&h1); + pk.z = *reinterpret_cast(&h2); + pk.w = *reinterpret_cast(&h3); + sts_u4(stg + lane * (HALF_N * 2) + v * 16, pk); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // st.shared visible to the TMA engine + __syncwarp(); + if (lane == 0) { + tma_store_2d(&tmap_out, stg, n0 + g * HALF_N, m0 + sub * 32); + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); // complete before exit + } + __syncwarp(); + } + cluster_sync_end_relaxed(); // single end barrier (matches the control warps) + } + + fence_before(); + __syncthreads(); + if (warp == 1) { + fence_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tmem_base), "r"(TMEM_COLS)); + } +} + +static void make_tmap(CUtensorMap* map, const void* ptr, uint64_t rows, uint64_t K, uint32_t box_rows) { + cuuint64_t dims[2] = {K, rows}; + cuuint64_t strides[1] = {K}; + cuuint32_t box[2] = {BLOCK_K, box_rows}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(map, CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, const_cast(ptr), dims, strides, + box, estr, 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\n", (int)r); +} + +} // namespace + +bool fp8_m256c_supported(int M, int N, int K) { + return M > 128 && M <= 256 && N % TN == 0 && K % (2 * BLOCK_K) == 0 && K >= 2 * BLOCK_K; +} + +// 1 if the 8-CTA A-multicast variant (NP = 2) can be launched for this N (even N-tile count, all clusters resident) +static int m256c_np2_ok(int N) { + static int np = 0; + static int np_ntiles = -1; + if (np == 0 || np_ntiles != N / TN) { + cudaFuncSetAttribute(fp8_m256c_kernel<1>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaFuncSetAttribute(fp8_m256c_kernel<1>, cudaFuncAttributeNonPortableClusterSizeAllowed, 1); + cudaFuncSetAttribute(fp8_m256c_kernel<2>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaFuncSetAttribute(fp8_m256c_kernel<2>, cudaFuncAttributeNonPortableClusterSizeAllowed, 1); + np = 1; + np_ntiles = N / TN; + if ((N / TN) % 2 == 0) { + cudaLaunchConfig_t q = {}; + q.gridDim = dim3((N / TN) * 4, 1, 1); + q.blockDim = dim3(NUM_THREADS, 1, 1); + q.dynamicSmemBytes = SMEM_BYTES; + cudaLaunchAttribute qa[1]; + qa[0].id = cudaLaunchAttributeClusterDimension; + qa[0].val.clusterDim.x = 8; + qa[0].val.clusterDim.y = 1; + qa[0].val.clusterDim.z = 1; + q.attrs = qa; + q.numAttrs = 1; + int n = 0; + if (cudaOccupancyMaxActiveClusters(&n, fp8_m256c_kernel<2>, &q) != cudaSuccess) { + cudaGetLastError(); + n = 0; + } + if (n >= (N / TN) / 2) np = 2; + } + } + return np == 2; +} + +bool fp8_m256c_amc_supported(int M, int N, int K) { return fp8_m256c_supported(M, N, K) && m256c_np2_ok(N); } + +void launch_fp8_m256c(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, int K, + cudaStream_t stream) { + launch_fp8_m256c_np(a, w, sx, sw, out, M, N, K, stream, 1); +} + +// np_req = 1: 4-CTA clusters (seed behaviour); 2: 8-CTA A-multicast clusters (falls back to 1 if unsupported) +void launch_fp8_m256c_np(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, + int K, cudaStream_t stream, int np_req) { + const int np = (np_req == 2 && m256c_np2_ok(N)) ? 2 : (m256c_np2_ok(N), 1); // also sets func attributes + CUtensorMap ta, tb, to; + make_tmap(&ta, a, (uint64_t)M, (uint64_t)K, np == 2 ? 64 : BLOCK_M); // NP=2: 64-row A halves + make_tmap(&tb, w, (uint64_t)N, (uint64_t)K, HALF_N); + { + // bf16 output map: dims {N, M}, box {112 cols (224 B), 32 rows}, no swizzle (row-major staging) + cuuint64_t dims[2] = {(cuuint64_t)N, (cuuint64_t)M}; + cuuint64_t strides[1] = {(cuuint64_t)N * 2}; + cuuint32_t box[2] = {HALF_N, 32}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(&to, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, out, dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled(out) failed: %d\n", (int)r); + } + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3((N / TN) * 4, 1, 1); + cfg.blockDim = dim3(NUM_THREADS, 1, 1); + cfg.dynamicSmemBytes = SMEM_BYTES; + cfg.stream = stream; + cudaLaunchAttribute attrs[2]; + attrs[0].id = cudaLaunchAttributeClusterDimension; + attrs[0].val.clusterDim.x = np == 2 ? 8 : 4; + attrs[0].val.clusterDim.y = 1; + attrs[0].val.clusterDim.z = 1; + cfg.attrs = attrs; + // programmatic dependent launch: launch processing / prologue overlaps the preceding grid + attrs[1].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attrs[1].val.programmaticStreamSerializationAllowed = 1; + cfg.numAttrs = 2; + if (np == 2) + cudaLaunchKernelEx(&cfg, fp8_m256c_kernel<2>, ta, tb, to, sx, sw, reinterpret_cast<__nv_bfloat16*>(out), M, N, K); + else + cudaLaunchKernelEx(&cfg, fp8_m256c_kernel<1>, ta, tb, to, sx, sw, reinterpret_cast<__nv_bfloat16*>(out), M, N, K); +} diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256c.h b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256c.h new file mode 100644 index 0000000000000000000000000000000000000000..17760504c6d2fc3959535d429a94afdb14ad4264 --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256c.h @@ -0,0 +1,11 @@ +#pragma once +#include +// 4-CTA-cluster (2 M-tiles x 2 K-halves) FP8 blockwise GEMM for 128 < M <= 256, 128x224 tiles, +// W TMA multicast, split-K pair reduced through DSMEM (no workspace). +bool fp8_m256c_supported(int M, int N, int K); +void launch_fp8_m256c(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, int K, + cudaStream_t stream); +// A-multicast variant (8-CTA clusters, 2 N-tiles x 2 M x 2 K): available iff all 8-clusters co-reside. +bool fp8_m256c_amc_supported(int M, int N, int K); +void launch_fp8_m256c_np(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, + int K, cudaStream_t stream, int np_req); diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256p.cu b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256p.cu new file mode 100644 index 0000000000000000000000000000000000000000..19154a4b26dc25d945e1da2de900b002e67ce1d9 --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256p.cu @@ -0,0 +1,768 @@ +// M = 256-class 2-SM UMMA kernel (kernel_m256p.cu), derived from kernel_m256v (variable-width N tiles, 4-CTA +// clusters filling all SMs, exact fp32 DSMEM K-pair reduction, bf16 TMA store). +// out[m, n] = sum_kb sx[m, kb] * sw[kb, n/128] * sum_{k in kb} A[m,k] * W[n,k] +// Difference vs m256v: instead of two cta_group::1 CTAs (one per 128-row M-block) that each receive the FULL W slab +// via TMA multicast, the two M-block CTAs form a 2-SM UMMA PAIR (ranks {2kh, 2kh+1} of the 4-CTA cluster): +// * one tcgen05.mma.cta_group::2 M=256 x N=16c x K32 issued by the pair leader (even rank) covers both M-blocks; +// * each CTA TMA-loads only its own 128-row A tile and its own 8c-row HALF of the W k-slab into its own smem +// (B operand split across the pair) -> per-SM smem ingest ~29 KB/kb instead of ~42 KB (multicast delivers the +// whole slab to both SMs), and the smaller stages allow a 7-deep ring. +// * TMA completions of both CTAs signal the LEADER's full barrier (.cta_group::2, count 2 = leader expect_tx + +// peer arrive); MMA commits are multicast to both CTAs' empty / tfull barriers; both CTAs' promotion warps +// release a TMEM buffer on the leader's tempty barrier (16 arrivals). +// Each CTA's TMEM holds its own 128 rows x 16c cols, so the promotion, the K-pair DSMEM push reduction between the +// two pairs (partner = rank ^ 2, CTA kh owns tile rows [kh*64, +64)) and the bf16 epilogue are as in m256v. +// Cluster rank r: mh = r & 1 (M-block, rows mh*128..+128), kh = r >> 1 (K half). +#include +#include +#include +#include +#include +#include "tmap_cache.h" +#include "kernel_m256p.h" +#include "raw_push.h" + +namespace { + +constexpr int BLOCK_M = 128; +constexpr int BLOCK_K = 128; +constexpr int MAX_HALF = 112; // widest W half (tile 224 cols) +constexpr int STAGES = 8; // MAX ring depth; actual depth per tile nst = RING_BYTES / stage size (narrow 192-col tiles: 8 x 28 KB, wide 208-col: 7 x 29 KB) +constexpr int TILE_A_BYTES = BLOCK_M * BLOCK_K; // 16 KB +constexpr int STAGE_BYTES = TILE_A_BYTES + MAX_HALF * BLOCK_K; // 30 KB (1024-multiple), widest possible stage +constexpr int RING_BYTES = 8 * (TILE_A_BYTES + 96 * BLOCK_K); // 224 KB operand ring (8 stages of a 192-col tile) +constexpr int NUM_EPI_WARPS = 8; +constexpr int EPI_WARP0 = 4; +constexpr int NUM_THREADS = 128 + NUM_EPI_WARPS * 32; +constexpr int TMEM_COLS = 512; +constexpr int SC_SLOTS = 4; // 4-slot scale ring (was 3); fits by trimming the align slack to 512 B (base is __align__(1024)) +constexpr int SC_SLOT_FLOATS = 132; // 128 sx (per row) + 4 sw +constexpr int SC_BYTES = SC_SLOTS * SC_SLOT_FLOATS * 4; +constexpr int ALIGN_SLACK = 512; // dynamic smem base declared __align__(1024); device trap guards the slack +constexpr int SMEM_BYTES = RING_BYTES + SC_BYTES + ALIGN_SLACK + 320; // barriers: 34 x 8 B + tmem slot +static_assert(SMEM_BYTES <= 232448, "smem budget"); +static_assert(STAGE_BYTES % 1024 == 0, "swizzle atom alignment"); +static_assert(RING_BYTES >= 7 * STAGE_BYTES, "widest tile still gets 7 stages"); +static_assert((2 * STAGES + 4 + 2 * SC_SLOTS + 8) * 8 + 4 <= 320, "barrier region"); +// push-reduction ring layout (after the mainloop): [0, 56K) recv slots, [56K, 112K) outgoing staging, +// [112K, 140K) bf16 output staging; slot q = g*2 + (sub&1), 14 KB fp32 (32 rows x 112 cols) per warp. +constexpr uint32_t WSL = 112 * 128; // 14336 B +constexpr uint32_t OUT_OFF = 4 * WSL; +constexpr uint32_t BF_OFF = 8 * WSL; +static_assert(rawpush::slice_bytes(112) <= WSL, "raw slice fits slot"); +static_assert(BF_OFF + 4 * 32 * 112 * 2 <= (uint32_t)(7 * (TILE_A_BYTES + 80 * BLOCK_K)), "push + bf16 staging area (smallest ring)"); +constexpr int REGS_CTRL = 56; +constexpr int REGS_EPI = 224; + +__device__ __forceinline__ uint32_t smem_u32(const void* p) { + return static_cast(__cvta_generic_to_shared(p)); +} +__device__ __forceinline__ uint32_t cluster_ctarank() { + uint32_t r; + asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(r)); + return r; +} +__device__ __forceinline__ void cluster_sync() { + asm volatile("barrier.cluster.arrive.release.aligned;\n\tbarrier.cluster.wait.acquire.aligned;" ::: "memory"); +} +__device__ __forceinline__ void cluster_sync_end_relaxed() { + asm volatile("barrier.cluster.arrive.relaxed.aligned;\n\tbarrier.cluster.wait.acquire.aligned;" ::: "memory"); +} +__device__ __forceinline__ void mbar_init(uint64_t* bar, uint32_t count) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(smem_u32(bar)), "r"(count)); +} +__device__ __forceinline__ void mbar_arrive_expect_tx(uint64_t* bar, uint32_t bytes) { + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(smem_u32(bar)), "r"(bytes) + : "memory"); +} +__device__ __forceinline__ void mbar_arrive(uint64_t* bar) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(smem_u32(bar)) : "memory"); +} +// remote (cluster address) arrive, default release.cta semantics (as CUTLASS ClusterBarrier::arrive) +// relaxed cluster-scope remote arrive for the TMEM-empty (tempty) release after tcgen05.wait::ld + +// tcgen05.fence::before_thread_sync: TMEM reads complete, no generic-proxy data published. +__device__ __forceinline__ void mbar_arrive_cl_relaxed(uint32_t cluster_addr) { + asm volatile("mbarrier.arrive.relaxed.cluster.shared::cluster.b64 _, [%0];" ::"r"(cluster_addr) : "memory"); +} +__device__ __forceinline__ void mbar_arrive_cl(uint32_t cluster_addr) { + asm volatile("mbarrier.arrive.shared::cluster.b64 _, [%0];" ::"r"(cluster_addr) : "memory"); +} +__device__ __forceinline__ void mbar_wait_sleep(uint64_t* bar, uint32_t parity) { + uint32_t addr = smem_u32(bar); + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITS_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITS_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +__device__ __forceinline__ void mbar_arrive_remote_relaxed(uint32_t cluster_addr) { + asm volatile("mbarrier.arrive.relaxed.cluster.shared::cluster.b64 _, [%0];" ::"r"(cluster_addr) : "memory"); +} +__device__ __forceinline__ void mbar_wait_cluster(uint32_t addr, uint32_t parity) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITC_%=:\n" + "mbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITC_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +__device__ __forceinline__ uint32_t mapa_shared(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; +} +// TMA load into MY smem, complete_tx signalled on the pair LEADER's mbarrier (cluster address), with L2 hint +__device__ __forceinline__ void tma_load_2d_c2(uint32_t dst, const CUtensorMap* map, uint32_t mbar_cl, int x, int y, + uint64_t policy) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.cta_group::2.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(dst), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(mbar_cl), "l"(policy) + : "memory"); +} +__device__ __forceinline__ void sts_u4(uint32_t a, uint4 v) { + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(a), "r"(v.x), "r"(v.y), "r"(v.z), "r"(v.w) : "memory"); +} +__device__ __forceinline__ float lds_f32(uint32_t a) { + float v; + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(v) : "r"(a) : "memory"); + return v; +} +__device__ __forceinline__ void tma_store_2d(const CUtensorMap* map, uint32_t src, int x, int y) { + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%1, %2}], [%3], %4;" ::"l"( + reinterpret_cast(map)), + "r"(x), "r"(y), "r"(src), "l"(pol) + : "memory"); +} +__device__ __forceinline__ void bulk_s2dsmem(uint32_t dst_cl, uint32_t src, uint32_t bytes, uint32_t mbar_cl) { + asm volatile("cp.async.bulk.shared::cluster.shared::cta.mbarrier::complete_tx::bytes [%0], [%1], %2, [%3];" ::"r"( + dst_cl), + "r"(src), "r"(bytes), "r"(mbar_cl) + : "memory"); +} +__device__ __forceinline__ uint64_t make_sdesc(uint32_t saddr) { + uint64_t d = 0; + d |= (uint64_t)((saddr & 0x3FFFF) >> 4); + d |= (uint64_t)1 << 16; + d |= (uint64_t)(1024 >> 4) << 32; // SBO: 8 rows x 128 B + d |= (uint64_t)1 << 46; // sm100 descriptor version + d |= (uint64_t)2 << 61; // SWIZZLE_128B + return d; +} +__device__ __forceinline__ void fence_after() { asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void fence_before() { asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void ffma2(float& a0, float& a1, uint32_t x0, uint32_t x1, float2 ss) { + const float2 d = __ffma2_rn(make_float2(__uint_as_float(x0), __uint_as_float(x1)), ss, make_float2(a0, a1)); + a0 = d.x; + a1 = d.y; +} + +#define TMEM_LD32(taddr, r) \ + 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)) +#define TMEM_LD16(taddr, r) \ + 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"(taddr)) +__device__ __forceinline__ void mbar_wait_sleep_u32(uint32_t addr, uint32_t parity) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITU_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITU_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +// HYBRID wait: one un-hinted try_wait (fast wake), then suspend-hinted loop +__device__ __forceinline__ void mbar_wait_hyb_u32(uint32_t addr, uint32_t parity) { + asm volatile( + "{\n.reg .pred p;\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n@p bra DONEY_%=;\n" + "WAITY_%=:\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n@!p bra WAITY_%=;\nDONEY_%=:\n}\n" + ::"r"(addr), "r"(parity), "n"(0x989680) : "memory"); +} +__device__ __forceinline__ void mbar_arrive_u32(uint32_t addr) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(addr) : "memory"); +} +__device__ __forceinline__ void tmem_ld_wait() { asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); } +__device__ __forceinline__ void tma_prefetch_l2(const CUtensorMap* map, int x, int y) { + asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile [%0, {%1, %2}];" ::"l"(reinterpret_cast(map)), + "r"(x), "r"(y) + : "memory"); +} + +__device__ __forceinline__ void tma_prefetch_l2_hint(const CUtensorMap* map, int x, int y, uint64_t pol) { + asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile.L2::cache_hint [%0, {%1, %2}], %3;" ::"l"( + reinterpret_cast(map)), + "r"(x), "r"(y), "l"(pol) + : "memory"); +} + +__device__ __forceinline__ void promo_chunk(float* a, const uint32_t* r, float s) { + const float2 ss = make_float2(s, s); +#pragma unroll + for (int j = 0; j < 16; j += 2) ffma2(a[j], a[j + 1], r[j], r[j + 1], ss); +} + +// Promotion (NC 16-col chunks of this warpgroup) + exact fp32 K-pair push reduction + bf16 store (as m256v). +// TMEM buffer release goes to the pair LEADER's tempty barrier (cluster address tempty_l0 + b*8). +template +__device__ __forceinline__ void promo_reduce(uint32_t taddr_b0, uint32_t sc_base, uint64_t* sfull_bar, + uint64_t* sempty_bar, uint64_t* tfull_bar, uint32_t tempty_l0, + uint64_t* ready_bar, uint64_t* recv_bar, uint8_t* smem, int g, int sub, + int lane, int row, int cb, int kbeg, int kend, int kh, int rank, + const CUtensorMap* tmap_o, int xcol, int m0, __nv_bfloat16* __restrict__ out, + int M, int N) { + static_assert(NC >= 5 && NC <= 7, "chunks"); + constexpr int NCOL = NC * 16; + float acc[NCOL]; +#pragma unroll + for (int j = 0; j < NCOL; ++j) acc[j] = 0.f; + // SASS AUDIT: warp-uniform 32-bit bases + immediates for the per-kb barrier / scale-ring addresses (no per-kb + // generic-pointer math). tfull = sfull - 32 (tfull[2], tempty[2] precede sfull), sempty = sfull + SC_SLOTS*8. + const uint32_t sfull_u = __shfl_sync(0xffffffffu, smem_u32(sfull_bar), 0); + const uint32_t sempty_u = sfull_u + SC_SLOTS * 8u, tfull_u = sfull_u - 32u; + (void)sempty_bar; (void)tfull_bar; + const uint32_t sc_u = __shfl_sync(0xffffffffu, sc_base, 0); + const uint32_t sc_row = sc_u + (uint32_t)row * 4u; + const uint32_t sc_w = sc_u + 512u + (uint32_t)g * 8u; + uint32_t it = 0; + uint32_t slot = 0, sph = 0; // running scale-ring slot / phase (no % 3 / divide per kb) + for (int kb = kbeg; kb < kend; ++kb, ++it) { + const int b = it & 1; + mbar_wait_sleep_u32(sfull_u + slot * 8u, sph); + const uint32_t soff = slot * (uint32_t)(SC_SLOT_FLOATS * 4); + const float sxr = lds_f32(sc_row + soff); + float wA, wB; + asm volatile("ld.shared.v2.f32 {%0, %1}, [%2];" : "=f"(wA), "=f"(wB) : "r"(sc_w + soff) : "memory"); + const float sA = sxr * wA, sB = sxr * wB; + // MERGED SCALE-SLOT RELEASE: sempty arrive deferred to the tempty release point (one shared __syncwarp) + const uint32_t rel_slot = slot; + if (++slot == SC_SLOTS) { slot = 0; sph ^= 1; } + float sc[NC]; +#pragma unroll + for (int c = 0; c < NC; ++c) sc[c] = c >= cb ? sB : sA; + mbar_wait_sleep_u32(tfull_u + (uint32_t)b * 8u, (it >> 1) & 1); // leader's multicast commit + fence_after(); + const uint32_t taddr = taddr_b0 + ((uint32_t)b << 8); + // early-release drain (64 staging regs): chunks 0..3 up front, later chunks loaded into freed registers + uint32_t ra[32], rb[32]; + TMEM_LD32(taddr + 0, ra); + TMEM_LD32(taddr + 32, rb); + tmem_ld_wait(); + promo_chunk(acc + 0, ra, sc[0]); + promo_chunk(acc + 16, ra + 16, sc[1]); + if constexpr (NC == 7) { + TMEM_LD32(taddr + 64, ra); + promo_chunk(acc + 32, rb, sc[2]); + TMEM_LD16(taddr + 96, rb); + promo_chunk(acc + 48, rb + 16, sc[3]); + } else if constexpr (NC == 6) { + TMEM_LD32(taddr + 64, ra); + promo_chunk(acc + 32, rb, sc[2]); + promo_chunk(acc + 48, rb + 16, sc[3]); + } else { + TMEM_LD16(taddr + 64, ra); + promo_chunk(acc + 32, rb, sc[2]); + promo_chunk(acc + 48, rb + 16, sc[3]); + } + tmem_ld_wait(); + fence_before(); + __syncwarp(); + if (lane == 0) { + mbar_arrive_cl_relaxed(tempty_l0 + (uint32_t)b * 8u); // release LEADER's tempty[b] + mbar_arrive_u32(sempty_u + rel_slot * 8u); // scale-ring slot free (s consumed long before) + } + promo_chunk(acc + 64, ra, sc[4]); + if constexpr (NC >= 6) promo_chunk(acc + 80, ra + 16, sc[5]); + if constexpr (NC == 7) promo_chunk(acc + 96, rb, sc[6]); + } + // EARLY PDL TRIGGER: mainloop done; the dependent grid may start its prologue (it griddepcontrol.wait's for this + // grid's full completion before touching global memory). + asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); + // ---- K-pair reduction by async DSMEM push: CTA kh owns rows [kh*64, +64) of its M-block; partner rank ^ 2. + // This CTA's ring is idle once its last tfull was observed (all MMAs reading it, hence all its TMA loads, done). + const bool own = (sub >> 1) == kh; + const uint32_t q = (uint32_t)(g * 2 + (sub & 1)); + const uint32_t ring = smem_u32(smem); + const uint32_t partner = (uint32_t)(rank ^ 2); + constexpr uint32_t SB = rawpush::slice_bytes(NCOL); + if (!own) { + // REGISTER -> REMOTE SMEM PUSH (st.async, as kernel_m128c): every lane waits for the partner owner warp's + // ring-idle 'ready', then writes its fp32 row slice straight from registers into the partner's recv slot q + // (rawpush layout: float4 v of lane at (v*32 + lane)*16), each 16 B store completing tx bytes on the partner's + // recv_bar[q]. No local staging / bulk copy; same values, same owner add order (bit-identical). + mbar_wait_cluster(smem_u32(&ready_bar[q]), 0); + { + const uint32_t mb = mapa_shared(smem_u32(&recv_bar[q]), partner); + const uint32_t dst = mapa_shared(ring + q * WSL, partner) + (uint32_t)lane * 16u; +#pragma unroll + for (int v = 0; v < NCOL / 4; ++v) + asm volatile("st.async.shared::cluster.mbarrier::complete_tx::bytes.v4.f32 [%0], {%1, %2, %3, %4}, [%5];" + ::"r"(dst + (uint32_t)v * 512u), "f"(acc[4 * v]), "f"(acc[4 * v + 1]), "f"(acc[4 * v + 2]), + "f"(acc[4 * v + 3]), "r"(mb) + : "memory"); + } + __syncwarp(); + } else { + if (lane == 0) { + mbar_arrive_expect_tx(&recv_bar[q], SB); + mbar_arrive_remote_relaxed(mapa_shared(smem_u32(&ready_bar[q]), partner)); + } + __syncwarp(); + mbar_wait_sleep(&recv_bar[q], 0); + rawpush::add(acc, ring + q * WSL, lane); + // DIRECT bf16 STORE (no smem staging / TMA store / bulk wait): thread = one tile row; each 16-col chunk is one + // 32-byte st.global.v8.b32. Rows >= M skipped. + (void)tmap_o; + const int grow = m0 + sub * 32 + lane; + if (grow < M) { + uint64_t pol_o; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_o)); + __nv_bfloat16* dst0 = out + (size_t)grow * N + xcol; +#pragma unroll + for (int c = 0; c < NC; ++c) { + uint32_t pk[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + __nv_bfloat162 h = __floats2bfloat162_rn(acc[c * 16 + 2 * j], acc[c * 16 + 2 * j + 1]); + pk[j] = *reinterpret_cast(&h); + } + // L1::no_allocate (written once, never re-read) + L2 evict_first hint: output lines should not evict + // operand (A / W) lines from L2; they reach DRAM anyway. + asm volatile("st.global.L1::no_allocate.L2::cache_hint.v8.b32 [%0], {%1, %2, %3, %4, %5, %6, %7, %8}, %9;" + ::"l"(dst0 + c * 16), "r"(pk[0]), "r"(pk[1]), "r"(pk[2]), "r"(pk[3]), "r"(pk[4]), "r"(pk[5]), + "r"(pk[6]), "r"(pk[7]), "l"(pol_o) + : "memory"); + } + } + __syncwarp(); + } +} + +// Cluster t (4 CTAs) owns tile cols [n0, n0 + 16c), c = q + (t < rr), n0 = 16*(t*q + min(t, rr)). +__global__ void __launch_bounds__(NUM_THREADS, 1) + fp8_m256p_kernel(const __grid_constant__ CUtensorMap tmap_a, const __grid_constant__ CUtensorMap tmap_b_lo, + const __grid_constant__ CUtensorMap tmap_b_hi, const __grid_constant__ CUtensorMap tmap_o_lo, + const __grid_constant__ CUtensorMap tmap_o_hi, const float* __restrict__ scale_x, + const float* __restrict__ scale_w, int M, int N, int K, int qch, int rr, int pro, + __nv_bfloat16* __restrict__ out) { + extern __shared__ __align__(1024) uint8_t smem_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(smem_raw) + 1023) & ~uintptr_t(1023)); + if (smem - smem_raw > ALIGN_SLACK) __trap(); // never expected: base is 1024-aligned + float* sc_ring = reinterpret_cast(smem + RING_BYTES); + uint64_t* full_bar = reinterpret_cast(smem + RING_BYTES + SC_BYTES); + uint64_t* empty_bar = full_bar + STAGES; + uint64_t* tfull_bar = empty_bar + STAGES; + uint64_t* tempty_bar = tfull_bar + 2; + uint64_t* sfull_bar = tempty_bar + 2; + uint64_t* sempty_bar = sfull_bar + SC_SLOTS; + uint64_t* ready_bar = sempty_bar + SC_SLOTS; // [4] + uint64_t* recv_bar = ready_bar + 4; // [4] + uint32_t* tmem_slot = reinterpret_cast(recv_bar + 4); + + const int warp = __shfl_sync(0xffffffffu, (int)(threadIdx.x / 32), 0); + const int lane = threadIdx.x % 32; + const int num_kb = K / BLOCK_K; + const int num_sblk = N / 128; + const int rank = (int)cluster_ctarank(); + const int mh = rank & 1, kh = (rank >> 1) & 1; + const uint32_t leader = (uint32_t)(rank & 2); // pair leader rank (even) + const int t = blockIdx.x >> 2; + const bool wide = t < rr; + const int c = qch + (wide ? 1 : 0); + const int c0 = (c + 1) >> 1, c1 = c >> 1; + const int n0 = 16 * (t * qch + (t < rr ? t : rr)); + const int wcols = 16 * c; + const int halfr = 8 * c; // W rows per pair-CTA half (multiple of 8 -> 1024 B aligned) + const uint32_t cta_tx = (uint32_t)(TILE_A_BYTES + halfr * BLOCK_K); + // per-tile stage stride (1024-multiple: halfr % 8 == 0) and ring depth (same for both CTAs of the pair: same tile) + const uint32_t sbytes = cta_tx; + const uint32_t nst = (uint32_t)RING_BYTES / sbytes < (uint32_t)STAGES ? (uint32_t)RING_BYTES / sbytes : (uint32_t)STAGES; + // W half loaded as TWO TMA sub-boxes (more independent DRAM requests in flight per SM): sub0 = 8*ceil(c/2) rows, + // sub1 = 8*floor(c/2) rows (both multiples of 8 -> sub1 starts 1024 B aligned, same contiguous 128B-swizzled layout + // as one box). Box-row maps: tmap_b_lo = 8*(q>>1) rows, tmap_b_hi = 8*(q>>1)+8 rows. + const int r0 = 8 * ((c + 1) >> 1), r1 = 8 * (c >> 1); + const int rlo = 8 * (qch >> 1); + const CUtensorMap* tmb0 = r0 == rlo ? &tmap_b_lo : &tmap_b_hi; + const CUtensorMap* tmb1 = r1 == rlo ? &tmap_b_lo : &tmap_b_hi; + (void)wide; + const int m0 = mh * BLOCK_M; + // EVEN K-PAIR SPLIT: each pair (kh = 0: ranks 0,1; kh = 1: ranks 2,3) runs num_kb/2 k-blocks (K % 256 == 0). + // Both CTAs of a pair use the identical issue range (2-SM UMMA requirement). + const int kmid = num_kb / 2; + const int kbeg = kh ? kmid : 0; + const int kend = kh ? num_kb : kmid; + const uint16_t pair_mask = (uint16_t)(0x3u << (rank & 2)); + + // HEAD A L2 PREFETCH (this version): warp 2 lane 0 (idle until the scale-producer role) issues an L2-only bulk-tensor + // prefetch of this CTA's own A tile for the first `pro` k-blocks at kernel entry, in parallel with thread 0's W-half + // prefetch below. A is a read-only input (never written by a preceding grid), the prefetch is a pure hint (no smem / + // barrier / visible state), so it may precede griddepcontrol.wait. evict_last: A is re-read by all clusters. + if (threadIdx.x == 64 && pro > 0) { + uint64_t pol_ap; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_ap)); + for (int kb = kbeg; kb < kend && kb < kbeg + pro; ++kb) { // A as two 64-row sub-boxes + tma_prefetch_l2_hint(&tmap_a, kb * BLOCK_K, m0, pol_ap); + tma_prefetch_l2_hint(&tmap_a, kb * BLOCK_K, m0 + 64, pol_ap); + } + } + if (threadIdx.x == 0) { + for (int i = 0; i < STAGES; ++i) { + mbar_init(&full_bar[i], 2); // leader: own arrive.expect_tx + peer's remote arrive (peer's copy unused) + mbar_init(&empty_bar[i], 1); // leader's multicast commit + } + for (int i = 0; i < 2; ++i) { + mbar_init(&tfull_bar[i], 1); + mbar_init(&tempty_bar[i], 2 * NUM_EPI_WARPS); // leader: one elected arrive per promotion warp of BOTH CTAs + } + for (int i = 0; i < SC_SLOTS; ++i) { + mbar_init(&sfull_bar[i], 64); + mbar_init(&sempty_bar[i], NUM_EPI_WARPS); + } + for (int i = 0; i < 4; ++i) { + mbar_init(&ready_bar[i], 1); + mbar_init(&recv_bar[i], 1); + } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_a)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_b_lo)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_b_hi)) : "memory"); + // HEAD W L2 PREFETCH of this CTA's own W half for the first `pro` k-blocks, issued BEFORE griddepcontrol.wait: + // W is a read-only input never written by a preceding grid and an L2 prefetch is a pure hint (no smem / barrier + // / visible state), so it may overlap the previous grid's tail. evict_first: W is streamed once per call. + if (pro > 0) { + uint64_t pol_pf; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_pf)); + for (int kb = kbeg; kb < kend && kb < kbeg + pro; ++kb) + { + tma_prefetch_l2_hint(tmb0, kb * BLOCK_K, n0 + mh * halfr, pol_pf); + tma_prefetch_l2_hint(tmb1, kb * BLOCK_K, n0 + mh * halfr + r0, pol_pf); + } + } + } + asm volatile("barrier.cluster.arrive.relaxed.aligned;" ::: "memory"); + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::2.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(smem_u32(tmem_slot)), + "r"(TMEM_COLS)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::2.sync.aligned;"); + } + fence_before(); + __syncthreads(); + asm volatile("griddepcontrol.wait;" ::: "memory"); + // EARLY PDL TRIGGER (cross-call overlap): all 148 CTAs (37 x 4-CTA clusters, 1 CTA/SM) are resident, so the + // dependent grid may start its prologue + pre-wait W/A L2 prefetch as SMs free up; it still griddepcontrol.wait's + // for this grid's full completion before touching global state (the later triggers become no-ops). + asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); + asm volatile("barrier.cluster.wait.acquire.aligned;" ::: "memory"); // peers' mbarrier inits visible + fence_after(); + const uint32_t tmem_base = __shfl_sync(0xffffffffu, *tmem_slot, 0); + + if (warp < EPI_WARP0) { + asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;" ::"n"(REGS_CTRL)); + if (warp == 0) { + // ------------------------------------------------ TMA producer (own A tile + own W half) + if (lane == 0) { + uint64_t pol, pol_a; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_a)); + // SASS AUDIT: running stage / phase counters (nst is a runtime value: no per-kb integer divide / modulo) + uint32_t s = 0, ph = 0; + for (int kb = kbeg; kb < kend; ++kb) { + mbar_wait_hyb_u32(smem_u32(&empty_bar[s]), ph ^ 1); // HYBRID; leader's MMAs (both halves) done with stage s + const uint32_t sa = smem_u32(smem) + (uint32_t)s * sbytes; + const uint32_t fb = mapa_shared(smem_u32(&full_bar[s]), leader); + if (mh) mbar_arrive_cl(fb); + else mbar_arrive_expect_tx(&full_bar[s], 2 * cta_tx); // both CTAs' A + W halves + // A tile as TWO 64-row sub-boxes (8 KB each, 1024 B aligned -> identical 128B-swizzled layout as one + // 128-row box; more independent TMA requests in flight). Rows >= M zero-filled, still counted in tx bytes. + tma_load_2d_c2(sa, &tmap_a, fb, kb * BLOCK_K, m0, pol_a); + tma_load_2d_c2(sa + (uint32_t)(64 * BLOCK_K), &tmap_a, fb, kb * BLOCK_K, m0 + 64, pol_a); + tma_load_2d_c2(sa + TILE_A_BYTES, tmb0, fb, kb * BLOCK_K, n0 + mh * halfr, pol); // own W half, sub-box 0 + tma_load_2d_c2(sa + TILE_A_BYTES + (uint32_t)(r0 * BLOCK_K), tmb1, fb, kb * BLOCK_K, n0 + mh * halfr + r0, + pol); // sub-box 1 + if (++s == nst) { s = 0; ph ^= 1; } + } + // drain: every stage's last use released (no multicast commit lands after this CTA exits) + for (uint32_t i = 0; i < nst; ++i) { + mbar_wait_sleep(&empty_bar[s], ph ^ 1); + if (++s == nst) { s = 0; ph ^= 1; } + } + } + } else if (warp == 1) { + // ------------------------------------------------ MMA issuer (pair leader only): M256 x N=16c x K32 + // SASS AUDIT: the issuer loop runs on the WHOLE warp 1 (warp-uniform state -> uniform registers); only the + // tcgen05.mma / commit block is predicated on elect.sync inside the asm (a lane-0-only loop makes ptxas wrap + // each tcgen05 instruction in an ELECT / BRA.U.ANY peeling loop + R2UR copies, as found in kernel_sk2c). + if (mh == 0) { + const uint32_t idesc = (1u << 4) | ((uint32_t)(wcols >> 3) << 17) | ((uint32_t)((2 * BLOCK_M) >> 4) << 24); + const uint32_t full0 = smem_u32(full_bar), empty0 = smem_u32(empty_bar); + const uint32_t tfull0 = smem_u32(tfull_bar), tempty0 = smem_u32(tempty_bar); + const uint64_t adesc0 = make_sdesc(smem_u32(smem)); + constexpr uint64_t BOFF = TILE_A_BYTES >> 4; + const uint64_t SOFF = sbytes >> 4; + uint32_t it = 0, s = 0, ph = 0; + for (int kb = kbeg; kb < kend; ++kb, ++it) { + const uint32_t b = it & 1; + const uint64_t ad = adesc0 + (uint64_t)s * SOFF, bd = ad + BOFF; + asm volatile( + "{\n.reg .pred p;\nWF_%=:\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n@!p bra WF_%=;\n}\n" + ::"r"(full0 + s * 8), "r"(ph) : "memory"); + asm volatile( + "{\n.reg .pred p;\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n@p bra WTD_%=;\nWT_%=:\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n@!p bra WT_%=;\nWTD_%=:\n}\n" + ::"r"(tempty0 + b * 8), "r"(((it >> 1) & 1) ^ 1), "n"(0x989680) : "memory"); + fence_after(); + asm volatile( + "{\n" + ".reg .pred pf, pt, e;\n" + "setp.eq.u32 pt, 1, 1;\n" + "setp.eq.u32 pf, 1, 0;\n" + "elect.sync _|e, 0xffffffff;\n" + "@e tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], %1, %2, %3, pf;\n" + "@e tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], %4, %5, %3, pt;\n" + "@e tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], %6, %7, %3, pt;\n" + "@e tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], %8, %9, %3, pt;\n" + /* TFULL-FIRST commit order: promotion hand-off (tfull, %11) signalled before the stage release (%10) */ + "@e tcgen05.commit.cta_group::2.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%11], %12;\n" + "@e tcgen05.commit.cta_group::2.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%10], %12;\n" + "}\n" ::"r"(tmem_base + b * 256u), + "l"(ad), "l"(bd), "r"(idesc), "l"(ad + 2), "l"(bd + 2), "l"(ad + 4), "l"(bd + 4), "l"(ad + 6), "l"(bd + 6), + "r"(empty0 + s * 8), "r"(tfull0 + b * 8), "h"(pair_mask) + : "memory"); + if (++s == nst) { s = 0; ph ^= 1; } + } + // drain: the final releases of both TMEM buffers (remote arrives from both CTAs) landed before exit + for (int i = 0; i < 2; ++i, ++it) + asm volatile( + "{\n.reg .pred p;\nWD_%=:\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n@!p bra WD_%=;\n}\n" + ::"r"(tempty0 + (it & 1) * 8), "r"(((it >> 1) & 1) ^ 1), "n"(0x989680) : "memory"); + } + } else { + // ------------------------------------------------ scale producer (warps 2,3) + const int lt = threadIdx.x - 64; + const int ra = m0 + lt, rb = ra + 64; + const float* pa = scale_x + (size_t)(ra < M ? ra : 0) * num_kb; + const float* pb = scale_x + (size_t)(rb < M ? rb : 0) * num_kb; + const int gg = (lt >> 1) & 1; + const int blk = ((n0 + gg * 16 * c0) >> 7) + (lt & 1); + const int wj = blk < num_sblk ? blk : num_sblk - 1; + // SOFTWARE-PIPELINED scale producer: the global loads of the NEXT 4-kb batch are issued BEFORE the current batch + // is written into the (only 3-slot) smem ring, so their L2 latency overlaps the sempty waits instead of being + // exposed after every 4 k-blocks (the producer is only ~3 kb ahead of promotion with 3 slots). Same values. + auto load_batch = [&](int kb, float* xa, float* xb, float* wv) __attribute__((always_inline)) { + const int nq = (kend - kb) < 4 ? (kend - kb) : 4; + if (nq == 4 && ((kb | num_kb) & 3) == 0) { + const float4 va = ra < M ? __ldg(reinterpret_cast(pa + kb)) : make_float4(0.f, 0.f, 0.f, 0.f); + const float4 vb = rb < M ? __ldg(reinterpret_cast(pb + kb)) : make_float4(0.f, 0.f, 0.f, 0.f); + xa[0] = va.x; xa[1] = va.y; xa[2] = va.z; xa[3] = va.w; + xb[0] = vb.x; xb[1] = vb.y; xb[2] = vb.z; xb[3] = vb.w; +#pragma unroll + for (int q = 0; q < 4; ++q) wv[q] = __ldg(scale_w + (size_t)(kb + q) * num_sblk + wj); + } else { +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + xa[q] = ra < M ? __ldg(pa + kb + q) : 0.f; + xb[q] = rb < M ? __ldg(pb + kb + q) : 0.f; + wv[q] = __ldg(scale_w + (size_t)(kb + q) * num_sblk + wj); + } else { + xa[q] = 0.f; xb[q] = 0.f; wv[q] = 0.f; + } + } + } + }; + uint32_t it = 0; + float xa[4], xb[4], wv[4]; + for (int kb = kbeg; kb < kend; kb += 32) { + if (ra < M) asm volatile("prefetch.global.L2 [%0];" ::"l"(pa + kb)); + if (rb < M) asm volatile("prefetch.global.L2 [%0];" ::"l"(pb + kb)); + } + for (int kb = kbeg + lt; kb < kend; kb += 64) + asm volatile("prefetch.global.L2 [%0];" ::"l"(scale_w + (size_t)kb * num_sblk + wj)); + if (kbeg < kend) load_batch(kbeg, xa, xb, wv); + for (int kb = kbeg; kb < kend; kb += 4) { + const int nq = (kend - kb) < 4 ? (kend - kb) : 4; + float ya[4], yb[4], yw[4]; + const bool more = kb + 4 < kend; + if (more) load_batch(kb + 4, ya, yb, yw); +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + const uint32_t ii = it + q; + const int slot = ii % SC_SLOTS; + mbar_wait_sleep(&sempty_bar[slot], ((ii / SC_SLOTS) & 1) ^ 1); + float* d = sc_ring + slot * SC_SLOT_FLOATS; + d[lt] = xa[q]; + d[lt + 64] = xb[q]; + if (lt < 4) d[128 + lt] = wv[q]; + mbar_arrive(&sfull_bar[slot]); + } + } + it += nq; + if (more) { +#pragma unroll + for (int q = 0; q < 4; ++q) { xa[q] = ya[q]; xb[q] = yb[q]; wv[q] = yw[q]; } + } + } + } + __syncwarp(); + asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); // EARLY PDL TRIGGER (control warps) + cluster_sync_end_relaxed(); + } else { + // ------------------------------------------------ promotion (warps 4..11) + asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;" ::"n"(REGS_EPI)); + const int g = (warp - EPI_WARP0) >> 2; + const int sub = warp & 3; + const int row = sub * 32 + lane; + const int ncg = g ? c1 : c0; + const int coff = g * 16 * c0; + // warp-uniform TMEM base (shfl broadcast -> uniform register) + const uint32_t taddr_b0 = __shfl_sync(0xffffffffu, tmem_base + ((uint32_t)(sub * 32) << 16) + coff, 0); + const uint32_t sc_base = smem_u32(sc_ring); + const int cbase = n0 + coff; + const int cb = (((cbase >> 7) + 1) * 128 - cbase) >> 4; + const CUtensorMap* tmo = ncg == (qch >> 1) ? &tmap_o_lo : &tmap_o_hi; + const uint32_t tempty_l0 = mapa_shared(smem_u32(&tempty_bar[0]), leader); + if (ncg == 7) + promo_reduce<7>(taddr_b0, sc_base, sfull_bar, sempty_bar, tfull_bar, tempty_l0, ready_bar, recv_bar, smem, g, + sub, lane, row, cb, kbeg, kend, kh, rank, tmo, cbase, m0, out, M, N); + else if (ncg == 6) + promo_reduce<6>(taddr_b0, sc_base, sfull_bar, sempty_bar, tfull_bar, tempty_l0, ready_bar, recv_bar, smem, g, + sub, lane, row, cb, kbeg, kend, kh, rank, tmo, cbase, m0, out, M, N); + else + promo_reduce<5>(taddr_b0, sc_base, sfull_bar, sempty_bar, tfull_bar, tempty_l0, ready_bar, recv_bar, smem, g, + sub, lane, row, cb, kbeg, kend, kh, rank, tmo, cbase, m0, out, M, N); + cluster_sync_end_relaxed(); + } + + fence_before(); + __syncthreads(); + if (warp == 1) { + fence_after(); + asm volatile("tcgen05.dealloc.cta_group::2.sync.aligned.b32 %0, %1;" ::"r"(tmem_base), "r"(TMEM_COLS)); + } +} + +static void make_tmap(CUtensorMap* map, const void* ptr, uint64_t rows, uint64_t K, uint32_t box_rows, + CUtensorMapL2promotion promo = CU_TENSOR_MAP_L2_PROMOTION_L2_256B) { + cuuint64_t dims[2] = {K, rows}; + cuuint64_t strides[1] = {K}; + cuuint32_t box[2] = {BLOCK_K, box_rows}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(map, CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, const_cast(ptr), dims, strides, + box, estr, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, + promo, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled failed: %d\n", (int)r); +} +static void make_tmap_out_w(CUtensorMap* map, void* out, int M, int N, int cols) { + cuuint64_t dims[2] = {(cuuint64_t)N, (cuuint64_t)M}; + cuuint64_t strides[1] = {(cuuint64_t)N * 2}; + cuuint32_t box[2] = {(cuuint32_t)cols, 32}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, out, dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled(out) failed: %d\n", (int)r); +} + +static int m256p_max_clusters() { + static int v = -1; + if (v < 0) { + cudaFuncSetAttribute(fp8_m256p_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + int dev, sms = 0; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev); + cudaLaunchConfig_t q = {}; + q.gridDim = dim3((sms / 4) * 4, 1, 1); + q.blockDim = dim3(NUM_THREADS, 1, 1); + q.dynamicSmemBytes = SMEM_BYTES; + cudaLaunchAttribute qa[1]; + qa[0].id = cudaLaunchAttributeClusterDimension; + qa[0].val.clusterDim.x = 4; + qa[0].val.clusterDim.y = 1; + qa[0].val.clusterDim.z = 1; + q.attrs = qa; + q.numAttrs = 1; + int n = 0; + if (cudaOccupancyMaxActiveClusters(&n, fp8_m256p_kernel, &q) != cudaSuccess) { + cudaGetLastError(); + n = 0; + } + v = n; + } + return v; +} +// tile plan: T clusters, q chunks per narrow tile, rr wide tiles (q+1 chunks); 10 <= q, q+1 <= 14 (160..224 cols) +static bool m256p_plan(int N, int& T, int& q, int& rr) { + if (N % 16 != 0) return false; + T = m256p_max_clusters(); + const int C = N / 16; + if (T <= 0) return false; + if (T > C) T = C; + // BN=224 UNIFORM TILES (this version): if N splits into 224-col tiles (N=7168 -> 32 tiles = 32 x 4-CTA clusters) + // and they all fit co-resident, use them instead of the max-cluster variable-width plan (192/208 cols). + if (N % 224 == 0 && N / 224 <= T) T = N / 224; + q = C / T; + rr = C - q * T; + if (q < 10) return false; + if (q + (rr > 0 ? 1 : 0) > 14) return false; + return true; +} + +} // namespace + +bool fp8_m256p_supported(int M, int N, int K) { + if (!(M > 128 && M <= 256 && K % (2 * BLOCK_K) == 0 && K >= 2 * BLOCK_K && N % 128 == 0)) return false; + int T, q, rr; + return m256p_plan(N, T, q, rr); +} + +void launch_fp8_m256p(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, int K, + cudaStream_t stream, int pro) { + int T, q, rr; + if (!m256p_plan(N, T, q, rr)) return; + CUtensorMap ta, tbl, tbh, tol, toh; + make_tmap(&ta, a, (uint64_t)M, (uint64_t)K, BLOCK_M / 2, CU_TENSOR_MAP_L2_PROMOTION_L2_256B); // 64-row A sub-boxes + make_tmap(&tbl, w, (uint64_t)N, (uint64_t)K, 8 * (q >> 1), CU_TENSOR_MAP_L2_PROMOTION_NONE); + make_tmap(&tbh, w, (uint64_t)N, (uint64_t)K, 8 * (q >> 1) + 8, CU_TENSOR_MAP_L2_PROMOTION_NONE); + make_tmap_out_w(&tol, out, M, N, 16 * (q >> 1)); + make_tmap_out_w(&toh, out, M, N, 16 * ((q >> 1) + 1)); + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3(T * 4, 1, 1); + cfg.blockDim = dim3(NUM_THREADS, 1, 1); + cfg.dynamicSmemBytes = SMEM_BYTES; + cfg.stream = stream; + cudaLaunchAttribute attrs[3]; + attrs[0].id = cudaLaunchAttributeClusterDimension; + attrs[0].val.clusterDim.x = 4; + attrs[0].val.clusterDim.y = 1; + attrs[0].val.clusterDim.z = 1; + attrs[1].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attrs[1].val.programmaticStreamSerializationAllowed = 1; + // CLUSTER SCHEDULING POLICY SPREAD (cluster kernel: DSMEM / cta_group::2 / multicast commits): ask the block + // scheduler to distribute the 32 4-CTA clusters across GPCs (128 of 148 SMs busy) for balanced L2/DRAM ingress. + attrs[2].id = cudaLaunchAttributeClusterSchedulingPolicyPreference; + attrs[2].val.clusterSchedulingPolicyPreference = cudaClusterSchedulingPolicySpread; + cfg.attrs = attrs; + cfg.numAttrs = 3; + cudaLaunchKernelEx(&cfg, fp8_m256p_kernel, ta, tbl, tbh, tol, toh, sx, sw, M, N, K, q, rr, pro, + reinterpret_cast<__nv_bfloat16*>(out)); +} diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256p.h b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256p.h new file mode 100644 index 0000000000000000000000000000000000000000..442af5d3bfcda254ba17e0e354a01ce9a5868164 --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256p.h @@ -0,0 +1,7 @@ +#pragma once +#include +// 128 < M <= 256: variable-width (192/208-col) tiles, 4-CTA clusters = 2 K-halves x 2-SM UMMA pair (cta_group::2, +// M=256 covers both 128-row M-blocks; each CTA loads only its own A tile + W half), exact fp32 DSMEM K-pair reduce. +bool fp8_m256p_supported(int M, int N, int K); +void launch_fp8_m256p(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, int K, + cudaStream_t stream, int pro = 3); diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256v.cu b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256v.cu new file mode 100644 index 0000000000000000000000000000000000000000..add0f513c8dec5cc88feee57b2ec346cbaeb79b8 --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256v.cu @@ -0,0 +1,864 @@ +// M = 256-class VARIABLE-WIDTH kernel (kernel_m256v.cu), derived from kernel_m256c (4-CTA cluster = 2 M-tiles x +// 2 K-halves, W TMA multicast across the M pair, FP24 DSMEM K-pair push reduction, bf16 TMA store). +// out[m, n] = sum_kb sx[m, kb] * sw[kb, n/128] * sum_{k in kb} A[m,k] * W[n,k] +// Difference: m256c uses 32 fixed 224-col tiles -> 128 CTAs (20 of 148 SMs idle). Here the N range is cut into +// T = (#co-resident 4-CTA clusters, 37 on B200) tiles of 16*q or 16*(q+1) cols (N=7168: 4 x 208 + 33 x 192), so +// every SM gets one CTA and the widest tile shrinks 224 -> 208 cols. Tile width is runtime (MMA N = 16c, W half +// box 8c rows from one of two tensor maps, promotion warpgroups get ceil/floor(c/2) 16-col chunks, templated +// promotion+reduction body per chunk count, output store via one of two box-width tensor maps). +#include +#include +#include +#include +#include +#include "tmap_cache.h" +#include "kernel_m256v.h" +#include "fp24_push.h" // fp24 push + +#ifdef M256V_DBG +__device__ unsigned long long* d_m256v_dbg; +__device__ __forceinline__ unsigned long long gt_now() { unsigned long long t; asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); return t; } +#define VDBG(i) do { if (d_m256v_dbg) d_m256v_dbg[blockIdx.x * 8 + (i)] = gt_now(); } while (0) +void m256v_set_dbg(unsigned long long* p) { cudaMemcpyToSymbol(d_m256v_dbg, &p, sizeof(p)); } +#else +#define VDBG(i) do {} while (0) +#endif +namespace { + +constexpr int BLOCK_M = 128; +constexpr int TN = 224; // tile cols (MMA N) +constexpr int HALF_N = TN / 2; // W rows loaded per CTA (multicast half) / cols per promotion warpgroup +constexpr int BLOCK_K = 128; +constexpr int STAGES = 5; // 5 x 44 KB ring (220 KB): absorbs K-pair / DRAM skew (empty barrier needs both multicast CTAs) +constexpr int TILE_A_BYTES = BLOCK_M * BLOCK_K; // 16 KB +constexpr int TILE_B_BYTES = TN * BLOCK_K; // 28 KB +constexpr int STAGE_BYTES = TILE_A_BYTES + TILE_B_BYTES; // 44 KB (1024-multiple) +constexpr int NUM_EPI_WARPS = 8; +constexpr int EPI_WARP0 = 4; +constexpr int NUM_THREADS = 128 + NUM_EPI_WARPS * 32; +constexpr int TMEM_COLS = 512; +constexpr int SC_SLOTS = 8; +constexpr int SC_SLOT_FLOATS = 136; // 128 sx (per row) + 3 sw (+pad) +constexpr int SC_BYTES = SC_SLOTS * SC_SLOT_FLOATS * 4; +constexpr int SMEM_BYTES = STAGES * STAGE_BYTES + SC_BYTES + 1024 + 512; +constexpr int NCHUNK = HALF_N / 16; // 7 x16 TMEM chunks per warpgroup +constexpr int PARK_F4 = HALF_N / 4; // 28 float4 per thread +static_assert(SMEM_BYTES <= 232448, "smem budget"); +static_assert(STAGE_BYTES % 1024 == 0 && (HALF_N * BLOCK_K) % 1024 == 0, "swizzle atom alignment"); +static_assert(2 * 64 * TN * 4 <= STAGES * STAGE_BYTES, "park area"); +// push-reduction ring layout (after the mainloop): [0, 56K) recv slots, [56K, 112K) outgoing staging, +// [112K, 140K) bf16 output staging; slot q = g*2 + (sub&1), 14 KB fp32 (32 rows x 112 cols) per warp. +constexpr uint32_t WSL = PARK_F4 * 32 * 16; // 14336 B +constexpr uint32_t OUT_OFF = 4 * WSL; +constexpr uint32_t BF_OFF = 8 * WSL; +static_assert(BF_OFF + 4 * 32 * HALF_N * 2 <= STAGES * STAGE_BYTES, "push + bf16 staging area"); +constexpr int REGS_CTRL = 56; +constexpr int REGS_EPI = 224; + +__device__ __forceinline__ uint32_t smem_u32(const void* p) { + return static_cast(__cvta_generic_to_shared(p)); +} +__device__ __forceinline__ uint32_t cluster_ctarank() { + uint32_t r; + asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(r)); + return r; +} +__device__ __forceinline__ void cluster_sync() { + asm volatile("barrier.cluster.arrive.release.aligned;\n\tbarrier.cluster.wait.acquire.aligned;" ::: "memory"); +} +__device__ __forceinline__ void mbar_init(uint64_t* bar, uint32_t count) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(smem_u32(bar)), "r"(count)); +} +__device__ __forceinline__ void mbar_arrive_expect_tx(uint64_t* bar, uint32_t bytes) { + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(smem_u32(bar)), "r"(bytes) + : "memory"); +} +__device__ __forceinline__ void mbar_arrive(uint64_t* bar) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(smem_u32(bar)) : "memory"); +} +__device__ __forceinline__ void mbar_wait(uint64_t* bar, uint32_t parity) { + uint32_t addr = smem_u32(bar); + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAIT_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n" + "@!p bra WAIT_%=;\n" + "}\n" ::"r"(addr), + "r"(parity) + : "memory"); +} +__device__ __forceinline__ void mbar_wait_sleep(uint64_t* bar, uint32_t parity) { + uint32_t addr = smem_u32(bar); + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITS_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITS_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +__device__ __forceinline__ void ffma2(float& a0, float& a1, uint32_t x0, uint32_t x1, float2 ss) { + const float2 d = __ffma2_rn(make_float2(__uint_as_float(x0), __uint_as_float(x1)), ss, make_float2(a0, a1)); + a0 = d.x; + a1 = d.y; +} +__device__ __forceinline__ void fadd2(float& a0, float& a1, float x0, float x1) { + const float2 d = __ffma2_rn(make_float2(x0, x1), make_float2(1.f, 1.f), make_float2(a0, a1)); + a0 = d.x; + a1 = d.y; +} +__device__ __forceinline__ void tma_load_2d(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1, {%2, %3}], [%4];" ::"r"( + smem_u32(dst)), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(smem_u32(bar)) + : "memory"); +} +__device__ __forceinline__ void tma_load_2d_hint(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y, + uint64_t policy) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(smem_u32(dst)), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(smem_u32(bar)), "l"(policy) + : "memory"); +} +__device__ __forceinline__ void tma_load_2d_mc_hint(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y, + uint16_t mask, uint64_t policy) { + 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"(smem_u32(dst)), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(smem_u32(bar)), "h"(mask), "l"(policy) + : "memory"); +} +__device__ __forceinline__ float lds_f32(uint32_t a) { + float v; + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(v) : "r"(a) : "memory"); + return v; +} +__device__ __forceinline__ void sts_f4(uint32_t a, float x, float y, float z, float w) { + asm volatile("st.shared.v4.f32 [%0], {%1, %2, %3, %4};" ::"r"(a), "f"(x), "f"(y), "f"(z), "f"(w) : "memory"); +} +__device__ __forceinline__ void sts_u4(uint32_t a, uint4 v) { + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(a), "r"(v.x), "r"(v.y), "r"(v.z), "r"(v.w) : "memory"); +} +__device__ __forceinline__ void tma_store_2d(const CUtensorMap* map, uint32_t src, int x, int y) { + // output store with an L2 evict_first policy: the bf16 output is written once and never re-read by this + // kernel, so its lines should not evict the W / A operand lines the tile raster reuses from L2. + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%1, %2}], [%3], %4;" ::"l"( + reinterpret_cast(map)), + "r"(x), "r"(y), "r"(src), "l"(pol) + : "memory"); +} +__device__ __forceinline__ uint32_t mapa_shared(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; +} +__device__ __forceinline__ float4 ld_dsmem_f4(uint32_t a) { + 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"(a) + : "memory"); + return v; +} +__device__ __forceinline__ void mbar_arrive_remote(uint32_t cluster_addr) { + asm volatile("mbarrier.arrive.release.cluster.shared::cluster.b64 _, [%0];" ::"r"(cluster_addr) : "memory"); +} +__device__ __forceinline__ void mbar_arrive_remote_relaxed(uint32_t cluster_addr) { + asm volatile("mbarrier.arrive.relaxed.cluster.shared::cluster.b64 _, [%0];" ::"r"(cluster_addr) : "memory"); +} +__device__ __forceinline__ void cluster_sync_end_relaxed() { + asm volatile("barrier.cluster.arrive.relaxed.aligned;\n\tbarrier.cluster.wait.acquire.aligned;" ::: "memory"); +} +__device__ __forceinline__ void mbar_wait_cluster(uint32_t addr, uint32_t parity) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITC_%=:\n" + "mbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITC_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +// local smem -> peer CTA smem bulk copy, completion (complete_tx) on the peer's mbarrier +__device__ __forceinline__ void bulk_s2dsmem(uint32_t dst_cl, uint32_t src, uint32_t bytes, uint32_t mbar_cl) { + asm volatile("cp.async.bulk.shared::cluster.shared::cta.mbarrier::complete_tx::bytes [%0], [%1], %2, [%3];" ::"r"( + dst_cl), + "r"(src), "r"(bytes), "r"(mbar_cl) + : "memory"); +} +__device__ __forceinline__ float4 lds_f4(uint32_t a) { + float4 v; + asm volatile("ld.shared.v4.f32 {%0, %1, %2, %3}, [%4];" : "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w) : "r"(a) : "memory"); + return v; +} +__device__ __forceinline__ uint64_t make_sdesc(uint32_t saddr) { + uint64_t d = 0; + d |= (uint64_t)((saddr & 0x3FFFF) >> 4); + d |= (uint64_t)1 << 16; + d |= (uint64_t)(1024 >> 4) << 32; + d |= (uint64_t)1 << 46; + d |= (uint64_t)2 << 61; + return d; +} +__device__ __forceinline__ void mma_f8(uint32_t tmem_d, uint64_t adesc, uint64_t bdesc, uint32_t idesc, + uint32_t accum) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "setp.ne.b32 p, %4, 0;\n" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %3, p;\n" + "}\n" ::"r"(tmem_d), + "l"(adesc), "l"(bdesc), "r"(idesc), "r"(accum)); +} +__device__ __forceinline__ void mma_commit(uint64_t* bar) { + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(smem_u32(bar)) + : "memory"); +} +__device__ __forceinline__ void mma_commit_mc(uint64_t* bar, uint16_t mask) { + asm volatile( + "tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%0], %1;" ::"r"( + smem_u32(bar)), + "h"(mask) + : "memory"); +} +__device__ __forceinline__ void fence_after() { asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void fence_before() { asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory"); } + +#define TMEM_LD32(taddr, r) \ + 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)) + +#define TMEM_LD16(taddr, r) \ + 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"(taddr)) + + +// HEAD W L2 PREFETCH helper: L2-only bulk-tensor prefetch of one W box (pure hint, no smem / barrier involvement). +__device__ __forceinline__ void tma_prefetch_l2(const CUtensorMap* map, int x, int y) { + asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile [%0, {%1, %2}];" ::"l"(reinterpret_cast(map)), + "r"(x), "r"(y) + : "memory"); +} +__device__ __forceinline__ void tmem_ld_wait() { asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); } + + +namespace rawpush { +__host__ __device__ constexpr uint32_t slice_bytes(int ncol) { return (uint32_t)ncol * 128u; } +template +__device__ __forceinline__ void pack(const float* acc, uint32_t stg, int lane) { +#pragma unroll + for (int v = 0; v < NCOL / 4; ++v) + asm volatile("st.shared.v4.f32 [%0], {%1, %2, %3, %4};" ::"r"(stg + (uint32_t)(v * 32 + lane) * 16), + "f"(acc[4 * v]), "f"(acc[4 * v + 1]), "f"(acc[4 * v + 2]), "f"(acc[4 * v + 3]) : "memory"); +} +template +__device__ __forceinline__ void add(float* acc, uint32_t src, int lane) { +#pragma unroll + for (int v0 = 0; v0 < NCOL / 4; v0 += 4) { + float4 p[4]; +#pragma unroll + for (int v = 0; v < 4 && v0 + v < NCOL / 4; ++v) + asm volatile("ld.shared.v4.f32 {%0, %1, %2, %3}, [%4];" : "=f"(p[v].x), "=f"(p[v].y), "=f"(p[v].z), "=f"(p[v].w) + : "r"(src + (uint32_t)((v0 + v) * 32 + lane) * 16) : "memory"); +#pragma unroll + for (int v = 0; v < 4 && v0 + v < NCOL / 4; ++v) { + float* a = acc + 4 * (v0 + v); + const float2 d0 = __ffma2_rn(make_float2(p[v].x, p[v].y), make_float2(1.f, 1.f), make_float2(a[0], a[1])); + const float2 d1 = __ffma2_rn(make_float2(p[v].z, p[v].w), make_float2(1.f, 1.f), make_float2(a[2], a[3])); + a[0] = d0.x; a[1] = d0.y; a[2] = d1.x; a[3] = d1.y; + } + } +} +} // namespace rawpush +static_assert(rawpush::slice_bytes(112) <= WSL, "raw slice fits slot"); +static_assert(14 * WSL + 2 * 32 * 112 * 2 <= STAGES * STAGE_BYTES, "KQ4 push areas fit in ring"); +// acc[c*16 .. +16) += partial chunk c * s +__device__ __forceinline__ void promo_chunk(float* a, const uint32_t* r, float s) { + const float2 ss = make_float2(s, s); +#pragma unroll + for (int j = 0; j < 16; j += 2) ffma2(a[j], a[j + 1], r[j], r[j + 1], ss); +} + +// NP = 1: 4-CTA cluster (2 M x 2 K) = one N-tile. NP = 2 (A-MULTICAST, this version): 8-CTA cluster = +// 2 N-tiles x 2 M x 2 K; rank r -> mh = r&1, kh = (r>>1)&1, nh = r>>2. Each CTA loads only a 64-row HALF of its +// A tile (rows m0 + nh*64) and multicasts it to itself and its N partner (r^4), so A L2->SM traffic halves. +// A stage is written by self, the M partner (W half) and the N partner (A half) -> empty count 3, MMA commit +// Promotion + K-pair push reduction + bf16 store for one warpgroup that owns NC 16-col chunks. +// (Templated on NC so acc[] / drain / push sizes are compile-time; dispatched on the warp-uniform chunk count.) +template +__device__ __forceinline__ void promo_reduce(uint32_t taddr_b0, uint32_t sc_base, uint64_t* sfull_bar, + uint64_t* sempty_bar, uint64_t* tfull_bar, uint64_t* tempty_bar, + uint64_t* ready_bar, uint64_t* recv_bar, uint8_t* smem, int g, int sub, + int lane, int row, int cb, int kbeg, int kend, int kh, int rank, + const CUtensorMap* tmap_o, int xcol, int m0) { + static_assert(NC >= 5 && NC <= 7, "chunks"); + constexpr int NCOL = NC * 16; + float acc[NCOL]; +#pragma unroll + for (int j = 0; j < NCOL; ++j) acc[j] = 0.f; + uint32_t it = 0; + for (int kb = kbeg; kb < kend; ++kb, ++it) { + const int b = it & 1; + const uint32_t slot = it % SC_SLOTS; + mbar_wait_sleep(&sfull_bar[slot], (it / SC_SLOTS) & 1); + const uint32_t sp = sc_base + slot * (SC_SLOT_FLOATS * 4); + const float sxr = lds_f32(sp + row * 4); + float wA, wB; + asm volatile("ld.shared.v2.f32 {%0, %1}, [%2];" : "=f"(wA), "=f"(wB) : "r"(sp + 512 + g * 8) : "memory"); + const float sA = sxr * wA, sB = sxr * wB; + __syncwarp(); + if (lane == 0) mbar_arrive(&sempty_bar[slot]); + float sc[NC]; +#pragma unroll + for (int c = 0; c < NC; ++c) sc[c] = c >= cb ? sB : sA; + mbar_wait_sleep(&tfull_bar[b], (it >> 1) & 1); + if (it == 0 && threadIdx.x == 128) VDBG(1); + fence_after(); + const uint32_t taddr = taddr_b0 + ((uint32_t)b << 8); + // early-release drain (64 staging regs): chunks 0..3 up front, later chunks loaded into freed registers + uint32_t ra[32], rb[32]; + TMEM_LD32(taddr + 0, ra); + TMEM_LD32(taddr + 32, rb); + tmem_ld_wait(); + promo_chunk(acc + 0, ra, sc[0]); + promo_chunk(acc + 16, ra + 16, sc[1]); + if constexpr (NC == 7) { + TMEM_LD32(taddr + 64, ra); + promo_chunk(acc + 32, rb, sc[2]); + TMEM_LD16(taddr + 96, rb); + promo_chunk(acc + 48, rb + 16, sc[3]); + } else if constexpr (NC == 6) { + TMEM_LD32(taddr + 64, ra); + promo_chunk(acc + 32, rb, sc[2]); + promo_chunk(acc + 48, rb + 16, sc[3]); + } else { + TMEM_LD16(taddr + 64, ra); + promo_chunk(acc + 32, rb, sc[2]); + promo_chunk(acc + 48, rb + 16, sc[3]); + } + tmem_ld_wait(); + fence_before(); + __syncwarp(); + if (lane == 0) mbar_arrive(&tempty_bar[b]); + promo_chunk(acc + 64, ra, sc[4]); + if constexpr (NC >= 6) promo_chunk(acc + 80, ra + 16, sc[5]); + if constexpr (NC == 7) promo_chunk(acc + 96, rb, sc[6]); + } + if (threadIdx.x == 128) VDBG(2); + if constexpr (KQ4) { + // ---- M<=128 K-QUARTER mode: 4-way split-K reduction by async DSMEM push (exact fp32). Owner CTA of tile rows + // [sub*32, +32) is rank == sub. Pusher warp (g, sub != rank) stages its 32 x NCOL slice at ring + (6 + g*4+sub)*WSL, + // waits its local ready[g*4+sub] (remote-arrived by owner warp g of CTA sub once that CTA's ring is idle) and bulk- + // copies into the owner's recv slot g*3 + j (j = source index 0..2), complete_tx on the owner's recv[g*3+j]. + constexpr uint32_t SB = rawpush::slice_bytes(NCOL); + const uint32_t ring = smem_u32(smem); + if (sub != rank) { + const uint32_t stg = ring + (uint32_t)(6 + g * 4 + sub) * WSL; + rawpush::pack(acc, stg, lane); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + if (lane == 0) { + mbar_wait_cluster(smem_u32(&ready_bar[g * 4 + sub]), 0); + const uint32_t j = (uint32_t)(rank < sub ? rank : rank - 1); + bulk_s2dsmem(mapa_shared(ring + (uint32_t)(g * 3 + j) * WSL, (uint32_t)sub), stg, SB, + mapa_shared(smem_u32(&recv_bar[g * 3 + j]), (uint32_t)sub)); + } + __syncwarp(); + } else { + if (lane == 0) { + for (int j = 0; j < 3; ++j) mbar_arrive_expect_tx(&recv_bar[g * 3 + j], SB); + for (int d = 0; d < 4; ++d) + if (d != rank) mbar_arrive_remote_relaxed(mapa_shared(smem_u32(&ready_bar[g * 4 + rank]), (uint32_t)d)); + } + __syncwarp(); +#pragma unroll 1 + for (int j = 0; j < 3; ++j) { + mbar_wait_sleep(&recv_bar[g * 3 + j], 0); + rawpush::add(acc, ring + (uint32_t)(g * 3 + j) * WSL, lane); + } + const uint32_t stg = ring + 14 * WSL + (uint32_t)g * (32 * 112 * 2); +#pragma unroll + for (int v = 0; v < NCOL / 8; ++v) { + __nv_bfloat162 h0 = __floats2bfloat162_rn(acc[v * 8 + 0], acc[v * 8 + 1]); + __nv_bfloat162 h1 = __floats2bfloat162_rn(acc[v * 8 + 2], acc[v * 8 + 3]); + __nv_bfloat162 h2 = __floats2bfloat162_rn(acc[v * 8 + 4], acc[v * 8 + 5]); + __nv_bfloat162 h3 = __floats2bfloat162_rn(acc[v * 8 + 6], acc[v * 8 + 7]); + uint4 pk; + pk.x = *reinterpret_cast(&h0); + pk.y = *reinterpret_cast(&h1); + pk.z = *reinterpret_cast(&h2); + pk.w = *reinterpret_cast(&h3); + sts_u4(stg + lane * (NCOL * 2) + v * 16, pk); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + if (lane == 0) { + tma_store_2d(tmap_o, stg, xcol, sub * 32); + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); + } + __syncwarp(); + } + return; + } + // ---- K-pair reduction by async DSMEM push (as kernel_m256c): CTA kh owns rows [kh*64, +64). + const bool own = (sub >> 1) == kh; + const uint32_t q = (uint32_t)(g * 2 + (sub & 1)); + const uint32_t ring = smem_u32(smem); + const uint32_t partner = (uint32_t)(rank ^ 2); + if (!own) { + if constexpr (RAW) rawpush::pack(acc, ring + OUT_OFF + q * WSL, lane); + else pushfmt::pack(acc, ring + OUT_OFF + q * WSL, lane); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + if (lane == 0) { + mbar_wait_cluster(smem_u32(&ready_bar[q]), 0); + bulk_s2dsmem(mapa_shared(ring + q * WSL, partner), ring + OUT_OFF + q * WSL, RAW ? rawpush::slice_bytes(NCOL) : pushfmt::slice_bytes(NCOL), + mapa_shared(smem_u32(&recv_bar[q]), partner)); + } + __syncwarp(); + } else { + if (lane == 0) { + mbar_arrive_expect_tx(&recv_bar[q], RAW ? rawpush::slice_bytes(NCOL) : pushfmt::slice_bytes(NCOL)); + mbar_arrive_remote_relaxed(mapa_shared(smem_u32(&ready_bar[q]), partner)); + } + __syncwarp(); + mbar_wait_sleep(&recv_bar[q], 0); + if constexpr (RAW) rawpush::add(acc, ring + q * WSL, lane); + else pushfmt::add(acc, ring + q * WSL, lane); + // bf16 row-major staging box 32 rows x NCOL cols (pitch NCOL*2 B), one TMA store (rows >= M clipped) + const uint32_t stg = ring + BF_OFF + q * (uint32_t)(32 * 112 * 2); +#pragma unroll + for (int v = 0; v < NCOL / 8; ++v) { + __nv_bfloat162 h0 = __floats2bfloat162_rn(acc[v * 8 + 0], acc[v * 8 + 1]); + __nv_bfloat162 h1 = __floats2bfloat162_rn(acc[v * 8 + 2], acc[v * 8 + 3]); + __nv_bfloat162 h2 = __floats2bfloat162_rn(acc[v * 8 + 4], acc[v * 8 + 5]); + __nv_bfloat162 h3 = __floats2bfloat162_rn(acc[v * 8 + 6], acc[v * 8 + 7]); + uint4 pk; + pk.x = *reinterpret_cast(&h0); + pk.y = *reinterpret_cast(&h1); + pk.z = *reinterpret_cast(&h2); + pk.w = *reinterpret_cast(&h3); + sts_u4(stg + lane * (NCOL * 2) + v * 16, pk); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + if (lane == 0) { + tma_store_2d(tmap_o, stg, xcol, m0 + sub * 32); + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); + } + __syncwarp(); + } +} + +// VARIABLE-WIDTH tiles: cluster t (4 CTAs: mh = r&1 M-tile, kh = r>>1 K half) owns cols [n0, n0 + 16c), +// c = q + (t < rr), n0 = 16*(t*q + min(t, rr)). Warpgroup 0 takes the first c0 = ceil(c/2) chunks, warpgroup 1 the +// remaining c1 = floor(c/2). Each M-pair CTA multicasts an 8c-row half of the W slab (box from tmap_b_lo / _hi). +template +__global__ void __launch_bounds__(NUM_THREADS, 1) + fp8_m256v_kernel(const __grid_constant__ CUtensorMap tmap_a, const __grid_constant__ CUtensorMap tmap_b_lo, + const __grid_constant__ CUtensorMap tmap_b_hi, const __grid_constant__ CUtensorMap tmap_o_lo, + const __grid_constant__ CUtensorMap tmap_o_hi, const float* __restrict__ scale_x, + const float* __restrict__ scale_w, int M, int N, int K, int qch, int rr, int wpol, int pro) { + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(smem_raw) + 1023) & ~uintptr_t(1023)); + float* sc_ring = reinterpret_cast(smem + STAGES * STAGE_BYTES); + uint64_t* full_bar = reinterpret_cast(smem + STAGES * STAGE_BYTES + SC_BYTES); + uint64_t* empty_bar = full_bar + STAGES; + uint64_t* tfull_bar = empty_bar + STAGES; + uint64_t* tempty_bar = tfull_bar + 2; + uint64_t* sfull_bar = tempty_bar + 2; + uint64_t* sempty_bar = sfull_bar + SC_SLOTS; + uint64_t* ready_bar = sempty_bar + SC_SLOTS; + uint64_t* recv_bar = ready_bar + 8; // [8] (KQ4 uses 8 ready / 6 recv; K-pair mode 4 / 4) + uint32_t* tmem_slot = reinterpret_cast(recv_bar + 8); + + const int warp = __shfl_sync(0xffffffffu, (int)(threadIdx.x / 32), 0); + const int lane = threadIdx.x % 32; + const int num_kb = K / BLOCK_K; + const int num_sblk = N / 128; + const int rank = (int)cluster_ctarank(); + // KQ4 (M <= 128): single M-tile, rank = K quarter; else mh = M-tile, kh = K half + const int mh = KQ4 ? 0 : (rank & 1), kh = KQ4 ? 0 : ((rank >> 1) & 1); + const int t = blockIdx.x >> 2; + const bool wide = t < rr; + const int c = qch + (wide ? 1 : 0); // 16-col chunks of this tile + const int c0 = (c + 1) >> 1, c1 = c >> 1; // chunks of warpgroup 0 / 1 + const int n0 = 16 * (t * qch + (t < rr ? t : rr)); + const int wcols = 16 * c; + const int halfr = 8 * c; // W rows per multicast half (multiple of 8 -> 1024 B aligned) + const uint32_t stage_tx = (uint32_t)(TILE_A_BYTES + wcols * BLOCK_K); + const CUtensorMap* tmb = wide ? &tmap_b_hi : &tmap_b_lo; + const int m0 = mh * BLOCK_M; + const int kbeg = KQ4 ? (rank * num_kb) / 4 : kh * (num_kb / 2); + const int kend = KQ4 ? ((rank + 1) * num_kb) / 4 : kbeg + num_kb / 2; + const uint16_t pair_mask = (uint16_t)(0x3u << (rank & 6)); + + if (threadIdx.x == 0) { + for (int i = 0; i < STAGES; ++i) { + mbar_init(&full_bar[i], 1); + mbar_init(&empty_bar[i], KQ4 ? 1 : 2); // KQ4: no multicast, local MMA commit only + } + for (int i = 0; i < 2; ++i) { + mbar_init(&tfull_bar[i], 1); + mbar_init(&tempty_bar[i], NUM_EPI_WARPS); + } + for (int i = 0; i < SC_SLOTS; ++i) { + mbar_init(&sfull_bar[i], 64); + mbar_init(&sempty_bar[i], NUM_EPI_WARPS); + } + for (int i = 0; i < 8; ++i) { + mbar_init(&ready_bar[i], 1); + mbar_init(&recv_bar[i], 1); + } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_a)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(tmb)) : "memory"); + // HEAD W L2 PREFETCH (pro k-blocks): thread 0 waits for the previous grid itself (PDL) and starts the DRAM + // fetch of its own W multicast half for the first k-blocks into L2 before TMEM alloc / __syncthreads / + // cluster barrier, so the first ring stages land sooner. + if (pro > 0) { + asm volatile("griddepcontrol.wait;" ::: "memory"); + for (int kb = kbeg; kb < kend && kb < kbeg + pro; ++kb) tma_prefetch_l2(tmb, kb * BLOCK_K, n0 + (KQ4 ? 0 : mh * halfr)); + } + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(smem_u32(tmem_slot)), + "r"(TMEM_COLS)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + fence_before(); + __syncthreads(); + asm volatile("griddepcontrol.wait;" ::: "memory"); + if (threadIdx.x == 0) VDBG(0); + asm volatile("barrier.cluster.arrive.relaxed.aligned;\n\tbarrier.cluster.wait.acquire.aligned;" ::: "memory"); /* RELAXED arrive: no generic data to publish */ + fence_after(); + const uint32_t tmem_base = __shfl_sync(0xffffffffu, *tmem_slot, 0); + + if (warp < EPI_WARP0) { + asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;" ::"n"(REGS_CTRL)); + if (warp == 0) { + // ------------------------------------------------ TMA producer + if (lane == 0) { + // W L2 policy (wpol): 0 evict_first (seed) | 1 evict_normal | 2 evict_last | 3 evict_unchanged. + // The 256B L2 promotion of the W map prefetches the NEXT k-block's 128B half-row; an evict_first mark on + // those lines may let them be evicted before that next-kb TMA reads them (DRAM refetch). + uint64_t pol_w; + const int wp = wpol & 3, ap = (wpol >> 2) & 3; // ap: A policy 0 none (seed) | 1 last | 2 first | 3 normal + if (wp == 1) asm volatile("createpolicy.fractional.L2::evict_normal.b64 %0, 1.0;" : "=l"(pol_w)); + else if (wp == 2) asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol_w)); + else if (wp == 3) asm volatile("createpolicy.fractional.L2::evict_unchanged.b64 %0, 1.0;" : "=l"(pol_w)); + else asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_w)); + uint64_t pol_a; + if (ap == 1) asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol_a)); + else if (ap == 2) asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_a)); + else asm volatile("createpolicy.fractional.L2::evict_normal.b64 %0, 1.0;" : "=l"(pol_a)); + uint32_t it = 0; + for (int kb = kbeg; kb < kend; ++kb, ++it) { + const int s = it % STAGES; + const uint32_t ph = (it / STAGES) & 1; + uint8_t* sa = smem + s * STAGE_BYTES; + uint8_t* sb = sa + TILE_A_BYTES; + mbar_wait_sleep(&empty_bar[s], ph ^ 1); + mbar_arrive_expect_tx(&full_bar[s], stage_tx); + if (ap) tma_load_2d_hint(sa, &tmap_a, &full_bar[s], kb * BLOCK_K, m0, pol_a); + else tma_load_2d(sa, &tmap_a, &full_bar[s], kb * BLOCK_K, m0); // rows >= M zero-filled + if constexpr (KQ4) // whole 16c-row W slab (box 16c rows), no multicast + tma_load_2d_hint(sb, tmb, &full_bar[s], kb * BLOCK_K, n0, pol_w); + else + tma_load_2d_mc_hint(sb + mh * (halfr * BLOCK_K), tmb, &full_bar[s], kb * BLOCK_K, n0 + mh * halfr, + pair_mask, pol_w); + } + for (int i = 0; i < STAGES; ++i, ++it) { + const int s = it % STAGES; + mbar_wait_sleep(&empty_bar[s], ((it / STAGES) & 1) ^ 1); + } + } + } else if (warp == 1) { + // ------------------------------------------------ MMA issuer (M128 x N=16c x K32) + if (lane == 0) { + // FUSED ISSUE (this version): barrier / descriptor addresses hoisted out of the loop as 32-bit values, the + // operand-full wait spins (operands are normally already resident: no suspend/wake latency), and the 4 K32 + // MMAs + both commits of a k-block are ONE asm block (no per-MMA predicate setup / address math between + // tcgen05.mma issues), shortening the serial issue segment after the tempty hand-off. Bit-identical math. + const uint32_t idesc = (1u << 4) | ((uint32_t)(wcols >> 3) << 17) | ((uint32_t)(BLOCK_M >> 4) << 24); + const uint32_t full0 = smem_u32(full_bar), empty0 = smem_u32(empty_bar); + const uint32_t tfull0 = smem_u32(tfull_bar), tempty0 = smem_u32(tempty_bar); + const uint64_t adesc0 = make_sdesc(smem_u32(smem)); + constexpr uint64_t BOFF = TILE_A_BYTES >> 4, SOFF = STAGE_BYTES >> 4; + const uint16_t cmask = KQ4 ? (uint16_t)(1u << rank) : pair_mask; // KQ4: commit to self only + uint32_t it = 0, s = 0, ph = 0; + for (int kb = kbeg; kb < kend; ++kb, ++it) { + const uint32_t b = it & 1; + const uint64_t ad = adesc0 + (uint64_t)s * SOFF, bd = ad + BOFF; + asm volatile( + "{\n.reg .pred p;\nWF_%=:\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n@!p bra WF_%=;\n}\n" + ::"r"(full0 + s * 8), "r"(ph) : "memory"); + asm volatile( + "{\n.reg .pred p;\nWT_%=:\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n@!p bra WT_%=;\n}\n" + ::"r"(tempty0 + b * 8), "r"(((it >> 1) & 1) ^ 1), "n"(0x989680) : "memory"); + fence_after(); + asm volatile( + "{\n" + ".reg .pred pf, pt;\n" + "setp.eq.u32 pt, 1, 1;\n" + "setp.eq.u32 pf, 1, 0;\n" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %3, pf;\n" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %4, %5, %3, pt;\n" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %6, %7, %3, pt;\n" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %8, %9, %3, pt;\n" + "tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%10], %11;\n" + "tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%12];\n" + "}\n" ::"r"(tmem_base + b * 256u), + "l"(ad), "l"(bd), "r"(idesc), "l"(ad + 2), "l"(bd + 2), "l"(ad + 4), "l"(bd + 4), "l"(ad + 6), "l"(bd + 6), + "r"(empty0 + s * 8), "h"(cmask), "r"(tfull0 + b * 8) + : "memory"); + if (++s == STAGES) { s = 0; ph ^= 1; } + if (kb == kbeg + 4) VDBG(5); + } + VDBG(6); + } + } else { + // ------------------------------------------------ scale producer (warps 2,3) + const int lt = threadIdx.x - 64; + const int ra = m0 + lt, rb = ra + 64; + const float* pa = scale_x + (size_t)(ra < M ? ra : 0) * num_kb; + const float* pb = scale_x + (size_t)(rb < M ? rb : 0) * num_kb; + const int gg = (lt >> 1) & 1; + const int blk = ((n0 + gg * 16 * c0) >> 7) + (lt & 1); + const int wj = blk < num_sblk ? blk : num_sblk - 1; + uint32_t it = 0; + for (int kb = kbeg; kb < kend; kb += 4) { + const int nq = (kend - kb) < 4 ? (kend - kb) : 4; + float xa[4], xb[4], wv[4]; + if (nq == 4 && ((kb | num_kb) & 3) == 0) { + const float4 va = ra < M ? __ldg(reinterpret_cast(pa + kb)) : make_float4(0.f, 0.f, 0.f, 0.f); + const float4 vb = rb < M ? __ldg(reinterpret_cast(pb + kb)) : make_float4(0.f, 0.f, 0.f, 0.f); + xa[0] = va.x; xa[1] = va.y; xa[2] = va.z; xa[3] = va.w; + xb[0] = vb.x; xb[1] = vb.y; xb[2] = vb.z; xb[3] = vb.w; +#pragma unroll + for (int q = 0; q < 4; ++q) wv[q] = __ldg(scale_w + (size_t)(kb + q) * num_sblk + wj); + } else { +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + xa[q] = ra < M ? __ldg(pa + kb + q) : 0.f; + xb[q] = rb < M ? __ldg(pb + kb + q) : 0.f; + wv[q] = __ldg(scale_w + (size_t)(kb + q) * num_sblk + wj); + } + } + } +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + const uint32_t ii = it + q; + const int slot = ii % SC_SLOTS; + mbar_wait_sleep(&sempty_bar[slot], ((ii / SC_SLOTS) & 1) ^ 1); + float* d = sc_ring + slot * SC_SLOT_FLOATS; + d[lt] = xa[q]; + d[lt + 64] = xb[q]; + if (lt < 4) d[128 + lt] = wv[q]; + mbar_arrive(&sfull_bar[slot]); + } + } + it += nq; + } + } + __syncwarp(); + cluster_sync_end_relaxed(); // end barrier (relaxed arrive, see top) + } else { + // ------------------------------------------------ promotion (warps 4..11) + asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;" ::"n"(REGS_EPI)); + const int g = (warp - EPI_WARP0) >> 2; + const int sub = warp & 3; + const int row = sub * 32 + lane; + const int ncg = g ? c1 : c0; // warp-uniform chunk count of this warpgroup + const int coff = g * 16 * c0; // first tile col of this warpgroup + const uint32_t taddr_b0 = tmem_base + ((uint32_t)(sub * 32) << 16) + coff; + const uint32_t sc_base = smem_u32(sc_ring); + const int cbase = n0 + coff; + const int cb = (((cbase >> 7) + 1) * 128 - cbase) >> 4; + const CUtensorMap* tmo = ncg == (qch >> 1) ? &tmap_o_lo : &tmap_o_hi; + if (ncg == 7) + promo_reduce<7, RAW, KQ4>(taddr_b0, sc_base, sfull_bar, sempty_bar, tfull_bar, tempty_bar, ready_bar, recv_bar, smem, g, + sub, lane, row, cb, kbeg, kend, kh, rank, tmo, cbase, m0); + else if (ncg == 6) + promo_reduce<6, RAW, KQ4>(taddr_b0, sc_base, sfull_bar, sempty_bar, tfull_bar, tempty_bar, ready_bar, recv_bar, smem, g, + sub, lane, row, cb, kbeg, kend, kh, rank, tmo, cbase, m0); + else + promo_reduce<5, RAW, KQ4>(taddr_b0, sc_base, sfull_bar, sempty_bar, tfull_bar, tempty_bar, ready_bar, recv_bar, smem, g, + sub, lane, row, cb, kbeg, kend, kh, rank, tmo, cbase, m0); + if (threadIdx.x == 128) VDBG(3); + cluster_sync_end_relaxed(); // end barrier (relaxed arrive, see top) + } + + fence_before(); + __syncthreads(); + if (threadIdx.x == 0) VDBG(4); + if (warp == 1) { + fence_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tmem_base), "r"(TMEM_COLS)); + } +} + +static void make_tmap(CUtensorMap* map, const void* ptr, uint64_t rows, uint64_t K, uint32_t box_rows, + CUtensorMapL2promotion promo = CU_TENSOR_MAP_L2_PROMOTION_L2_256B) { + cuuint64_t dims[2] = {K, rows}; + cuuint64_t strides[1] = {K}; + cuuint32_t box[2] = {BLOCK_K, box_rows}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(map, CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, const_cast(ptr), dims, strides, + box, estr, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, + promo, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled failed: %d\n", (int)r); +} + +static void make_tmap_out_w(CUtensorMap* map, void* out, int M, int N, int cols) { + cuuint64_t dims[2] = {(cuuint64_t)N, (cuuint64_t)M}; + cuuint64_t strides[1] = {(cuuint64_t)N * 2}; + cuuint32_t box[2] = {(cuuint32_t)cols, 32}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, out, dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled(out) failed: %d\n", (int)r); +} + +// number of co-resident 4-CTA clusters (cached) +static int m256v_max_clusters() { + static int v = -1; + if (v < 0) { + cudaFuncSetAttribute(fp8_m256v_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaFuncSetAttribute(fp8_m256v_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaFuncSetAttribute(fp8_m256v_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + int dev, sms = 0; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev); + cudaLaunchConfig_t q = {}; + q.gridDim = dim3((sms / 4) * 4, 1, 1); + q.blockDim = dim3(NUM_THREADS, 1, 1); + q.dynamicSmemBytes = SMEM_BYTES; + cudaLaunchAttribute qa[1]; + qa[0].id = cudaLaunchAttributeClusterDimension; + qa[0].val.clusterDim.x = 4; + qa[0].val.clusterDim.y = 1; + qa[0].val.clusterDim.z = 1; + q.attrs = qa; + q.numAttrs = 1; + int n = 0; + if (cudaOccupancyMaxActiveClusters(&n, fp8_m256v_kernel, &q) != cudaSuccess) { + cudaGetLastError(); + n = 0; + } + v = n; + } + return v; +} + +// tile plan: T clusters, q = chunks per narrow tile, rr = #wide tiles (q+1 chunks); valid iff chunk counts per +// warpgroup are in [5, 7] (tile width 160..224 cols) +static bool m256v_plan(int N, int& T, int& q, int& rr) { + if (N % 16 != 0) return false; + T = m256v_max_clusters(); + const int C = N / 16; + if (T <= 0) return false; + if (T > C) T = C; + q = C / T; + rr = C - q * T; + if (q < 10) return false; + if (q + (rr > 0 ? 1 : 0) > 14) return false; + return true; +} + +} // namespace + +bool fp8_m256v_supported(int M, int N, int K) { + if (!(M > 128 && M <= 256 && K % (2 * BLOCK_K) == 0 && K >= 2 * BLOCK_K && N % 128 == 0)) return false; + int T, q, rr; + return m256v_plan(N, T, q, rr); +} + +void launch_fp8_m256v(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, int K, + cudaStream_t stream, int raw, int wpol, int pro) { + int T, q, rr; + if (!m256v_plan(N, T, q, rr)) return; + CUtensorMap ta, tbl, tbh, tol, toh; + make_tmap(&ta, a, (uint64_t)M, (uint64_t)K, BLOCK_M); + // wpol bits 4-5: W tensor-map L2 sector promotion (0 = 256B seed, 1 = none, 2 = 128B) + const int wpr = (wpol >> 4) & 3; + const CUtensorMapL2promotion wpromo = wpr == 1 ? CU_TENSOR_MAP_L2_PROMOTION_NONE + : (wpr == 2 ? CU_TENSOR_MAP_L2_PROMOTION_L2_128B : CU_TENSOR_MAP_L2_PROMOTION_L2_256B); + make_tmap(&tbl, w, (uint64_t)N, (uint64_t)K, 8 * q, wpromo); + make_tmap(&tbh, w, (uint64_t)N, (uint64_t)K, 8 * (q + 1), wpromo); + make_tmap_out_w(&tol, out, M, N, 16 * (q >> 1)); + make_tmap_out_w(&toh, out, M, N, 16 * ((q >> 1) + 1)); + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3(T * 4, 1, 1); + cfg.blockDim = dim3(NUM_THREADS, 1, 1); + cfg.dynamicSmemBytes = SMEM_BYTES; + cfg.stream = stream; + cudaLaunchAttribute attrs[2]; + attrs[0].id = cudaLaunchAttributeClusterDimension; + attrs[0].val.clusterDim.x = 4; + attrs[0].val.clusterDim.y = 1; + attrs[0].val.clusterDim.z = 1; + attrs[1].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attrs[1].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = attrs; + cfg.numAttrs = 2; + if (raw) cudaLaunchKernelEx(&cfg, fp8_m256v_kernel, ta, tbl, tbh, tol, toh, sx, sw, M, N, K, q, rr, wpol, pro); + else cudaLaunchKernelEx(&cfg, fp8_m256v_kernel, ta, tbl, tbh, tol, toh, sx, sw, M, N, K, q, rr, wpol, pro); +} + +// M <= 128 K-QUARTER variant (kernel_m256v): same 37 variable-width (192/208-col) N-tiles, each a +// 4-CTA cluster of K quarters -> 148 CTAs (all SMs; each streams 16c x K/4 W bytes, max 208x4096 vs m128c 160x5461), +// exact fp32 4-way DSMEM split-K reduction. +bool fp8_m128v_supported(int M, int N, int K) { + if (!(M >= 1 && M <= 128 && K % BLOCK_K == 0 && K / BLOCK_K >= 4 && N % 128 == 0)) return false; + int T, q, rr; + return m256v_plan(N, T, q, rr); +} +void launch_fp8_m128v(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, int K, + cudaStream_t stream, int pro) { + int T, q, rr; + if (!m256v_plan(N, T, q, rr)) return; + CUtensorMap ta, tbl, tbh, tol, toh; + make_tmap(&ta, a, (uint64_t)M, (uint64_t)K, BLOCK_M); + make_tmap(&tbl, w, (uint64_t)N, (uint64_t)K, 16 * q); // full-width W slab boxes (<= 208 rows) + make_tmap(&tbh, w, (uint64_t)N, (uint64_t)K, 16 * (q + 1)); + make_tmap_out_w(&tol, out, M, N, 16 * (q >> 1)); + make_tmap_out_w(&toh, out, M, N, 16 * ((q >> 1) + 1)); + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3(T * 4, 1, 1); + cfg.blockDim = dim3(NUM_THREADS, 1, 1); + cfg.dynamicSmemBytes = SMEM_BYTES; + cfg.stream = stream; + cudaLaunchAttribute attrs[2]; + attrs[0].id = cudaLaunchAttributeClusterDimension; + attrs[0].val.clusterDim.x = 4; + attrs[0].val.clusterDim.y = 1; + attrs[0].val.clusterDim.z = 1; + attrs[1].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attrs[1].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = attrs; + cfg.numAttrs = 2; + cudaLaunchKernelEx(&cfg, fp8_m256v_kernel, ta, tbl, tbh, tol, toh, sx, sw, M, N, K, q, rr, 8, pro); +} diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256v.h b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256v.h new file mode 100644 index 0000000000000000000000000000000000000000..25bc72fa7c561a662c6526c191bc2810de38d9ba --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256v.h @@ -0,0 +1,14 @@ +#pragma once +#include +// pro = number of head W k-slabs L2-prefetched by thread 0 before the CTA prologue (0 = off) +#ifndef M256V_PRO_DEFAULT +#define M256V_PRO_DEFAULT 4 +#endif +// 128 < M <= 256: variable-width (192/208-col) tiles, 4-CTA clusters filling all SMs (kernel_m256v.cu). +bool fp8_m256v_supported(int M, int N, int K); +void launch_fp8_m256v(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, int K, + cudaStream_t stream, int raw = 0, int wpol = 8, + int pro = 3 ); +bool fp8_m128v_supported(int M, int N, int K); +void launch_fp8_m128v(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, int K, + cudaStream_t stream, int pro = M256V_PRO_DEFAULT); diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256x2.cu b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256x2.cu new file mode 100644 index 0000000000000000000000000000000000000000..056d8c2bc137713352d010318dd10a15d32825ee --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256x2.cu @@ -0,0 +1,526 @@ +// 128 < M <= 256 KERNEL "m256x2": the kernel_m128x2 2-CTAs-per-SM design applied to two 128-row M-blocks. +// +// out[m, n] = sum_kb sx[m, kb] * sw[kb, n/128] * sum_{k in kb} A[m,k] * W[n,k] +// +// Tile = 128 rows x 128 cols (one 128-col scale block). 2 M-blocks x N/128 (=56) N-tiles, split-K 2. +// Cluster of 4 CTAs = one N-tile: rank r -> mh = r & 1 (M-block rows mh*128..+128), kh = r >> 1 (K half). +// * W multicast: the two CTAs {mh = 0, 1} of a K half consume the same 128x128 W k-slab; each TMA-loads its +// 64-row half (8 KB) with .multicast::cluster to both (mask 0b11 << 2*kh) -> W read from L2 once per K half. +// full barrier: local, expects A (16 KB) + both W halves (16 KB); empty barrier: count 2, released by the +// multicast tcgen05.commit of both CTAs' MMAs. +// * grid = 4 * N/128 = 224 CTAs, sized for 2 co-resident CTAs/SM: 256 threads, ~102 KB smem (3-stage ring), +// 256 TMEM cols (2 partial buffers x 128), setmaxnreg 56 / 200. +// Roles (8 warps): warp0 TMA producer, warp1 TMEM alloc + single-thread tcgen05.mma (kind::f8f6f4 M128 N128 +// K32, each k-block accumulated fresh into buffer it&1), warps 2-3 scale producer (s[row] = sx*sw into an +// 8-slot smem ring), warps 4-7 promotion (thread = tile row = TMEM lane, 128 fp32 accumulators). +// K-pair reduction by ASYNC DSMEM PUSH (FP24 = top 24 bits of fp32, fp24_push.h): CTA kh owns tile rows [kh*64, +64) +// = promotion warps sub in {2kh, 2kh+1}. A non-owner warp packs its 32x128 slice in its idle ring, waits the +// partner (rank ^ 2) warp's 'ready' (partner ring idle) and issues one cp.async.bulk smem -> partner smem +// (complete_tx on the partner's recv barrier). The owner adds it, packs bf16 and TMA-stores 2 x (32x64) boxes. +// One end-of-kernel cluster barrier keeps all smem alive until the copies completed. +#include +#include +#include +#include +#include +#include "tmap_cache.h" +#include "kernel_m256x2.h" +#include "fp24_push.h" // fp24 push + +namespace { + +constexpr int BLOCK_M = 128; +constexpr int TILE_N = 128; +constexpr int BLOCK_K = 128; +constexpr int CL = 4; // cluster = 2 M-blocks x 2 K-halves +constexpr int STAGES = 3; +constexpr int TILE_A_BYTES = BLOCK_M * BLOCK_K; // 16 KB +constexpr int TILE_B_BYTES = TILE_N * BLOCK_K; // 16 KB +constexpr int STAGE_BYTES = TILE_A_BYTES + TILE_B_BYTES; +constexpr int NUM_EPI_WARPS = 4; +constexpr int EPI_WARP0 = 4; +constexpr int NUM_THREADS = 128 + NUM_EPI_WARPS * 32; // 256 +constexpr int TMEM_COLS = 256; // 2 buffers x 128 cols (two CTAs share the 512 cols) +constexpr int SC_SLOTS = 8; +constexpr int SC_BYTES = SC_SLOTS * BLOCK_M * 4; // 4 KB +constexpr int SMEM_BYTES = STAGES * STAGE_BYTES + SC_BYTES + 1024 /*align*/ + 512 /*barriers*/; +// post-mainloop ring layout: [0, 2*PSLOT) recv slots (q = sub&1), [2*PSLOT, 4*PSLOT) outgoing FP24 staging (q), +// [4*PSLOT, +2 x 8 KB) bf16 output staging (owner warp q) +constexpr uint32_t PSL_BYTES = pushfmt::slice_bytes(TILE_N); // FP24 slice (12 KB) +constexpr uint32_t PSLOT = (PSL_BYTES + 127u) & ~127u; +constexpr uint32_t OUT_OFF = 2 * PSLOT; +constexpr uint32_t BF_OFF = 4 * PSLOT; +constexpr uint32_t BF_BOX = 32 * TILE_N * 2; // 8 KB +static_assert(((BF_OFF + 1023u) & ~1023u) + 2 * BF_BOX <= (uint32_t)(STAGES * STAGE_BYTES), "push areas fit in ring"); +static_assert(2 * (SMEM_BYTES + 1024) <= 233472, "two CTAs per SM"); +constexpr int REGS_CTRL = 56; +constexpr int REGS_EPI = 200; // 128*56 + 128*200 = 32768 = 128 regs x 256 threads (launch bound for 2 CTAs/SM) + +__device__ __forceinline__ uint32_t smem_u32(const void* p) { + return static_cast(__cvta_generic_to_shared(p)); +} +__device__ __forceinline__ uint32_t cluster_ctarank() { + uint32_t r; + asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(r)); + return r; +} +__device__ __forceinline__ void mbar_init(uint64_t* bar, uint32_t count) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(smem_u32(bar)), "r"(count)); +} +__device__ __forceinline__ void mbar_arrive_expect_tx(uint64_t* bar, uint32_t bytes) { + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(smem_u32(bar)), "r"(bytes) + : "memory"); +} +__device__ __forceinline__ void mbar_arrive(uint64_t* bar) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(smem_u32(bar)) : "memory"); +} +__device__ __forceinline__ void mbar_wait_sleep(uint64_t* bar, uint32_t parity) { + uint32_t addr = smem_u32(bar); + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITS_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITS_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +__device__ __forceinline__ void tma_load_2d_hint(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y, + uint64_t policy) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(smem_u32(dst)), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(smem_u32(bar)), "l"(policy) + : "memory"); +} +__device__ __forceinline__ uint64_t make_sdesc(uint32_t saddr) { + uint64_t d = 0; + d |= (uint64_t)((saddr & 0x3FFFF) >> 4); + d |= (uint64_t)1 << 16; + d |= (uint64_t)(1024 >> 4) << 32; // SBO: 8 rows x 128 B + d |= (uint64_t)1 << 46; // sm100 descriptor version + d |= (uint64_t)2 << 61; // SWIZZLE_128B + return d; +} +__device__ __forceinline__ void mma_f8(uint32_t tmem_d, uint64_t adesc, uint64_t bdesc, uint32_t idesc, + uint32_t accum) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "setp.ne.b32 p, %4, 0;\n" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %3, p;\n" + "}\n" ::"r"(tmem_d), + "l"(adesc), "l"(bdesc), "r"(idesc), "r"(accum)); +} +__device__ __forceinline__ void mma_commit(uint64_t* bar) { + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(smem_u32(bar)) + : "memory"); +} +__device__ __forceinline__ void fence_after() { asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void fence_before() { asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void ffma2(float& a0, float& a1, uint32_t x0, uint32_t x1, float2 ss) { + const float2 d = __ffma2_rn(make_float2(__uint_as_float(x0), __uint_as_float(x1)), ss, make_float2(a0, a1)); + a0 = d.x; + a1 = d.y; +} +__device__ __forceinline__ uint32_t mapa_rank(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; +} +__device__ __forceinline__ void cluster_arrive() { asm volatile("barrier.cluster.arrive.release.aligned;" ::: "memory"); } +__device__ __forceinline__ void cluster_wait() { asm volatile("barrier.cluster.wait.acquire.aligned;" ::: "memory"); } +__device__ __forceinline__ void mbar_arrive_remote(uint32_t cluster_addr) { + asm volatile("mbarrier.arrive.release.cluster.shared::cluster.b64 _, [%0];" ::"r"(cluster_addr) : "memory"); +} +__device__ __forceinline__ void mbar_wait_cluster(uint32_t addr, uint32_t parity) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITC_%=:\n" + "mbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITC_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +__device__ __forceinline__ void bulk_s2dsmem(uint32_t dst_cl, uint32_t src, uint32_t bytes, uint32_t mbar_cl) { + asm volatile("cp.async.bulk.shared::cluster.shared::cta.mbarrier::complete_tx::bytes [%0], [%1], %2, [%3];" ::"r"( + dst_cl), + "r"(src), "r"(bytes), "r"(mbar_cl) + : "memory"); +} +__device__ __forceinline__ void tma_load_2d(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1, {%2, %3}], [%4];" ::"r"( + smem_u32(dst)), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(smem_u32(bar)) + : "memory"); +} +// multicast TMA: box lands at the same smem offset in every CTA of mask, signalling each CTA's barrier +__device__ __forceinline__ void tma_load_2d_mc_hint(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y, + uint16_t mask, uint64_t policy) { + 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"(smem_u32(dst)), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(smem_u32(bar)), "h"(mask), "l"(policy) + : "memory"); +} +__device__ __forceinline__ void mma_commit_mc(uint64_t* bar, uint16_t mask) { + asm volatile( + "tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%0], %1;" ::"r"( + smem_u32(bar)), + "h"(mask) + : "memory"); +} +__device__ __forceinline__ void tma_store_2d_u32(const CUtensorMap* map, uint32_t src, int x, int y) { + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%1, %2}], [%3], %4;" ::"l"( + reinterpret_cast(map)), + "r"(x), "r"(y), "r"(src), "l"(pol) + : "memory"); +} + +#define TMEM_LD16(taddr, r) \ + 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"(taddr)) +__device__ __forceinline__ void tmem_ld_wait() { asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); } + +__device__ __forceinline__ void promo16(float* a, const uint32_t* r, float2 ss) { +#pragma unroll + for (int j = 0; j < 16; j += 2) ffma2(a[j], a[j + 1], r[j], r[j + 1], ss); +} + +__global__ void __launch_bounds__(NUM_THREADS, 2) + fp8_m256x2_kernel(const __grid_constant__ CUtensorMap tmap_a, const __grid_constant__ CUtensorMap tmap_b, + const __grid_constant__ CUtensorMap tmap_out, const float* __restrict__ scale_x, + const float* __restrict__ scale_w, int M, int N, int K) { + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(smem_raw) + 1023) & ~uintptr_t(1023)); + float* sc_ring = reinterpret_cast(smem + STAGES * STAGE_BYTES); + uint64_t* full_bar = reinterpret_cast(smem + STAGES * STAGE_BYTES + SC_BYTES); + uint64_t* empty_bar = full_bar + STAGES; + uint64_t* tfull_bar = empty_bar + STAGES; // [2] + uint64_t* tempty_bar = tfull_bar + 2; // [2] + uint64_t* ready_bar = tempty_bar + 2; // [2 slots q]: partner owner warp q's ring idle -> may push + uint64_t* recv_bar = ready_bar + 2; // [2 slots q]: (owner) partner's slice landed (complete_tx) + uint64_t* sfull_bar = recv_bar + 2; // [SC_SLOTS] + uint64_t* sempty_bar = sfull_bar + SC_SLOTS; + uint32_t* tmem_slot = reinterpret_cast(sempty_bar + SC_SLOTS); + + const int warp = __shfl_sync(0xffffffffu, (int)(threadIdx.x / 32), 0); + const int lane = threadIdx.x % 32; + const int num_kb = K / BLOCK_K; + const int num_sblk = N / 128; + const int rank = (int)cluster_ctarank(); + const int mh = rank & 1, kh = rank >> 1; + const int nt = blockIdx.x / CL; + const int n0 = nt * TILE_N; + const int m0 = mh * BLOCK_M; + const int kb0 = (kh * num_kb) / 2; // identical k range for both CTAs of a multicast pair + const int kb1 = ((kh + 1) * num_kb) / 2; + const uint16_t pair_mask = (uint16_t)(0x3u << (2 * kh)); + + if (threadIdx.x == 0) { + for (int i = 0; i < STAGES; ++i) { + mbar_init(&full_bar[i], 1); + mbar_init(&empty_bar[i], 2); // both pair CTAs' MMAs must release the stage (peer writes into it) + } + for (int i = 0; i < 2; ++i) { + mbar_init(&tfull_bar[i], 1); + mbar_init(&tempty_bar[i], NUM_EPI_WARPS); + mbar_init(&ready_bar[i], 1); + mbar_init(&recv_bar[i], 1); + } + for (int i = 0; i < SC_SLOTS; ++i) { + mbar_init(&sfull_bar[i], 64); + mbar_init(&sempty_bar[i], NUM_EPI_WARPS); + } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_a)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_b)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_out)) : "memory"); + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(smem_u32(tmem_slot)), + "r"(TMEM_COLS)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + fence_before(); + __syncthreads(); + asm volatile("griddepcontrol.wait;" ::: "memory"); // PDL: no global memory touched before this + asm volatile("barrier.cluster.arrive.relaxed.aligned;" ::: "memory"); // peer barriers initialised before any multicast TMA / remote arrive + cluster_wait(); + fence_after(); + const uint32_t tmem_base = __shfl_sync(0xffffffffu, *tmem_slot, 0); + + if (warp < EPI_WARP0) { + asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;" ::"n"(REGS_CTRL)); + if (warp == 0 && lane == 0) { + // ------------------------------------------------ TMA producer + uint64_t pol_w; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_w)); + uint32_t it = 0; + for (int kb = kb0; kb < kb1; ++kb, ++it) { + const int s = it % STAGES; + const uint32_t ph = (it / STAGES) & 1; + mbar_wait_sleep(&empty_bar[s], ph ^ 1); // both pair CTAs finished reading stage s + uint8_t* sa = smem + s * STAGE_BYTES; + mbar_arrive_expect_tx(&full_bar[s], STAGE_BYTES); // A (OOB rows zero-filled) + both W halves + // my 64-row half of the 128-row W slab -> same offset in both pair CTAs + tma_load_2d_mc_hint(sa + TILE_A_BYTES + mh * (TILE_B_BYTES / 2), &tmap_b, &full_bar[s], kb * BLOCK_K, + n0 + mh * (TILE_N / 2), pair_mask, pol_w); + tma_load_2d(sa, &tmap_a, &full_bar[s], kb * BLOCK_K, m0); + } + // drain: every stage's last use released by both pair CTAs (no remote arrive after the end barrier) + for (int i = 0; i < STAGES; ++i, ++it) { + const int s = it % STAGES; + mbar_wait_sleep(&empty_bar[s], ((it / STAGES) & 1) ^ 1); + } + } else if (warp == 1 && lane == 0) { + // ------------------------------------------------ MMA issuer (single thread) + const uint32_t idesc = (1u << 4) | ((uint32_t)(TILE_N >> 3) << 17) | ((uint32_t)(BLOCK_M >> 4) << 24); + uint32_t it = 0; + for (int kb = kb0; kb < kb1; ++kb, ++it) { + const int s = it % STAGES; + const uint32_t ph = (it / STAGES) & 1; + const int b = it & 1; + mbar_wait_sleep(&full_bar[s], ph); + const uint32_t sa = smem_u32(smem + s * STAGE_BYTES); + const uint64_t adesc = make_sdesc(sa); + const uint64_t bdesc = make_sdesc(sa + TILE_A_BYTES); + const uint32_t tmem_d = tmem_base + b * TILE_N; + mbar_wait_sleep(&tempty_bar[b], ((it >> 1) & 1) ^ 1); + fence_after(); +#pragma unroll + for (int k = 0; k < BLOCK_K / 32; ++k) mma_f8(tmem_d, adesc + 2 * k, bdesc + 2 * k, idesc, k > 0 ? 1u : 0u); + mma_commit_mc(&empty_bar[s], pair_mask); // free stage s in both pair CTAs + mma_commit(&tfull_bar[b]); + } + } else if (warp >= 2) { + // ------------------------------------------------ scale producer (warps 2,3; 64 threads, rows lt, lt+64) + const int lt = threadIdx.x - 64; + const int ra = m0 + lt, rb = ra + 64; + const float* pa = scale_x + (size_t)(ra < M ? ra : 0) * num_kb; + const float* pb = scale_x + (size_t)(rb < M ? rb : 0) * num_kb; + const int wj = nt < num_sblk ? nt : num_sblk - 1; + uint32_t it = 0; + for (int kb = kb0; kb < kb1; kb += 4) { + const int nq = (kb1 - kb) < 4 ? (kb1 - kb) : 4; + float xa[4], xb[4], wv[4]; +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + xa[q] = ra < M ? __ldg(pa + kb + q) : 0.f; + xb[q] = rb < M ? __ldg(pb + kb + q) : 0.f; + wv[q] = __ldg(scale_w + (size_t)(kb + q) * num_sblk + wj); + } + } +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + const uint32_t ii = it + q; + const int slot = ii % SC_SLOTS; + mbar_wait_sleep(&sempty_bar[slot], ((ii / SC_SLOTS) & 1) ^ 1); + float* d = sc_ring + slot * BLOCK_M; + d[lt] = xa[q] * wv[q]; + d[lt + 64] = xb[q] * wv[q]; + mbar_arrive(&sfull_bar[slot]); + } + } + it += nq; + } + } + __syncwarp(); + } else { + // ------------------------------------------------ promotion (warps 4..7) + asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;" ::"n"(REGS_EPI)); + const int sub = warp & 3; + const int row = sub * 32 + lane; + const uint32_t taddr_b0 = tmem_base + ((uint32_t)(sub * 32) << 16); + const uint32_t sc_mine = smem_u32(sc_ring) + row * 4; + float acc[TILE_N]; +#pragma unroll + for (int j = 0; j < TILE_N; ++j) acc[j] = 0.f; + uint32_t it = 0; + for (int kb = kb0; kb < kb1; ++kb, ++it) { + const int b = it & 1; + const uint32_t slot = it % SC_SLOTS; + mbar_wait_sleep(&sfull_bar[slot], (it / SC_SLOTS) & 1); + float s; + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(s) : "r"(sc_mine + slot * (BLOCK_M * 4)) : "memory"); + __syncwarp(); + if (lane == 0) mbar_arrive(&sempty_bar[slot]); + const float2 ss = make_float2(s, s); + mbar_wait_sleep(&tfull_bar[b], (it >> 1) & 1); + fence_after(); + const uint32_t taddr = taddr_b0 + (uint32_t)(b * TILE_N); + // 2-deep pipelined drain (8 x16 tcgen05.ld, 4 wait::ld, 32 staging regs) + uint32_t ra[16], rb[16]; + TMEM_LD16(taddr + 0, ra); + TMEM_LD16(taddr + 16, rb); + tmem_ld_wait(); + promo16(acc + 0, ra, ss); + TMEM_LD16(taddr + 32, ra); + promo16(acc + 16, rb, ss); + TMEM_LD16(taddr + 48, rb); + tmem_ld_wait(); + promo16(acc + 32, ra, ss); + TMEM_LD16(taddr + 64, ra); + promo16(acc + 48, rb, ss); + TMEM_LD16(taddr + 80, rb); + tmem_ld_wait(); + promo16(acc + 64, ra, ss); + TMEM_LD16(taddr + 96, ra); + promo16(acc + 80, rb, ss); + TMEM_LD16(taddr + 112, rb); + tmem_ld_wait(); + fence_before(); + __syncwarp(); + if (lane == 0) mbar_arrive(&tempty_bar[b]); // TMEM buffer free + promo16(acc + 96, ra, ss); + promo16(acc + 112, rb, ss); + } + // ---- K-pair reduction by async DSMEM push. Warp (sub) here pairs with warp (sub) in the K partner rank^2. + // The operand ring is idle once the last tfull was observed: every inbound A / multicast-W write targeted a + // k-block this CTA consumed. + static_assert(pushfmt::slice_bytes(TILE_N) == PSL_BYTES, "push slice size"); + const uint32_t ring = smem_u32(smem); + const bool own = (sub >> 1) == kh; + const uint32_t q = (uint32_t)(sub & 1); + const uint32_t partner = (uint32_t)(rank ^ 2); + if (!own) { + const uint32_t stg = ring + OUT_OFF + q * PSLOT; + pushfmt::pack(acc, stg, lane); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + if (lane == 0) { + mbar_wait_cluster(smem_u32(&ready_bar[q]), 0); // partner's ring idle + bulk_s2dsmem(mapa_rank(ring + q * PSLOT, partner), stg, PSL_BYTES, mapa_rank(smem_u32(&recv_bar[q]), partner)); + } + __syncwarp(); + } else { + if (lane == 0) { + mbar_arrive_expect_tx(&recv_bar[q], PSL_BYTES); + mbar_arrive_remote(mapa_rank(smem_u32(&ready_bar[q]), partner)); + } + __syncwarp(); + mbar_wait_sleep(&recv_bar[q], 0); + pushfmt::add(acc, ring + q * PSLOT, lane); + // bf16 pack into a 32 rows x 128 cols box as two 64-col 128B-swizzled halves (4 KB each), TMA store + // clips rows >= M. 16 B chunk c of row lane at (c ^ (lane & 7)). + const uint32_t bst = ((ring + BF_OFF + 1023u) & ~1023u) + q * BF_BOX; +#pragma unroll + for (int c = 0; c < TILE_N / 8; ++c) { + const int e = c * 8; + __nv_bfloat162 h0 = __floats2bfloat162_rn(acc[e + 0], acc[e + 1]); + __nv_bfloat162 h1 = __floats2bfloat162_rn(acc[e + 2], acc[e + 3]); + __nv_bfloat162 h2 = __floats2bfloat162_rn(acc[e + 4], acc[e + 5]); + __nv_bfloat162 h3 = __floats2bfloat162_rn(acc[e + 6], acc[e + 7]); + const uint32_t addr = bst + (uint32_t)(c >> 3) * 4096u + lane * 128 + (((c & 7) ^ (lane & 7)) << 4); + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(addr), + "r"(*reinterpret_cast(&h0)), "r"(*reinterpret_cast(&h1)), + "r"(*reinterpret_cast(&h2)), "r"(*reinterpret_cast(&h3)) + : "memory"); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + if (lane == 0) { + tma_store_2d_u32(&tmap_out, bst, n0, m0 + sub * 32); + tma_store_2d_u32(&tmap_out, bst + 4096u, n0 + 64, m0 + sub * 32); + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); + } + __syncwarp(); + } + } + // single end barrier: no CTA exits while peers may still multicast / copy into or from its smem + fence_before(); + asm volatile("barrier.cluster.arrive.relaxed.aligned;" ::: "memory"); + cluster_wait(); + if (warp == 1) { + fence_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tmem_base), "r"(TMEM_COLS)); + } +} + +static void make_tmap(CUtensorMap* map, const void* ptr, uint64_t rows, uint64_t K, uint32_t box_rows) { + cuuint64_t dims[2] = {K, rows}; + cuuint64_t strides[1] = {K}; + cuuint32_t box[2] = {BLOCK_K, box_rows}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(map, CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, const_cast(ptr), dims, strides, + box, estr, 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\n", (int)r); +} + +static cudaLaunchConfig_t make_cfg(int grid, cudaStream_t stream, cudaLaunchAttribute* attr) { + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3(grid, 1, 1); + cfg.blockDim = dim3(NUM_THREADS, 1, 1); + cfg.dynamicSmemBytes = SMEM_BYTES; + cfg.stream = stream; + attr[0].id = cudaLaunchAttributeClusterDimension; + attr[0].val.clusterDim.x = CL; + attr[0].val.clusterDim.y = 1; + attr[0].val.clusterDim.z = 1; + attr[1].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attr[1].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = attr; + cfg.numAttrs = 2; + return cfg; +} + +static int max_active_clusters() { + static int v = -1; + if (v < 0) { + cudaFuncSetAttribute(fp8_m256x2_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaFuncSetAttribute(fp8_m256x2_kernel, cudaFuncAttributeNonPortableClusterSizeAllowed, 1); + cudaLaunchAttribute attr[2]; + cudaLaunchConfig_t q = make_cfg(CL * 56, 0, attr); + q.numAttrs = 1; + int n = 0; + if (cudaOccupancyMaxActiveClusters(&n, fp8_m256x2_kernel, &q) != cudaSuccess) { + cudaGetLastError(); + n = 0; + } + v = n; + } + return v; +} + +} // namespace + +bool fp8_m256x2_supported(int M, int N, int K) { + if (!(M > BLOCK_M && M <= 2 * BLOCK_M && N % 128 == 0 && K % BLOCK_K == 0 && K / BLOCK_K >= 2)) return false; + // only worthwhile if every cluster is resident at once (2 CTAs/SM); otherwise the caller uses kernel_m256c + return max_active_clusters() >= N / TILE_N; +} + +void launch_fp8_m256x2(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, int K, + cudaStream_t stream) { + (void)max_active_clusters(); // sets the smem / cluster attributes once + CUtensorMap ta, tb, to; + make_tmap(&ta, a, (uint64_t)M, (uint64_t)K, BLOCK_M); + make_tmap(&tb, w, (uint64_t)N, (uint64_t)K, TILE_N / 2); // 64-row multicast half + { + // bf16 output map: dims {N, M}, box {64 cols (128 B), 32 rows}, 128B swizzle + cuuint64_t dims[2] = {(cuuint64_t)N, (cuuint64_t)M}; + cuuint64_t strides[1] = {(cuuint64_t)N * 2}; + cuuint32_t box[2] = {64, 32}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(&to, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, out, dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) fprintf(stderr, "cuTensorMapEncodeTiled(out) failed: %d\n", (int)r); + } + cudaLaunchAttribute attr[2]; + cudaLaunchConfig_t cfg = make_cfg((N / TILE_N) * CL, stream, attr); + cudaLaunchKernelEx(&cfg, fp8_m256x2_kernel, ta, tb, to, sx, sw, M, N, K); +} diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256x2.h b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256x2.h new file mode 100644 index 0000000000000000000000000000000000000000..73aea011171b8ad99f1a4cee8d3edce576b0e114 --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256x2.h @@ -0,0 +1,7 @@ +#pragma once +#include +// 128 < M <= 256: 128x128 tiles, 4-CTA clusters (2 M-blocks x 2 K-halves, W multicast), 2 CTAs/SM (kernel_m256x2.cu). +// Returns false if the shape is unsupported or the 2-CTA/SM cluster grid cannot be fully co-resident. +bool fp8_m256x2_supported(int M, int N, int K); +void launch_fp8_m256x2(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, int K, + cudaStream_t stream); diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk.cu b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk.cu new file mode 100644 index 0000000000000000000000000000000000000000..c924a4c647c5e01752f822ce1a9aa599149d7e0e --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk.cu @@ -0,0 +1,786 @@ +// POWER (this version): all idle-role mbarrier waits (TMA producer, scale producer, mailbox) suspend-hinted; +// scale producer loads sx as one float4 per row per 4 k-blocks. +// OFF-PATH CONTRIBUTOR PUBLISH (this version): contributor pieces (writer / middle) no longer bar.sync + fence.acq_rel.gpu +// in promotion warp 4; all 256 promotion threads arrive (release.cta) on pub_bar right after their stores and continue, +// and idle lane 1 of the TMA warp waits on it, fences (gpu scope, cumulative) and publishes the k-block count. +// PIPELINED x32 DRAIN (this version): promotion drain = large2-style overlapped tcgen05.ld x32 / FFMA2. +// UNIFORM WARP INDEX / TMEM BASE (this version): __shfl_sync-broadcast so tcgen05.ld addresses are warp-uniform. +// 32-BIT STREAM-K WALKER (this version): 64-bit pos/end divisions replaced by 32-bit math (no division CALLs). +// EPILOGUE STAGING RING (this version): per-warp output staging 2 KB single buffer -> 3-slot 1 KB ring (32x16 boxes, +// 32B swizzle), wait_group.read 2 + cross-unit box counter, so the 8 TMA-store boxes per warp do not serialize. +// 8-PROMO-WARP 2-PASS DRAIN (this version): promotion warps get decoded units (m0, n0, kb0|kb1, wsi) from a +// 4-slot smem UNIT MAILBOX (mfull/mempty mbarriers) written by the scale producer, which runs the 64-bit +// stream-K walker; per k-block 2 passes of 4 back-to-back x16 tcgen05.ld -> 1 wait::ld -> FFMA2, one elected +// tempty arrive per warp (count 8); owner fixup in 4-float4 batches. +// FUSED OWNER FIXUP (this version; writer-overwrite variant, ws never re-zeroed -- see the fixup comment): split / tail pieces no longer go through a zeroed ws + convert kernel. +// Contributor pieces (kb0 > 0) red.add fp32 into a persistent zeroed workspace (thread-ownership coalesced +// float4 layout) and bump a per-tile k-block counter; the owner piece (kb0 == 0, always last in its CTA's +// walk) spins (ld.acquire) on the counter, adds the ws partial in registers, re-zeroes ws + counter and +// stores bf16 via the normal TMA-store epilogue. Grid capped at the co-resident CTA count. +// STREAM-K-TAIL KERNEL (kernel_sk.cu): used ONLY by the large-partial-last-wave plan +// (e.g. M=1024: 224 tiles = 148 whole tiles + 76 tail tiles whose 76*K/128 k-blocks are split +// evenly over all 148 CTAs). Specialised copy of kernel.cu's general variant (streamk=1, dualm=0, +// fused=0) in its own TU so no other plan's SASS changes, plus a SCALE PRODUCER: +// +// out[m, n] = sum_kb sx[m, kb] * sw[kb, n/128] * sum_{k in kb} A[m,k] * W[n,k] +// +// Persistent, grid = #SMs. Each CTA first walks whole 128x256 tiles u = blockIdx.x + i*grid < direct +// (bf16 TMA-store epilogue), then its contiguous equal share of the tail's (tile, k-block) space; +// tail pieces red.global.add fp32 partials into a pre-zeroed workspace (converted by ws_to_bf16). +// Tiles are rasterised column-major (M fastest, group_n = 0) so concurrent tiles share W in L2. +// +// 12 warps = 3 warpgroups (setmaxnreg 40 / 232): +// warp 0 : TMA producer, 4-stage ring of A 128x128 + W 256x128 fp8 (128B swizzle). +// warp 1 : TMEM alloc + single-thread tcgen05.mma (kind::f8f6f4 M128 N256 K32, 4 per k-block), +// each k-block accumulated fresh into one of 2 TMEM buffers (2 x 256 cols). +// warps 2,3 : SCALE PRODUCER (64 threads): per k-block writes s[half][row] = sx[m0+row,kb]*sw[kb,nb*2+half] +// (256 fp32) into an 8-slot smem ring (sfull: 64 arrivals / sempty: 1 arrival per promotion +// warp); global loads batched 4 k-blocks at a time to hide latency. +// warps 4-11: promotion epilogue; warpgroup g owns cols [g*128,+128), thread = tile row = TMEM lane. +// Per k-block: 1 ld.shared of its scale, then software-pipelined 4 x tcgen05.ld x32 from +// the precomputed TMEM address of buffer b, acc += partial * s (fp32 regs). +// Direct tile end: bf16 pack -> 64B-swizzled 2 KB per-warp staging (32 rows x 32 cols) +// -> TMA store, 4 boxes per warp (staging shrunk from 4 KB so the 8 KB ring fits in smem). +#include +#include +#include +#include +#include +#include "tmap_cache.h" +#include "kernel_sk.h" + +namespace { + +constexpr int BLOCK_M = 128; +constexpr int BLOCK_N = 256; +constexpr int BLOCK_K = 128; +constexpr int STAGES = 4; +constexpr int TILE_A_BYTES = BLOCK_M * BLOCK_K; // fp8, 16 KB +constexpr int TILE_B_BYTES = BLOCK_N * BLOCK_K; // 32 KB +constexpr int STAGE_BYTES = TILE_A_BYTES + TILE_B_BYTES; +constexpr int NUM_EPI_WARPS = 8; +constexpr int WARP_STAGE_BYTES = 32 * 32; // 32 rows x 16 bf16 cols (one TMA box), 1 KB +constexpr int OUT_SLOTS = 3; // per-warp staging ring: up to 2 TMA stores in flight while packing the next box +constexpr int OUT_STAGE_BYTES = NUM_EPI_WARPS * OUT_SLOTS * WARP_STAGE_BYTES; // 24 KB +constexpr int SC_SLOTS = 8; // scale ring depth (k-blocks) +constexpr int SC_BYTES = SC_SLOTS * 256 * 4; // 8 KB: [slot][half][128 rows] fp32 +constexpr int EPI_WARP0 = 4; +constexpr int NUM_THREADS = 128 + NUM_EPI_WARPS * 32; // 384 +constexpr int TMEM_COLS = 512; +constexpr int SMEM_BYTES = STAGES * STAGE_BYTES + OUT_STAGE_BYTES + SC_BYTES + 1024 /*align*/ + 512 /*barriers + unit mailbox*/; +constexpr int MB_SLOTS = 4; // unit mailbox depth (control -> promotion warps) +static_assert(SMEM_BYTES <= 232448, "smem budget"); +constexpr int WS_TILE_FLOATS = BLOCK_M * BLOCK_N; +// setmaxnreg: 128*56 + 256*224 = 168*384 (ptxas allocates per region; 40 spilled the control WG) +constexpr int REGS_CTRL = 56; +constexpr int REGS_EPI = 224; + +__host__ __device__ __forceinline__ void tile_coords(int t, int num_mblk, int num_nblk, int group_n, int& mb, + int& nb) { + if (group_n <= 0) { // column-major (M-fastest): tiles sharing a W N-block are adjacent + nb = t / num_mblk; + mb = t - nb * num_mblk; + return; + } + const int per_band = group_n * num_mblk; + const int band = t / per_band; + const int r = t - band * per_band; + const int n_first = band * group_n; + const int rem = num_nblk - n_first; + const int gn = rem < group_n ? rem : group_n; + mb = r / gn; + nb = n_first + (r - mb * gn); +} + +// Work unit -> (tile, K-block range [kb0, kb1), workspace tile index wsi or -1 for a direct unit). +__device__ __forceinline__ void unit_coords(int u, int direct, int tail, int split, int num_kb, int& t, int& kb0, + int& kb1, int& wsi) { + if (u < direct) { + t = u; + kb0 = 0; + kb1 = num_kb; + wsi = -1; + return; + } + const int v = u - direct; + const int ks = v / tail; + wsi = v - ks * tail; + t = direct + wsi; + kb0 = (ks * num_kb) / split; + kb1 = ((ks + 1) * num_kb) / split; +} + +// Per-CTA work walker. streamk == 0: units u = blockIdx.x + i*gridDim.x < direct + tail*split +// (unit_coords). streamk == 1 ("stream-K tail"): first the direct whole tiles u < direct, then a +// contiguous, equal share [pos, end) of the tail's linear (tail tile, k-block) space of size +// tail*num_kb; every tail piece (even a whole one) goes through the fp32 workspace (wsi = tail idx). +struct WorkIter { + int u; + int pos, end; // 32-bit on purpose: 64-bit div compiles to a CALL; host guarantees grid*tail*num_kb < 2^31 +}; +__device__ __forceinline__ WorkIter work_begin(int direct, int tail, int streamk, int num_kb) { + WorkIter w; + w.u = blockIdx.x; + const unsigned tt = streamk ? (unsigned)(tail * num_kb) : 0u; + w.pos = (int)(blockIdx.x * tt / gridDim.x); + w.end = (int)((blockIdx.x + 1) * tt / gridDim.x); + return w; +} +__device__ __forceinline__ bool work_next(WorkIter& w, int direct, int tail, int split, int streamk, int num_kb, + int& t, int& kb0, int& kb1, int& wsi) { + if (!streamk) { + if (w.u >= direct + tail * split) return false; + unit_coords(w.u, direct, tail, split, num_kb, t, kb0, kb1, wsi); + w.u += gridDim.x; + return true; + } + if (w.u < direct) { + t = w.u; + kb0 = 0; + kb1 = num_kb; + wsi = -1; + w.u += gridDim.x; + return true; + } + if (w.pos >= w.end) return false; + const int ti = w.pos / num_kb; + kb0 = w.pos - ti * num_kb; + const int rem = w.end - w.pos; + kb1 = (num_kb - kb0) < rem ? num_kb : kb0 + rem; + w.pos += kb1 - kb0; + t = direct + ti; + wsi = ti; + return true; +} + +// ---------------------------------------------------------------- PTX helpers +__device__ __forceinline__ uint32_t smem_u32(const void* p) { + return static_cast(__cvta_generic_to_shared(p)); +} +__device__ __forceinline__ void mbar_init(uint64_t* bar, uint32_t count) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(smem_u32(bar)), "r"(count)); +} +__device__ __forceinline__ void mbar_arrive_expect_tx(uint64_t* bar, uint32_t bytes) { + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(smem_u32(bar)), "r"(bytes) + : "memory"); +} +__device__ __forceinline__ void mbar_arrive(uint64_t* bar) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(smem_u32(bar)) : "memory"); +} +__device__ __forceinline__ void mbar_wait(uint64_t* bar, uint32_t parity) { + uint32_t addr = smem_u32(bar); + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAIT_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n" + "@!p bra WAIT_%=;\n" + "}\n" ::"r"(addr), + "r"(parity) + : "memory"); +} +// mbarrier wait with a suspend-time hint (waiting warp parked instead of hot-spinning; frees issue slots). +__device__ __forceinline__ void mbar_wait_sleep(uint64_t* bar, uint32_t parity) { + uint32_t addr = smem_u32(bar); + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITS_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITS_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +// packed promotion FMA (fma.rn.f32x2): {a0,a1} += {x0,x1} * ss +__device__ __forceinline__ void ffma2(float& a0, float& a1, uint32_t x0, uint32_t x1, float2 ss) { + const float2 d = __ffma2_rn(make_float2(__uint_as_float(x0), __uint_as_float(x1)), ss, make_float2(a0, a1)); + a0 = d.x; + a1 = d.y; +} +// packed add via fma.rn.f32x2 with 1.0 multiplier (bit-identical to two fp32 adds) +__device__ __forceinline__ void fadd2(float& a0, float& a1, float x0, float x1) { + const float2 d = __ffma2_rn(make_float2(x0, x1), make_float2(1.f, 1.f), make_float2(a0, a1)); + a0 = d.x; + a1 = d.y; +} +__device__ __forceinline__ void tma_load_2d(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1, {%2, %3}], [%4];" ::"r"( + smem_u32(dst)), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(smem_u32(bar)) + : "memory"); +} +__device__ __forceinline__ void tma_store_2d(const CUtensorMap* map, const void* src, int x, int y) { + // output store with an L2 evict_first policy: the bf16 output is written once and never re-read by this + // kernel, so its lines should not evict the W / A operand lines the tile raster reuses from L2. + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%1, %2}], [%3], %4;" ::"l"( + reinterpret_cast(map)), + "r"(x), "r"(y), "r"(smem_u32(src)), "l"(pol) + : "memory"); +} +__device__ __forceinline__ void tma_store_commit() { asm volatile("cp.async.bulk.commit_group;" ::: "memory"); } +__device__ __forceinline__ void tma_store_wait_read() { + asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); +} +// wait until at most OUT_SLOTS-1 most recent bulk store groups still read their smem source +__device__ __forceinline__ void tma_store_wait_read_ring() { + asm volatile("cp.async.bulk.wait_group.read %0;" ::"n"(OUT_SLOTS - 1) : "memory"); +} +__device__ __forceinline__ void tma_store_wait_all() { asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); } +__device__ __forceinline__ void red_add_v4(float* p, float a, float b, float c, float d) { + asm volatile("red.global.add.v4.f32 [%0], {%1, %2, %3, %4};" ::"l"(p), "f"(a), "f"(b), "f"(c), "f"(d) + : "memory"); +} +// UMMA shared-memory descriptor: K-major, 128B swizzle, rows of 128 bytes, +// 8-row core-matrix groups 1024 B apart (SBO), sm100 descriptor version = 1. +__device__ __forceinline__ uint64_t make_sdesc(uint32_t saddr) { + uint64_t d = 0; + d |= (uint64_t)((saddr & 0x3FFFF) >> 4); + d |= (uint64_t)1 << 16; // LBO (unused for swizzled K-major) + d |= (uint64_t)(1024 >> 4) << 32; // SBO + d |= (uint64_t)1 << 46; // version + d |= (uint64_t)2 << 61; // SWIZZLE_128B + return d; +} +__device__ __forceinline__ void mma_f8(uint32_t tmem_d, uint64_t adesc, uint64_t bdesc, uint32_t idesc, + uint32_t accum) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "setp.ne.b32 p, %4, 0;\n" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %3, p;\n" + "}\n" ::"r"(tmem_d), + "l"(adesc), "l"(bdesc), "r"(idesc), "r"(accum)); +} +__device__ __forceinline__ void mma_commit(uint64_t* bar) { + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(smem_u32(bar)) + : "memory"); +} +__device__ __forceinline__ void fence_after() { asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void fence_before() { asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory"); } + +#define TMEM_LD32(taddr, r) \ + 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)) + +#define TMEM_LD16(taddr, r) \ + 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"(taddr)) + +__device__ __forceinline__ void tmem_ld_wait() { asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); } + + +// ---------------------------------------------------------------- kernel +__global__ void __launch_bounds__(NUM_THREADS, 1) + fp8_sk_kernel(const __grid_constant__ CUtensorMap tmap_a, const __grid_constant__ CUtensorMap tmap_b, + const __grid_constant__ CUtensorMap tmap_out, const float* __restrict__ scale_x, + const float* __restrict__ scale_w, float* __restrict__ ws, int* __restrict__ cnt, int M, int N, int K, int direct, + int tail) { + constexpr int streamk = 1, split = 1, group_n = 0; + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(smem_raw) + 1023) & ~uintptr_t(1023)); + uint8_t* out_stage = smem + STAGES * STAGE_BYTES; // 16 KB, 1024-aligned + float* sc_ring = reinterpret_cast(out_stage + OUT_STAGE_BYTES); // 8 KB scale ring + uint64_t* full_bar = reinterpret_cast(out_stage + OUT_STAGE_BYTES + SC_BYTES); + uint64_t* empty_bar = full_bar + STAGES; + uint64_t* tfull_bar = empty_bar + STAGES; // [2] + uint64_t* tempty_bar = tfull_bar + 2; // [2] + uint64_t* sfull_bar = tempty_bar + 2; // [SC_SLOTS] + uint64_t* sempty_bar = sfull_bar + SC_SLOTS; // [SC_SLOTS] + uint64_t* mfull_bar = sempty_bar + SC_SLOTS; // [MB_SLOTS] unit mailbox: written (1 arrival) + uint64_t* mempty_bar = mfull_bar + MB_SLOTS; // [MB_SLOTS] unit mailbox: consumed (1 arrival per promo warp) + uint64_t* pub_bar = mempty_bar + MB_SLOTS; // contributor piece stored (256 promo-thread arrivals) + uint32_t* tmem_slot = reinterpret_cast(pub_bar + 1); + // UNIT MAILBOX (16 B per slot): {m0, n0 (256-col block base), kb0 | kb1 << 16, wsi (-1 direct, -2 = end)}. + // The scale producer (control WG) runs the 64-bit stream-K walker; promotion warps only read decoded units. + int4* mbox = reinterpret_cast(reinterpret_cast(full_bar) + 384); + + const int warp = __shfl_sync(0xffffffffu, (int)(threadIdx.x / 32), 0); // warp-uniform for ptxas (uniform regs) + const int lane = threadIdx.x % 32; + const int num_kb = K / BLOCK_K; + const int num_sblk = N / 128; + const int num_mt = (M + BLOCK_M - 1) / BLOCK_M; + const int num_nt = N / BLOCK_N; + + if (threadIdx.x == 0) { + for (int i = 0; i < STAGES; ++i) { + mbar_init(&full_bar[i], 1); + mbar_init(&empty_bar[i], 1); + } + for (int i = 0; i < 2; ++i) { + mbar_init(&tfull_bar[i], 1); + mbar_init(&tempty_bar[i], NUM_EPI_WARPS); // one elected arrive per promotion warp + } + for (int i = 0; i < MB_SLOTS; ++i) { + mbar_init(&mfull_bar[i], 1); + mbar_init(&mempty_bar[i], NUM_EPI_WARPS); + } + for (int i = 0; i < SC_SLOTS; ++i) { + mbar_init(&sfull_bar[i], 64); // 64 scale-producer threads + mbar_init(&sempty_bar[i], NUM_EPI_WARPS); // one arrive per promotion warp + } + mbar_init(pub_bar, NUM_EPI_WARPS * 32); + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_a)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_b)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_out)) : "memory"); + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(smem_u32(tmem_slot)), + "r"(TMEM_COLS)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + fence_before(); + __syncthreads(); + // PDL: barrier init / TMEM alloc / tensormap prefetch above overlap the previous grid's tail; no global + // memory (inputs, workspace, counters, output) is touched before the previous grid completed and flushed. + asm volatile("griddepcontrol.wait;" ::: "memory"); + fence_after(); + const uint32_t tmem_base = __shfl_sync(0xffffffffu, *tmem_slot, 0); // warp-uniform TMEM base + + if (warp < EPI_WARP0) { + asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;" ::"n"(REGS_CTRL)); + if (warp == 0) { + // ------------------------------------------------ TMA producer + if (lane == 0) { + uint32_t it = 0; + WorkIter wk = work_begin(direct, tail, streamk, num_kb); + int t, kb0, kb1, wsi; + while (work_next(wk, direct, tail, split, streamk, num_kb, t, kb0, kb1, wsi)) { + int mbk, nbk; + tile_coords(t, num_mt, num_nt, group_n, mbk, nbk); + const int m0 = mbk * BLOCK_M; + const int n0 = nbk * BLOCK_N; + for (int kb = kb0; kb < kb1; ++kb, ++it) { + const int s = it % STAGES; + const uint32_t ph = (it / STAGES) & 1; + mbar_wait_sleep(&empty_bar[s], ph ^ 1); + uint8_t* sa = smem + s * STAGE_BYTES; + mbar_arrive_expect_tx(&full_bar[s], STAGE_BYTES); + tma_load_2d(sa, &tmap_a, &full_bar[s], kb * BLOCK_K, m0); + tma_load_2d(sa + TILE_A_BYTES, &tmap_b, &full_bar[s], kb * BLOCK_K, n0); // 256-row box + } + } + } else if (lane == 1) { + // ------------------------------------------------ contributor PUBLISHER (off the promotion critical path) + // A contributor piece (kb0 > 0; at most one per CTA: always the first piece of its tail range) is stored + // by the 256 promotion threads, which then only arrive (release.cta) on pub_bar and move on to the next + // unit. This idle lane waits for those arrivals (acquire.cta), issues the cumulative gpu-scope fence and + // publishes the k-block count -- the fence's drain of the 128 KB of stores no longer stalls a promotion + // warp (and through its tempty arrive, the MMA issuer). + WorkIter wk = work_begin(direct, tail, streamk, num_kb); + int t, kb0, kb1, wsi; + while (work_next(wk, direct, tail, split, streamk, num_kb, t, kb0, kb1, wsi)) { + if (wsi >= 0 && kb0 > 0) { + mbar_wait_sleep(pub_bar, 0); // single use per launch (<= 1 contributor piece per CTA) + asm volatile("fence.acq_rel.gpu;" ::: "memory"); + asm volatile("red.relaxed.gpu.global.add.s32 [%0], %1;" ::"l"(cnt + wsi), "r"(kb1 - kb0) : "memory"); + } + } + } + } else if (warp == 1) { + // ------------------------------------------------ MMA issuer (single thread) + if (lane == 0) { + const uint32_t idesc = (1u << 4) | ((uint32_t)(BLOCK_N >> 3) << 17) | ((uint32_t)(BLOCK_M >> 4) << 24); + uint32_t it = 0; + WorkIter wk = work_begin(direct, tail, streamk, num_kb); + int t, kb0, kb1, wsi; + while (work_next(wk, direct, tail, split, streamk, num_kb, t, kb0, kb1, wsi)) { + for (int kb = kb0; kb < kb1; ++kb, ++it) { + const int s = it % STAGES; + const uint32_t ph = (it / STAGES) & 1; + const int b = it & 1; + // reordered: wait operands + build descriptors first, then tempty -> fence -> MMA directly + mbar_wait_sleep(&full_bar[s], ph); // operands landed + const uint32_t sa = smem_u32(smem + s * STAGE_BYTES); + const uint64_t adesc = make_sdesc(sa); + const uint64_t bdesc = make_sdesc(sa + TILE_A_BYTES); + const uint32_t tmem_d = tmem_base + b * BLOCK_N; + mbar_wait_sleep(&tempty_bar[b], ((it >> 1) & 1) ^ 1); // epilogue drained this TMEM buffer + fence_after(); +#pragma unroll + for (int k = 0; k < BLOCK_K / 32; ++k) // +32 B along K inside the swizzle atom = +2 (16 B units) + mma_f8(tmem_d, adesc + 2 * k, bdesc + 2 * k, idesc, k > 0 ? 1u : 0u); + mma_commit(&empty_bar[s]); // smem stage free once MMAs complete + mma_commit(&tfull_bar[b]); // partial accumulator ready + } + } + } + } else { + // ------------------------------------------------ scale producer (warps 2,3; 64 threads) + // thread lt owns rows lt and lt+64 of the tile, both 128-col scale halves. + const int lt = threadIdx.x - 64; + uint32_t it = 0; + uint32_t ui = 0; // unit counter (mailbox ring position) + WorkIter wk = work_begin(direct, tail, streamk, num_kb); + int t, kb0, kb1, wsi; + while (work_next(wk, direct, tail, split, streamk, num_kb, t, kb0, kb1, wsi)) { + int mbk, nbk; + tile_coords(t, num_mt, num_nt, group_n, mbk, nbk); + if (lt == 0) { // publish the decoded unit to the promotion warps + const int ms = ui % MB_SLOTS; + mbar_wait_sleep(&mempty_bar[ms], ((ui / MB_SLOTS) & 1) ^ 1); + mbox[ms] = make_int4(mbk * BLOCK_M, nbk * BLOCK_N, kb0 | (kb1 << 16), wsi); + mbar_arrive(&mfull_bar[ms]); // release semantics: mailbox st.shared visible to waiters + } + ++ui; + const int ra = mbk * BLOCK_M + lt, rb = ra + 64; + const float* pa = scale_x + (size_t)(ra < M ? ra : 0) * num_kb; // rows >= M: value unused + const float* pb = scale_x + (size_t)(rb < M ? rb : 0) * num_kb; + for (int kb = kb0; kb < kb1; kb += 4) { + const int nq = (kb1 - kb) < 4 ? (kb1 - kb) : 4; + float xa[4], xb[4]; + float2 w[4]; + if (nq == 4 && ((kb | num_kb) & 3) == 0) { + // POWER: one 16 B load per row per 4 k-blocks (row base 16B-aligned since num_kb % 4 == 0) + const float4 va = __ldg(reinterpret_cast(pa + kb)); + const float4 vb = __ldg(reinterpret_cast(pb + kb)); + xa[0] = va.x; xa[1] = va.y; xa[2] = va.z; xa[3] = va.w; + xb[0] = vb.x; xb[1] = vb.y; xb[2] = vb.z; xb[3] = vb.w; +#pragma unroll + for (int q = 0; q < 4; ++q) + w[q] = __ldg(reinterpret_cast(scale_w + (size_t)(kb + q) * num_sblk) + nbk); + } else { +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + xa[q] = __ldg(pa + kb + q); + xb[q] = __ldg(pb + kb + q); + w[q] = __ldg(reinterpret_cast(scale_w + (size_t)(kb + q) * num_sblk) + nbk); + } + } + } +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + const uint32_t ii = it + q; + const int slot = ii % SC_SLOTS; + mbar_wait_sleep(&sempty_bar[slot], ((ii / SC_SLOTS) & 1) ^ 1); + float* d = sc_ring + slot * 256; + d[lt] = xa[q] * w[q].x; + d[lt + 64] = xb[q] * w[q].x; + d[128 + lt] = xa[q] * w[q].y; + d[128 + lt + 64] = xb[q] * w[q].y; + mbar_arrive(&sfull_bar[slot]); + } + } + it += nq; + } + } + if (lt == 0) { // end-of-work marker + const int ms = ui % MB_SLOTS; + mbar_wait_sleep(&mempty_bar[ms], ((ui / MB_SLOTS) & 1) ^ 1); + mbox[ms] = make_int4(0, 0, 0, -2); + mbar_arrive(&mfull_bar[ms]); + } + } + } else { + // ------------------------------------------------ promotion epilogue (warps 4..11) + asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;" ::"n"(REGS_EPI)); + const int g = (warp - EPI_WARP0) >> 2; // 128-col half of the tile + const int sub = warp & 3; // TMEM sub-partition + const int row = sub * 32 + lane; // tile row == TMEM lane + // EPILOGUE STAGING RING: OUT_SLOTS x 1 KB per warp; box counter `ob` runs across units, box ob uses slot + // ob % OUT_SLOTS, so only the store of box ob - OUT_SLOTS must have finished reading before packing. + uint8_t* wstage0 = out_stage + (g * 4 + sub) * OUT_SLOTS * WARP_STAGE_BYTES; + uint32_t ob = 0; + // precomputed TMEM addresses of both accumulator buffers for this warp's lanes / cols + const uint32_t taddr_b0 = tmem_base + ((uint32_t)(sub * 32) << 16) + g * 128; + const uint32_t sc_mine = smem_u32(sc_ring + g * 128 + row); // 32-bit shared-window address // my scale within a ring slot + uint32_t it = 0; + const uint32_t mbox_s = smem_u32(mbox); + for (uint32_t ui = 0;; ++ui) { + // next decoded unit from the control WG's mailbox (no walker / 64-bit math in the promotion warps) + const uint32_t ms = ui % MB_SLOTS; + mbar_wait_sleep(&mfull_bar[ms], (ui / MB_SLOTS) & 1); + int m0, nbase, kbp, wsi; + asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4];" + : "=r"(m0), "=r"(nbase), "=r"(kbp), "=r"(wsi) + : "r"(mbox_s + ms * 16u) + : "memory"); + __syncwarp(); + if (lane == 0) mbar_arrive(&mempty_bar[ms]); + if (wsi == -2) break; + const int kb0 = kbp & 0xFFFF, kb1 = kbp >> 16; + const int n0 = nbase + g * 128; + const int m = m0 + row; + float acc[128]; +#pragma unroll + for (int j = 0; j < 128; ++j) acc[j] = 0.f; + + for (int kb = kb0; kb < kb1; ++kb, ++it) { + const int b = it & 1; + const uint32_t slot = it % SC_SLOTS; + // promotion scale from the producer's smem ring (one ld.shared), slot released per warp + mbar_wait_sleep(&sfull_bar[slot], (it / SC_SLOTS) & 1); + float s; + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(s) : "r"(sc_mine + slot * 1024u) : "memory"); + const float2 ss = make_float2(s, s); + __syncwarp(); + if (lane == 0) mbar_arrive(&sempty_bar[slot]); + mbar_wait_sleep(&tfull_bar[b], (it >> 1) & 1); + fence_after(); + const uint32_t taddr = taddr_b0 + ((uint32_t)b << 8); // buffer b at TMEM col b*BLOCK_N + // PIPELINED x32 TMEM DRAIN (ported from kernel_large2): the loads of cols 64..95 / 96..127 are in flight + // while the FFMA2s of cols 0..31 / 32..63 run (staging peak 64 regs); 2 wait::ld per k-block, the TMEM + // buffer is released (one elected arrive per warp, tempty count 8) before the last 64 FFMA2s. + { + uint32_t ra[32], rb[32]; + TMEM_LD32(taddr + 0, ra); + TMEM_LD32(taddr + 32, rb); + tmem_ld_wait(); +#pragma unroll + for (int j = 0; j < 32; j += 2) ffma2(acc[j], acc[j + 1], ra[j], ra[j + 1], ss); + uint32_t rc[32]; + TMEM_LD32(taddr + 64, rc); +#pragma unroll + for (int j = 0; j < 32; j += 2) ffma2(acc[32 + j], acc[32 + j + 1], rb[j], rb[j + 1], ss); + uint32_t rd[32]; + TMEM_LD32(taddr + 96, rd); + tmem_ld_wait(); + fence_before(); + __syncwarp(); + if (lane == 0) mbar_arrive(&tempty_bar[b]); +#pragma unroll + for (int j = 0; j < 32; j += 2) ffma2(acc[64 + j], acc[64 + j + 1], rc[j], rc[j + 1], ss); +#pragma unroll + for (int j = 0; j < 32; j += 2) ffma2(acc[96 + j], acc[96 + j + 1], rd[j], rd[j + 1], ss); + } + } + if (wsi >= 0 && !(kb0 == 0 && kb1 == num_kb)) { + const int etid = threadIdx.x - EPI_WARP0 * 32; // 0..255 + float4* wrow = reinterpret_cast(ws + (size_t)wsi * WS_TILE_FLOATS) + (g * 32) * BLOCK_M + row; + if (kb0 > 0) { + if (kb1 == num_kb) { + if (m < M) { +#pragma unroll + for (int v = 0; v < 32; ++v) + __stcg(wrow + v * BLOCK_M, make_float4(acc[v * 4 + 0], acc[v * 4 + 1], acc[v * 4 + 2], acc[v * 4 + 3])); + } + } else { + if (etid == 0) { + const int need = num_kb - kb1; + int c; + while (true) { + asm volatile("ld.acquire.gpu.global.b32 %0, [%1];" : "=r"(c) : "l"(cnt + wsi) : "memory"); + if (c >= need) break; + __nanosleep(32); + } + } + asm volatile("bar.sync 1, 256;" ::: "memory"); + if (m < M) { +#pragma unroll + for (int v = 0; v < 32; ++v) + red_add_v4(reinterpret_cast(wrow + v * BLOCK_M), acc[v * 4 + 0], acc[v * 4 + 1], + acc[v * 4 + 2], acc[v * 4 + 3]); + } + } + mbar_arrive(pub_bar); // release.cta of this thread's partial; publisher lane (warp 0 lane 1) fences + counts + continue; + } + if (etid == 0) { + const int need = num_kb - kb1; + int c; + while (true) { + asm volatile("ld.acquire.gpu.global.b32 %0, [%1];" : "=r"(c) : "l"(cnt + wsi) : "memory"); + if (c >= need) break; + __nanosleep(32); + } + cnt[wsi] = 0; // all contributions arrived: reset for the next call + } + asm volatile("bar.sync 1, 256;" ::: "memory"); + if (m < M) { +#pragma unroll + for (int q = 0; q < 8; ++q) { // 8 batches of 4 float4 loads (16 regs: no spills) + float4 p[4]; +#pragma unroll + for (int v = 0; v < 4; ++v) p[v] = __ldcg(wrow + (q * 4 + v) * BLOCK_M); +#pragma unroll + for (int v = 0; v < 4; ++v) { + fadd2(acc[(q * 4 + v) * 4 + 0], acc[(q * 4 + v) * 4 + 1], p[v].x, p[v].y); + fadd2(acc[(q * 4 + v) * 4 + 2], acc[(q * 4 + v) * 4 + 3], p[v].z, p[v].w); + } + } + } + } +#pragma unroll + for (int h = 0; h < 8; ++h) { + // the store that last used this ring slot (box ob - OUT_SLOTS) must have finished reading it + if (lane == 0) tma_store_wait_read_ring(); + __syncwarp(); + uint8_t* wstage = wstage0 + (ob % OUT_SLOTS) * WARP_STAGE_BYTES; + ++ob; + // bf16 pack -> 32B-swizzled staging (32 B rows): 16B chunk j of row lane at (j ^ ((lane>>2)&1)) +#pragma unroll + for (int j = 0; j < 2; ++j) { + const int v = h * 2 + j; + uint4 pk; + __nv_bfloat162 h0 = __floats2bfloat162_rn(acc[v * 8 + 0], acc[v * 8 + 1]); + __nv_bfloat162 h1 = __floats2bfloat162_rn(acc[v * 8 + 2], acc[v * 8 + 3]); + __nv_bfloat162 h2 = __floats2bfloat162_rn(acc[v * 8 + 4], acc[v * 8 + 5]); + __nv_bfloat162 h3 = __floats2bfloat162_rn(acc[v * 8 + 6], acc[v * 8 + 7]); + pk.x = *reinterpret_cast(&h0); + pk.y = *reinterpret_cast(&h1); + pk.z = *reinterpret_cast(&h2); + pk.w = *reinterpret_cast(&h3); + *reinterpret_cast(wstage + lane * 32 + ((j ^ ((lane >> 2) & 1)) << 4)) = pk; + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // make st.shared visible to TMA + __syncwarp(); + if (lane == 0) { + tma_store_2d(&tmap_out, wstage, n0 + h * 16, m0 + sub * 32); + tma_store_commit(); + } + } + } + if (lane == 0) tma_store_wait_all(); + __syncwarp(); + } + + fence_before(); + __syncthreads(); + // PDL: all of this CTA's work is issued/complete -> let the next grid start its prologue (it still + // griddepcontrol.wait's for this grid's full completion before touching global memory). + asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); + if (warp == 1) { + fence_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tmem_base), "r"(TMEM_COLS)); + } +} + +// 8 elements (32 B in, 16 B out) per thread; ws tile ti <-> output tile (direct + ti). +__global__ void ws_to_bf16_kernel(const float4* __restrict__ ws, __nv_bfloat16* __restrict__ out, int M, int N, + int num_mblk, int num_nblk, int group_n, int direct, size_t n8) { + constexpr int PER_TILE8 = WS_TILE_FLOATS / 8; // 4096 8-element chunks per tile + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n8; i += (size_t)gridDim.x * blockDim.x) { + const int ti = (int)(i / PER_TILE8); + const int rem = (int)(i - (size_t)ti * PER_TILE8); + const int r = rem / (BLOCK_N / 8); + const int c = (rem - r * (BLOCK_N / 8)) * 8; + int mb, nb; + tile_coords(direct + ti, num_mblk, num_nblk, group_n, mb, nb); + const int m = mb * BLOCK_M + r; + if (m >= M) continue; + const float4 a = __ldcs(ws + 2 * i); + const float4 b = __ldcs(ws + 2 * i + 1); + __nv_bfloat162 h0 = __floats2bfloat162_rn(a.x, a.y); + __nv_bfloat162 h1 = __floats2bfloat162_rn(a.z, a.w); + __nv_bfloat162 h2 = __floats2bfloat162_rn(b.x, b.y); + __nv_bfloat162 h3 = __floats2bfloat162_rn(b.z, b.w); + uint4 pk; + pk.x = *reinterpret_cast(&h0); + pk.y = *reinterpret_cast(&h1); + pk.z = *reinterpret_cast(&h2); + pk.w = *reinterpret_cast(&h3); + *reinterpret_cast(out + (size_t)m * N + nb * BLOCK_N + c) = pk; + } +} + +// 2D K-major fp8 tensor map: dims {K, rows}, box {128, box_rows}, 128B swizzle. +static void make_tmap(CUtensorMap* map, const void* ptr, uint64_t rows, uint64_t K, uint32_t box_rows) { + cuuint64_t dims[2] = {K, rows}; + cuuint64_t strides[1] = {K}; + cuuint32_t box[2] = {BLOCK_K, box_rows}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(map, CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, const_cast(ptr), dims, strides, + box, estr, 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\n", (int)r); + } +} +// bf16 output map: dims {N, M}, box {16 cols (32 B), 32 rows}, 32B swizzle (3-slot per-warp staging ring). +static void make_tmap_out(CUtensorMap* map, void* ptr, uint64_t M, uint64_t N) { + cuuint64_t dims[2] = {N, M}; + cuuint64_t strides[1] = {N * 2}; + cuuint32_t box[2] = {16, 32}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, ptr, dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_32B, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) { + fprintf(stderr, "cuTensorMapEncodeTiled(out) failed: %d\n", (int)r); + } +} + + +struct SkWs { + float* ws = nullptr; + int* cnt = nullptr; + size_t floats = 0; + size_t cnts = 0; +}; + +} // namespace + +void launch_fp8_sk(const void* a, const void* w, const float* sx, const float* sw, void* out, float* ws, int direct, + int tail, int M, int N, int K, cudaStream_t stream) { + static int sms = 0; + if (sms == 0) { + int dev; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev); + cudaFuncSetAttribute(fp8_sk_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + } + CUtensorMap ta, tb, to; + make_tmap(&ta, a, (uint64_t)M, (uint64_t)K, BLOCK_M); + make_tmap(&tb, w, (uint64_t)N, (uint64_t)K, BLOCK_N); + make_tmap_out(&to, out, (uint64_t)M, (uint64_t)N); + const int num_nblk = N / BLOCK_N; + const int num_mblk = (M + BLOCK_M - 1) / BLOCK_M; + // Persistent self-cleaning fp32 workspace + per-tail-tile counters (heap-held, never freed). + (void)ws; + static SkWs& S = *new SkWs(); + if (tail > 0) { + const size_t need = (size_t)tail * WS_TILE_FLOATS; + if (need > S.floats || (size_t)tail > S.cnts) { + if (S.ws) { + cudaStreamSynchronize(stream); + cudaFree(S.ws); + cudaFree(S.cnt); + } + S.floats = need > S.floats ? need : S.floats; + S.cnts = (size_t)tail > S.cnts ? (size_t)tail : S.cnts; + cudaMalloc(&S.ws, S.floats * sizeof(float)); + cudaMalloc(&S.cnt, S.cnts * sizeof(int)); + cudaMemsetAsync(S.ws, 0, S.floats * sizeof(float), stream); + cudaMemsetAsync(S.cnt, 0, S.cnts * sizeof(int), stream); + } + } + // owner pieces spin on contributors in other CTAs -> cap the grid at the co-resident CTA count + static int max_per_sm = 0; + if (max_per_sm == 0) { + if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&max_per_sm, fp8_sk_kernel, NUM_THREADS, SMEM_BYTES) != + cudaSuccess || max_per_sm <= 0) + max_per_sm = 1; + } + const int grid = sms < max_per_sm * sms ? sms : max_per_sm * sms; + { + // programmatic dependent launch: launch processing / prologue overlaps the preceding grid + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3(grid, 1, 1); + cfg.blockDim = dim3(NUM_THREADS, 1, 1); + cfg.dynamicSmemBytes = SMEM_BYTES; + cfg.stream = stream; + cudaLaunchAttribute pattr[1]; + pattr[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + pattr[0].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = pattr; + cfg.numAttrs = 1; + cudaLaunchKernelEx(&cfg, fp8_sk_kernel, ta, tb, to, sx, sw, S.ws, S.cnt, M, N, K, direct, tail); + } + (void)num_nblk; + (void)num_mblk; +} diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk.h b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk.h new file mode 100644 index 0000000000000000000000000000000000000000..70646253fd109dc1d7cfe1efa3422cf056c5276e --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk.h @@ -0,0 +1,6 @@ +#pragma once +#include +// Stream-K-tail FP8 blockwise GEMM (plan: `direct` whole tiles + `tail` tiles split evenly over all SMs). +// ws must hold tail*128*256 floats, ZEROED before the call. +void launch_fp8_sk(const void* a, const void* w, const float* sx, const float* sw, void* out, float* ws, int direct, + int tail, int M, int N, int K, cudaStream_t stream); diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk2c.cu b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk2c.cu new file mode 100644 index 0000000000000000000000000000000000000000..eee3b99920e1ee8bde29cb7ed20ac1c3a7582aea --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk2c.cu @@ -0,0 +1,1568 @@ +// POWER (this version): all idle-role mbarrier waits (TMA producer, scale producer, mailbox) suspend-hinted; +// scale producer loads sx as one float4 per row per 4 k-blocks. +// OFF-PATH CONTRIBUTOR PUBLISH (this version): contributor pieces (writer / middle) no longer bar.sync + fence.acq_rel.gpu +// in promotion warp 4; all 256 promotion threads arrive (release.cta) on pub_bar right after their stores and continue, +// and idle lane 1 of the TMA warp waits on it, fences (gpu scope, cumulative) and publishes the k-block count. +// PIPELINED x32 DRAIN (this version): promotion drain = large2-style overlapped tcgen05.ld x32 / FFMA2. +// UNIFORM WARP INDEX / TMEM BASE (this version): __shfl_sync-broadcast so tcgen05.ld addresses are warp-uniform. +// 32-BIT STREAM-K WALKER (this version): 64-bit pos/end divisions replaced by 32-bit math (no division CALLs). +// EPILOGUE STAGING RING (this version): per-warp output staging 2 KB single buffer -> 3-slot 1 KB ring (32x16 boxes, +// 32B swizzle), wait_group.read 2 + cross-unit box counter, so the 8 TMA-store boxes per warp do not serialize. +// 8-PROMO-WARP 2-PASS DRAIN (this version): promotion warps get decoded units (m0, n0, kb0|kb1, wsi) from a +// 4-slot smem UNIT MAILBOX (mfull/mempty mbarriers) written by the scale producer, which runs the 64-bit +// stream-K walker; per k-block 2 passes of 4 back-to-back x16 tcgen05.ld -> 1 wait::ld -> FFMA2, one elected +// tempty arrive per warp (count 8); owner fixup in 4-float4 batches. +// FUSED OWNER FIXUP (this version; writer-overwrite variant, ws never re-zeroed -- see the fixup comment): split / tail pieces no longer go through a zeroed ws + convert kernel. +// Contributor pieces (kb0 > 0) red.add fp32 into a persistent zeroed workspace (thread-ownership coalesced +// float4 layout) and bump a per-tile k-block counter; the owner piece (kb0 == 0, always last in its CTA's +// walk) spins (ld.acquire) on the counter, adds the ws partial in registers, re-zeroes ws + counter and +// stores bf16 via the normal TMA-store epilogue. Grid capped at the co-resident CTA count. +// STREAM-K-TAIL KERNEL (kernel_sk.cu): used ONLY by the large-partial-last-wave plan +// (e.g. M=1024: 224 tiles = 148 whole tiles + 76 tail tiles whose 76*K/128 k-blocks are split +// evenly over all 148 CTAs). Specialised copy of kernel.cu's general variant (streamk=1, dualm=0, +// fused=0) in its own TU so no other plan's SASS changes, plus a SCALE PRODUCER: +// +// out[m, n] = sum_kb sx[m, kb] * sw[kb, n/128] * sum_{k in kb} A[m,k] * W[n,k] +// +// Persistent, grid = #SMs. Each CTA first walks whole 128x256 tiles u = blockIdx.x + i*grid < direct +// (bf16 TMA-store epilogue), then its contiguous equal share of the tail's (tile, k-block) space; +// tail pieces red.global.add fp32 partials into a pre-zeroed workspace (converted by ws_to_bf16). +// Tiles are rasterised column-major (M fastest, group_n = 0) so concurrent tiles share W in L2. +// +// 12 warps = 3 warpgroups (setmaxnreg 40 / 232): +// warp 0 : TMA producer, 4-stage ring of A 128x128 + W 256x128 fp8 (128B swizzle). +// warp 1 : TMEM alloc + single-thread tcgen05.mma (kind::f8f6f4 M128 N256 K32, 4 per k-block), +// each k-block accumulated fresh into one of 2 TMEM buffers (2 x 256 cols). +// warps 2,3 : SCALE PRODUCER (64 threads): per k-block writes s[half][row] = sx[m0+row,kb]*sw[kb,nb*2+half] +// (256 fp32) into an 8-slot smem ring (sfull: 64 arrivals / sempty: 1 arrival per promotion +// warp); global loads batched 4 k-blocks at a time to hide latency. +// warps 4-11: promotion epilogue; warpgroup g owns cols [g*128,+128), thread = tile row = TMEM lane. +// Per k-block: 1 ld.shared of its scale, then software-pipelined 4 x tcgen05.ld x32 from +// the precomputed TMEM address of buffer b, acc += partial * s (fp32 regs). +// Direct tile end: bf16 pack -> 64B-swizzled 2 KB per-warp staging (32 rows x 32 cols) +// -> TMA store, 4 boxes per warp (staging shrunk from 4 KB so the 8 KB ring fits in smem). +#include +#include +#include +#include +#include +#include "tmap_cache.h" +#include "kernel_sk2c.h" + +#ifndef SK2C_STAGES +#define SK2C_STAGES 6 +#endif +#define SK2C_MAX_CL 128 +// WRITER FLAG: the writer piece (kb1 == num_kb, plain overwrite of the ws tile) publishes its k-block count PLUS +// SK2C_WFLAG; middle contributors wait only for the flag, the owner for SK2C_WFLAG + (num_kb - kb1) (all pieces). +#define SK2C_WFLAG (1 << 20) +namespace { + +constexpr int BLOCK_M = 128; +constexpr int BLOCK_N = 256; +constexpr int BLOCK_K = 128; +constexpr int STAGES = SK2C_STAGES; // 32 KB stages (A 16 KB + own W half 16 KB) +constexpr int TILE_A_BYTES = BLOCK_M * BLOCK_K; // fp8, 16 KB +constexpr int TILE_B_BYTES = (BLOCK_N / 2) * BLOCK_K; // 16 KB: own 128-row W half +constexpr int STAGE_BYTES = TILE_A_BYTES + TILE_B_BYTES; +constexpr int NUM_EPI_WARPS = 8; +constexpr int WARP_STAGE_BYTES = 32 * 32; // 32 rows x 16 bf16 cols (one TMA box), 1 KB +constexpr int OUT_SLOTS = 3; // per-warp staging ring: up to 2 TMA stores in flight while packing the next box +constexpr int OUT_STAGE_BYTES = NUM_EPI_WARPS * OUT_SLOTS * WARP_STAGE_BYTES; // 24 KB +constexpr int SC_SLOTS = 8; // scale ring depth (k-blocks) +constexpr int SC_BYTES = SC_SLOTS * 256 * 4; // 8 KB: [slot][half][128 rows] fp32 +constexpr int EPI_WARP0 = 4; +constexpr int NUM_THREADS = 128 + NUM_EPI_WARPS * 32; // 384 +constexpr int TMEM_COLS = 512; +constexpr int SMEM_BYTES = STAGES * STAGE_BYTES + OUT_STAGE_BYTES + SC_BYTES + 1024 /*align*/ + 512 /*barriers + unit mailbox*/; +constexpr int MB_SLOTS = 4; // unit mailbox depth (control -> promotion warps) +static_assert(SMEM_BYTES <= 232448, "smem budget"); +constexpr int WS_TILE_FLOATS = BLOCK_M * BLOCK_N; +// setmaxnreg: 128*56 + 256*224 = 168*384 (ptxas allocates per region; 40 spilled the control WG) +constexpr int REGS_CTRL = 56; +constexpr int REGS_EPI = 224; + +__host__ __device__ __forceinline__ void tile_coords(int t, int num_mblk, int num_nblk, int group_n, int& mb, + int& nb) { + if (group_n <= 0) { // column-major (M-fastest): tiles sharing a W N-block are adjacent + nb = t / num_mblk; + mb = t - nb * num_mblk; + return; + } + const int per_band = group_n * num_mblk; + const int band = t / per_band; + const int r = t - band * per_band; + const int n_first = band * group_n; + const int rem = num_nblk - n_first; + const int gn = rem < group_n ? rem : group_n; + mb = r / gn; + nb = n_first + (r - mb * gn); +} + +// Work unit -> (tile, K-block range [kb0, kb1), workspace tile index wsi or -1 for a direct unit). +__device__ __forceinline__ void unit_coords(int u, int direct, int tail, int split, int num_kb, int& t, int& kb0, + int& kb1, int& wsi) { + if (u < direct) { + t = u; + kb0 = 0; + kb1 = num_kb; + wsi = -1; + return; + } + const int v = u - direct; + const int ks = v / tail; + wsi = v - ks * tail; + t = direct + wsi; + kb0 = (ks * num_kb) / split; + kb1 = ((ks + 1) * num_kb) / split; +} + +// Per-CTA work walker. streamk == 0: units u = blockIdx.x + i*gridDim.x < direct + tail*split +// (unit_coords). streamk == 1 ("stream-K tail"): first the direct whole tiles u < direct, then a +// contiguous, equal share [pos, end) of the tail's linear (tail tile, k-block) space of size +// tail*num_kb; every tail piece (even a whole one) goes through the fp32 workspace (wsi = tail idx). +struct WorkIter { + int u; + int ph; // QUAD mode: pair index within the 4-CTA quad (0 / 1); 0 in pair mode + int pos, end; // 32-bit on purpose: 64-bit div compiles to a CALL; host guarantees grid*tail*num_kb < 2^31 +}; +// ROLE-AWARE TAIL RANGES: per-LOGICAL-cluster tail range boundaries [b[cid], b[cid+1]) +// in linear (tail pair tile, kb) space, computed on the host (sk2c_tail_bounds), passed as a __grid_constant__ param. +// nb == 0: uniform split. Composes with the cluster rotation (boundaries indexed by the rotated logical cluster id). +// CHAINED-CHUNK TILE REMAP (this version, M=4096/8192 chained 2048-row launches): each launch sees the FULL M +// (A / scale / output over all rows); its native tiles are pair rows [pr0, pr0 + nmt) (nmt == 0: all of M, pr0 = 0), +// and it may be given nx EXTRA whole pair tiles (xpr global pair row, xnb N-block) that come FIRST in its linear tile +// list: inner chunks run only their full waves of whole tiles and forward their leftover tiles to the LAST chunk, +// whose single folded stream-K tail then covers the combined remainder. +#define SK2C_MAX_X 256 // forwarded whole pair tiles (3072-row inner chunks forward 40 each) +struct SkTail { + int nb; + int b[SK2C_MAX_CL + 1]; + int nx, pr0, nmt; + int krev; // 2 = also reverse stream-K tail pieces (M=8192 chain); 1 (M=8192 chain only): SERPENTINE K order -- whole tiles of ODD wave index (u / #clusters) walk + // their k-blocks in REVERSE, so each wave starts on the A k-slabs the previous wave just streamed + int kpar; // serpentine-K wave parity offset (M>=12288 cascaded chains: cumulative whole waves of earlier launches) + int mir; // 1: MIRRORED N raster for this launch's native tiles (nb -> num_nt-1-nb; bijective) + int xpr[SK2C_MAX_X], xnb[SK2C_MAX_X]; +}; +// QUAD raster (Q): tiles 2j, 2j+1 = SAME pair row, ADJACENT N-blocks (2*nbp, 2*nbp+1); pairs j column-major +// (M fastest). Bijective for an even N-block count. The two pairs of a quad always process tiles 2j / 2j+1. +__host__ __device__ __forceinline__ void quad_coords(int t, int nmt, int& mb, int& nb) { + const int j = t >> 1; + const int nbp = j / nmt; + mb = j - nbp * nmt; + nb = 2 * nbp + (t & 1); +} +template +__device__ __forceinline__ void tcoord(int t, int num_mt, int num_nt, const SkTail& bt, int& mb, int& nb) { + if (t < bt.nx) { + mb = bt.xpr[t]; + nb = bt.xnb[t]; + return; + } + t -= bt.nx; + if constexpr (Q) quad_coords(t, bt.nmt > 0 ? bt.nmt : num_mt, mb, nb); + else tile_coords(t, bt.nmt > 0 ? bt.nmt : num_mt, num_nt, 0, mb, nb); + if (bt.mir) nb = num_nt - 1 - nb; + mb += bt.pr0; +} +// QUAD walker (Q): logical quad lq = (physical quad + rot) % nq, logical pair cid = 2*lq + ph. Whole tiles: u = cid + +// i*ncl (ncl = 2*nq, direct even -> the quad's two pairs get tiles u, u+1 with u even). Stream-K tail: the QUAD's +// range [pos, end) over the tail SUPER-tile space (tail/2 super tiles x nkb); both pairs walk the identical k range, +// pair ph works on tail tile 2*pj + ph -> identical k-block sequences in both pairs (needed for the shared A halves). +template +__device__ __forceinline__ WorkIter work_begin_q(int direct, int tail, int num_kb, int rot, const SkTail& bt) { + WorkIter w; + const unsigned nq = gridDim.x >> 2, lq = ((blockIdx.x >> 2) + (unsigned)rot) % nq; + w.ph = (int)((blockIdx.x >> 1) & 1); + w.u = (int)(2 * lq) + w.ph; + const unsigned tt = (unsigned)((tail >> 1) * num_kb); + if (bt.nb > 0) { + w.pos = bt.b[lq]; + w.end = bt.b[lq + 1]; + } else { + w.pos = (int)(lq * tt / nq); + w.end = (int)((lq + 1) * tt / nq); + } + return w; +} +template +__device__ __forceinline__ bool work_next_q(WorkIter& w, int direct, int num_kb, int& t, int& kb0, int& kb1, int& wsi) { + if (w.u < direct) { + t = w.u; + kb0 = 0; + kb1 = num_kb; + wsi = -1; + w.u += (int)(gridDim.x >> 1); + return true; + } + if (w.pos >= w.end) return false; + const int pj = w.pos / num_kb; + kb0 = w.pos - pj * num_kb; + const int rem = w.end - w.pos; + kb1 = (num_kb - kb0) < rem ? num_kb : kb0 + rem; + w.pos += kb1 - kb0; + wsi = 2 * pj + w.ph; + t = direct + wsi; + return true; +} +__device__ __forceinline__ WorkIter work_begin(int direct, int tail, int streamk, int num_kb, int rot, const SkTail& bt) { + WorkIter w; + w.ph = 0; + // CLUSTER ROTATION: logical cluster = (physical + rot) % ncl (bijection -> same work set, different SM placement) + const unsigned ncl = gridDim.x >> 1, cid = ((blockIdx.x >> 1) + (unsigned)rot) % ncl; // one stream-K range per cluster + w.u = (int)cid; + const unsigned tt = streamk ? (unsigned)(tail * num_kb) : 0u; + if (bt.nb > 0 && streamk) { + w.pos = bt.b[cid]; + w.end = bt.b[cid + 1]; + } else { + w.pos = (int)(cid * tt / ncl); + w.end = (int)((cid + 1) * tt / ncl); + } + return w; +} +__device__ __forceinline__ bool work_next(WorkIter& w, int direct, int tail, int split, int streamk, int num_kb, + int& t, int& kb0, int& kb1, int& wsi) { + if (!streamk) { + if (w.u >= direct + tail * split) return false; + unit_coords(w.u, direct, tail, split, num_kb, t, kb0, kb1, wsi); + w.u += (int)(gridDim.x >> 1); + return true; + } + if (w.u < direct) { + t = w.u; + kb0 = 0; + kb1 = num_kb; + wsi = -1; + w.u += (int)(gridDim.x >> 1); + return true; + } + if (w.pos >= w.end) return false; + const int ti = w.pos / num_kb; + kb0 = w.pos - ti * num_kb; + const int rem = w.end - w.pos; + kb1 = (num_kb - kb0) < rem ? num_kb : kb0 + rem; + w.pos += kb1 - kb0; + t = direct + ti; + wsi = ti; + return true; +} + +// ---------------------------------------------------------------- PTX helpers +__device__ __forceinline__ int cl_rank() { + uint32_t r; + asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(r)); + return (int)r; +} +// RELAXED arrive + acquire wait: startup only publishes mbarrier inits (fence.mbarrier_init.release.cluster), the end +// barrier publishes no generic-proxy data (all cross-CTA traffic is mbarrier / TMA / tcgen05.commit completion based). +__device__ __forceinline__ void cl_sync_relaxed() { + asm volatile("barrier.cluster.arrive.relaxed.aligned;\n\tbarrier.cluster.wait.acquire.aligned;" ::: "memory"); +} +__device__ __forceinline__ void cl_sync() { + asm volatile("barrier.cluster.arrive.release.aligned;\n\tbarrier.cluster.wait.acquire.aligned;" ::: "memory"); +} +__device__ __forceinline__ uint32_t mapa_u32(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; +} +// TMA load into MY smem whose complete_tx is signalled on the LEADER CTA's mbarrier (cluster address mbar_cl) +__device__ __forceinline__ void tma_load_2d_c2(void* dst, const CUtensorMap* map, uint32_t mbar_cl, int x, int y) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.cta_group::2" + " [%0], [%1, {%2, %3}], [%4];" ::"r"(static_cast(__cvta_generic_to_shared(dst))), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(mbar_cl) + : "memory"); +} +// same with an L2 cache-policy hint (createpolicy) +__device__ __forceinline__ void tma_load_2d_c2_hint(void* dst, const CUtensorMap* map, uint32_t mbar_cl, int x, int y, + uint64_t pol) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.cta_group::2.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(static_cast(__cvta_generic_to_shared(dst))), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(mbar_cl), "l"(pol) + : "memory"); +} +__device__ __forceinline__ void mma_f8_c2(uint32_t tmem_d, uint64_t adesc, uint64_t bdesc, uint32_t idesc, + uint32_t accum) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "setp.ne.b32 p, %4, 0;\n" + "tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], %1, %2, %3, p;\n" + "}\n" ::"r"(tmem_d), + "l"(adesc), "l"(bdesc), "r"(idesc), "r"(accum)); +} +// commit (cta_group::2): arrive on the barrier at this smem offset in both CTAs of the pair +__device__ __forceinline__ void mma_commit_c2(uint64_t* bar) { + asm volatile( + "tcgen05.commit.cta_group::2.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%0], %1;" ::"r"( + static_cast(__cvta_generic_to_shared(bar))), + "h"((uint16_t)0x3) + : "memory"); +} +__device__ __forceinline__ void mbar_arrive_cl_relaxed(uint32_t cluster_addr) { + asm volatile("mbarrier.arrive.relaxed.cluster.shared::cluster.b64 _, [%0];" ::"r"(cluster_addr) : "memory"); +} +__device__ __forceinline__ void mbar_arrive_cl(uint32_t cluster_addr) { + asm volatile("mbarrier.arrive.shared::cluster.b64 _, [%0];" ::"r"(cluster_addr) : "memory"); +} +__device__ __forceinline__ uint32_t smem_u32(const void* p) { + return static_cast(__cvta_generic_to_shared(p)); +} +__device__ __forceinline__ void mbar_init(uint64_t* bar, uint32_t count) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(smem_u32(bar)), "r"(count)); +} +__device__ __forceinline__ void mbar_arrive_expect_tx(uint64_t* bar, uint32_t bytes) { + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(smem_u32(bar)), "r"(bytes) + : "memory"); +} +__device__ __forceinline__ void mbar_arrive(uint64_t* bar) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(smem_u32(bar)) : "memory"); +} +// 32-bit shared-address variants (SASS audit: warp-uniform barrier base + immediates in the promotion loop) +__device__ __forceinline__ void mbar_wait_sleep_u32(uint32_t addr, uint32_t parity) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITU_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITU_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +// TSPIN: promotion tfull wait without suspend hint (pure poll; minimal wake latency after the MMA commit); used only +// by the M=2048 WSUB (V&32) instantiation +__device__ __forceinline__ void mbar_wait_spin_tf(uint32_t addr, uint32_t parity) { + asm volatile( + "{\n.reg .pred p;\nWAITP_%=:\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n@!p bra WAITP_%=;\n}\n" + ::"r"(addr), "r"(parity) : "memory"); +} +// HYBRID wait (promotion tfull, as kernel_large2): one un-hinted try_wait (fast wake when the MMA finishes soon), +// then a suspend-hinted loop (long waits park the warp). +__device__ __forceinline__ void mbar_wait_hybrid_u32(uint32_t addr, uint32_t parity) { + asm volatile( + "{\n.reg .pred p;\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n@p bra DONEH_%=;\n" + "WAITH_%=:\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n@!p bra WAITH_%=;\nDONEH_%=:\n}\n" + ::"r"(addr), "r"(parity), "n"(0x989680) : "memory"); +} +__device__ __forceinline__ void mbar_arrive_u32(uint32_t addr) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(addr) : "memory"); +} +__device__ __forceinline__ void mbar_wait(uint64_t* bar, uint32_t parity) { + uint32_t addr = smem_u32(bar); + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAIT_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n" + "@!p bra WAIT_%=;\n" + "}\n" ::"r"(addr), + "r"(parity) + : "memory"); +} +// mbarrier wait with a suspend-time hint (waiting warp parked instead of hot-spinning; frees issue slots). +__device__ __forceinline__ void mbar_wait_sleep(uint64_t* bar, uint32_t parity) { + uint32_t addr = smem_u32(bar); + asm volatile( + "{\n" + ".reg .pred p;\n" + "WAITS_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITS_%=;\n" + "}\n" ::"r"(addr), + "r"(parity), "n"(0x989680) + : "memory"); +} +// packed promotion FMA (fma.rn.f32x2): {a0,a1} += {x0,x1} * ss +__device__ __forceinline__ void ffma2(float& a0, float& a1, uint32_t x0, uint32_t x1, float2 ss) { + const float2 d = __ffma2_rn(make_float2(__uint_as_float(x0), __uint_as_float(x1)), ss, make_float2(a0, a1)); + a0 = d.x; + a1 = d.y; +} +// packed multiply (mul.rn.f32x2): {a0,a1} = {x0,x1} * ss (first k-block of a unit, FM variant) +__device__ __forceinline__ void fmul2_set(float& a0, float& a1, uint32_t x0, uint32_t x1, float2 ss) { + const float2 d = __fmul2_rn(make_float2(__uint_as_float(x0), __uint_as_float(x1)), ss); + a0 = d.x; + a1 = d.y; +} +// packed add via fma.rn.f32x2 with 1.0 multiplier (bit-identical to two fp32 adds) +__device__ __forceinline__ void fadd2(float& a0, float& a1, float x0, float x1) { + const float2 d = __ffma2_rn(make_float2(x0, x1), make_float2(1.f, 1.f), make_float2(a0, a1)); + a0 = d.x; + a1 = d.y; +} +__device__ __forceinline__ void tma_load_2d(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1, {%2, %3}], [%4];" ::"r"( + smem_u32(dst)), + "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(smem_u32(bar)) + : "memory"); +} +__device__ __forceinline__ void tma_store_2d(const CUtensorMap* map, const void* src, int x, int y) { + // output store with an L2 evict_first policy: the bf16 output is written once and never re-read by this + // kernel, so its lines should not evict the W / A operand lines the tile raster reuses from L2. + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%1, %2}], [%3], %4;" ::"l"( + reinterpret_cast(map)), + "r"(x), "r"(y), "r"(smem_u32(src)), "l"(pol) + : "memory"); +} +__device__ __forceinline__ void tma_store_commit() { asm volatile("cp.async.bulk.commit_group;" ::: "memory"); } +__device__ __forceinline__ void tma_store_wait_read() { + asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); +} +// wait until at most OUT_SLOTS-1 most recent bulk store groups still read their smem source +__device__ __forceinline__ void tma_store_wait_read_ring() { + asm volatile("cp.async.bulk.wait_group.read %0;" ::"n"(OUT_SLOTS - 1) : "memory"); +} +__device__ __forceinline__ void tma_store_wait_all() { asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); } +__device__ __forceinline__ void red_add_v4(float* p, float a, float b, float c, float d) { + asm volatile("red.global.add.v4.f32 [%0], {%1, %2, %3, %4};" ::"l"(p), "f"(a), "f"(b), "f"(c), "f"(d) + : "memory"); +} +// UMMA shared-memory descriptor: K-major, 128B swizzle, rows of 128 bytes, +// 8-row core-matrix groups 1024 B apart (SBO), sm100 descriptor version = 1. +__device__ __forceinline__ uint64_t make_sdesc(uint32_t saddr) { + uint64_t d = 0; + d |= (uint64_t)((saddr & 0x3FFFF) >> 4); + d |= (uint64_t)1 << 16; // LBO (unused for swizzled K-major) + d |= (uint64_t)(1024 >> 4) << 32; // SBO + d |= (uint64_t)1 << 46; // version + d |= (uint64_t)2 << 61; // SWIZZLE_128B + return d; +} +__device__ __forceinline__ void mma_f8(uint32_t tmem_d, uint64_t adesc, uint64_t bdesc, uint32_t idesc, + uint32_t accum) { + asm volatile( + "{\n" + ".reg .pred p;\n" + "setp.ne.b32 p, %4, 0;\n" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %3, p;\n" + "}\n" ::"r"(tmem_d), + "l"(adesc), "l"(bdesc), "r"(idesc), "r"(accum)); +} +__device__ __forceinline__ void mma_commit(uint64_t* bar) { + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(smem_u32(bar)) + : "memory"); +} +__device__ __forceinline__ void fence_after() { asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void fence_before() { asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory"); } + +#define TMEM_LD32(taddr, r) \ + 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)) + +#define TMEM_LD16(taddr, r) \ + 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"(taddr)) + +__device__ __forceinline__ void tmem_ld_wait() { asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); } + + +// ---------------------------------------------------------------- kernel +// FM (first-kb FMUL): the first k-block of every unit writes acc = partial * s with packed FMUL2 instead of +// zero-initialising the 128 accumulators and FFMA2-ing into them (bit-identical: 0 + x*s == x*s up to the sign of +// zero, which bf16 / fp32 comparisons treat as equal). Removes 128 MOVs per unit and moves the first write of the +// accumulator registers behind the next unit's first tfull wait + TMEM load, so the register WAR hazard on the +// previous unit's 128 KB st.cg / red.add / bf16 epilogue stores is hidden behind that latency. FM=false = seed. +// V (offline A/B variant bits): 1 = EARLY operand prologue, 2 = W TMA loads L2 evict_normal (else evict_first) +// V bit 3 (8) = QUAD: 4-CTA cluster = 2 cta_group::2 pairs at adjacent N-blocks (same pair row); each CTA TMA-loads +// one 64-row HALF of its 128-row A tile and multicasts it to itself and the same-crank CTA of the other pair (rank^2). +#define WB(d_, t_, sk_, nkb_, r_, b_) ([&]() { if constexpr (Q) return work_begin_q(d_, t_, nkb_, r_, b_); else return work_begin(d_, t_, sk_, nkb_, r_, b_); }()) +#define WN(w_, d_, t_, sp_, sk_, nkb_, T_, k0_, k1_, ws_) ([&]() { if constexpr (Q) return work_next_q(w_, d_, nkb_, T_, k0_, k1_, ws_); else return work_next(w_, d_, t_, sp_, sk_, nkb_, T_, k0_, k1_, ws_); }()) +template +__global__ void __launch_bounds__(NUM_THREADS, 1) + fp8_sk2c_kernel(const __grid_constant__ CUtensorMap tmap_a, const __grid_constant__ CUtensorMap tmap_b, + const __grid_constant__ CUtensorMap tmap_out, const float* __restrict__ scale_x, + const float* __restrict__ scale_w, float* __restrict__ ws, int* __restrict__ cnt, int M, int N, int K, int direct, + int tail, int rot, const __grid_constant__ SkTail bnd) { + constexpr int streamk = 1, split = 1, group_n = 0; + constexpr bool Q = (V & 8) != 0; + static_assert(!(Q && (V & 1)), "quad mode without the early prologue"); + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(smem_raw) + 1023) & ~uintptr_t(1023)); + uint8_t* out_stage = smem + STAGES * STAGE_BYTES; // 16 KB, 1024-aligned + float* sc_ring = reinterpret_cast(out_stage + OUT_STAGE_BYTES); // 8 KB scale ring + uint64_t* full_bar = reinterpret_cast(out_stage + OUT_STAGE_BYTES + SC_BYTES); + uint64_t* empty_bar = full_bar + STAGES; + uint64_t* tfull_bar = empty_bar + STAGES; // [2] + uint64_t* tempty_bar = tfull_bar + 2; // [2] + uint64_t* sfull_bar = tempty_bar + 2; // [SC_SLOTS] + uint64_t* sempty_bar = sfull_bar + SC_SLOTS; // [SC_SLOTS] + uint64_t* mfull_bar = sempty_bar + SC_SLOTS; // [MB_SLOTS] unit mailbox: written (1 arrival) + uint64_t* mempty_bar = mfull_bar + MB_SLOTS; // [MB_SLOTS] unit mailbox: consumed (1 arrival per promo warp) + uint64_t* pub_bar = mempty_bar + MB_SLOTS; // contributor piece stored (256 promo-thread arrivals) + uint32_t* tmem_slot = reinterpret_cast(pub_bar + 1); + // UNIT MAILBOX (16 B per slot): {m0, n0 (256-col block base), kb0 | kb1 << 16, wsi (-1 direct, -2 = end)}. + // The scale producer (control WG) runs the 64-bit stream-K walker; promotion warps only read decoded units. + int4* mbox = reinterpret_cast(reinterpret_cast(full_bar) + 384); + // OWNER WS PREFETCH barrier (after the 4-slot mailbox, +448 of the 512 B barrier region): the owner piece's fp32 + // ws tile (128 KB) is bulk-copied by the TMA producer lane into 4 freed ring stages while the CTA's last k-blocks + // still run; completion (complete_tx 128 KB) signalled here. At most one owner piece per CTA -> phase 0. + uint64_t* fix_bar = reinterpret_cast(reinterpret_cast(full_bar) + 448); + + const int warp = __shfl_sync(0xffffffffu, (int)(threadIdx.x / 32), 0); // warp-uniform for ptxas (uniform regs) + const int lane = threadIdx.x % 32; + const int num_kb = K / BLOCK_K; + const int num_sblk = N / 128; + const int num_mt = (((M + BLOCK_M - 1) / BLOCK_M) + 1) / 2; // PAIR-tile rows (odd M-block count: the last pair's + // rank-1 CTA covers rows >= M only: its A box is TMA zero-filled, its stores / ws writes are guarded by m < M) + const int num_nt = N / BLOCK_N; + + if (threadIdx.x == 0) { + for (int i = 0; i < STAGES; ++i) { + mbar_init(&full_bar[i], 2); // leader: own arrive.expect_tx + peer's remote arrive (peer's copy unused) + mbar_init(&empty_bar[i], Q ? 2 : 1); // leader's multicast commit (QUAD: both pair leaders) + } + for (int i = 0; i < 2; ++i) { + mbar_init(&tfull_bar[i], 1); + mbar_init(&tempty_bar[i], 2 * NUM_EPI_WARPS); // leader: one elected arrive per promotion warp of BOTH CTAs + } + for (int i = 0; i < MB_SLOTS; ++i) { + mbar_init(&mfull_bar[i], 1); + mbar_init(&mempty_bar[i], NUM_EPI_WARPS); + } + for (int i = 0; i < SC_SLOTS; ++i) { + mbar_init(&sfull_bar[i], 64); // 64 scale-producer threads + mbar_init(&sempty_bar[i], NUM_EPI_WARPS); // one arrive per promotion warp + } + mbar_init(pub_bar, NUM_EPI_WARPS * 32); + for (int i = 0; i < 4; ++i) mbar_init(fix_bar + i, 1); // one per 32 KB ws slice (SLICED OWNER FIXUP) + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_a)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_b)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_out)) : "memory"); + } + const int crank_full = cl_rank(); + const int crank = crank_full & 1; // rank within the 2-SM UMMA pair + const uint32_t leader = Q ? (uint32_t)(crank_full & 2) : 0u; // pair leader rank in the cluster + cl_sync_relaxed(); // both CTAs resident (and barrier inits released) before the 2-CTA TMEM allocation + // EARLY OPERAND PROLOGUE (this version): thread 0 (= TMA producer, warp 0 lane 0) issues the TMA loads of its first + // pre (<= STAGES) k-blocks right here, BEFORE the 2-CTA TMEM alloc / __syncthreads / setmaxnreg, so the first + // DRAM fetches overlap the CTA setup (fresh ring: no empty wait). Leader: arms its full barrier (expect_tx of both + // CTAs' bytes) now. Peer: its complete_tx lands on the leader's barrier now (tx-count may go transiently negative, + // the phase cannot complete while arrivals are pending), but its remote ARRIVE stays in the producer loop after + // the peer's own TMEM alloc + __syncthreads, so the leader's first MMA still follows the peer's allocation. + constexpr bool EARLY = (V & 1) != 0; + uint32_t pre = 0; + if (EARLY && threadIdx.x == 0) { + // CROSS-CALL OVERLAP: the W (weight: read-only, never written by a preceding grid) TMA loads of the first + // stages are issued BEFORE griddepcontrol.wait, so they overlap the previous grid's tail; the A loads (A may be + // produced by the preceding grid) are issued only after the wait. Same barrier / byte accounting. + int pre_kx[STAGES], pre_m0[STAGES]; + uint64_t pol_a, pol_w; + asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol_a)); + if constexpr ((V & 2) != 0) asm volatile("createpolicy.fractional.L2::evict_normal.b64 %0, 1.0;" : "=l"(pol_w)); + else asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_w)); + const uint32_t lfull0 = smem_u32(full_bar), lring0 = smem_u32(smem); + const uint32_t lfull_l0 = mapa_u32(lfull0, 0u); + WorkIter wk = work_begin(direct, tail, 1, num_kb, rot, bnd); + int t, kb0, kb1, wsi; + while (pre < (uint32_t)STAGES && work_next(wk, direct, tail, 1, 1, num_kb, t, kb0, kb1, wsi)) { + int mbk, nbk; + tcoord(t, num_mt, num_nt, bnd, mbk, nbk); + const int m0 = (mbk * 2 + crank) * BLOCK_M; + const int ncol = nbk * BLOCK_N + crank * 128; + const bool rev = (bnd.krev && wsi < 0 && ((t / (int)(gridDim.x >> 1) + bnd.kpar) & 1)) || (bnd.krev == 2 && wsi >= 0); + for (int kb = kb0; kb < kb1 && pre < (uint32_t)STAGES; ++kb, ++pre) { + const uint32_t sa = lring0 + pre * (uint32_t)STAGE_BYTES; + const uint32_t fb = lfull_l0 + pre * 8u; + if (!crank) + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(lfull0 + pre * 8u), + "r"((uint32_t)(2 * STAGE_BYTES)) : "memory"); + const int kx = (rev ? kb0 + kb1 - 1 - kb : kb) * BLOCK_K; + pre_kx[pre] = kx; + pre_m0[pre] = m0; + tma_load_2d_c2_hint(smem + pre * STAGE_BYTES + TILE_A_BYTES, &tmap_b, fb, kx, ncol, pol_w); + (void)sa; + } + } + asm volatile("griddepcontrol.wait;" ::: "memory"); // PDL: A (possibly produced by the previous grid) after this + for (uint32_t i = 0; i < pre; ++i) + tma_load_2d_c2_hint(smem + i * STAGE_BYTES, &tmap_a, lfull_l0 + i * 8u, pre_kx[i], pre_m0[i], pol_a); + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::2.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(smem_u32(tmem_slot)), + "r"(TMEM_COLS)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::2.sync.aligned;"); + } + fence_before(); + __syncthreads(); + // PDL: barrier init / TMEM alloc / tensormap prefetch above overlap the previous grid's tail; no global + // memory (inputs, workspace, counters, output) is touched before the previous grid completed and flushed. + // PDL (split wait): no CTA-wide griddepcontrol.wait here. Read-only roles (TMA producer: A/W operands, scale + // producer: scale_x/scale_w, MMA issuer: smem/TMEM only) start right away -- no preceding kernel in the stream + // writes these inputs while triggering early (all our kernels trigger launch_dependents only after their own + // work, a non-PDL predecessor completes before this grid starts). Roles that WRITE / read-modify global state + // (promotion warps: ws, counters, output; publisher lane: counters) execute griddepcontrol.wait first. + // STARTUP TRIM: the former 2nd cluster barrier here is redundant. The 1st cl_sync (after thread 0's barrier + // init + fence.mbarrier_init.release.cluster) already makes every peer barrier visible before any cluster TMA / + // multicast commit / remote arrive; the peer's 2-CTA TMEM alloc precedes the leader's first MMA because the + // leader waits on its full barrier, which needs the peer producer's arrive (issued after the peer's alloc + + // fence::before_thread_sync + __syncthreads). The end-of-kernel cl_sync before dealloc is unchanged. + // early trigger: the dependent grid may begin its prologue (it still griddepcontrol.wait's for this grid's full + // completion before touching global memory); all CTAs of this grid are already resident. + asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); // every thread (per-CTA trigger) + fence_after(); + const uint32_t tmem_base = __shfl_sync(0xffffffffu, *tmem_slot, 0); // warp-uniform TMEM base + + if (warp < EPI_WARP0) { + asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;" ::"n"(REGS_CTRL)); + if (warp == 0) { + // ------------------------------------------------ TMA producer + if (lane == 0) { + asm volatile("griddepcontrol.wait;" ::: "memory"); // PDL: no operand load before the previous grid completes + // L2 hints: A tiles evict_last (re-read by every N pair tile of the M-block), W evict_first (each W k-slab + // is read by the few concurrent pair tiles of its N-block; W map keeps 256B L2 promotion) + uint64_t pol_a, pol_w; + asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol_a)); + if constexpr ((V & 2) != 0) asm volatile("createpolicy.fractional.L2::evict_normal.b64 %0, 1.0;" : "=l"(pol_w)); + else asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_w)); + uint32_t it = 0; + const uint32_t lfull0 = smem_u32(full_bar), lempty0 = smem_u32(empty_bar), lring0 = smem_u32(smem); + const uint32_t lfull_l0 = mapa_u32(lfull0, leader); + const uint16_t amask = (uint16_t)((1u << crank_full) | (1u << (crank_full ^ 2))); + const uint32_t aoff = (uint32_t)((crank_full >> 1) * (TILE_A_BYTES / 2)); + const int arow = (crank_full >> 1) * (BLOCK_M / 2); + const uint64_t lmap_a = reinterpret_cast(&tmap_a), lmap_b = reinterpret_cast(&tmap_b); + uint32_t ls = 0, lph = 0; // running stage / phase (== it % STAGES, (it / STAGES) & 1) + int own_ws = -1, own_need = 0; // owner piece (kb0 == 0, partial K; always this CTA's last unit) + WorkIter wk = WB(direct, tail, streamk, num_kb, rot, bnd); + int t, kb0, kb1, wsi; + while (WN(wk, direct, tail, split, streamk, num_kb, t, kb0, kb1, wsi)) { + int mbk, nbk; + tcoord(t, num_mt, num_nt, bnd, mbk, nbk); + if (wsi >= 0 && kb0 == 0 && kb1 < num_kb) { own_ws = wsi * 2 + crank; own_need = num_kb - kb1; } + mbk = mbk * 2 + crank; + const int m0 = mbk * BLOCK_M; + const int n0 = nbk * BLOCK_N; + const int ncol = n0 + crank * 128; + const bool rev = (bnd.krev && wsi < 0 && ((t / (int)(gridDim.x >> 1) + bnd.kpar) & 1)) || (bnd.krev == 2 && wsi >= 0); // serpentine K (see SkTail) + for (int kb = kb0; kb < kb1; ++kb, ++it) { + // LEAN: hoisted 32-bit barrier / ring / leader-full bases + running stage/phase counters (no % / div) + mbar_wait_sleep_u32(lempty0 + ls * 8u, lph ^ 1); // leader's MMAs (both halves) done with stage ls + const uint32_t sa = lring0 + ls * (uint32_t)STAGE_BYTES; + const uint32_t fb = lfull_l0 + ls * 8u; // leader's full barrier (cluster address) + if (EARLY && it < pre) { // loads (+ leader expect_tx) already issued by the early prologue + if (crank) mbar_arrive_cl(fb); + if (++ls == (uint32_t)STAGES) { ls = 0; lph ^= 1; } + continue; + } + if (crank) mbar_arrive_cl(fb); + else asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(lfull0 + ls * 8u), + "r"((uint32_t)(2 * STAGE_BYTES)) : "memory"); // both CTAs' A + W halves + const int kx = (rev ? kb0 + kb1 - 1 - kb : kb) * BLOCK_K; // k-block loaded into this stage + if constexpr (Q) { + // my 64-row half of the shared A tile -> same offset in me and in rank^2 (other pair, same crank); + // complete_tx lands on each destination pair's leader full barrier + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.multicast::cluster.cta_group::2.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5, %6;" ::"r"(sa + aoff), "l"(lmap_a), "r"(kx), "r"(m0 + arow), "r"(fb), + "h"(amask), "l"(pol_a) + : "memory"); + } else { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.cta_group::2.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(sa), "l"(lmap_a), "r"(kx), "r"(m0), "r"(fb), "l"(pol_a) + : "memory"); + } + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.cta_group::2.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(sa + (uint32_t)TILE_A_BYTES), "l"(lmap_b), "r"(kx), "r"(ncol), + "r"(fb), "l"(pol_w) + : "memory"); // own W half (WSUB: first 64-row sub-box; tmap_b box = 64 rows) + if constexpr ((V & 32) != 0) { + // WSUB (V bit 32, M=2048 class): second 64-row sub-box of the own 128-row W half (8 KB at +64*128 B, + // 1024 B aligned -> identical 128B-swizzled layout as one 128-row box); same full barrier / byte total. + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.cta_group::2.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(sa + (uint32_t)(TILE_A_BYTES + 64 * BLOCK_K)), "l"(lmap_b), + "r"(kx), "r"(ncol + 64), "r"(fb), "l"(pol_w) + : "memory"); + } + if (++ls == (uint32_t)STAGES) { ls = 0; lph ^= 1; } + } + } + // drain: every stage's last use released (no multicast commit lands after this CTA exits) + // OWNER WS PREFETCH: the first 4 stages released in this drain (they free while the CTA's last ~2-5 + // k-blocks are still in the MMA / promotion pipeline) receive the 4 x 32 KB slices of the owner piece's fp32 + // ws tile (slice q -> stage (it_end + q) % STAGES, q = float4 index >> 11), after the contributors' counts + // arrived (acquire) -> the owner fixup reads smem instead of 4 latency-bound L2 batches at the kernel end. + for (int i = 0; i < STAGES; ++i, ++it) { + const uint32_t dstage = ls; + mbar_wait_sleep_u32(lempty0 + ls * 8u, lph ^ 1); + if (++ls == (uint32_t)STAGES) { ls = 0; lph ^= 1; } + if (own_ws >= 0 && i < 4) { + if (i == 0) { + asm volatile("griddepcontrol.wait;" ::: "memory"); // PDL: counters / ws of THIS call only + int c; + while (true) { + asm volatile("ld.acquire.gpu.global.b32 %0, [%1];" : "=r"(c) : "l"(cnt + own_ws) : "memory"); + if (c >= SK2C_WFLAG + own_need) break; // writer flag + all contributor k-blocks + __nanosleep(32); + } + cnt[own_ws] = 0; // all contributions arrived: reset for the next call + asm volatile("fence.proxy.async.global;" ::: "memory"); // generic-proxy ws writes -> bulk reads + } + // SLICED OWNER FIXUP: issue order i -> slice sq = {0, 2, 1, 3}[i] (each warpgroup's first slice first), + // each slice completes on its own barrier fix_bar[sq] so a warpgroup adds slice data as soon as it lands + const int sq = (i & 1) * 2 + (i >> 1); + mbar_arrive_expect_tx(fix_bar + sq, (uint32_t)(WS_TILE_FLOATS)); + const float* src = ws + (size_t)own_ws * WS_TILE_FLOATS + (size_t)sq * (WS_TILE_FLOATS / 4); + asm volatile("cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1], %2, [%3];" ::"r"( + lring0 + dstage * (uint32_t)STAGE_BYTES), + "l"(reinterpret_cast(src)), "r"((uint32_t)(WS_TILE_FLOATS)), "r"(smem_u32(fix_bar + sq)) + : "memory"); + } + } + } else if (lane == 1) { + asm volatile("griddepcontrol.wait;" ::: "memory"); // PDL: counters touched below + // ------------------------------------------------ contributor PUBLISHER (off the promotion critical path) + // A contributor piece (kb0 > 0; at most one per CTA: always the first piece of its tail range) is stored + // by the 256 promotion threads, which then only arrive (release.cta) on pub_bar and move on to the next + // unit. This idle lane waits for those arrivals (acquire.cta), issues the cumulative gpu-scope fence and + // publishes the k-block count -- the fence's drain of the 128 KB of stores no longer stalls a promotion + // warp (and through its tempty arrive, the MMA issuer). + WorkIter wk = WB(direct, tail, streamk, num_kb, rot, bnd); + int t, kb0, kb1, wsi; + while (WN(wk, direct, tail, split, streamk, num_kb, t, kb0, kb1, wsi)) { + if (wsi >= 0 && kb0 > 0) { + mbar_wait_sleep(pub_bar, 0); // single use per launch (<= 1 contributor piece per CTA) + asm volatile("fence.acq_rel.gpu;" ::: "memory"); + asm volatile("red.relaxed.gpu.global.add.s32 [%0], %1;" ::"l"(cnt + wsi * 2 + crank), "r"((kb1 - kb0) + (kb1 == num_kb ? SK2C_WFLAG : 0)) : "memory"); + } + } + } + } else if (warp == 1) { + // ------------------------------------------------ MMA issuer (single thread) + // SASS AUDIT: the issuer loop runs on the WHOLE warp 1 (warp-uniform state -> uniform registers) and only the + // tcgen05.mma / commit block is predicated on elect.sync inside the asm; the previous lane-0-only loop made ptxas + // wrap every tcgen05 instruction in an ELECT / BRA.U.ANY peeling loop + R2UR copies (~84 -> fewer instr / kb). + if (crank == 0) { + // instr descriptor: D=f32, A=B=e4m3, K-major, N=256, M=256 over the CTA pair + const uint32_t idesc = (1u << 4) | ((uint32_t)(BLOCK_N >> 3) << 17) | ((uint32_t)((2 * BLOCK_M) >> 4) << 24); + // FUSED ISSUE (m256v / m128c style): barrier + descriptor addresses hoisted as 32-bit values, running + // stage/phase counters (no % / div), spin wait on operands-full (normally resident), suspend-hinted wait on + // the TMEM hand-off, and the 4 K32 cta_group::2 MMAs + both multicast commits issued as ONE asm block. + const uint32_t full0 = smem_u32(full_bar), empty0 = smem_u32(empty_bar); + const uint32_t tfull0 = smem_u32(tfull_bar), tempty0 = smem_u32(tempty_bar); + const uint64_t adesc0 = make_sdesc(smem_u32(smem)); + constexpr uint64_t BOFF = TILE_A_BYTES >> 4, SOFF = STAGE_BYTES >> 4; + uint32_t it = 0, s = 0, ph = 0; + WorkIter wk = WB(direct, tail, streamk, num_kb, rot, bnd); + int t, kb0, kb1, wsi; + while (WN(wk, direct, tail, split, streamk, num_kb, t, kb0, kb1, wsi)) { + for (int kb = kb0; kb < kb1; ++kb, ++it) { + const uint32_t b = it & 1; + const uint64_t ad = adesc0 + (uint64_t)s * SOFF, bd = ad + BOFF; + asm volatile( + "{\n.reg .pred p;\nWF_%=:\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n@!p bra WF_%=;\n}\n" + ::"r"(full0 + s * 8), "r"(ph) : "memory"); + asm volatile( + "{\n.reg .pred p;\nWT_%=:\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n@!p bra WT_%=;\n}\n" + ::"r"(tempty0 + b * 8), "r"(((it >> 1) & 1) ^ 1), "n"(0x989680) : "memory"); + fence_after(); + asm volatile( + "{\n" + ".reg .pred pf, pt, e;\n" + "setp.eq.u32 pt, 1, 1;\n" + "setp.eq.u32 pf, 1, 0;\n" + "elect.sync _|e, 0xffffffff;\n" + "@e tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], %1, %2, %3, pf;\n" + "@e tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], %4, %5, %3, pt;\n" + "@e tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], %6, %7, %3, pt;\n" + "@e tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], %8, %9, %3, pt;\n" + /* TFULL-FIRST commit order: promotion hand-off (tfull, %11) signalled before the stage release (%10) */ + "@e tcgen05.commit.cta_group::2.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%11], %12;\n" + "@e tcgen05.commit.cta_group::2.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%10], %13;\n" + "}\n" ::"r"(tmem_base + b * (uint32_t)BLOCK_N), + "l"(ad), "l"(bd), "r"(idesc), "l"(ad + 2), "l"(bd + 2), "l"(ad + 4), "l"(bd + 4), "l"(ad + 6), "l"(bd + 6), + "r"(empty0 + s * 8), "r"(tfull0 + b * 8), "h"((uint16_t)(0x3u << leader)), "h"((uint16_t)(Q ? 0xFu : 0x3u)) + : "memory"); + if (++s == STAGES) { s = 0; ph ^= 1; } + } + } + } + } else { + // ------------------------------------------------ scale producer (warps 2,3; 64 threads) + // thread lt owns rows lt and lt+64 of the tile, both 128-col scale halves. + asm volatile("griddepcontrol.wait;" ::: "memory"); // PDL: scale loads after the previous grid completes + const int lt = threadIdx.x - 64; + uint32_t it = 0; + uint32_t ui = 0; // unit counter (mailbox ring position) + const uint32_t lsfull0 = smem_u32(sfull_bar), lsempty0 = smem_u32(sempty_bar); + const uint32_t lsc0 = smem_u32(sc_ring) + (uint32_t)lt * 4u; // my row lt within a slot + uint32_t lslot = 0, lsph = 0; // running scale-ring slot / phase + WorkIter wk = WB(direct, tail, streamk, num_kb, rot, bnd); + int t, kb0, kb1, wsi; + while (WN(wk, direct, tail, split, streamk, num_kb, t, kb0, kb1, wsi)) { + int mbk, nbk; + tcoord(t, num_mt, num_nt, bnd, mbk, nbk); + mbk = mbk * 2 + crank; + const bool rev = (bnd.krev && wsi < 0 && ((t / (int)(gridDim.x >> 1) + bnd.kpar) & 1)) || (bnd.krev == 2 && wsi >= 0); // same order as the TMA producer + if (wsi >= 0) wsi = wsi * 2 + crank; // per-CTA ws tile / counter of the pair tile + if (lt == 0) { // publish the decoded unit to the promotion warps + const int ms = ui % MB_SLOTS; + mbar_wait_sleep(&mempty_bar[ms], ((ui / MB_SLOTS) & 1) ^ 1); + mbox[ms] = make_int4(mbk * BLOCK_M, nbk * BLOCK_N, kb0 | (kb1 << 16), wsi); + mbar_arrive(&mfull_bar[ms]); // release semantics: mailbox st.shared visible to waiters + } + ++ui; + const int ra = mbk * BLOCK_M + lt, rb = ra + 64; + const float* pa = scale_x + (size_t)(ra < M ? ra : 0) * num_kb; // rows >= M: value unused + const float* pb = scale_x + (size_t)(rb < M ? rb : 0) * num_kb; + for (int kb = kb0; kb < kb1; kb += 4) { + const int nq = (kb1 - kb) < 4 ? (kb1 - kb) : 4; + float xa[4], xb[4]; + float2 w[4]; + if (rev) { + // SERPENTINE K: ring entry q of this batch holds k-block kb0 + kb1 - 1 - (kb + q) + if (nq == 4 && ((kb | kb0 | kb1) & 3) == 0) { + const int kr = kb0 + kb1 - 4 - kb; // 16B-aligned (num_kb % 4 == 0 checked via kb1) + const float4 va = __ldg(reinterpret_cast(pa + kr)); + const float4 vb = __ldg(reinterpret_cast(pb + kr)); + xa[0] = va.w; xa[1] = va.z; xa[2] = va.y; xa[3] = va.x; + xb[0] = vb.w; xb[1] = vb.z; xb[2] = vb.y; xb[3] = vb.x; +#pragma unroll + for (int q = 0; q < 4; ++q) + w[q] = __ldg(reinterpret_cast(scale_w + (size_t)(kr + 3 - q) * num_sblk) + nbk); + } else { +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + const int kr = kb0 + kb1 - 1 - (kb + q); + xa[q] = __ldg(pa + kr); + xb[q] = __ldg(pb + kr); + w[q] = __ldg(reinterpret_cast(scale_w + (size_t)kr * num_sblk) + nbk); + } + } + } + } else if (nq == 4 && ((kb | num_kb) & 3) == 0) { + // POWER: one 16 B load per row per 4 k-blocks (row base 16B-aligned since num_kb % 4 == 0) + const float4 va = __ldg(reinterpret_cast(pa + kb)); + const float4 vb = __ldg(reinterpret_cast(pb + kb)); + xa[0] = va.x; xa[1] = va.y; xa[2] = va.z; xa[3] = va.w; + xb[0] = vb.x; xb[1] = vb.y; xb[2] = vb.z; xb[3] = vb.w; +#pragma unroll + for (int q = 0; q < 4; ++q) + w[q] = __ldg(reinterpret_cast(scale_w + (size_t)(kb + q) * num_sblk) + nbk); + } else { +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + xa[q] = __ldg(pa + kb + q); + xb[q] = __ldg(pb + kb + q); + w[q] = __ldg(reinterpret_cast(scale_w + (size_t)(kb + q) * num_sblk) + nbk); + } + } + } +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q < nq) { + // LEAN: hoisted 32-bit barrier / ring bases + running slot / phase counters + mbar_wait_sleep_u32(lsempty0 + lslot * 8u, lsph ^ 1); + const uint32_t d = lsc0 + lslot * 1024u; + asm volatile("st.shared.f32 [%0], %1;" ::"r"(d), "f"(xa[q] * w[q].x) : "memory"); + asm volatile("st.shared.f32 [%0], %1;" ::"r"(d + 256u), "f"(xb[q] * w[q].x) : "memory"); + asm volatile("st.shared.f32 [%0], %1;" ::"r"(d + 512u), "f"(xa[q] * w[q].y) : "memory"); + asm volatile("st.shared.f32 [%0], %1;" ::"r"(d + 768u), "f"(xb[q] * w[q].y) : "memory"); + mbar_arrive_u32(lsfull0 + lslot * 8u); + if (++lslot == (uint32_t)SC_SLOTS) { lslot = 0; lsph ^= 1; } + } + } + it += nq; + } + } + if (lt == 0) { // end-of-work marker + const int ms = ui % MB_SLOTS; + mbar_wait_sleep(&mempty_bar[ms], ((ui / MB_SLOTS) & 1) ^ 1); + mbox[ms] = make_int4(0, 0, 0, -2); + mbar_arrive(&mfull_bar[ms]); + } + } + } else { + // ------------------------------------------------ promotion epilogue (warps 4..11) + asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;" ::"n"(REGS_EPI)); + asm volatile("griddepcontrol.wait;" ::: "memory"); // PDL: ws / counters / output written by this role + const int g = (warp - EPI_WARP0) >> 2; // 128-col half of the tile + const int sub = warp & 3; // TMEM sub-partition + const int row = sub * 32 + lane; // tile row == TMEM lane + // EPILOGUE STAGING RING: OUT_SLOTS x 1 KB per warp; box counter `ob` runs across units, box ob uses slot + // ob % OUT_SLOTS, so only the store of box ob - OUT_SLOTS must have finished reading before packing. + uint8_t* wstage0 = out_stage + (g * 4 + sub) * OUT_SLOTS * WARP_STAGE_BYTES; + uint32_t ob = 0; + // precomputed TMEM addresses of both accumulator buffers for this warp's lanes / cols + // warp-uniform broadcast (SASS audit): keeps the TMEM base in a uniform register instead of rematerialising it + // from the warp index every k-block + const uint32_t taddr_b0 = __shfl_sync(0xffffffffu, tmem_base + ((uint32_t)(sub * 32) << 16) + g * 128, 0); + // SASS AUDIT (promotion k-loop): every per-kb shared address is a WARP-UNIFORM 32-bit base + immediate / small + // index term, instead of re-deriving generic pointers (&sfull_bar[slot] etc.: S2UR SR_SWINHI + 1024-align + cvta) + // every k-block. My scale = sc_u + slot*1024 + threadIdx.x*4 (g*128 + row == threadIdx.x - 128: the -512 B is + // folded into the uniform base). Same loads / barriers / math (bit-identical). + const uint32_t bar_u = __shfl_sync(0xffffffffu, smem_u32(full_bar), 0); + constexpr uint32_t TFULL_OFF = (2 * STAGES) * 8, SFULL_OFF = TFULL_OFF + 32, SEMPTY_OFF = SFULL_OFF + SC_SLOTS * 8; + const uint32_t sc_u = __shfl_sync(0xffffffffu, smem_u32(sc_ring), 0) - 512u; + uint32_t it = 0; + const uint32_t mbox_s = smem_u32(mbox); + const uint32_t tempty_leader = + __shfl_sync(0xffffffffu, mapa_u32(smem_u32(&tempty_bar[0]), leader), 0); // leader CTA's tempty[0] (cluster addr) + for (uint32_t ui = 0;; ++ui) { + // next decoded unit from the control WG's mailbox (no walker / 64-bit math in the promotion warps) + const uint32_t ms = ui % MB_SLOTS; + mbar_wait_sleep(&mfull_bar[ms], (ui / MB_SLOTS) & 1); + // SASS AUDIT (register pressure): only {kb0|kb1, wsi} are read before the k-loop; the full record is RE-READ + // from the (not yet released) mailbox slot after it, so m0 / nbase / n0 / m / wsi are not live across the + // promotion loop (they made the 224-reg promotion warps spill 8 accumulators = 4 STL.64 + 4 LDL.64 per kb). + int kbp, wsi; + asm volatile("ld.shared.v2.b32 {%0, %1}, [%2];" : "=r"(kbp), "=r"(wsi) : "r"(mbox_s + ms * 16u + 8u) : "memory"); + if (wsi == -2) { + __syncwarp(); + if (lane == 0) mbar_arrive(&mempty_bar[ms]); + break; + } + const int kb1 = kbp >> 16; + float acc[128]; + if constexpr (!FM) { +#pragma unroll + for (int j = 0; j < 128; ++j) acc[j] = 0.f; + } + +#define SK2C_P16(A_, R_, OP) _Pragma("unroll") for (int j = 0; j < 16; j += 2) OP((A_)[j], (A_)[j + 1], (R_)[j], (R_)[j + 1], ss); +// EARLY-RELEASE DRAIN (kernel_large2 LDN=33 schedule, 80 staging regs): cols 0..79 in flight first; after the first +// wait::ld the FFMA2s of cols 0..31 free ra -> cols 80..111 loaded into it; after cols 32..47 rb[0..16) -> cols +// 112..127. Spill-free at 224 regs (the previous 4 x32 schedule spilled 8 accumulators per k-block). +#define SK2C_DRAIN(OP) \ + { \ + uint32_t ra[32], rb[32], rc[16]; \ + TMEM_LD32(taddr + 0, ra); \ + TMEM_LD32(taddr + 32, rb); \ + TMEM_LD16(taddr + 64, rc); \ + tmem_ld_wait(); \ + SK2C_P16(acc + 0, ra, OP) SK2C_P16(acc + 16, ra + 16, OP) \ + TMEM_LD16(taddr + 80, ra); \ + TMEM_LD16(taddr + 96, (ra + 16)); \ + SK2C_P16(acc + 32, rb, OP) \ + TMEM_LD16(taddr + 112, rb); \ + SK2C_P16(acc + 48, rb + 16, OP) \ + tmem_ld_wait(); \ + fence_before(); \ + __syncwarp(); \ + if (lane == 0) { /* MERGED RELEASE: one __syncwarp covers both the TMEM buffer and the scale slot (s already consumed) */ \ + mbar_arrive_cl_relaxed(tempty_leader + (uint32_t)b * 8u); /* release LEADER's tempty[b] */ \ + mbar_arrive_u32(bar_u + SEMPTY_OFF + slot * 8u); /* scale-ring slot free */ \ + } \ + SK2C_P16(acc + 64, rc, OP) SK2C_P16(acc + 80, ra, OP) \ + SK2C_P16(acc + 96, ra + 16, OP) SK2C_P16(acc + 112, rb, OP) \ + } +// One promotion k-block: scale from the smem ring, wait the leader's multicast tfull commit, then the pipelined x32 +// TMEM drain (SK2C_DRAIN) with OP = ffma2 (acc += partial*s) or fmul2_set (acc = partial*s, first k-block, FM). +// SK2C_STEPX: SLOT_ = scale-ring slot, SPAR_ / TPAR_ = scale-ring / TMEM-buffer mbarrier phases (passed in so a k-block +// PAIR computes them once: it even -> both steps share both phases, slot of the 2nd step = slot + 1 since SC_SLOTS even). +#define SK2C_STEPX(OP, B_, SLOT_, SPAR_, TPAR_) \ + { \ + const int b = (B_); \ + const uint32_t slot = (SLOT_); \ + mbar_wait_sleep_u32(bar_u + SFULL_OFF + slot * 8u, (SPAR_)); \ + float s; \ + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(s) : "r"(sc_u + slot * 1024u + (uint32_t)threadIdx.x * 4u) : "memory"); \ + const float2 ss = make_float2(s, s); /* sempty released at the tempty point (SK2C_DRAIN) */ \ + if constexpr ((V & (32 | 128)) != 0) mbar_wait_spin_tf(bar_u + TFULL_OFF + (uint32_t)b * 8u, (TPAR_)); /* TSPIN (M=2048 WSUB; V&128: M>=12288 cascaded chain) */ \ + else mbar_wait_hybrid_u32(bar_u + TFULL_OFF + (uint32_t)b * 8u, (TPAR_)); /* HYBRID tfull wait */ \ + fence_after(); \ + const uint32_t taddr = taddr_b0 + ((uint32_t)b << 8); \ + SK2C_DRAIN(OP) \ + } +#define SK2C_STEP(OP, B_) SK2C_STEPX(OP, B_, it % SC_SLOTS, (it / SC_SLOTS) & 1, (it >> 1) & 1) + // FM: first k-block peeled out of the loop (acc = partial*s), no in-loop branch + int kb = kbp & 0xFFFF; + if constexpr (FM) { + SK2C_STEP(fmul2_set, (int)(it & 1)) + ++kb; + ++it; + } + // 2x-UNROLLED k-loop with COMPILE-TIME TMEM buffer index: align `it` to even with one generic step, then pairs + // (buffer 0, buffer 1) whose tfull barrier / tempty arrive / TMEM addresses are immediates off uniform bases, + // then at most one generic tail step. Same per-kb operations in the same order (bit-identical). + if ((it & 1) && kb < kb1) { SK2C_STEP(ffma2, 1) ++kb; ++it; } + for (; kb + 1 < kb1; kb += 2, it += 2) { + static_assert(SC_SLOTS % 2 == 0, "pair shares the scale-ring round"); + const uint32_t s0 = it % SC_SLOTS, sp = (it / SC_SLOTS) & 1, tp = (it >> 1) & 1; + SK2C_STEPX(ffma2, 0, s0, sp, tp) + SK2C_STEPX(ffma2, 1, s0 + 1, sp, tp) + } + if (kb < kb1) { SK2C_STEP(ffma2, 0) ++kb; ++it; } +#undef SK2C_STEP +#undef SK2C_STEPX +#undef SK2C_DRAIN +#undef SK2C_P16 + int m0, nbase; + asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4];" + : "=r"(m0), "=r"(nbase), "=r"(kbp), "=r"(wsi) + : "r"(mbox_s + ms * 16u) + : "memory"); + __syncwarp(); + if (lane == 0) mbar_arrive(&mempty_bar[ms]); // mailbox slot released only now (record re-read above) + const int kb0 = kbp & 0xFFFF; + const int n0 = nbase + g * 128; + const int m = m0 + row; + if (wsi >= 0 && !(kb0 == 0 && kb1 == num_kb)) { + const int etid = threadIdx.x - EPI_WARP0 * 32; // 0..255 + float4* wrow = reinterpret_cast(ws + (size_t)wsi * WS_TILE_FLOATS) + (g * 32) * BLOCK_M + row; + if (kb0 > 0) { + if (kb1 == num_kb) { + if (m < M) { + if constexpr ((V & 16) != 0) { + // WSKEEP (V bit 16, M=1024 class): writer ws partial stored with an L2 evict_last policy so it stays + // L2-resident until the owner's bulk copy reads it (dirty-L2 regime; ws is re-read exactly once). + uint64_t pol_ws; + asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol_ws)); +#pragma unroll + for (int v = 0; v < 32; ++v) + asm volatile("st.global.cg.L2::cache_hint.v4.f32 [%0], {%1, %2, %3, %4}, %5;" ::"l"(wrow + v * BLOCK_M), + "f"(acc[v * 4 + 0]), "f"(acc[v * 4 + 1]), "f"(acc[v * 4 + 2]), "f"(acc[v * 4 + 3]), + "l"(pol_ws) : "memory"); + } else { +#pragma unroll + for (int v = 0; v < 32; ++v) + __stcg(wrow + v * BLOCK_M, make_float4(acc[v * 4 + 0], acc[v * 4 + 1], acc[v * 4 + 2], acc[v * 4 + 3])); + } + } + } else { + if (etid == 0) { + // PARALLEL MIDDLES: a middle contributor waits ONLY for the writer's overwrite (flag SK2C_WFLAG in the + // counter), not for every higher-k piece -> no serial chain of middle contributors (red.add commutes) + // POWER: exponential nanosleep backoff in this non-critical polling loop + int c; + unsigned bo = 32; + while (true) { + asm volatile("ld.acquire.gpu.global.b32 %0, [%1];" : "=r"(c) : "l"(cnt + wsi) : "memory"); + if (c >= SK2C_WFLAG) break; + __nanosleep(bo); + bo = bo < 256 ? bo * 2 : 256; + } + } + asm volatile("bar.sync 1, 256;" ::: "memory"); + if (m < M) { + if constexpr ((V & 16) != 0) { + uint64_t pol_ws; // WSKEEP: middle red.add with L2 evict_last (owner reads these lines next) + asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol_ws)); +#pragma unroll + for (int v = 0; v < 32; ++v) + asm volatile("red.global.add.L2::cache_hint.v4.f32 [%0], {%1, %2, %3, %4}, %5;" ::"l"( + reinterpret_cast(wrow + v * BLOCK_M)), + "f"(acc[v * 4 + 0]), "f"(acc[v * 4 + 1]), "f"(acc[v * 4 + 2]), "f"(acc[v * 4 + 3]), + "l"(pol_ws) : "memory"); + } else { +#pragma unroll + for (int v = 0; v < 32; ++v) + red_add_v4(reinterpret_cast(wrow + v * BLOCK_M), acc[v * 4 + 0], acc[v * 4 + 1], + acc[v * 4 + 2], acc[v * 4 + 3]); + } + } + } + mbar_arrive(pub_bar); // release.cta of this thread's partial; publisher lane (warp 0 lane 1) fences + counts + continue; + } + // owner: the TMA producer lane waited for the contributors and bulk-copied this CTA's ws tile into 4 freed + // ring stages (slice q of float4 index f = (g*32+v)*128 + row is f >> 11 = g*2 + (v >> 4), at stage + // (it + q) % STAGES; `it` = this CTA's total k-block count = the producer's drain start). + // slice 2g landed at drain position g, slice 2g+1 at position 2+g (issue order 0,2,1,3) + mbar_wait_sleep(fix_bar + g * 2, 0); + (void)wrow; + { + const uint32_t ring0 = smem_u32(smem); + const uint32_t s0 = (it + (uint32_t)g) % STAGES, s1 = (it + (uint32_t)(2 + g)) % STAGES; + const uint32_t a0 = ring0 + s0 * STAGE_BYTES + (uint32_t)row * 16u; + const uint32_t a1 = ring0 + s1 * STAGE_BYTES + (uint32_t)row * 16u; +#pragma unroll + for (int q = 0; q < 4; ++q) { // 4 batches of 8 ld.shared.v4 (conflict-free: lane = consecutive 16 B) + if (q == 2) mbar_wait_sleep(fix_bar + g * 2 + 1, 0); // second slice of this warpgroup + if (m >= M) continue; // rows >= M: nothing to add (waits still executed by every thread) + float4 p[8]; +#pragma unroll + for (int v = 0; v < 8; ++v) { + const int vv = q * 8 + v; + const uint32_t ad = (vv < 16 ? a0 : a1) + (uint32_t)((vv & 15) * BLOCK_M * 16); + asm volatile("ld.shared.v4.f32 {%0, %1, %2, %3}, [%4];" + : "=f"(p[v].x), "=f"(p[v].y), "=f"(p[v].z), "=f"(p[v].w) : "r"(ad) : "memory"); + } +#pragma unroll + for (int v = 0; v < 8; ++v) { + fadd2(acc[(q * 8 + v) * 4 + 0], acc[(q * 8 + v) * 4 + 1], p[v].x, p[v].y); + fadd2(acc[(q * 8 + v) * 4 + 2], acc[(q * 8 + v) * 4 + 3], p[v].z, p[v].w); + } + } + } + } + // TRIPLE-BOX EPILOGUE GROUPS: the 8 bf16 boxes (32 rows x 16 cols) of this warp are written in groups of + // 3/3/2 that fill the whole 3-slot staging ring: ONE wait_group.read 0 (previous group's stores finished + // reading the ring), pack all boxes of the group, ONE fence.proxy.async + __syncwarp, then lane 0 issues the + // group's TMA stores and ONE commit. 3 fences / waits / syncwarp pairs per tile instead of 8. Same bytes, + // same box coordinates (bit-identical output). + (void)ob; +#pragma unroll + for (int h0b = 0; h0b < 8; h0b += OUT_SLOTS) { + const int nbx = (8 - h0b) < OUT_SLOTS ? (8 - h0b) : OUT_SLOTS; + if (lane == 0) tma_store_wait_read(); // whole ring free (stores of the previous group read their smem) + __syncwarp(); +#pragma unroll + for (int q = 0; q < OUT_SLOTS; ++q) { + if (q >= nbx) continue; + const int h = h0b + q; + uint8_t* wstage = wstage0 + q * WARP_STAGE_BYTES; + // bf16 pack -> 32B-swizzled staging (32 B rows): 16B chunk j of row lane at (j ^ ((lane>>2)&1)) +#pragma unroll + for (int j = 0; j < 2; ++j) { + const int v = h * 2 + j; + uint4 pk; + __nv_bfloat162 h0 = __floats2bfloat162_rn(acc[v * 8 + 0], acc[v * 8 + 1]); + __nv_bfloat162 h1 = __floats2bfloat162_rn(acc[v * 8 + 2], acc[v * 8 + 3]); + __nv_bfloat162 h2 = __floats2bfloat162_rn(acc[v * 8 + 4], acc[v * 8 + 5]); + __nv_bfloat162 h3 = __floats2bfloat162_rn(acc[v * 8 + 6], acc[v * 8 + 7]); + pk.x = *reinterpret_cast(&h0); + pk.y = *reinterpret_cast(&h1); + pk.z = *reinterpret_cast(&h2); + pk.w = *reinterpret_cast(&h3); + *reinterpret_cast(wstage + lane * 32 + ((j ^ ((lane >> 2) & 1)) << 4)) = pk; + } + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // make st.shared visible to TMA + __syncwarp(); + if (lane == 0) { +#pragma unroll + for (int q = 0; q < OUT_SLOTS; ++q) { + if (q >= nbx) continue; + tma_store_2d(&tmap_out, wstage0 + q * WARP_STAGE_BYTES, n0 + (h0b + q) * 16, m0 + sub * 32); + } + tma_store_commit(); + } + } + } + // only the smem READ of in-flight output stores must finish before exit (CUTLASS tma_store_wait): + // the global writes complete asynchronously and are flushed at grid completion. + if (lane == 0) tma_store_wait_read(); + __syncwarp(); + } + + fence_before(); + __syncthreads(); + // PDL: all of this CTA's work is issued/complete -> let the next grid start its prologue (it still + // griddepcontrol.wait's for this grid's full completion before touching global memory). + asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); + cl_sync_relaxed(); // no CTA exits (or frees TMEM) while its peer may still TMA / commit / arrive into it + if (warp == 1) { + fence_after(); + asm volatile("tcgen05.dealloc.cta_group::2.sync.aligned.b32 %0, %1;" ::"r"(tmem_base), "r"(TMEM_COLS)); + } +} + +// 2D K-major fp8 tensor map: dims {K, rows}, box {128, box_rows}, 128B swizzle. +static void make_tmap(CUtensorMap* map, const void* ptr, uint64_t rows, uint64_t K, uint32_t box_rows, + CUtensorMapL2promotion promo = CU_TENSOR_MAP_L2_PROMOTION_L2_256B) { + cuuint64_t dims[2] = {K, rows}; + cuuint64_t strides[1] = {K}; + cuuint32_t box[2] = {BLOCK_K, box_rows}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(map, CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, const_cast(ptr), dims, strides, + box, estr, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, + promo, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) { + fprintf(stderr, "cuTensorMapEncodeTiled failed: %d\n", (int)r); + } +} +// bf16 output map: dims {N, M}, box {16 cols (32 B), 32 rows}, 32B swizzle (3-slot per-warp staging ring). +static void make_tmap_out(CUtensorMap* map, void* ptr, uint64_t M, uint64_t N) { + cuuint64_t dims[2] = {N, M}; + cuuint64_t strides[1] = {N * 2}; + cuuint32_t box[2] = {16, 32}; + cuuint32_t estr[2] = {1, 1}; + CUresult r = tmc::encode2d_cached(map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, ptr, dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_32B, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + if (r != CUDA_SUCCESS) { + fprintf(stderr, "cuTensorMapEncodeTiled(out) failed: %d\n", (int)r); + } +} + + +struct SkWs { + float* ws = nullptr; + int* cnt = nullptr; + size_t floats = 0; + size_t cnts = 0; +}; + +} // namespace + +namespace { +cudaLaunchConfig_t sk2c_cfg(int grid, cudaStream_t stream, cudaLaunchAttribute* attr) { + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3(grid, 1, 1); + cfg.blockDim = dim3(NUM_THREADS, 1, 1); + cfg.dynamicSmemBytes = SMEM_BYTES; + cfg.stream = stream; + attr[0].id = cudaLaunchAttributeClusterDimension; + attr[0].val.clusterDim.x = 2; + attr[0].val.clusterDim.y = 1; + attr[0].val.clusterDim.z = 1; + attr[1].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attr[1].val.programmaticStreamSerializationAllowed = 1; + // CLUSTER SCHEDULING POLICY SPREAD (kernel uses cta_group::2 2-SM UMMA, cluster barriers, multicast commits): spread the + // pair clusters across GPCs. Placement hint only; math unchanged. + attr[2].id = cudaLaunchAttributeClusterSchedulingPolicyPreference; + attr[2].val.clusterSchedulingPolicyPreference = cudaClusterSchedulingPolicySpread; + cfg.attrs = attr; + cfg.numAttrs = 3; + return cfg; +} +// co-resident 2-CTA clusters (owner pieces spin on contributors of other clusters -> all must be resident) +int sk2c_max_clusters() { + static int v = -1; + if (v < 0) { + cudaFuncSetAttribute(fp8_sk2c_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaFuncSetAttribute(fp8_sk2c_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + int dev, sms = 0; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev); + cudaLaunchAttribute attr[3]; + cudaLaunchConfig_t q = sk2c_cfg(2 * (sms / 2), 0, attr); + q.numAttrs = 1; + int n = 0; + if (cudaOccupancyMaxActiveClusters(&n, fp8_sk2c_kernel, &q) != cudaSuccess) { + cudaGetLastError(); + n = 0; + } + const int cap = sms / 2 < SK2C_MAX_CL ? sms / 2 : SK2C_MAX_CL; // SkTail boundary table size + v = n < cap ? n : cap; + } + return v; +} +// QUAD mode availability: the 4-CTA-cluster quad kernel (V = 8) must have >= ncl/2 co-resident clusters +int g_quad_clusters = -1; // cached cudaOccupancyMaxActiveClusters of the quad (4-CTA) config +bool sk2c_quad_ok(int ncl) { + int& v = g_quad_clusters; + if (v < 0) { + cudaFuncSetAttribute(fp8_sk2c_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + cudaLaunchAttribute attr[3]; + cudaLaunchConfig_t q = sk2c_cfg(4 * (ncl / 2 > 0 ? ncl / 2 : 1), 0, attr); + attr[0].val.clusterDim.x = 4; + q.numAttrs = 1; + int n = 0; + if (cudaOccupancyMaxActiveClusters(&n, fp8_sk2c_kernel, &q) != cudaSuccess) { + cudaGetLastError(); + n = 0; + } + v = n; + } + return ncl >= 2 && ncl % 2 == 0 && v >= ncl / 2; +} +// pair-tile plan: whole pair tiles for full waves of clusters, the last partial wave's k-blocks stream-K'd +// all_sk = 1: no whole-tile waves, every pair tile goes through the stream-K range (finer tail granularity: +// each cluster gets ~tiles*nkb/ncl contiguous k-blocks; tuning alternative at M=1024). +bool sk2c_plan(int M, int N, int K, int& ncl, int& direct, int& tail, int all_sk = 0) { + const int nmb = (M + BLOCK_M - 1) / BLOCK_M; + if (M < 1 || N % BLOCK_N != 0 || K % BLOCK_K != 0 || K < BLOCK_K) return false; + ncl = sk2c_max_clusters(); + if (ncl < 1) return false; + const int tiles = ((nmb + 1) / 2) * (N / BLOCK_N); + direct = all_sk ? 0 : (tiles / ncl) * ncl; + tail = tiles - direct; + // LAST-WAVE STREAM-K for TINY tails (M=2048: 224 pair tiles = 3 x 74 + 2): a tail of < ncl/4 pair tiles would be + // cut ~ncl/tail ways (M=2048: 37 pieces/tile of ~3.5 kb -> 35 middle contributors red.add'ing the same 128 KB ws + // lines at the very end of the kernel, then the owner waits for all of them). Folding the last full wave into the + // stream-K range (direct -= ncl) makes every range > one tile long (M=2048: 76 x 128 / 74 = 131.5 kb), so each tail + // tile has <= 2 pieces: writer (first unit of its cluster, never waits) + owner (last unit, its writer finished long + // before; ws prefetched into the ring during the drain). No middle contributors -> no contention chain. Same total + // per-cluster work; deadlock-safe (owners wait only on writers, which wait on nothing). Static, host-only. + if (!all_sk && tail > 0 && 4 * tail < ncl && direct >= ncl) { + direct -= ncl; + tail += ncl; + } + // 32-bit walker: cid * tail * num_kb must fit + if ((long long)ncl * tail * (K / BLOCK_K) >= (1LL << 31)) return false; + return true; +} +} // namespace + +void fp8_sk2c_diag(int* pair_clusters, int* quad_clusters) { + const int ncl = sk2c_max_clusters(); + *pair_clusters = ncl; + (void)sk2c_quad_ok(ncl); + *quad_clusters = g_quad_clusters; +} +bool fp8_sk2c_supported(int M, int N, int K) { + int ncl, direct, tail; + if (((M + BLOCK_M - 1) / BLOCK_M) % 2 != 0) return false; // even M-block count (no padded pair) + return sk2c_plan(M, N, K, ncl, direct, tail); +} +// padded variant: any M-block count (odd -> last pair tile half empty); used for small M (M <= 128) +bool fp8_sk2c_pad_supported(int M, int N, int K) { + int ncl, direct, tail; + return sk2c_plan(M, N, K, ncl, direct, tail); +} + +// ROLE-AWARE TAIL RANGE SIZING (host). With uniform stream-K ranges (~nkb/2 per cluster) every tail tile is covered +// by [owner head | MIDDLE | writer]; the middle piece is a cluster's whole range, so it ends together with the owner +// (whose head piece is the END of its range) and its 128 KB red.add + publish sits on the owner's critical path at the +// very end of the kernel. Here ranges that lie strictly inside one tile (0 < kb0, kb1 < nkb: pure middle contributors) +// are made `delta` k-blocks shorter than the others (mean length unchanged), so they finish (and publish) earlier. +// Fixed-point iteration (classification depends on the boundaries); any monotone boundary set is correct for the +// fixup protocol (contributors are first pieces, owners last pieces, middles wait only on higher-k first pieces). +static void sk2c_tail_bounds(int ncl, int tail, int nkb, int delta, SkTail& bt) { + bt.nb = 0; + const int S = tail * nkb; + if (delta <= 0 || tail <= 0 || ncl <= 1 || ncl > SK2C_MAX_CL) return; + const double L = (double)S / ncl; + if (delta >= L / 2) return; + int b[SK2C_MAX_CL + 1]; + bool mid[SK2C_MAX_CL]; + for (int c = 0; c <= ncl; ++c) b[c] = (int)((long long)c * S / ncl); + for (int iter = 0; iter < 8; ++iter) { + int nm = 0; + for (int c = 0; c < ncl; ++c) { + const int p0 = b[c], p1 = b[c + 1]; + mid[c] = p1 > p0 && (p0 % nkb) != 0 && (p1 % nkb) != 0 && p0 / nkb == (p1 - 1) / nkb; + nm += mid[c]; + } + if (nm == 0 || nm == ncl) break; + const double lm = L - (double)delta * (ncl - nm) / ncl, lo = L + (double)delta * nm / ncl; + double acc = 0.0; + int nb[SK2C_MAX_CL + 1]; + nb[0] = 0; + for (int c = 0; c < ncl; ++c) { + acc += mid[c] ? lm : lo; + nb[c + 1] = (int)(acc + 0.5); + } + nb[ncl] = S; + bool same = true; + for (int c = 0; c <= ncl; ++c) { same &= nb[c] == b[c]; b[c] = nb[c]; } + if (same) break; + } + for (int c = 0; c < ncl; ++c) + if (b[c + 1] < b[c]) return; // safety: keep uniform + for (int c = 0; c <= ncl; ++c) bt.b[c] = b[c]; + bt.nb = ncl; +} + +static void sk2c_launch_core(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, + int K, cudaStream_t stream, int ncl, int direct, int tail, const SkTail& BT, int fm, + int var, bool quad = false, int rot_ovr = -1); +void launch_fp8_sk2c(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, int K, + cudaStream_t stream, int all_sk, int fm, int delta, int var) { + int ncl, direct, tail; + if (!sk2c_plan(M, N, K, ncl, direct, tail, all_sk)) return; + // memoised boundary table (pure function of ncl, tail, nkb, delta) + static SkTail& BT = *new SkTail(); + static int bk[4] = {-1, -1, -1, -1}; + if (bk[0] != ncl || bk[1] != tail || bk[2] != K / BLOCK_K || bk[3] != delta) { + sk2c_tail_bounds(ncl, tail, K / BLOCK_K, delta, BT); + bk[0] = ncl; bk[1] = tail; bk[2] = K / BLOCK_K; bk[3] = delta; + } + // SERPENTINE K (single-launch classes): M=2048 (WSUB, var 32) krev 1 = odd-wave whole tiles walk k reversed; + // M=1024 (WSKEEP, var 16) krev 2 = stream-K tail pieces walk k reversed (start on just-streamed high-k slabs). + // Bijective k-order permutations only; fixup roles depend on kb0/kb1, not on traversal order. + BT.krev = (var & 32) ? 1 : ((var & 16) ? 2 : 0); + sk2c_launch_core(a, w, sx, sw, out, M, N, K, stream, ncl, direct, tail, BT, fm, var); +} + +// CHAINED LAUNCH over row chunks starting at rows starts[0]=0 < starts[1] < ... (each a multiple of 256 rows, chunk +// sizes even M-block counts except possibly the last). MAKESPAN MODEL (74 clusters, 256x256 pair tiles, N=7168: +// 28 N-blocks): per 2048-row chunk 224 tiles = 3 x 74 + 2. Old: every chunk 148 whole + 76-tile folded stream-K tail +// (~3.03 tile-times + one writer/owner fixup per chunk). New: inner chunks 222 whole tiles = exactly 3 waves (no +// tail, no fixup, no ws traffic), their 2 leftover tiles each are forwarded as whole tiles to the LAST chunk +// (M=4096: 226 = 148 + 78-tile tail; M=8192: 230 = 148 + 82): same total tile-time, one fixup instead of P. +// Inner grids write only their own tiles; the final grid's writes are ordered after all earlier grids by PDL +// (griddepcontrol.wait in every global-writing role), so the shared ws / counters stay safe. +void launch_fp8_sk2c_chain(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, + int K, const int* starts, int nch, cudaStream_t stream, int mir) { + int ncl, d0, t0; + if (!sk2c_plan(M, N, K, ncl, d0, t0, 0)) return; + const int nnb = N / BLOCK_N; +#ifndef SK2C_ENABLE_QUAD +#define SK2C_ENABLE_QUAD 0 +#endif + const bool quad = SK2C_ENABLE_QUAD && nnb % 2 == 0 && sk2c_quad_ok(ncl); + int xpr[SK2C_MAX_X], xnb[SK2C_MAX_X]; // forwarded leftover tiles + int nx = 0; + // CROSS-LAUNCH SERPENTINE PARITY (M>=12288 mir-3 chains, nch > 2): wave parity of serpentine K continues across + // PDL-chained launches (kpar = whole waves already run mod 2), so a launch following an odd-wave-count launch that + // ended forward (kb nkb-1) starts reversed on the just-streamed high-k slabs instead of restarting at kb 0. + int wsum = 0; + for (int c = 0; c < nch; ++c) { + const int r0 = starts[c], r1 = c + 1 < nch ? starts[c + 1] : M; + const int pr0 = r0 / 256; + const int nmt = (((r1 - r0 + BLOCK_M - 1) / BLOCK_M) + 1) / 2; + const int T = nmt * nnb; + SkTail bt = SkTail(); + bt.pr0 = pr0; + bt.nmt = nmt; + // ALTERNATING MIRRORED N RASTER (mir, M>=12288 chains): odd chunks walk N-blocks in reverse, so each chunk starts + // on the W N-blocks the previous chunk just streamed (still L2-resident) -> fewer W DRAM re-reads at chunk seams. + bt.mir = ((mir == 1 || mir == 3) && (c & 1)) ? 1 : 0; + bt.krev = mir == 2 ? 2 : (mir == 3 ? 1 : 0); // krev 2 (M=8192 chain): stream-K tail pieces (wsi >= 0) also walk their k-blocks REVERSED (the preceding even whole wave ended at kb nkb-1, so the writer piece starts on just-streamed A k-slabs); roles (owner kb0==0 last, writer kb1==nkb) unchanged, only the in-piece accumulation order // mir 3 (M>=12288): mirror + cascade + serpentine K // M=8192 chain: serpentine K order over whole-tile waves + if (c + 1 < nch && (mir == 1 || mir == 3) && !quad) { + // CASCADED FORWARDING (M>=12288 mirrored chains only): this inner chunk runs the PREVIOUS chunk's leftover pair + // tiles FIRST (their A rows / W N-blocks were just streamed by the previous chunk -> L2-resident; with the + // alternating mirrored raster they sit on the N-blocks this chunk starts on), then its native tiles, as whole + // waves only; its own (native) leftovers are carried to the NEXT chunk. The last chunk's folded stream-K tail + // gets only the final carry. Same total whole-tile waves / tail size; bijective tile cover. + const int tiles = nx + T; + int direct = (tiles / ncl) * ncl; + if (direct < nx || tiles - direct > SK2C_MAX_X) direct = tiles; // cannot carry: run all here + bt.nx = nx; + for (int i = 0; i < nx; ++i) { bt.xpr[i] = xpr[i]; bt.xnb[i] = xnb[i]; } + int nnx = 0; + for (int t = direct - nx; t < T; ++t) { // native leftovers (column-major: M fastest), chunk's own mirror + xpr[nnx] = pr0 + t % nmt; + xnb[nnx] = (c & 1) ? nnb - 1 - t / nmt : t / nmt; + ++nnx; + } + nx = nnx; + bt.kpar = (mir == 3 && nch > 2) ? (wsum & 1) : 0; + wsum += direct / ncl; + sk2c_launch_core(a, w, sx, sw, out, M, N, K, stream, ncl, direct, 0, bt, 1, (mir == 3) ? (128 | 256) : SK2C_VAR_DEFAULT /* TSPIN: all mir-3 chains; var bit 256 (host-only): A map L2 promotion NONE for all mir-3 chains (M=4096 2-chunk + M>=12288) */, false); + } else if (c + 1 < nch) { + int direct = (T / ncl) * ncl; + if (T - direct + nx > SK2C_MAX_X || direct == 0) direct = T; // cannot forward: run all whole tiles here + for (int t = direct; t < T; ++t) { // forwarded leftover tiles (column-major: M fastest) + if (quad) { + int mb, nb; + quad_coords(t, nmt, mb, nb); // direct even -> forwarded in (n, n+1) same-row pairs + xpr[nx] = pr0 + mb; + xnb[nx] = nb; + } else { + xpr[nx] = pr0 + t % nmt; + xnb[nx] = ((mir == 1 || mir == 3) && (c & 1)) ? nnb - 1 - t / nmt : t / nmt; // same mirror as the chunk's native raster + } + ++nx; + } + sk2c_launch_core(a, w, sx, sw, out, M, N, K, stream, ncl, direct, 0, bt, 1, SK2C_VAR_DEFAULT, quad); + } else { + const int tiles = nx + T; + int direct = (tiles / ncl) * ncl, tail = tiles - direct; + if (tail > 0 && 4 * tail < ncl && direct >= ncl) { direct -= ncl; tail += ncl; } // same fold rule as sk2c_plan + const bool q = quad && (tail % 2) == 0 && (direct % 2) == 0; + static SkTail& BT = *new SkTail(); + static int bk[4] = {-1, -1, -1, -1}; + if (bk[0] != ncl || bk[1] != tail || bk[2] != K / BLOCK_K || bk[3] != (int)q) { + // quad: ranges per QUAD over the tail super-tile space (tail/2 super tiles) + if (q) sk2c_tail_bounds(ncl / 2, tail / 2, K / BLOCK_K, SK2C_DELTA_DEFAULT, BT); + else sk2c_tail_bounds(ncl, tail, K / BLOCK_K, SK2C_DELTA_DEFAULT, BT); + bk[0] = ncl; bk[1] = tail; bk[2] = K / BLOCK_K; bk[3] = (int)q; + } + bt.nb = BT.nb; + for (int i = 0; i <= SK2C_MAX_CL; ++i) bt.b[i] = BT.b[i]; + bt.nx = nx; + for (int i = 0; i < nx; ++i) { bt.xpr[i] = xpr[i]; bt.xnb[i] = xnb[i]; } + // M=4096 (mir 3, 2-chunk chain): wave parity also carried into the last chunk (nch >= 2), and its stream-K + // tail pieces walk k reversed (krev 2) when its last whole wave ran forward (ended at kb nkb-1), so the tail + // starts on the just-streamed high-k slabs. Bijective k-order permutations only (fixup roles by kb0/kb1). + bt.kpar = (mir == 3 && nch >= 2) ? (wsum & 1) : 0; + if (mir == 3 && nch >= 2 && tail > 0 && (((direct / ncl) + bt.kpar) & 1)) bt.krev = 2; // M>=12288 chains too + if (mir == 2 && tail > 0 && !(((direct / ncl) + bt.kpar) & 1)) bt.krev = 1; + // PER-CHUNK CLUSTER ROTATION (M=4096 2-chunk mir-3 chain only): last chunk uses logical rot 18 (bijection). + const int rov = (mir == 3 && nch == 2 && ncl == 74) ? 18 : -1; + sk2c_launch_core(a, w, sx, sw, out, M, N, K, stream, ncl, direct, tail, bt, 1, (mir == 3) ? (128 | 256) : SK2C_VAR_DEFAULT /* TSPIN: all mir-3 chains; var bit 256 (host-only): A map L2 promotion NONE for all mir-3 chains (M=4096 2-chunk + M>=12288) */, q, rov); + } + } +} + +static void sk2c_launch_core(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, + int K, cudaStream_t stream, int ncl, int direct, int tail, const SkTail& BT, int fm, + int var, bool quad, int rot_ovr) { + CUtensorMap ta, tb, to; + // QUAD: 64-row A half boxes (each CTA multicasts one half of its pair-row A tile to both pairs) + // var bit 256 (host-only hint, M>=12288 cascaded chain): A map L2 sector promotion NONE (A k-slabs are re-read by + // all N pair tiles of a row; 256B promotion fetches the neighbouring 128B half-row of the NEXT k-block early, + // which in the 26 MB/chunk A working set competes with W lines). Bit-identical. + const bool apromo_none = (var & 256) != 0; + // var bit 1024 (host-only hint, M=1024 class): own-W-half tensor map L2 sector promotion 128B (else NONE / 256B by bit 2) + const bool wpromo128 = (var & 1024) != 0; + // var bit 2048 (host-only hint, M=2048 WSUB class): A tensor map L2 sector promotion 128B (else 256B / NONE by bit 256) + const bool apromo128 = (var & 2048) != 0; + var &= ~(256 | 1024 | 2048); + make_tmap(&ta, a, (uint64_t)M, (uint64_t)K, quad ? BLOCK_M / 2 : BLOCK_M, + apromo_none ? CU_TENSOR_MAP_L2_PROMOTION_NONE + : (apromo128 ? CU_TENSOR_MAP_L2_PROMOTION_L2_128B : CU_TENSOR_MAP_L2_PROMOTION_L2_256B)); + make_tmap(&tb, w, (uint64_t)N, (uint64_t)K, (var & 32) ? 64 : BLOCK_N / 2, // var bit 5: two 64-row W sub-boxes + (var & 4) ? CU_TENSOR_MAP_L2_PROMOTION_L2_256B : (wpromo128 ? CU_TENSOR_MAP_L2_PROMOTION_L2_128B : CU_TENSOR_MAP_L2_PROMOTION_NONE)); // own W half (var bit 2: 256B promo) + make_tmap_out(&to, out, (uint64_t)M, (uint64_t)N); + // Persistent fp32 workspace (2 CTA tiles per tail pair tile) + counters (heap-held, never freed). The writer + // piece overwrites, so ws needs no zeroing; counters zeroed once on allocation and reset by their owner. + static SkWs& S = *new SkWs(); + if (tail > 0) { + const size_t need = (size_t)tail * 2 * WS_TILE_FLOATS; + if (need > S.floats || (size_t)tail * 2 > S.cnts) { + if (S.ws) { + cudaStreamSynchronize(stream); + cudaFree(S.ws); + cudaFree(S.cnt); + } + S.floats = need > S.floats ? need : S.floats; + S.cnts = (size_t)tail * 2 > S.cnts ? (size_t)tail * 2 : S.cnts; + cudaMalloc(&S.ws, S.floats * sizeof(float)); + cudaMalloc(&S.cnt, S.cnts * sizeof(int)); + cudaMemsetAsync(S.ws, 0, S.floats * sizeof(float), stream); + cudaMemsetAsync(S.cnt, 0, S.cnts * sizeof(int), stream); + } + } + const int rot = rot_ovr >= 0 ? rot_ovr % ncl : ((ncl == 74) ? 55 : 0); + cudaLaunchAttribute attr[3]; + cudaLaunchConfig_t cfg = sk2c_cfg(2 * ncl, stream, attr); + if (quad) { + attr[0].val.clusterDim.x = 4; + const int qrot = (ncl == 74) ? 27 : 0; // logical quad rotation (bijection; ~ the pair rot 55 / 2) + cudaLaunchKernelEx(&cfg, fp8_sk2c_kernel, ta, tb, to, sx, sw, S.ws, S.cnt, M, N, K, direct, tail, qrot, BT); + return; + } + if (fm && var == 128) { + // TSPIN-only variant (pure-spin promotion tfull wait), M>=12288 cascaded mir-3 chain only + static bool attr128 = false; + if (!attr128) { + cudaFuncSetAttribute(fp8_sk2c_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + attr128 = true; + } + cudaLaunchKernelEx(&cfg, fp8_sk2c_kernel, ta, tb, to, sx, sw, S.ws, S.cnt, M, N, K, direct, tail, rot, BT); + } else if (fm && (var & 32)) { + // WSUB variant (two 64-row W sub-boxes per k-block), used only by the M=2048 class + static bool attr32 = false; + if (!attr32) { + cudaFuncSetAttribute(fp8_sk2c_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + attr32 = true; + } + cudaLaunchKernelEx(&cfg, fp8_sk2c_kernel, ta, tb, to, sx, sw, S.ws, S.cnt, M, N, K, direct, tail, rot, BT); + } else if (fm && (var & 3)) { + auto kf = (var & 3) == 1 ? fp8_sk2c_kernel : (var & 3) == 2 ? fp8_sk2c_kernel : fp8_sk2c_kernel; + static const void* done[4] = {}; + if (done[var & 3] != (const void*)kf) { + cudaFuncSetAttribute(kf, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + done[var & 3] = (const void*)kf; + } + cudaLaunchKernelEx(&cfg, kf, ta, tb, to, sx, sw, S.ws, S.cnt, M, N, K, direct, tail, rot, BT); + } else if (fm && var == 16) { + // WSKEEP (M=1024 class only): ws writer / middle stores with L2 evict_last + static bool attr16 = false; + if (!attr16) { + cudaFuncSetAttribute(fp8_sk2c_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); + attr16 = true; + } + cudaLaunchKernelEx(&cfg, fp8_sk2c_kernel, ta, tb, to, sx, sw, S.ws, S.cnt, M, N, K, direct, tail, rot, BT); + } else if (fm) + cudaLaunchKernelEx(&cfg, fp8_sk2c_kernel, ta, tb, to, sx, sw, S.ws, S.cnt, M, N, K, direct, tail, rot, BT); + else + cudaLaunchKernelEx(&cfg, fp8_sk2c_kernel, ta, tb, to, sx, sw, S.ws, S.cnt, M, N, K, direct, tail, rot, BT); +} diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk2c.h b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk2c.h new file mode 100644 index 0000000000000000000000000000000000000000..6610020a4c54647a2c87f2a6b8102afe4e7f4751 --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk2c.h @@ -0,0 +1,20 @@ +#pragma once +#include +#ifndef SK2C_DELTA_DEFAULT +#define SK2C_DELTA_DEFAULT 7 // role-aware tail sizing: pure-middle stream-K ranges 7 k-blocks shorter (0 = uniform) +#endif +#ifndef SK2C_VAR_DEFAULT +#define SK2C_VAR_DEFAULT 0 // VALIDITY: early operand prologue (W TMA before griddepcontrol.wait) deadlocked back-to-back PDL launches +#endif +// 2-SM UMMA (cta_group::2, 256x256 pair tiles on 2-CTA clusters) variant of the stream-K-tail kernel (kernel_sk2c.cu). +// Supported iff the M-block count is even and at least one 2-CTA cluster can be resident. +bool fp8_sk2c_supported(int M, int N, int K); +void launch_fp8_sk2c(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, int K, + cudaStream_t stream, int all_sk = 0, int fm = 1, + int delta = SK2C_DELTA_DEFAULT, int var = SK2C_VAR_DEFAULT); +bool fp8_sk2c_pad_supported(int M, int N, int K); +// Chained row-chunk launches (starts[0] = 0, nch chunks): inner chunks run whole-tile waves only and forward their +// leftover pair tiles to the last chunk, whose single stream-K tail covers the combined remainder. +void launch_fp8_sk2c_chain(const void* a, const void* w, const float* sx, const float* sw, void* out, int M, int N, + int K, const int* starts, int nch, cudaStream_t stream, int mir = 0); +void fp8_sk2c_diag(int* pair_clusters, int* quad_clusters); diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/main.cpp b/kernels/Quant/015_fp8_mla_attention_output_projection/src/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..53acf05f1c2fd7d529c3c1823372ef0117d69469 --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/main.cpp @@ -0,0 +1,694 @@ +#include +#include +#include +#include +#include "kernel.h" +#include "kernel_large.h" +#include "kernel_large2.h" +#include "kernel_m256.h" +#include "kernel_sk.h" +#include "kernel_m128c.h" +#include "kernel_m256c.h" +#include "kernel_m128x2.h" +#include "kernel_l2x.h" +#include "kernel_m256x2.h" +#include "kernel_m256v.h" +#include "kernel_m256p.h" +#include "kernel_l2sk.h" +#include "kernel_sk2c.h" +#include "kernel_largev.h" +#include +#include +#include +#include + +struct TuneCache { int64_t M = -1, N = -1, K = -1; int choice = 0; }; +// LEAN HOST DISPATCH (M <= 256 / M = 1024-class / M = 2048-4096 l2x paths): once a path's choice is known (autotuned +// and cached, or the only supported candidate), it is recorded as a POD descriptor {kind, a0, a1} keyed by (M,N,K). +// A steady-state call then does one key compare + one launch right after the output allocation: no support queries, +// std::function vectors, plan lookups or device-attribute calls. Kernels / candidate sets / autotune unchanged. +enum FastKind { FK_NONE = 0, FK_M128X2, FK_M128C, FK_M256C1, FK_M256C2, FK_M256X2, FK_M256V, FK_L2X, FK_SK2C, + FK_SK2C_ALL, FK_SK, FK_L2SK, FK_LARGE2, FK_M128V, FK_LARGE2_SPLIT, FK_M256P, FK_LARGE2_SPLIT3, FK_SK2C_SPLIT, + FK_SK2C_SPLITP, FK_SK2C_WSUB }; +// FK_LARGE2 (M >= 2048 kernel_large2 / l2x / sk2c path): a0 = launcher kind (0 large2 plan, 1 l2x, 2 sk2c, +// 3 large2_ex), a1 = dyn, a2 = split override, p2 = memoised plan. Host audit: this path previously skipped the slim +// dispatch (4 .contiguous() handle copies + support queries + plan cache + tune cache per call); no per-call +// cudaMemset / workspace zeroing / stream sync exists on any steady-state path (ws/counters are zeroed only on +// (re)allocation; self-cleaning kernels keep them zero). +struct FastDesc { int64_t M = -1, N = -1, K = -1; int kind = FK_NONE, a0 = 0, a1 = 0, a2 = 0; Fp8PlanL2 p2{0, 0, 1, 0}; Fp8PlanL2 p2b{0, 0, 1, 0}; Fp8PlanL2 p2c{0, 0, 1, 0}; }; +static FastDesc& fast_desc() { static FastDesc& F = *new FastDesc(); return F; } +static void fast_set(int64_t M, int64_t N, int64_t K, int kind, int a0 = 0, int a1 = 0) { + FastDesc& F = fast_desc(); + F.M = M; F.N = N; F.K = K; F.kind = kind; F.a0 = a0; F.a1 = a1; +} +// SPLIT LARGE-M PATH (M >= 12288, e.g. M=16384): two PDL-chained kernel_large2 launches over row halves +// [0, M1) and [M1, M), each with its own (M=8192-class) plan: SPF8 (tail pieces first, split 8) + spf_rot from the +// plan (40 at 64 M-blocks on 148 SMs), band 8. The 2nd launch's N raster is MIRRORED (group_n bit 17) so it starts on +// the N band the 1st launch ended on (that W band is still L2-resident at the seam). The 2nd grid griddepcontrol.wait's +// for the 1st grid's completion before touching global memory, so the shared tail workspace / counters are safe. +static void launch_large2_half(const void* x, const void* w, const float* sx, const float* sw, void* o, + const Fp8PlanL2& p, int M, int N, int K, cudaStream_t st, bool mirror, + bool pieces_last = false) { + Fp8PlanL2 pp = p; + if (mirror) pp.group_n = (pp.group_n > 0 ? pp.group_n : 8) | (1 << 17); + if (p.tail > 0 && (K / 128) >= 32 && p.tail * 2 <= 148) { + // SPF split: largest split with tail*split <= #SMs (1 piece per CTA); split 10 would need 160 pieces > 148 CTAs + // for the 16-tile tail of an M=8192 half, so 9 (144 pieces). Piece holder rotation rot = 52 - (ts - 144) places + // the grid - ts piece-less CTAs at blockIdx 96..99, inside the consistently-slow window 88..107. + { + const int sms = 148; + // largest split <= 10 with tail*split <= #SMs (1 piece per CTA). FIX: the old floor of 8 (sp > 8) gave + // 32 x 8 = 256 pieces > 148 CTAs for the 54-M-block exact-wave 1st half (M=16384), which made + // launch_fp8_large2_ex silently drop the K-split tail (whole tiles only: 32-tile last wave, 116 SMs idle). + int sp = 10; + while (sp > 2 && p.tail * sp > sms) --sp; + pp.split = sp; + const int ts = p.tail * sp; + // piece-less CTAs b = ts-rot.. sms-1-rot -> 88.. + if (ts < sms) pp.spf_rot = (ts - 88 + sms) % sms; + } + // PIECES-LAST (1st half of the M>=12288 split): static walk, K-split tail pieces run AFTER the whole tiles + // (owner kb0==0 pieces on CTAs 0..tail-1 wait for contributors), so the tail/fixup overlaps the 2nd launch's + // prologue via PDL instead of running first. dyn 0 -> elected whole-warp issuer (EISS) static order. + launch_fp8_large2_ex(x, w, sx, sw, o, nullptr, pp, M, N, K, st, pieces_last ? 0 : 64, nullptr); + } else { + launch_fp8_large2(x, w, sx, sw, o, nullptr, pp, M, N, K, st); + } +} +static void launch_large2_split(const void* x, const void* w, const float* sx, const float* sw, void* o, int M, + int N, int K, int M1, const Fp8PlanL2& pa, const Fp8PlanL2& pb, cudaStream_t st) { + // 1st half: SPF (K-split tail pieces run FIRST, concurrently) instead of pieces-last + launch_large2_half(x, w, sx, sw, o, pa, M1, N, K, st, false, /*pieces_last=*/false); + const uint8_t* x2 = static_cast(x) + (size_t)M1 * K; + const float* sx2 = sx + (size_t)M1 * (K / 128); + uint16_t* o2 = static_cast(o) + (size_t)M1 * N; + launch_large2_half(x2, w, sx2, sw, o2, pb, M - M1, N, K, st, true); +} +// 3-WAY SPLIT (M=16384: 74 | 37 | 17 M-blocks): launches 1 and 2 have exact-wave whole-tile counts (74x28 = 14 x 148, +// 37x28 = 7 x 148 tiles: no K-split tail), the K-split SPF tail lives only in the small last launch. PDL-chained; +// N raster alternates normal / mirrored / normal so each launch starts on the W band the previous one ended on. +static void launch_large2_split3(const void* x, const void* w, const float* sx, const float* sw, void* o, int M, + int N, int K, int M1, int M2, const Fp8PlanL2& pa, const Fp8PlanL2& pb, + const Fp8PlanL2& pc, cudaStream_t st) { + launch_large2_half(x, w, sx, sw, o, pa, M1, N, K, st, false); + const uint8_t* x2 = static_cast(x) + (size_t)M1 * K; + const float* sx2 = sx + (size_t)M1 * (K / 128); + uint16_t* o2 = static_cast(o) + (size_t)M1 * N; + launch_large2_half(x2, w, sx2, sw, o2, pb, M2 - M1, N, K, st, true); + const uint8_t* x3 = static_cast(x) + (size_t)M2 * K; + const float* sx3 = sx + (size_t)M2 * (K / 128); + uint16_t* o3 = static_cast(o) + (size_t)M2 * N; + launch_large2_half(x3, w, sx3, sw, o3, pc, M - M2, N, K, st, false); +} +// M=4096-CLASS 2-WAY SPLIT (sk2c): two PDL-chained kernel_sk2c launches over row halves [0, M1) and [M1, M), each an +// M=2048-class sk2c plan (2 x 74 whole pair tiles + 76-tile folded stream-K tail). The 2nd grid's ws / counter / +// output roles griddepcontrol.wait for the 1st grid's completion, so the shared persistent ws / counters are safe. +static void launch_sk2c_split(const void* x, const void* w, const float* sx, const float* sw, void* o, int M, int N, + int K, int M1, cudaStream_t st) { + const int starts[2] = {0, M1}; + // mir 3 (M=4096 class): mirrored N raster on chunk 2 + serpentine K order on odd-wave whole tiles + launch_fp8_sk2c_chain(x, w, sx, sw, o, M, N, K, starts, 2, st, 3); +} +// M=8192-CLASS P-WAY SPLIT (sk2c): P PDL-chained kernel_sk2c launches over consecutive row chunks of MP rows +// (last chunk = remainder), each an M=2048-class sk2c plan. Every grid's ws / counter / output roles +// griddepcontrol.wait for the previous grid's completion (transitively all earlier ones), so the shared persistent +// ws / counters are safe. MP is a multiple of 256 (even M-block count per chunk). +static void launch_sk2c_splitp(const void* x, const void* w, const float* sx, const float* sw, void* o, int M, int N, + int K, int MP, cudaStream_t st, int mir = 0) { + int starts[64]; + int n = 0; + for (int m0 = 0; m0 < M && n < 64; m0 += MP) starts[n++] = m0; + launch_fp8_sk2c_chain(x, w, sx, sw, o, M, N, K, starts, n, st, mir); +} +static bool fast_launch(const FastDesc& d, const void* x, const void* w, const float* sx, const float* sw, void* o, + int M, int N, int K, cudaStream_t st) { + switch (d.kind) { + case FK_M128X2: launch_fp8_m128x2(x, w, sx, sw, o, M, N, K, st); return true; + case FK_M128C: launch_fp8_m128c(x, w, sx, sw, o, M, N, K, st); return true; + case FK_M128V: launch_fp8_m128v(x, w, sx, sw, o, M, N, K, st); return true; + case FK_M256C1: launch_fp8_m256c_np(x, w, sx, sw, o, M, N, K, st, 1); return true; + case FK_M256C2: launch_fp8_m256c_np(x, w, sx, sw, o, M, N, K, st, 2); return true; + case FK_M256X2: launch_fp8_m256x2(x, w, sx, sw, o, M, N, K, st); return true; + case FK_M256V: launch_fp8_m256v(x, w, sx, sw, o, M, N, K, st, 1); return true; // raw fp32 K-pair push + case FK_L2X: launch_fp8_l2x(x, w, sx, sw, o, M, N, K, st); return true; + case FK_M256P: launch_fp8_m256p(x, w, sx, sw, o, M, N, K, st); return true; + case FK_LARGE2_SPLIT3: launch_large2_split3(x, w, sx, sw, o, M, N, K, d.a1, d.a2, d.p2, d.p2b, d.p2c, st); return true; + case FK_LARGE2_SPLIT: launch_large2_split(x, w, sx, sw, o, M, N, K, d.a1, d.p2, d.p2b, st); return true; + case FK_SK2C: launch_fp8_sk2c(x, w, sx, sw, o, M, N, K, st, 0, 1, SK2C_DELTA_DEFAULT, (M > 512 && M <= 1536) ? (16 | 1024) : SK2C_VAR_DEFAULT); return true; // M=1024 class: WSKEEP + case FK_SK2C_WSUB: launch_fp8_sk2c(x, w, sx, sw, o, M, N, K, st, 0, 1, SK2C_DELTA_DEFAULT, 32 | 2048); return true; // M=2048: WSUB + A promo 128B + case FK_SK2C_SPLIT: launch_sk2c_split(x, w, sx, sw, o, M, N, K, d.a1, st); return true; + case FK_SK2C_SPLITP: launch_sk2c_splitp(x, w, sx, sw, o, M, N, K, d.a1, st, d.a0); return true; + case FK_SK2C_ALL: launch_fp8_sk2c(x, w, sx, sw, o, M, N, K, st, 1); return true; + case FK_SK: launch_fp8_sk(x, w, sx, sw, o, nullptr, d.a0, d.a1, M, N, K, st); return true; + case FK_L2SK: launch_fp8_l2sk(x, w, sx, sw, o, M, N, K, st); return true; + case FK_LARGE2: + if (d.a0 == 1) launch_fp8_l2x(x, w, sx, sw, o, M, N, K, st); + else if (d.a0 == 2) launch_fp8_sk2c(x, w, sx, sw, o, M, N, K, st); + else if (d.a0 == 3) { + Fp8PlanL2 pp = d.p2; + pp.split = d.a2 & 255; + if (d.a2 >> 8) pp.group_n = d.a2 >> 8; // band-width override (M-major full-N raster candidate) + launch_fp8_large2_ex(x, w, sx, sw, o, nullptr, pp, M, N, K, st, d.a1, nullptr); + } else launch_fp8_large2(x, w, sx, sw, o, nullptr, d.p2, M, N, K, st); + return true; + default: return false; + } +} + + + +torch::Tensor run(torch::Tensor hidden_states, torch::Tensor weight, torch::Tensor scale_x, torch::Tensor scale_w) { + const int64_t B = hidden_states.size(0), L = hidden_states.size(1), K = hidden_states.size(2); + const int64_t N = weight.size(0); + const int64_t M = B * L; + // SLIM HOST PATH: steady-state calls with contiguous inputs (always the case for this op) skip the four + // .contiguous() Tensor handle copies and launch directly on raw pointers right after the output allocation + // (bf16 options cached once; allocation goes through the caching allocator, no device sync). + + static const at::TensorOptions& bf16_opts = *new at::TensorOptions(at::TensorOptions().dtype(torch::kBFloat16)); + if (M > 0 && hidden_states.is_contiguous() && weight.is_contiguous() && scale_x.is_contiguous() && + scale_w.is_contiguous()) { + const FastDesc& F = fast_desc(); + if (F.M == M && F.N == N && F.K == K && F.kind != FK_NONE) { + // HOST FAST PATH: allocate the fresh output via at::detail::empty_cuda directly (caching allocator, no + // dispatcher round-trip / TensorOptions merge); device taken once from the input's storage. + const int64_t osz[3] = {B, L, N}; + auto out = at::detail::empty_cuda(c10::IntArrayRef(osz, 3), at::kBFloat16, hidden_states.device(), c10::nullopt); + fast_launch(F, hidden_states.data_ptr(), weight.data_ptr(), scale_x.data_ptr(), + scale_w.data_ptr(), out.data_ptr(), (int)M, (int)N, (int)K, + at::cuda::getCurrentCUDAStream()); + return out; + } + } + auto x = hidden_states.contiguous(); + auto w = weight.contiguous(); + auto sx = scale_x.contiguous(); + auto sw = scale_w.contiguous(); + auto out = torch::empty({B, L, N}, hidden_states.options().dtype(torch::kBFloat16)); + if (M == 0) return out; + { + const FastDesc& F = fast_desc(); + if (F.M == M && F.N == N && F.K == K && + fast_launch(F, x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), (int)M, + (int)N, (int)K, at::cuda::getCurrentCUDAStream())) + return out; + } + + + + if (M <= 64) { + // tiny-M: swap-AB stream-K kernel (W streamed once per token tile, fused reduction) + launch_fp8_swapab(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, at::cuda::getCurrentCUDAStream()); + return out; + } + { + // + kernel_m128v (m256v K-QUARTER mode: 37 variable-width 192/208-col N-tiles x 4 K-quarter CTAs = all 148 SMs, + // W bytes per SM 208x4096 max vs m128c's 160x5461; exact fp32 4-way DSMEM reduction). All supported candidates go + // now chosen by a STATIC pick (m128c) -- no runtime timing. + const bool x2_ok = M > 64 && fp8_m128x2_supported((int)M, (int)N, (int)K); + const bool c_ok = M > 64 && fp8_m128c_supported((int)M, (int)N, (int)K); + const bool v_ok = M > 64 && fp8_m128v_supported((int)M, (int)N, (int)K); + if (x2_ok || c_ok || v_ok) { + cudaStream_t st = at::cuda::getCurrentCUDAStream(); + std::vector> fns; + std::vector kinds; + if (x2_ok) { + kinds.push_back(FK_M128X2); + fns.push_back([&]() { + launch_fp8_m128x2(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st); + }); + } + if (c_ok) { + kinds.push_back(FK_M128C); + fns.push_back([&]() { + launch_fp8_m128c(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st); + }); + } + if (v_ok) { + kinds.push_back(FK_M128V); + fns.push_back([&]() { + launch_fp8_m128v(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st); + }); + } + static TuneCache& T = *new TuneCache(); + int choice = 0; + bool known = false; + if (T.M == M && T.N == N && T.K == K) { + choice = T.choice; + known = true; + } else { + // STATIC PICK + int c = 0; + for (int i = 0; i < (int)kinds.size(); ++i) if (kinds[i] == FK_M128C) c = i; + T.choice = c; T.M = M; T.N = N; T.K = K; choice = c; known = true; + } + if (choice >= (int)fns.size()) choice = 0; + if (known) fast_set(M, N, K, kinds[choice]); + fns[choice](); + return out; + } + } + if (fp8_m256c_supported((int)M, (int)N, (int)K)) { + // 128 < M <= 256 candidates (first-use autotune, cached per (M,N,K)): + // 0: kernel_m256c 4-CTA cluster (2 M-tiles x 2 K-halves), 128x224 tiles, W multicast, DSMEM split-K reduce + // 1: kernel_m256c 8-CTA cluster variant with A multicast across N-tile pairs (if all clusters co-reside) + // 2: kernel_m256x2 128x128 tiles, 2 CTAs/SM, 4-CTA clusters (if all clusters co-reside) + cudaStream_t st = at::cuda::getCurrentCUDAStream(); + std::vector> fns; + std::vector kinds{FK_M256C1}; + const int plan_direct_ = 0, plan_tail_ = 0; + fns.push_back([&]() { + launch_fp8_m256c_np(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st, 1); + }); + if (fp8_m256c_amc_supported((int)M, (int)N, (int)K) && (kinds.push_back(FK_M256C2), true)) + fns.push_back([&]() { + launch_fp8_m256c_np(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st, 2); + }); + if (fp8_m256x2_supported((int)M, (int)N, (int)K) && (kinds.push_back(FK_M256X2), true)) + fns.push_back([&]() { + launch_fp8_m256x2(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st); + }); + // 3: kernel_m256v variable-width (192/208-col) tiles, one 4-CTA cluster per 4 SMs (all 148 SMs busy) + if (fp8_m256v_supported((int)M, (int)N, (int)K) && (kinds.push_back(FK_M256V), true)) + fns.push_back([&]() { + launch_fp8_m256v(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st, 1); // raw fp32 K-pair push + }); + // 4: kernel_m256p = m256v tiles on 2-SM UMMA pairs (cta_group::2 M=256, own A + W half per CTA) + if (fp8_m256p_supported((int)M, (int)N, (int)K) && (kinds.push_back(FK_M256P), true)) + fns.push_back([&]() { + launch_fp8_m256p(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st); + }); + static TuneCache& T = *new TuneCache(); + int choice = 0; + bool known = false; + if (T.M == M && T.N == N && T.K == K) { + choice = T.choice; + known = true; + } else { + // STATIC PICK: m256p (2-SM UMMA pairs) if supported, else m256v + int c = 0; + for (int i = 0; i < (int)kinds.size(); ++i) if (kinds[i] == FK_M256V) c = i; + for (int i = 0; i < (int)kinds.size(); ++i) if (kinds[i] == FK_M256P) c = i; + T.choice = c; T.M = M; T.N = N; T.K = K; choice = c; known = true; + } + if (choice >= (int)fns.size()) choice = 0; + if (known) fast_set(M, N, K, kinds[choice], plan_direct_, plan_tail_); + fns[choice](); + return out; + } + if ((M + 127) / 128 == 2) { + // 128 < M <= 256 (2 M-blocks): 2-CTA cluster along M (W TMA-multicast, W read once) + stream-K over + // the N/256 pair tiles x K/128 k-blocks split evenly over #SMs/2 clusters (kernel_m256.cu); fp32 + // partials red.add'ed into a zeroed workspace, then converted to bf16. + // ws = nullptr -> persistent self-cleaning workspace owned by kernel_m256.cu (no zero-fill launch) + launch_fp8_m256(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + nullptr, (int)M, (int)N, (int)K, at::cuda::getCurrentCUDAStream()); + return out; + } + // 3072 <= M < 6144 goes to the static kernel_large2 SPF pick below (not the l2x / sk2c autotune) + // 1536 < M < 3072 now uses the static kernel_large2 SPF pick below + if (false && M > 1536 && M < 3072 && fp8_l2x_supported((int)M, (int)N, (int)K)) { + // 1536 < M <= 4096 (M=2048 / 4096): 2 CTAs/SM persistent 128x112 tiles (kernel_l2x.cu). Wave quantization: + // M=2048 -> 1024 tiles / 296 CTA slots = 3.46 waves (vs 448 128x256 tiles / 148 = 3.03 for kernel_large2). + // First-use in-process autotune (L2-flushed) vs kernel_sk2c (2-SM UMMA 256x256 pair tiles + stream-K tail). + cudaStream_t st = at::cuda::getCurrentCUDAStream(); + std::vector> fns; + std::vector kinds{FK_L2X}; + const int plan_direct_ = 0, plan_tail_ = 0; + fns.push_back([&]() { + launch_fp8_l2x(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), (int)M, + (int)N, (int)K, st); + }); + if (fp8_sk2c_supported((int)M, (int)N, (int)K) && (kinds.push_back(FK_SK2C), true)) + fns.push_back([&]() { + launch_fp8_sk2c(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st); + }); + static TuneCache& T = *new TuneCache(); + int choice = 0; + bool known = false; + if (T.M == M && T.N == N && T.K == K) { + choice = T.choice; + known = true; + } else { + // STATIC PICK: candidate 0 (default) -- no runtime timing + T.choice = 0; T.M = M; T.N = N; T.K = K; choice = 0; known = true; + } + if (choice >= (int)fns.size()) choice = 0; + if (known) fast_set(M, N, K, kinds[choice], plan_direct_, plan_tail_); + fns[choice](); + return out; + } + struct PlanCache { int64_t M = -1, N = -1, K = -1; Fp8Plan p; Fp8PlanL pl; Fp8PlanL2 p2; }; + static PlanCache& PC = *new PlanCache(); + if (PC.M != M || PC.N != N || PC.K != K) { + PC.p = fp8_bs_plan((int)M, (int)N, (int)K); + PC.pl = fp8_large_plan((int)M, (int)N, (int)K); + PC.p2 = fp8_large2_plan((int)M, (int)N, (int)K); + PC.M = M; PC.N = N; PC.K = K; + } + const Fp8Plan plan = PC.p; + if (!plan.streamk && !plan.dualm && !plan.fused) { + // Plain plans (M=128-class classic split-K, and large-M whole-tile waves + split tail): + // the isolated large-M kernel (kernel_large.cu), with its own identical plan. + const Fp8PlanL pl = PC.pl; + if (pl.direct > 0) { + // large M (whole-tile waves [+ K-split last partial wave]): 16-promotion-warp kernel (kernel_large2.cu) + Fp8PlanL2 p2 = PC.p2; + // tail K-split tiles use kernel_large2's persistent self-cleaning ws + fused owner fixup (no extra launches) + float* ws2_ptr = nullptr; + cudaStream_t st = at::cuda::getCurrentCUDAStream(); + struct L2Desc { int kind, dyn, split; }; + struct L2Cache { int64_t M = -1, N = -1, K = -1; L2Desc d{0, 0, 0}; }; + static L2Cache& LC = *new L2Cache(); + auto launch_desc = [&](const L2Desc& d) { + switch (d.kind) { + case 1: + launch_fp8_l2x(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st); + break; + case 2: + launch_fp8_sk2c(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st); + break; + case 3: { + Fp8PlanL2 pp = p2; + pp.split = d.split & 255; + if (d.split >> 8) pp.group_n = d.split >> 8; // band-width override (split bits 8+) + launch_fp8_large2_ex(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), + out.data_ptr(), ws2_ptr, pp, (int)M, (int)N, (int)K, st, d.dyn, nullptr); + break; + } + default: + launch_fp8_large2(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + ws2_ptr, p2, (int)M, (int)N, (int)K, st); + } + }; + auto record_fast = [&]() { + fast_set(M, N, K, FK_LARGE2, LC.d.kind, LC.d.dyn); + fast_desc().a2 = LC.d.split; + fast_desc().p2 = p2; + }; + if (LC.M == M && LC.N == N && LC.K == K) { + record_fast(); + launch_desc(LC.d); + return out; + } + if (false && M > 1536 && M < 3072 && fp8_l2sk_supported((int)M, (int)N, (int)K)) { // M=2048 -> large2 SPF18 below + fast_set(M, N, K, FK_L2SK); + launch_fp8_l2sk(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st); + return out; + } + // M=2048 class A/B: 2-SM UMMA pair tiles (kernel_sk2c: 222 whole pair tiles + 2-tile stream-K tail over 74 + // clusters, LDN33-style early-release drain, fused elected issuer) with PARALLEL middle contributors. + // M=2048 and M=4096 classes: 2-SM sk2c pair tiles (M=4096: 448 pair tiles = 6 waves of 74 clusters + 4-tile + // stream-K tail with parallel middle contributors) + // M=4096 class (3072 <= M < 6144) now -> kernel_large2 SPF7 band-8 serpentine (below); sk2c only for M=2048 class + // M=4096 class re-routed to sk2c: its plan now gets the LAST-WAVE STREAM-K rule (448 pair tiles = 6x74+4 -> + // 5x74 whole + 78-tile stream-K tail, ~135 kb/cluster, <=2 pieces/tile, no middle-contributor chain). + if (M >= 3072 && M < 6144) { + // M=4096 class: 2 PDL-chained M=2048-class sk2c launches (half rows, even M-block counts) + const int nmb = (int)((M + 127) / 128); + const int M1 = ((nmb / 2) & ~1) * 128; + if (M1 > 0 && fp8_sk2c_supported(M1, (int)N, (int)K) && fp8_sk2c_supported((int)M - M1, (int)N, (int)K)) { + fast_set(M, N, K, FK_SK2C_SPLIT, 0, M1); + launch_sk2c_split(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, M1, st); + return out; + } + } + if (M > 1536 && M < 3072 && fp8_sk2c_supported((int)M, (int)N, (int)K)) { + // M=2048 class: sk2c with the own W half loaded as two 64-row TMA sub-boxes (var bit 5 = 32) + fast_set(M, N, K, FK_SK2C_WSUB); + launch_fp8_sk2c(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st, 0, 1, SK2C_DELTA_DEFAULT, 32 | 2048); // A map L2 promo 128B + return out; + } + if (M > 1536 && M < 6144 && fp8_sk2c_supported((int)M, (int)N, (int)K)) { + fast_set(M, N, K, FK_SK2C); + launch_fp8_sk2c(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st); + return out; + } + if (M > 1536 && M < 3072 && p2.tail > 0 && p2.split >= 2) { + // SPF36: 4 tail tiles x 36 = 144 pieces (<= grid; boundaries even kb -> 2/4-kb pieces) when it fits + p2.spf_rot = 30; // SPF34 piece holders rotated by 30 (any rot is a bijection) + p2.group_n = 4 | (1 << 16) | (1 << 21); // bit 21: OUTN output-store L2 policy evict_normal + LC.d = L2Desc{3, 64, (p2.tail * 36 <= 148 && (K / 128) >= 72) ? 36 + : ((p2.tail * 18 <= 148 && (K / 128) >= 36) ? 18 : (p2.split < 32 ? p2.split : 32))}; + LC.M = M; LC.N = N; LC.K = K; + record_fast(); + launch_desc(LC.d); + return out; + } + if (M >= 6144 && M < 12288) { + // M=8192 class: 4 PDL-chained M=2048-class sk2c launches (row chunks with even M-block counts) + const int nmb = (int)((M + 127) / 128); + // merged-tail chain: 3072|3072|2048 (inner chunks 12 pair rows = 336 pair tiles = 4 waves of 74 + 40 forwarded) + const int MP = (((nmb * 3) / 8) & ~1) * 128; + bool ok = MP > 0; + for (int m0 = 0; ok && m0 < (int)M; m0 += MP) { + const int mr = ((int)M - m0) < MP ? ((int)M - m0) : MP; + ok = fp8_sk2c_supported(mr, (int)N, (int)K); + } + if (ok) { + // a0 = 2: SERPENTINE K order (odd-wave whole tiles walk k-blocks in reverse; M=8192 chain only) + fast_set(M, N, K, FK_SK2C_SPLITP, 2, MP); + launch_sk2c_splitp(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, MP, st, 2); + return out; + } + } + if (M >= 6144 && fp8_l2sk_supported((int)M, (int)N, (int)K)) { // M=4096 class -> large2 SPF7 below + + // M=8192 class (this version): 128x128 tiles, TWO co-resident CTAs per SM (kernel_l2sk: ~110 KB smem, + // 256 TMEM cols per CTA) so one CTA's promotion overlaps the other's MMA; whole-tile waves over 2*#SMs + // CTA slots + stream-K tail with fused fp32 fixup. Static pick (no runtime timing). + fast_set(M, N, K, FK_L2SK); + launch_fp8_l2sk(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st); + return out; + } + if (M >= 6144 && M < 12288) { + // M=8192 class: SERPENTINE band-8 raster (bit 16, bijective; A row-block reuse at band switches) + p2.group_n = ((p2.group_n & 0xFFFF) > 0 ? p2.group_n : 8) | (1 << 16); + // WBOX1 (bit 19): whole 256-row W slab as ONE TMA box per stage + p2.group_n |= 1 << 19; + // W tensor-map L2 sector promotion NONE (bit 20, host-only hint, bit-identical) + p2.group_n |= 1 << 20; + std::vector cands; + if (p2.tail > 0 && (K / 128) >= 32) { + const int sms_e = 148; + const int ts = p2.tail * 8; + if (ts < sms_e) p2.spf_rot = (ts - 88 + sms_e) % sms_e; + } + cands.push_back((p2.tail > 0 && (K / 128) >= 32) ? L2Desc{3, 64, 8} : L2Desc{0, 0, p2.split}); + if (fp8_sk2c_supported((int)M, (int)N, (int)K)) cands.push_back({2, 0, 0}); + if (cands[0].kind == 3 && (N / 256) > 8 && (N / 256) < (1 << 20)) + cands.push_back({3, 64, 8 | ((int)(N / 256) << 8)}); + // DEFERRED EPILOGUE (kernel_large2 MODE 8192): bf16 tile stores issued after the next tile's first TMEM + // drain + buffer release, so the MMA does not idle through the epilogue at every tile switch. Same SPF8 g8. + if (cands[0].kind == 3) cands.push_back({3, 64 | 8192, 8}); + std::vector> fns; + for (const L2Desc& d : cands) fns.push_back([&, d]() { launch_desc(d); }); + int ch = 0; // STATIC PICK: SPF8 g8 (seed default; archive probes never adopted the alternatives) + if (ch >= 0 && ch < (int)cands.size()) { + LC.d = cands[ch]; LC.M = M; LC.N = N; LC.K = K; + record_fast(); + } else ch = 0; + launch_desc(cands[ch]); + return out; + } + if (M >= 3072 && M < 6144 && p2.tail > 0 && (K / 128) >= 32) { + p2.spf_rot = 40; + p2.group_n = 8 | (1 << 16) | (1 << 18); + LC.d = L2Desc{3, 64, 7}; // SPF7: 8 tail tiles x 7 = 56 pieces (~18 kb, even boundaries) run FIRST; rot 40 (plan) keeps + // the consistently-slow CTA window 88..107 piece-less (holders = CTAs 108..147, 0..15) + LC.M = M; LC.N = N; LC.K = K; + record_fast(); + launch_desc(LC.d); + return out; + } + if (M >= 12288) { + // M=16384 class: 8 PDL-chained 2048-row sk2c chunks; inner chunks run exactly 3 whole waves (222 pair tiles) + // and forward their 2 leftover tiles to the last chunk, whose single folded stream-K tail covers the remainder. + if (M % 256 == 0 && (M + 3071) / 3072 <= 64) { + constexpr int MP = 3072; + bool ok = true; + for (int m0 = 0; ok && m0 < (int)M; m0 += MP) { + const int mr = ((int)M - m0) < MP ? ((int)M - m0) : MP; + ok = fp8_sk2c_supported(mr, (int)N, (int)K); + } + if (ok) { + // a0 = 1: alternating mirrored N raster on odd chunks (M>=12288 chain only; W L2 reuse at chunk seams) + fast_set(M, N, K, FK_SK2C_SPLITP, 3, MP); + launch_sk2c_splitp(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, MP, st, 3); // mir 3: mirrored cascaded chain + SERPENTINE K order + return out; + } + } + { + // two PDL-chained half launches (see launch_large2_split); M1 = M/2 rounded down to a 128-row multiple + // EXACT-WAVE SECOND HALF: the split point is moved (nearest to M/2, within +-M/4) so that the 2nd launch's + // whole-tile count is a multiple of #SMs (M=16384: 54 | 74 M-blocks, 74 x 28 = 2072 = 14 x 148 tiles) -> the + // 2nd launch has NO K-split tail / fixup at all and ends on uniform full waves; the whole K-split tail + // (32 tiles x SPF4) runs in the 1st launch, pieces-first, overlapping its whole tiles. Static, any M. + static int nsm_s = 0; + if (nsm_s == 0) { + int dev = 0; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&nsm_s, cudaDevAttrMultiProcessorCount, dev); + if (nsm_s <= 0) nsm_s = 148; + } + const int nmb_all = (int)((M + 127) / 128), nnb = (int)(N / 256); + int m1b = nmb_all / 2; + for (int d = 0; d <= nmb_all / 4; ++d) { + const int c1 = nmb_all / 2 - d, c2 = nmb_all / 2 + d; + if (c1 >= 1 && ((long long)(nmb_all - c1) * nnb) % nsm_s == 0) { m1b = c1; break; } + if (c2 < nmb_all && ((long long)(nmb_all - c2) * nnb) % nsm_s == 0) { m1b = c2; break; } + } + const int M1 = m1b * 128; + Fp8PlanL2 pa = fp8_large2_plan(M1, (int)N, (int)K); + Fp8PlanL2 pb = fp8_large2_plan((int)M - M1, (int)N, (int)K); + // each half = M=8192-class plan: add the SERPENTINE band-8 raster (bit 16) the standalone M=8192 path + // uses (the plan itself only carries spf_rot 40); bijective, static. + auto serp8 = [](Fp8PlanL2& p, int mh) { + const int nmb = (mh + 127) / 128; + if (nmb >= 48 && nmb < 96) p.group_n = ((p.group_n & 0xFFFF) > 0 ? p.group_n : 8) | (1 << 16); + }; + serp8(pa, M1); + serp8(pb, (int)M - M1); + // WBOX1 (group_n bit 19): whole 256-row W slab as ONE TMA box per stage (was 2 x 128-row boxes) + auto wbox1 = [](Fp8PlanL2& p) { p.group_n = ((p.group_n & 0xFFFF) > 0 ? p.group_n : 8) | (p.group_n & ~0xFFFF) | (1 << 19); }; + wbox1(pa); + wbox1(pb); + pa.group_n |= 1 << 20; + pb.group_n |= 1 << 20; + // next-unit scale-strip L2 prefetch in the scale producer (group_n bit 22, pure hint) + pa.group_n |= 1 << 22; + pb.group_n |= 1 << 22; + fast_set(M, N, K, FK_LARGE2_SPLIT, 0, M1); + fast_desc().p2 = pa; + fast_desc().p2b = pb; + launch_large2_split(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, M1, pa, pb, st); + return out; + } + LC.d = p2.tail > 0 ? L2Desc{3, 64, p2.split} : L2Desc{3, 128 | 4096, p2.split}; + LC.M = M; LC.N = N; LC.K = K; + record_fast(); + launch_desc(LC.d); + return out; + } + std::vector descs; + descs.push_back({0, 0, p2.split}); + if (M > 4096) { + if (fp8_l2x_supported((int)M, (int)N, (int)K)) descs.push_back({1, 0, 0}); + if (fp8_sk2c_supported((int)M, (int)N, (int)K)) descs.push_back({2, 0, 0}); + } + // kernel_large2 SPF mode (dyn 64): each CTA's K-split tail piece runs FIRST; only for many-piece tails + // (split >= 24), plus SPF with fewer, larger pieces (split 16 / 8). Autotune keeps whichever is fastest. + if (p2.tail > 0 && p2.split >= 24) descs.push_back({3, 64, p2.split}); + if (p2.tail > 0 && p2.split >= 24 && (K / 128) % 32 == 0) { + descs.push_back({3, 64, 16}); + descs.push_back({3, 64, 8}); + } + std::vector> fns; + for (const L2Desc& d : descs) fns.push_back([&, d]() { launch_desc(d); }); + int choice = 0; // STATIC PICK: plain kernel_large2 plan (no runtime timing) + LC.d = descs[choice]; LC.M = M; LC.N = N; LC.K = K; record_fast(); + if (choice < 0 || choice >= (int)descs.size()) choice = 0; + launch_desc(descs[choice]); + return out; + } + torch::Tensor wsl; + float* wsl_ptr = nullptr; + if (pl.ws_floats > 0 && pl.direct > 0) { // direct == 0 plans use the persistent self-cleaning ws + wsl = torch::zeros({(int64_t)pl.ws_floats}, hidden_states.options().dtype(torch::kFloat32)); + wsl_ptr = wsl.data_ptr(); + } + launch_fp8_large(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), wsl_ptr, + pl, (int)M, (int)N, (int)K, at::cuda::getCurrentCUDAStream()); + return out; + } + if (plan.streamk && !plan.dualm && !plan.fused && plan.direct > 0 && plan.ws_floats > 0) { + // large partial last wave (e.g. M=1024): whole-tile waves + stream-K tail, scale-producer kernel (kernel_sk.cu) + // ws = nullptr: kernel_sk.cu owns a persistent self-cleaning workspace (fused owner fixup, no convert) + // candidates (first-use autotune, cached per (M,N,K)): 0 kernel_sk; 1 kernel_l2sk (2 CTAs/SM 128x128 tiles + + // stream-K tail over 2*#SMs slots); 2 kernel_l2x (2 CTAs/SM 128x112 tiles, whole tiles only) + cudaStream_t st = at::cuda::getCurrentCUDAStream(); + if (fp8_sk2c_supported((int)M, (int)N, (int)K)) { + fast_set(M, N, K, FK_SK2C); + launch_fp8_sk2c(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), (int)M, + (int)N, (int)K, st, 0, 1, SK2C_DELTA_DEFAULT, (M > 512 && M <= 1536) ? (16 | 1024) : SK2C_VAR_DEFAULT); + return out; + } + std::vector> fns; + std::vector kinds{FK_SK}; + const int plan_direct_ = plan.direct, plan_tail_ = plan.tail; + fns.push_back([&]() { + launch_fp8_sk(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), nullptr, + plan.direct, plan.tail, (int)M, (int)N, (int)K, st); + }); + if (fp8_l2sk_supported((int)M, (int)N, (int)K) && (kinds.push_back(FK_L2SK), true)) + fns.push_back([&]() { + launch_fp8_l2sk(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st); + }); + if (fp8_l2x_supported((int)M, (int)N, (int)K) && (kinds.push_back(FK_L2X), true)) + fns.push_back([&]() { + launch_fp8_l2x(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st); + }); + // 3: kernel_sk2c = same stream-K-tail schedule on 2-CTA clusters with 2-SM UMMA (cta_group::2 M256xN256 pair + // tiles, 32 KB/kb smem ingest per SM instead of 48 KB); only if the M-block count is even + const bool sk2c_ok = fp8_sk2c_supported((int)M, (int)N, (int)K); + if (sk2c_ok && (kinds.push_back(FK_SK2C), true)) + fns.push_back([&]() { + launch_fp8_sk2c(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st); + }); + // 4: kernel_sk2c with ALL pair tiles stream-K'd (no direct whole-tile wave; finer split granularity) + if (sk2c_ok && (kinds.push_back(FK_SK2C_ALL), true)) + fns.push_back([&]() { + launch_fp8_sk2c(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), + (int)M, (int)N, (int)K, st, 1); + }); + static TuneCache& T = *new TuneCache(); + int choice = 0; + bool known = false; + if (T.M == M && T.N == N && T.K == K) { + choice = T.choice; + known = true; + } else { + // STATIC PICK: candidate 0 (default) -- no runtime timing + T.choice = 0; T.M = M; T.N = N; T.K = K; choice = 0; known = true; + } + if (choice >= (int)fns.size()) choice = 0; + if (known) fast_set(M, N, K, kinds[choice], plan_direct_, plan_tail_); + fns[choice](); + return out; + } + // small-M features (dual-M / fused reduction): kernel.cu general variant + torch::Tensor ws; + float* ws_ptr = nullptr; + if (plan.ws_floats > 0) { + ws = torch::zeros({(int64_t)plan.ws_floats}, hidden_states.options().dtype(torch::kFloat32)); + ws_ptr = ws.data_ptr(); + } + launch_fp8_bs_gemm(x.data_ptr(), w.data_ptr(), sx.data_ptr(), sw.data_ptr(), out.data_ptr(), ws_ptr, + plan, (int)M, (int)N, (int)K, at::cuda::getCurrentCUDAStream()); + return out; +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("run", &run, "FP8 MLA output projection"); } diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/raw_push.h b/kernels/Quant/015_fp8_mla_attention_output_projection/src/raw_push.h new file mode 100644 index 0000000000000000000000000000000000000000..c782b34ea6b2e50ee9cae0084c7735d2cb8d4034 --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/raw_push.h @@ -0,0 +1,34 @@ +#pragma once +// RAW FP32 DSMEM push format (exact: no rounding) for the cluster split-K reductions of kernel_m128c.cu / +// kernel_m256c.cu (same scheme as kernel_m256v's raw path). A pusher warp's 32 rows x NCOL fp32 slice: +// float4 v (cols 4v..4v+3) of lane at (v*32 + lane)*16 (conflict-free st/ld.shared.v4); owner adds with packed fadd. +#include +namespace rawpush { +__host__ __device__ constexpr uint32_t slice_bytes(int ncol) { return (uint32_t)ncol * 128u; } +template +__device__ __forceinline__ void pack(const float* acc, uint32_t stg, int lane) { + static_assert(NCOL % 4 == 0, "cols multiple of 4"); +#pragma unroll + for (int v = 0; v < NCOL / 4; ++v) + asm volatile("st.shared.v4.f32 [%0], {%1, %2, %3, %4};" ::"r"(stg + (uint32_t)(v * 32 + lane) * 16), + "f"(acc[4 * v]), "f"(acc[4 * v + 1]), "f"(acc[4 * v + 2]), "f"(acc[4 * v + 3]) : "memory"); +} +template +__device__ __forceinline__ void add(float* acc, uint32_t src, int lane) { +#pragma unroll + for (int v0 = 0; v0 < NCOL / 4; v0 += 4) { + float4 p[4]; +#pragma unroll + for (int v = 0; v < 4 && v0 + v < NCOL / 4; ++v) + asm volatile("ld.shared.v4.f32 {%0, %1, %2, %3}, [%4];" : "=f"(p[v].x), "=f"(p[v].y), "=f"(p[v].z), "=f"(p[v].w) + : "r"(src + (uint32_t)((v0 + v) * 32 + lane) * 16) : "memory"); +#pragma unroll + for (int v = 0; v < 4 && v0 + v < NCOL / 4; ++v) { + float* a = acc + 4 * (v0 + v); + const float2 d0 = __ffma2_rn(make_float2(p[v].x, p[v].y), make_float2(1.f, 1.f), make_float2(a[0], a[1])); + const float2 d1 = __ffma2_rn(make_float2(p[v].z, p[v].w), make_float2(1.f, 1.f), make_float2(a[2], a[3])); + a[0] = d0.x; a[1] = d0.y; a[2] = d1.x; a[3] = d1.y; + } + } +} +} // namespace rawpush diff --git a/kernels/Quant/015_fp8_mla_attention_output_projection/src/tmap_cache.h b/kernels/Quant/015_fp8_mla_attention_output_projection/src/tmap_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..c6baa0d944ae1b8ac5a0b3574c2c693b1e74deba --- /dev/null +++ b/kernels/Quant/015_fp8_mla_attention_output_projection/src/tmap_cache.h @@ -0,0 +1,46 @@ +#pragma once +#include +#include +#include +namespace tmc { +struct Key { + int dtype, swz, promo, oob, inter; + uint64_t ptr, d0, d1, s0; + uint32_t b0, b1, e0, e1; +}; +struct Entry { + Key k; + CUtensorMap map; + bool valid; +}; +constexpr int NENT = 128; +static inline CUresult encode2d_cached(CUtensorMap* map, CUtensorMapDataType dt, cuuint32_t rank, void* ptr, + const cuuint64_t* dims, const cuuint64_t* strides, const cuuint32_t* box, + const cuuint32_t* estr, CUtensorMapInterleave il, CUtensorMapSwizzle sw, + CUtensorMapL2promotion pr, CUtensorMapFloatOOBfill oob) { + static Entry cache[NENT]; + static int next = 0, last = 0; + Key k; + std::memset(&k, 0, sizeof(k)); + k.dtype = (int)dt; k.swz = (int)sw; k.promo = (int)pr; k.oob = (int)oob; k.inter = (int)il; + k.ptr = reinterpret_cast(ptr); k.d0 = dims[0]; k.d1 = dims[1]; k.s0 = strides[0]; + k.b0 = box[0]; k.b1 = box[1]; k.e0 = estr[0]; k.e1 = estr[1]; + for (int j = 0; j < NENT; ++j) { + const int i = (last + j) & (NENT - 1); + const Entry& e = cache[i]; + if (e.valid && e.k.ptr == k.ptr && std::memcmp(&e.k, &k, sizeof(k)) == 0) { + *map = e.map; + last = (i + 1) & (NENT - 1); // next map of the same call is usually the next entry + return CUDA_SUCCESS; + } + } + CUresult r = cuTensorMapEncodeTiled(map, dt, rank, ptr, dims, strides, box, estr, il, sw, pr, oob); + if (r == CUDA_SUCCESS) { + Entry& e = cache[next]; + e.k = k; e.map = *map; e.valid = true; + next = (next + 1) & (NENT - 1); + last = next; + } + return r; +} +} // namespace tmc diff --git a/kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/README.md b/kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/README.md new file mode 100644 index 0000000000000000000000000000000000000000..583eaa9363c243e666b33feccc75a99ab89e31b4 --- /dev/null +++ b/kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/README.md @@ -0,0 +1,10 @@ +# FP8 multi latent attention QKV projection (Quant 016) + +MLA query and key/value projections in FP8: down-project the input to q and kv latents, apply RMSNorm to each latent, then up-project. It returns q, k and v per head, with the RoPE parts split out. + +- Language: CUDA C++. Entry point: `main.cpp::run`. Files: 3 (7,781 lines). +- Idea: Quantizes input and weights to block-scaled FP8; FP8 down-proj GEMM, latent RMSNorms with requant, persistent tcgen05 FP8 up-proj GEMMs; two streams in one CUDA graph +- Result: SOL score 0.941; speedup 9.19x over the benchmark's baseline (geometric mean). Public SOL-ExecBench results as of 2026-11-11. +- Origin: search agent (Claude). +- Comments edited; the code that runs is identical to the scored submission. +- Generated by Claude via Amazon Bedrock. Verified on the SOL-ExecBench site; not production-ready. diff --git a/kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/kernel.json b/kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/kernel.json new file mode 100644 index 0000000000000000000000000000000000000000..6b3e14830254fc1f6d6885a5ec9a3202254857db --- /dev/null +++ b/kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/kernel.json @@ -0,0 +1,64 @@ +{ + "board": "Quant", + "id": "016_fp8_multi_latent_attention_qkv_projection", + "name": "FP8 multi latent attention QKV projection", + "language": "CUDA C++", + "files": [ + { + "path": "src/kernel.cu", + "lines": 6579, + "bytes": 377078 + }, + { + "path": "src/kernel.h", + "lines": 153, + "bytes": 13036 + }, + { + "path": "src/main.cpp", + "lines": 1049, + "bytes": 70841 + } + ], + "origin": "search agent (Claude)", + "result": { + "public": true, + "sol_score": 0.941222, + "speedup": 9.194, + "board_row": true, + "note": "the row the public SOL-ExecBench board shows for this problem, as of 2026-11-11" + }, + "idea": "Quantizes input and weights to block-scaled FP8; FP8 down-proj GEMM, latent RMSNorms with requant, persistent tcgen05 FP8 up-proj GEMMs; two streams in one CUDA graph", + "spec": { + "languages": [ + "cuda_cpp" + ], + "target_hardware": [ + "B200", + "LOCAL" + ], + "entry_point": "main.cpp::run", + "binding": "torch", + "destination_passing_style": false, + "dependencies": [], + "compile_options": { + "cuda_cflags": [ + "-std=c++17", + "-O3", + "-gencode=arch=compute_100a,code=sm_100a", + "--expt-relaxed-constexpr", + "-DNDEBUG", + "-DCUTLASS_ENABLE_GDC_FOR_SM100=1" + ], + "ld_flags": [ + "-lcuda" + ], + "cflags": [] + }, + "sources": [ + "kernel.h", + "kernel.cu", + "main.cpp" + ] + } +} diff --git a/kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/src/kernel.cu b/kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/src/kernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..fe5ecc4acc654536185e971f91600ced00eb15a6 --- /dev/null +++ b/kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/src/kernel.cu @@ -0,0 +1,6579 @@ +/* + * FP8 MLA QKV projection (DeepSeek-V3) for B200 (sm_100a). + * + * Pipeline per call: + * 1. quant_kernel (x2 launches, one per stream): fused weight + activation quantization. + * 256-thread CTAs, 32 KB bf16 each, 4 independent 32 B ld.global.nc.v8 loads per thread. + * - weight CTAs: one 128x128 block of a bf16 weight -> FP8 e4m3, scale = max(amax/448,1e-12), + * q = w/scale (satfinite). q_a_proj and kv_a_proj are written into ONE concatenated + * [2176,7168] buffer so both A-projections run as one GEMM. Scales MN-major ([kb][nb]). + * - act CTAs (only in the main-stream launch): 128 contiguous 1x128 groups, 8 lanes x 32 B + * per group, scales MN-major [kb][m]; padding rows M..Mp-1 become zeros. + * The division w/scale uses rcp + one FMA residual correction (correctly rounded quotient) + * with packed f32x2 mul/fma. + * Small M (Mp <= 512): instead ONE persistent TMA-ring launch (section 8, pquant_kernel) over all four + * weights + activation, fp8 stores with L2 evict_last so the GEMMs read the weights from L2. + * 2. GEMM1 (CUTLASS SM100 tcgen05 blockwise-scaled FP8 GEMM, TMA + TMEM, warp-specialized): + * (non-split path: 1-SM 128x128, or 2-SM 256x128 over a 2x1 cluster, chosen per M on the + * first call by timing the WHOLE captured graph with each variant, so co-running effects count) + * y1[Mp,2112] = Xq * Wa^T (N = 2112: the 64 discarded kv_a padding outputs are skipped; scales still over all 640 rows). For small M (only 17*Mp/128 output tiles) it runs split-K as a + * batched GEMM over K-chunks (L = S splits, A/B batch stride = K/S elements) producing fp32 + * partials so ~136 CTAs stream the weights instead of 17. + * 4. q_b_proj (N=24576,K=1536): custom persistent tcgen05 kernel (section 7): 128x256 tiles (128x128 + * at small M), TMA ring, TMEM k-block ring, 16 promotion warps, per-warp TMA-store epilogue. + */ +#include "kernel.h" +#ifndef AQE_DEFAULT +#define AQE_DEFAULT 0 +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(TLG_PROBE) || defined(FX_PROBE) +#include +#endif + +// Launch with the programmatic-stream-serialization attribute (PDL) when pdl != 0. +template +static cudaError_t launch_pdl(void (*k)(P...), dim3 grid, dim3 block, size_t smem, cudaStream_t st, int pdl, A&&... a) { + cudaLaunchConfig_t c = {}; + c.gridDim = grid; c.blockDim = block; c.dynamicSmemBytes = smem; c.stream = st; + cudaLaunchAttribute at[1]; + at[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + at[0].val.programmaticStreamSerializationAllowed = 1; + c.attrs = at; c.numAttrs = pdl ? 1 : 0; + return cudaLaunchKernelEx(&c, k, std::forward(a)...); +} +// Small-M fused path (fg2): PDL chain act quant -> fused GEMM1 -> split-K norm (set around the capture). +static int g_fg_pdl = 0; +void set_fg_pdl(int on) { g_fg_pdl = on; } +static int g_late = 0; +void set_late_trig(int on) { g_late = on; } +static int g_aq_early = AQE_DEFAULT; +void set_aq_early(int on) { g_aq_early = on; } +static int g_g1_pdl = 0; +void set_g1_pdl(int on) { g_g1_pdl = on; } +// Mid-M late-trigger PDL chain (table wq bits 14-17, rows 512/1024): +// g_pq_ptrig (bit14): pquant / wquant producers trigger launch_dependents after their last job claim (dependent: +// the CUTLASS GEMM1 launched via GDC, or aquant); +// g_nf_etrig (bit16): norm_fast triggers right after its griddepcontrol.wait (q_b PDL dependent scheduled early); +// g_aq_pdl (bit17): act-only aquant launched as PDL dependent of the A-weight wquant (same stream). +static int g_pq_ptrig = 0, g_nf_etrig = 0, g_aq_pdl = 0; +void set_pq_ptrig(int on) { g_pq_ptrig = on; } +void set_nf_etrig(int on) { g_nf_etrig = on; } +void set_aq_pdl(int on) { g_aq_pdl = on; } +#define PDL_TRIGGER() asm volatile("griddepcontrol.launch_dependents;" ::: "memory") +// WB_EF (probe): every L2 allocation of our kernels low priority (evict_last policies -> evict_first; unhinted TMA +// loads / bulk loads / TMA stores carry an evict_first policy). +#ifdef WB_EF +#define WB_EFL +#define WB_EFS +#define WB_EFT +#endif +#ifdef WB_EFS +#define KPOL_LAST "evict_first" +#else +#define KPOL_LAST "evict_last" +#endif + +#include "cutlass/cutlass.h" +#include "cute/tensor.hpp" +#include "cutlass/gemm/dispatch_policy.hpp" +#include "cutlass/gemm/collective/collective_builder.hpp" +#include "cutlass/epilogue/dispatch_policy.hpp" +#include "cutlass/epilogue/collective/collective_builder.hpp" +#include "cutlass/gemm/device/gemm_universal_adapter.h" +#include "cutlass/gemm/kernel/gemm_universal.hpp" +#include "cutlass/util/packed_stride.hpp" + +#define FP8_MAX 448.0f + +// ---- Programmatic dependent launch (PDL). g_pdl != 0: the gq GEMM launches below carry +// cudaLaunchAttributeProgrammaticStreamSerialization (used for q_b right after the RMSNorm on the main stream), so +// inside the captured graph the q_b grid is scheduled while its in-stream predecessor drains (launch latency + prologue: +// barrier init, TMEM alloc, tensormap prefetch overlap the predecessor's tail). gq_kernel / norm_quant_kernel execute +// griddepcontrol.wait before touching any predecessor output (waits for the predecessor grids to complete and their +// memory to be visible); without a PDL launch it is a no-op. Math is unchanged. +static int g_pdl = 0; +void set_pdl(int on) { g_pdl = on; } +__device__ __forceinline__ void pdl_wait() { asm volatile("griddepcontrol.wait;" ::: "memory"); } +#ifdef NT_PROBE +// probe: contention-free per-CTA globaltimer stamps (plain stores): [0,8192) norm_fast end, [8192,16384) norm_fast +// start, [16384,16640) GEMM1 (gq) CTA end, [16640,16896) kv_b start, [16896,17152) q_b start +__device__ unsigned long long* g_ntp = nullptr; +__device__ __forceinline__ unsigned long long ntp_now() { unsigned long long t; asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); return t; } +void ntp_set(void* p) { cudaMemcpyToSymbol(g_ntp, &p, sizeof(p)); } +#define NTP(off) do { if (threadIdx.x == 0 && g_ntp) g_ntp[(off) + blockIdx.x] = ntp_now(); } while (0) +#else +#define NTP(off) +#endif +#ifdef TLG_PROBE +// probe: per-kernel globaltimer windows. [0,16) min start, [16,32) max end, [32,48) CTA count, [48,64) max start, [64,80) min end +__device__ unsigned long long* g_tlg = nullptr; +__device__ __forceinline__ unsigned long long tlg_now() { unsigned long long t; asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); return t; } +#define TLG_S(id) do { if (threadIdx.x == 0 && g_tlg) { const unsigned long long t_ = tlg_now(); atomicMin(g_tlg + (id), t_); atomicMax(g_tlg + 48 + (id), t_); atomicAdd(g_tlg + 32 + (id), 1ull); } } while (0) +#define TLG_E(id) do { if (threadIdx.x == 0 && g_tlg) { const unsigned long long t_ = tlg_now(); atomicMax(g_tlg + 16 + (id), t_); atomicMin(g_tlg + 64 + (id), t_); } } while (0) +void tlg_set(void* p) { cudaMemcpyToSymbol(g_tlg, &p, sizeof(p)); } +#else +#define TLG_S(id) +#define TLG_E(id) +#endif +// NOTE: scale = amax * (1/448) (not amax/448) to bit-match torch, which turns division by a +// python scalar into multiplication by its fp32 reciprocal; x/scale stays a (correctly rounded) division. + +// n / d via the host multiplier dvm40(d) (see kernel.h): one IMAD.WIDE + shift instead of a software divide. +__device__ __forceinline__ int udiv40(int n, unsigned long long m) { + return (int)(((unsigned long long)(unsigned)n * m) >> 40); +} +__device__ __forceinline__ float bf2f(uint16_t v) { return __uint_as_float(((uint32_t)v) << 16); } + +// fp32 -> e4m3 (round-to-nearest-even, satfinite); inputs are already clamped to +-448. +__device__ __forceinline__ uint16_t f2_to_fp8x2(float a, float b) { + __nv_fp8x2_storage_t r = __nv_cvt_float2_to_fp8x2(make_float2(a, b), __NV_SATFINITE, __NV_E4M3); + return (uint16_t)r; +} +// relaxed: callers pass the reciprocal 1/scale; the satfinite cvt does the +-448 clamp. +__device__ __forceinline__ float qclamp(float x, float inv) { + return x * inv; +} + +// ------------------------------------------------------------------ 1. fused quant kernel +// Both job types use the same CTA shape (256 threads, 32 KB of bf16 per CTA): every thread issues +// 4 independent 32-byte ld.global.nc.v8 loads before any math, then requantizes from registers and +// writes 16 B of fp8 per load (no second global read). Division w/scale uses packed f32x2 +// mul/fma (rcp + one residual correction = correctly rounded quotient); satfinite clamps to +-448. +// g1cnt (large M, wq bit19): per-128-row GEMM1 tile-completion counters, zeroed by block 0 at the start of every replay +// (GEMM1 increments them only after its griddepcontrol.wait on this grid; norm_fast polls them). +// Early-start mode (large M, wq bit29): acnt != nullptr -> every CTA triggers launch_dependents at ENTRY (the gq GEMM1 +// dependent can then take SMs as soon as quant CTAs drain), and after its stores each CTA release-adds 1 to +// wdn (weight block) or acnt[row block] (act CTA; one 128-row block = K/128 act CTAs). GEMM1 (nowait) acquire-polls +// wdn >= nwblk once and acnt[m0/128] >= K/128 per tile before its TMA loads. Counters are zeroed at the end of the +// replay by the first q_b/kv_b gq launch (GQArgs::rst), i.e. after the norm (and hence every GEMM1 read) completed. +struct QuantParams { WSeg s[4]; int nseg; int nwblk; ActJob a; int nablk; float* alpha; unsigned* g1cnt = nullptr; int ng1cnt = 0; + unsigned* acnt = nullptr; unsigned* wdn = nullptr; }; +static unsigned* g_q_g1cnt = nullptr; static int g_q_ng1cnt = 0; +void set_quant_g1cnt(unsigned* p, int n) { g_q_g1cnt = p; g_q_ng1cnt = n; } +static unsigned* g_q_acnt = nullptr; static unsigned* g_q_wdn = nullptr; +void set_quant_early(unsigned* acnt, unsigned* wdn) { g_q_acnt = acnt; g_q_wdn = wdn; } + +#define QTHREADS 256 +// The fake-quant fp16 GEMM1 path is disabled (kF16Gemm1 = false in main.cpp): compile its quant_kernel branches out +// (dead runtime f16 predicates / ldexpf / pre_exp / deq16 code and their registers). launch_quant rejects f16 jobs. +constexpr bool kQuantF16 = false; +#define ACT_GROUPS_PER_CTA 128 // 1x128 groups per act CTA (32 groups per pass x 4 passes) + +// 32-byte read-only streaming load (16 bf16): sm_100 256-bit global load. +__device__ __forceinline__ void ld32(const void* p, uint4& a, uint4& b) { + asm volatile("ld.global.nc.L1::no_allocate.v8.b32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];" + : "=r"(a.x), "=r"(a.y), "=r"(a.z), "=r"(a.w), "=r"(b.x), "=r"(b.y), "=r"(b.z), "=r"(b.w) + : "l"(p)); +} + +// Same 32-byte load with an L2 cache-policy hint (evict_first for read-once bf16 inputs). +__device__ __forceinline__ void ld32_hint(const void* p, uint4& a, uint4& b, uint64_t pol) { + asm volatile("ld.global.nc.L1::no_allocate.L2::cache_hint.v8.b32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8], %9;" + : "=r"(a.x), "=r"(a.y), "=r"(a.z), "=r"(a.w), "=r"(b.x), "=r"(b.y), "=r"(b.z), "=r"(b.w) + : "l"(p), "l"(pol)); +} + +// Ordered scalar loads of predecessor-kernel outputs (audit 2): VOLATILE ld.global.cg + "memory" clobber, so they can +// never be hoisted above a griddepcontrol.wait / counter poll (unlike __ldg / __ldcg, readnone asm), and they bypass +// the non-coherent nc/L1 path. Same values as the replaced loads: bit-identical. +__device__ __forceinline__ float ldcg_f32v(const float* p) { + float r; + asm volatile("ld.global.cg.f32 %0, [%1];" : "=f"(r) : "l"(p) : "memory"); + return r; +} +__device__ __forceinline__ unsigned ldcg_u32v(const unsigned* p) { + unsigned r; + asm volatile("ld.global.cg.u32 %0, [%1];" : "=r"(r) : "l"(p) : "memory"); + return r; +} +__device__ __forceinline__ unsigned long long ldcg_u64v(const unsigned long long* p) { + unsigned long long r; + asm volatile("ld.global.cg.u64 %0, [%1];" : "=l"(r) : "l"(p) : "memory"); + return r; +} +// |bf16| max of 8 packed bf16 words (16 values) folded into a bf16x2 accumulator (returned as |.|, sign bits clear). +// max.xorsign.abs.bf16x2: magnitude = max(|a|,|b|) (exact), sign = xor of the input signs (garbage, masked once at +// the end). Balanced tree: 8 HMNMX2 + 1 LOP per 16 elements (was 8 LOP + 8 HMNMX2 in one serial chain). +__device__ __forceinline__ uint32_t mxa2(uint32_t x, uint32_t y) { + uint32_t r; + asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(r) : "r"(x), "r"(y)); + return r; +} +// plain max of two bf16x2 words (non-negative, non-NaN operands: exact per half) +__device__ __forceinline__ uint32_t mxb2(uint32_t x, uint32_t y) { + uint32_t r; + asm("max.bf16x2 %0, %1, %2;" : "=r"(r) : "r"(x), "r"(y)); + return r; +} +__device__ __forceinline__ uint32_t amax16(const uint4& a, const uint4& b, uint32_t acc) { + const uint32_t t0 = mxa2(a.x, a.y), t1 = mxa2(a.z, a.w), t2 = mxa2(b.x, b.y), t3 = mxa2(b.z, b.w); + const uint32_t u = mxa2(mxa2(t0, t1), mxa2(t2, t3)); + return mxa2(u, acc) & 0x7fff7fffu; +} +__device__ __forceinline__ float bf2max_to_f(uint32_t acc) { + return fmaxf(__uint_as_float(acc << 16), __uint_as_float(acc & 0xffff0000u)); +} + +// q = x / s for a bf16 pair word (lo = element 2j, hi = element 2j+1) using packed f32x2 ops: +// q0 = x*inv; r = fma(q0,-s,x); q = fma(r,inv,q0) (correctly rounded quotient), then e4m3x2 satfinite. +// RELAXED (was rcp + FMA residual correction = correctly rounded x/s): q = x * (1/s) with ONE packed FMUL2 per +// bf16 pair, then cvt.rn.satfinite.e4m3x2.f32. Differs from x/s by <= 1 fp32 ulp -> an e4m3 code changes (by 1 ulp) +// only when x/s sits within 1 ulp of an e4m3 rounding boundary (rare; far inside tolerance). ns2 is unused. +// Per pair: 1 FMUL2 + 1 CVT (was FMUL2 + 2 FFMA2 + CVT). +__device__ __forceinline__ uint16_t quant_pair(uint32_t w, unsigned long long inv2, unsigned long long /*ns2*/) { + float lo = __uint_as_float(w << 16), hi = __uint_as_float(w & 0xffff0000u); + uint16_t r; + asm("{\n\t.reg .b64 x, q;\n\t.reg .f32 a, b;\n\t" + "mov.b64 x, {%1, %2};\n\t" + "mul.rn.f32x2 q, x, %3;\n\t" + "mov.b64 {a, b}, q;\n\t" + "cvt.rn.satfinite.e4m3x2.f32 %0, b, a;\n\t}" + : "=h"(r) : "f"(lo), "f"(hi), "l"(inv2)); + return r; +} +__device__ __forceinline__ unsigned long long pack2(float a) { + unsigned long long r; + asm("mov.b64 %0, {%1, %1};" : "=l"(r) : "f"(a)); + return r; +} +// two bf16x2 words -> 4 e4m3 codes in ONE asm block (2 FMUL2 + 2 CVT, no 16-bit merge). Same math as quant_pair. +__device__ __forceinline__ uint32_t qword4(uint32_t w0, uint32_t w1, unsigned long long inv2) { + const float l0 = __uint_as_float(w0 << 16), h0 = __uint_as_float(w0 & 0xffff0000u); + const float l1 = __uint_as_float(w1 << 16), h1 = __uint_as_float(w1 & 0xffff0000u); + uint32_t r; + asm("{\n\t.reg .b64 x0, x1, q0, q1;\n\t.reg .f32 a0, b0, a1, b1;\n\t.reg .b16 c0, c1;\n\t" + "mov.b64 x0, {%1, %2};\n\tmov.b64 x1, {%3, %4};\n\t" + "mul.rn.f32x2 q0, x0, %5;\n\tmul.rn.f32x2 q1, x1, %5;\n\t" + "mov.b64 {a0, b0}, q0;\n\tmov.b64 {a1, b1}, q1;\n\t" + "cvt.rn.satfinite.e4m3x2.f32 c0, b0, a0;\n\tcvt.rn.satfinite.e4m3x2.f32 c1, b1, a1;\n\t" + "mov.b32 %0, {c0, c1};\n\t}" + : "=r"(r) : "f"(l0), "f"(h0), "f"(l1), "f"(h1), "l"(inv2)); + return r; +} +// 16 bf16 (two uint4) -> 16 fp8 (one uint4) +__device__ __forceinline__ uint4 quant16(const uint4& a, const uint4& b, float s, float inv) { + unsigned long long inv2 = pack2(inv), ns2 = pack2(-s); + const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w}; + (void)ns2; + uint32_t o[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) o[j] = qword4(w[2 * j], w[2 * j + 1], inv2); // lean 4-code asm + return make_uint4(o[0], o[1], o[2], o[3]); +} + +// Power-of-two prescale exponent of a fake-quant fp16 operand: the tensor's |max| G (fp32 bits) maps to < 2^14 +// (G = m*2^e, m in [0.5,1) -> s = 14 - e), so no fp16 overflow (65504) and as few subnormals (< 2^-14) as possible. +// The GEMM result is multiplied by 2^-(sA+sW) (exact) in the epilogue. a == nullptr or G == 0 -> s = 0. +__device__ __forceinline__ int pre_exp(const unsigned* a) { + if (!a) return 0; + const float G = __uint_as_float(ldcg_u32v(a)); + if (!(G > 0.f)) return 0; + int e; + frexpf(G, &e); + return min(64, max(-64, 14 - e)); +} +__device__ __forceinline__ void deq16_store(const uint4& q, float s, uint16_t* dst) { + const uint32_t w[4] = {q.x, q.y, q.z, q.w}; + uint32_t o[8]; +#pragma unroll + for (int j = 0; j < 4; ++j) +#pragma unroll + for (int h = 0; h < 2; ++h) { + __half2_raw hr = __nv_cvt_fp8x2_to_halfraw2((__nv_fp8x2_storage_t)((w[j] >> (16 * h)) & 0xffffu), __NV_E4M3); + const float2 f = __half22float2(*reinterpret_cast<__half2*>(&hr)); + __half2 r = __floats2half2_rn(f.x * s, f.y * s); + o[2 * j + h] = *reinterpret_cast(&r); + } + reinterpret_cast(dst)[0] = make_uint4(o[0], o[1], o[2], o[3]); + reinterpret_cast(dst)[1] = make_uint4(o[4], o[5], o[6], o[7]); +} + +// ---- fast quant (pquant consumers): q = x * (1/scale) with ONE packed FMUL2 per bf16 pair, then +// cvt.rn.satfinite.e4m3x2.f32. Differs from the correctly rounded x/scale by <= 1 fp32 ulp, which changes +// an fp8 code (by 1) only for values sitting exactly on an e4m3 rounding boundary (rare). +__device__ __forceinline__ uint16_t quant_pair_fast(uint32_t w, unsigned long long inv2) { + float lo = __uint_as_float(w << 16), hi = __uint_as_float(w & 0xffff0000u); + uint16_t r; + asm("{\n\t.reg .b64 x, q;\n\t.reg .f32 a, b;\n\t" + "mov.b64 x, {%1, %2};\n\t" + "mul.rn.f32x2 q, x, %3;\n\t" + "mov.b64 {a, b}, q;\n\t" + "cvt.rn.satfinite.e4m3x2.f32 %0, b, a;\n\t}" // hi byte = b (element 2j+1), lo byte = a + : "=h"(r) : "f"(lo), "f"(hi), "l"(inv2)); + return r; +} +// 8 bf16 (one uint4) -> 8 fp8 (one uint2) +__device__ __forceinline__ uint2 quant8_fast(const uint4& a, unsigned long long inv2) { + uint2 o; + o.x = (uint32_t)quant_pair_fast(a.x, inv2) | ((uint32_t)quant_pair_fast(a.y, inv2) << 16); + o.y = (uint32_t)quant_pair_fast(a.z, inv2) | ((uint32_t)quant_pair_fast(a.w, inv2) << 16); + return o; +} +// 16 bf16 loaded as (first, second) 16-B halves; hsw = 1 means `first` holds the HIGH half (cols 8..15). +__device__ __forceinline__ uint4 quant16_fast(const uint4& first, const uint4& second, float inv, int hsw) { + const unsigned long long inv2 = pack2(inv); // lean: 4 codes per asm block + const uint32_t f0 = qword4(first.x, first.y, inv2), f1 = qword4(first.z, first.w, inv2); + const uint32_t s0 = qword4(second.x, second.y, inv2), s1 = qword4(second.z, second.w, inv2); + return hsw ? make_uint4(s0, s1, f0, f1) : make_uint4(f0, f1, s0, s1); +} + +// 16-B fp8 store with an L2 cache-policy hint (GEMM1 operands: evict_last so the next kernel reads them from L2). +__device__ __forceinline__ void st16_hint(void* p, const uint4& v, uint64_t pol) { + asm volatile("st.global.L2::cache_hint.v4.b32 [%0], {%1,%2,%3,%4}, %5;" + ::"l"(p), "r"(v.x), "r"(v.y), "r"(v.z), "r"(v.w), "l"(pol) : "memory"); +} + +// Weight path: one CTA per 128x128 block. tid -> (row r0 = tid>>3, 16-col chunk c = tid&7); +// pass i covers rows r0 + 32*i. All 4 x 32 B loads are in flight before the reduction. +__device__ __forceinline__ void weight_block(const QuantParams& P, int b) { + int si = 0; +#pragma unroll + for (int i = 1; i < 4; ++i) if (i < P.nseg && b >= P.s[i].nblk_start) si = i; + const WSeg& sg = P.s[si]; + const int lb = b - sg.nblk_start; + const int nkb = sg.K >> 7; + const int nb = udiv40(lb, sg.dvm), kb = lb - nb * nkb; + const int tid = threadIdx.x; + const int r0 = tid >> 3, c = (tid & 7) * 16; + const uint16_t* src = (const uint16_t*)sg.src + (size_t)(nb * 128 + r0) * sg.K + kb * 128 + c; + const size_t rstep = (size_t)32 * sg.K; // 32 rows between passes + uint4 va[4], vb[4]; + uint64_t pef; // read-once bf16 weights: L2 evict_first (energy / keeps the fp8 operands L2-resident) + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pef)); +#pragma unroll + for (int i = 0; i < 4; ++i) ld32_hint(src + i * rstep, va[i], vb[i], pef); + uint32_t acc = 0u; +#pragma unroll + for (int i = 0; i < 4; ++i) acc = amax16(va[i], vb[i], acc); + // shuffle diet: warp |max| via ONE redux.sync.max.u32 (non-negative non-NaN fp32 bits order like u32; exact) + uint32_t amu = __float_as_uint(bf2max_to_f(acc)); + asm volatile("redux.sync.max.u32 %0, %0, 0xffffffff;" : "+r"(amu)); + float amax = __uint_as_float(amu); + __shared__ float red[QTHREADS / 32]; + if ((tid & 31) == 0) red[tid >> 5] = amax; + __syncthreads(); + amax = red[0]; +#pragma unroll + for (int i = 1; i < QTHREADS / 32; ++i) amax = fmaxf(amax, red[i]); + const float s = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float inv = __fdividef(1.0f, s); // fast approx reciprocal (MUFU.RCP) + const size_t eoff = (size_t)(sg.row_off + nb * 128 + r0) * sg.K + kb * 128 + c; // element offset + if (kQuantF16 && sg.f16) { + uint16_t* dh = (uint16_t*)sg.dst + eoff; +#pragma unroll + const float sp = ldexpf(s, pre_exp(sg.amax)); // exact power-of-two prescale +#pragma unroll + for (int i = 0; i < 4; ++i) deq16_store(quant16(va[i], vb[i], s, inv), sp, dh + i * rstep); + } else { + uint8_t* dst = (uint8_t*)sg.dst + eoff; + uint64_t pel; // fp8 A weights: re-read by every GEMM1 m-tile -> L2 evict_last (cache policy only) + asm volatile("createpolicy.fractional.L2::" KPOL_LAST ".b64 %0, 1.0;" : "=l"(pel)); +#pragma unroll + for (int i = 0; i < 4; ++i) // pad rows (>= vrows) only contribute to the block amax: no code store + if (!sg.vrows || nb * 128 + r0 + 32 * i < sg.vrows) st16_hint(dst + i * rstep, quant16(va[i], vb[i], s, inv), pel); + } + if (tid == 0) sg.sf[kb * sg.ld_sf + (sg.row_off >> 7) + nb] = s; +} + +// Act path: CTA b owns groups [b*128, b*128+128) of the row-major [Mp, K/128] group grid, which +// is 32 KB of contiguous hidden_states (group g starts at element g*128 since K = 128*nkb). +// 8 lanes x 32 B per group; pass i handles groups b*128 + 32*i + (tid>>3). +__device__ __forceinline__ void act_block(const QuantParams& P, int b) { + const ActJob& A = P.a; + const int nkb = A.K >> 7; + const int total = A.Mp * nkb; // all groups (incl. zero padding rows) + const int valid = A.M * nkb; // groups backed by real input rows + const int tid = threadIdx.x, sub = tid & 7; + const uint16_t* x = (const uint16_t*)A.x; + uint64_t pef; // read-once bf16 activation: L2 evict_first + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pef)); + if (A.rev) b = P.nablk - 1 - b; // rev: high row blocks first, so GEMM1 (low -> high) starts on L2-hot rows + // Energy diet fast path (full tile: all 128 groups backed by real rows, fp8 output): no per-group bounds checks, + // one base pointer + compile-time pass offsets (32 groups = 8 KB per pass), scale index from one division. + // Same loads / math / stores as the generic path below (bit-identical). + if ((!kQuantF16 || !A.f16) && (b + 1) * ACT_GROUPS_PER_CTA <= valid) { + const int g0 = b * ACT_GROUPS_PER_CTA + (tid >> 3); + const uint16_t* src = x + (size_t)g0 * 128 + sub * 16; + uint8_t* dq = (uint8_t*)A.q + (size_t)g0 * 128 + sub * 16; + uint4 fa[4], fb[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) ld32_hint(src + i * 32 * 128, fa[i], fb[i], pef); + uint64_t pel; + asm volatile("createpolicy.fractional.L2::" KPOL_LAST ".b64 %0, 1.0;" : "=l"(pel)); + int m = 0, kb = 0; + if (sub == 0) { m = udiv40(g0, A.dvm); kb = g0 - m * nkb; } + // shuffle diet (as aqt_kernel): the 1x128 |max| is an exact bf16 value, so passes i (even) and i+1 share ONE + // bf16x2 word (lo = pass i, hi = pass i+1) -> 3 SHFL + 3 HMNMX2 per pass PAIR. Same max: bit-identical. + uint32_t pwp = 0u; +#pragma unroll + for (int i = 0; i < 4; ++i) { + if ((i & 1) == 0) { + const uint32_t a2 = amax16(fa[i], fb[i], 0u), b2 = amax16(fa[i + 1], fb[i + 1], 0u); + uint32_t pw = mxb2(__byte_perm(a2, b2, 0x5410), __byte_perm(a2, b2, 0x7632)); +#pragma unroll + for (int o = 4; o; o >>= 1) pw = mxb2(pw, __shfl_xor_sync(0xffffffffu, pw, o)); // 8-lane group + pwp = pw; + } + const float amax = (i & 1) ? __uint_as_float(pwp & 0xffff0000u) : __uint_as_float(pwp << 16); + const float s = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float inv = __fdividef(1.0f, s); + st16_hint(dq + i * 32 * 128, quant16(fa[i], fb[i], s, inv), pel); // fp8 act: read by all 9 GEMM1 n-tiles + if (sub == 0) { + A.sf[(size_t)kb * A.Mp + m] = s; + kb += 32; while (kb >= nkb) { kb -= nkb; ++m; } // group g + 32 (nkb >= 1) + } + } + return; + } + uint4 va[4], vb[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int g = b * ACT_GROUPS_PER_CTA + i * 32 + (tid >> 3); + va[i] = make_uint4(0u, 0u, 0u, 0u); vb[i] = va[i]; + if (g < valid) ld32_hint(x + (size_t)g * 128 + sub * 16, va[i], vb[i], pef); + } +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int g = b * ACT_GROUPS_PER_CTA + i * 32 + (tid >> 3); + float amax = bf2max_to_f(amax16(va[i], vb[i], 0u)); +#pragma unroll + for (int o = 4; o; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); // 8-lane group + const float s = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float inv = __fdividef(1.0f, s); // fast approx reciprocal (MUFU.RCP) + if (g < total) { + const uint4 qv = quant16(va[i], vb[i], s, inv); + if (kQuantF16 && A.f16) deq16_store(qv, ldexpf(s, pre_exp(A.amax)), (uint16_t*)A.q + (size_t)g * 128 + sub * 16); + else *(uint4*)((uint8_t*)A.q + (size_t)g * 128 + sub * 16) = qv; + if (sub == 0) { + const int m = udiv40(g, A.dvm), kb = g - m * nkb; + A.sf[(size_t)kb * A.Mp + m] = s; + } + } + } +} + +// Flat grid: CTAs [0, nwblk) are weight blocks, [nwblk, nwblk+nablk) are activation chunks. +// __launch_bounds__(256,4): <=64 regs so >=32 warps (4+ CTAs) stay resident per SM. +__global__ void __launch_bounds__(QTHREADS, 4) quant_kernel(const __grid_constant__ QuantParams P) { + int b = blockIdx.x; + TLG_S(8); + if (kQuantF16 && P.alpha && b == 0 && threadIdx.x == 0) // epilogue factor undoing both fp16 operand prescales (exact) + *P.alpha = ldexpf(1.0f, -(pre_exp(P.s[0].amax) + pre_exp(P.a.amax))); + if (P.g1cnt && b == 0) + for (int i = threadIdx.x; i < P.ng1cnt; i += blockDim.x) P.g1cnt[i] = 0u; // reset per replay + if (P.acnt) { + // early mode: make block 0's resets visible, then let the GEMM1 dependent launch once every CTA got here + if (b == 0) __threadfence(); + __syncthreads(); + asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); + } + if (!P.acnt) asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); + if (b < P.nwblk) weight_block(P, b); + else act_block(P, b - P.nwblk); + TLG_E(8); + if (P.acnt) { + // publish this CTA's fp8 codes + scales (all threads' stores fenced, then one release add) + __threadfence(); + __syncthreads(); + if (threadIdx.x == 0) { + unsigned* c; + if (b < P.nwblk) c = P.wdn; + else { + int ab = b - P.nwblk; + if (P.a.rev) ab = P.nablk - 1 - ab; + c = P.acnt + (unsigned)udiv40(ab, P.a.dvm); // 128 rows = (K/128) act CTAs of 128 groups + } + asm volatile("red.release.gpu.global.add.u32 [%0], %1;" ::"l"(c), "r"(1u) : "memory"); + } + } + // (the former end-of-CTA trigger moved to entry, see above; a repeated launch_dependents would be a no-op) +} + +// Global |max| of bf16 tensors (fp16 fake-quant prescale): grid-stride 32 B loads, bf16x2 max, warp redux, +// one atomicMax (u32 order == float order for non-negative floats) per warp. Tensor t: x (t = 0) or w0|w1 (t = 1). +__global__ void __launch_bounds__(256) amax_kernel(const uint16_t* __restrict__ x, size_t n0, const uint16_t* __restrict__ w0, + size_t n1, const uint16_t* __restrict__ w1, size_t n2, unsigned* out) { + const size_t c0 = n0 / 16, c1 = n1 / 16, c2 = n2 / 16; // 16-element chunks + uint32_t ax = 0u, aw = 0u; + for (size_t c = (size_t)blockIdx.x * blockDim.x + threadIdx.x; c < c0 + c1 + c2; c += (size_t)gridDim.x * blockDim.x) { + uint4 a, b; + if (c < c0) { ld32(x + c * 16, a, b); ax = amax16(a, b, ax); } + else if (c < c0 + c1) { ld32(w0 + (c - c0) * 16, a, b); aw = amax16(a, b, aw); } + else { ld32(w1 + (c - c0 - c1) * 16, a, b); aw = amax16(a, b, aw); } + } + uint32_t mx = __float_as_uint(bf2max_to_f(ax)), mw = __float_as_uint(bf2max_to_f(aw)); + asm volatile("redux.sync.max.u32 %0, %0, 0xffffffff;" : "+r"(mx)); + asm volatile("redux.sync.max.u32 %0, %0, 0xffffffff;" : "+r"(mw)); + if ((threadIdx.x & 31) == 0) { + if (mx) atomicMax(out, mx); + if (mw) atomicMax(out + 1, mw); + } +} + +void launch_amax(const void* x, size_t n0, const void* w0, size_t n1, const void* w1, size_t n2, unsigned* out, cudaStream_t st) { + cudaMemsetAsync(out, 0, 2 * sizeof(unsigned), st); + amax_kernel<<<148 * 8, 256, 0, st>>>((const uint16_t*)x, n0, (const uint16_t*)w0, n1, (const uint16_t*)w1, n2, out); +} + +// Chunked large-M pipeline: activation-only 1x128 quant of one M-chunk as a persistent grid-stride launch over the +// act_block() jobs (same math/layout as quant_kernel), capped at `ctas` CTAs so it runs on a small SM partition next +// to the (SM-capped) GEMM1 of the previous chunk. +__global__ void __launch_bounds__(QTHREADS, 4) act_loop_kernel(const __grid_constant__ QuantParams P) { + for (int b = blockIdx.x; b < P.nablk; b += gridDim.x) act_block(P, b); +} +void launch_act_capped(const ActJob* act, int ctas, cudaStream_t st) { + QuantParams P; + memset(&P, 0, sizeof(P)); + P.a = *act; + P.a.dvm = dvm40((unsigned)(act->K >> 7)); + const long groups = (long)act->Mp * (act->K / 128); + P.nablk = (int)((groups + ACT_GROUPS_PER_CTA - 1) / ACT_GROUPS_PER_CTA); + const int grid = ctas < P.nablk ? ctas : P.nablk; + act_loop_kernel<<>>(P); +} + +void launch_quant(const WSeg* segs, int nseg, int total_wblocks, const ActJob* act, cudaStream_t st, float* alpha) { + QuantParams P; + if (!kQuantF16) { + bool f = act && act->f16; + for (int i = 0; i < nseg; ++i) f |= segs[i].f16 != 0; + if (f) { fprintf(stderr, "launch_quant: fp16 fake-quant path compiled out\n"); return; } + } + P.alpha = alpha; + P.g1cnt = g_q_g1cnt; P.ng1cnt = g_q_ng1cnt; + P.acnt = act ? g_q_acnt : nullptr; P.wdn = g_q_wdn; + P.nseg = nseg; + for (int i = 0; i < nseg; ++i) { P.s[i] = segs[i]; P.s[i].dvm = dvm40((unsigned)(segs[i].K >> 7)); } + P.nwblk = total_wblocks; + P.nablk = 0; + if (act) { + P.a = *act; + P.a.dvm = dvm40((unsigned)(act->K >> 7)); + long groups = (long)act->Mp * (act->K / 128); + P.nablk = (int)((groups + ACT_GROUPS_PER_CTA - 1) / ACT_GROUPS_PER_CTA); + } + quant_kernel<<>>(P); +} + + +// Hardening: predecessor outputs (y1 / split-K partials) are read with VOLATILE ld.global.cg asm + "memory" clobber. +// CUDA's __ldcg is a non-volatile asm without a memory operand, which the compiler may legally hoist above the +// griddepcontrol.wait / counter-poll __syncthreads (readnone asm). Same instruction, same bytes: bit-identical. +__device__ __forceinline__ float4 ldcg_f4v(const float4* p) { + float4 r; + asm volatile("ld.global.cg.v4.f32 {%0,%1,%2,%3}, [%4];" : "=f"(r.x), "=f"(r.y), "=f"(r.z), "=f"(r.w) : "l"(p) : "memory"); + return r; +} +__device__ __forceinline__ uint4 ldcg_u4v(const uint4* p) { + uint4 r; + asm volatile("ld.global.cg.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(r.x), "=r"(r.y), "=r"(r.z), "=r"(r.w) : "l"(p) : "memory"); + return r; +} +// 256-bit (8 x fp32) coherent load of a predecessor output (sm_100 ld.global.v8), same bytes as two ldcg_f4v. +__device__ __forceinline__ void ldcg_f8v(const float* p, float4& a, float4& b) { + asm volatile("ld.global.cg.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) : "memory"); +} +// Vectorized partial-sum read (norm kernels): the 8 per-warp row sums of a row (16-B aligned smem) are fetched with +// two broadcast LDS.128 instead of 6 (q_a) / 2 (kv) scalar LDS; the summation order is unchanged +// (q_a: ((((p0+p1)+p2)+p3)+p4)+p5, kv: p6+p7): bit-identical. +__device__ __forceinline__ float row_tot8(const float* p, bool isq) { + const float4 a = *reinterpret_cast(p), b = *reinterpret_cast(p + 4); + return isq ? ((((a.x + a.y) + a.z) + a.w) + b.x) + b.y : b.z + b.w; +} +template +__global__ void __launch_bounds__(288) norm_quant_kernel(uint16_t* __restrict__ y1, int ldy, + const float* __restrict__ part, int nsplit, size_t pstride, + const uint16_t* __restrict__ wq, + const uint16_t* __restrict__ wkv, + uint8_t* __restrict__ qq, float* __restrict__ qs, + uint8_t* __restrict__ kq, float* __restrict__ ks, + float eps, int Mp, int rev, int late, + unsigned long long* __restrict__ epoch) { + // PDL trigger: a programmatic-dependent successor (M=128: the combined q_b+kv_b gq launch) may be scheduled now; + // it runs only its prologue and then griddepcontrol.wait's for THIS grid's completion before reading any output. + // late != 0: trigger only after this CTA's final stores (end of kernel) so dependents do not occupy SM slots early. + if (!late) PDL_TRIGGER(); + TLG_S(2); + // Latency diet: the RMSNorm weight slice (a model input, never written by a predecessor grid) is loaded BEFORE the + // PDL wait, so its L2 round trip overlaps the predecessor's tail instead of following the row-sum __syncthreads. + uint4 wv_pre = make_uint4(0u, 0u, 0u, 0u); + if (threadIdx.x < 256) { + const int c0 = (int)threadIdx.x * 8; + wv_pre = __ldg((const uint4*)(threadIdx.x < 192 ? wq + c0 : wkv + (c0 - 1536))); + } + pdl_wait(); // PDL: GEMM1 output (y1 / split partials) complete and visible (no-op without a PDL launch) + // predecessor outputs are read with ld.global.cg (coherent; an ld.global.nc may be scheduled above the wait) + TLG_S(3); + // Per-graph-replay epoch (small-M B-quant join removal, wq bit18): exactly one increment per replay; the dependent + // gq launch reads it after its griddepcontrol.wait and waits for the wquant completion counter >= epoch * nwblk. + if (epoch && blockIdx.x == 0 && threadIdx.x == 0) { atomicAdd(epoch, 1ull); epoch[2] = 0ull; epoch[3] = 0ull; } // epoch[2] / [3]: GV_DYN claim counters (reset per replay) + const int row = rev ? (int)(gridDim.x - 1 - blockIdx.x) : (int)blockIdx.x; // rev: GEMM1's last-written rows first + const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31; + const int col = tid * 8; // 0..2047 (norm part), 2048..ldy-1 for warp 8 (k_pe) + const bool active = col < ldy; + float f[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) f[j] = 0.f; + if (SPLIT) { + if (active) { + const float* p0 = part + (size_t)row * ldy + col; + float4 a, c; + if constexpr (NS > 0) { + float4 xa[NS], xc[NS]; +#pragma unroll + for (int sp = 0; sp < NS; ++sp) // one 256-bit load per split (32-B aligned: ldy, col, pstride % 8 == 0) + ldcg_f8v(p0 + sp * pstride, xa[sp], xc[sp]); + a = xa[0]; c = xc[0]; +#pragma unroll + for (int sp = 1; sp < NS; ++sp) { // same summation order as the generic loop + a.x += xa[sp].x; a.y += xa[sp].y; a.z += xa[sp].z; a.w += xa[sp].w; + c.x += xc[sp].x; c.y += xc[sp].y; c.z += xc[sp].z; c.w += xc[sp].w; + } + } else { + a = ldcg_f4v((const float4*)p0); c = ldcg_f4v((const float4*)(p0 + 4)); + for (int sp = 1; sp < nsplit; ++sp) { + const float* p = p0 + sp * pstride; + float4 x = ldcg_f4v((const float4*)p), y = ldcg_f4v((const float4*)(p + 4)); + a.x += x.x; a.y += x.y; a.z += x.z; a.w += x.w; + c.x += y.x; c.y += y.y; c.z += y.z; c.w += y.w; + } + } + const float v[8] = {a.x, a.y, a.z, a.w, c.x, c.y, c.z, c.w}; + uint32_t hb[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + __nv_bfloat162 h = __floats2bfloat162_rn(v[2 * j], v[2 * j + 1]); + hb[j] = *reinterpret_cast(&h); + f[2 * j] = bf2f((uint16_t)(hb[j] & 0xffffu)); + f[2 * j + 1] = bf2f((uint16_t)(hb[j] >> 16)); + } + if (warp == 8) *(uint4*)(y1 + (size_t)row * ldy + col) = make_uint4(hb[0], hb[1], hb[2], hb[3]); + } + } else { + if (tid < 256) { + uint4 v = ldcg_u4v((const uint4*)(y1 + (size_t)row * ldy + col)); + const uint32_t w[4] = {v.x, v.y, v.z, v.w}; +#pragma unroll + for (int j = 0; j < 4; ++j) { f[2 * j] = bf2f((uint16_t)(w[j] & 0xffffu)); f[2 * j + 1] = bf2f((uint16_t)(w[j] >> 16)); } + } + } + // k_pe warp 8 needs no row sum (its partsum slot is never read): skip its reduction (warp-uniform branch) + __shared__ __align__(16) float partsum[12]; + if (warp < 8) { + float ss = 0.f; +#pragma unroll + for (int j = 0; j < 8; ++j) ss += f[j] * f[j]; +#pragma unroll + for (int o = 16; o; o >>= 1) ss += __shfl_xor_sync(0xffffffffu, ss, o); + if (lane == 0) partsum[warp] = ss; + } + __syncthreads(); + if (warp >= 8) { if (late) PDL_TRIGGER(); return; } // k_pe warp done (its y1 store is issued) + const bool isq = warp < 6; + const float tot = row_tot8(partsum, isq); + const float D = isq ? 1536.f : 512.f; + const float r = rsqrtf(tot * (1.0f / D) + eps); // torch mean = sum * (1/D) + const int lc = isq ? col : col - 1536; // column inside q_a / compressed_kv + const uint4 wv = wv_pre; // hoisted above pdl_wait (same 16 B of the norm weight) + const uint32_t ww[4] = {wv.x, wv.y, wv.z, wv.w}; + uint32_t hb[4]; + uint32_t am = 0u; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float w0 = bf2f((uint16_t)(ww[j] & 0xffffu)), w1 = bf2f((uint16_t)(ww[j] >> 16)); + // lean: (x * r) * w as two packed FMUL2 (mul.rn.f32x2 == two IEEE mul.rn, same order): bit-identical + const float2 t2 = __fmul2_rn(__fmul2_rn(make_float2(f[2 * j], f[2 * j + 1]), make_float2(r, r)), make_float2(w0, w1)); + __nv_bfloat162 t = __floats2bfloat162_rn(t2.x, t2.y); + hb[j] = *reinterpret_cast(&t); + am = mxa2(am, hb[j]); + } + float amax = bf2max_to_f(am & 0x7fff7fffu); +#pragma unroll + for (int o = 8; o; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); // 16-lane group + const float s = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float sinv = __fdividef(1.0f, s); // fast approx reciprocal (MUFU.RCP) // relaxed: x * (1/s) (satfinite cvt clamps to +-448) instead of IEEE x/s per element + const unsigned long long sinv2 = pack2(sinv); + uint2 o; + o.x = qword4(hb[0], hb[1], sinv2); // lean 4-code asm (same x * (1/s), RN satfinite) + o.y = qword4(hb[2], hb[3], sinv2); + const int blk = lc >> 7; + // hoisted output selection (q_a or compressed_kv half): one pointer per array, no store branch + uint8_t* op = isq ? qq + (size_t)row * 1536 : kq + (size_t)row * 512; + float* sp = isq ? qs : ks; + *(uint2*)(op + lc) = o; + if ((lane & 15) == 0) sp[(size_t)blk * Mp + row] = s; + if (late) PDL_TRIGGER(); // final stores issued + TLG_E(2); TLG_E(3); +} + +// ---- norm_fast_kernel (non-split path, table column nq): same RMSNorm + 1x128 requant math as +// norm_quant_kernel, restructured because the 1-row-per-CTA kernel was issue/latency bound (8 IEEE divisions +// per thread, one CTA-wide sync per 2112-element row): +// * one CTA (256 threads, thread -> 8 contiguous columns, warps 0-5 q_a / 6-7 compressed_kv as before) owns R rows; +// all R x 16 B y1 loads (+ one 16 B norm-weight load shared by the R rows) are issued before any math; +// * one __syncthreads for the R row sums (same per-row reduction order as norm_quant_kernel); +// * normed values rounded to bf16 pairwise (RN per element, == __float2bfloat16_rn), 16-lane bf16x2 amax, and the +// quotient x/s via packed rcp + FMA residual correction (quant_pair, as in quant_kernel), e4m3 satfinite +// (== clamp to +-448 then RNE). +// MB: __launch_bounds__ min blocks per SM (1 = default register allocation; 6 / 8 cap registers at 40 / 32 so more +// row blocks are in flight per SM: the large-M norm runs latency-bound behind GEMM1). Same code / math. +// LV = 1 (lean): register / instruction diet with the same math (bit-identical): the R x 8 fp32 row values are NOT +// kept live across the row-sum __syncthreads (only the R x 16 B bf16 loads are; they are re-unpacked after the sync: +// 16 instead of 32 live registers per thread), x*r*w runs as two packed FMUL2 per bf16 pair (mul.rn.f32x2 == two +// IEEE mul.rn, same order (x*r)*w), and the 1x128 |max| of rows i, i+1 (exact bf16 values) are packed into ONE +// bf16x2 word -> 4 SHFL + 4 HMNMX2 per row PAIR instead of 4 SHFL + 4 FMNMX per row. +template +__global__ void __launch_bounds__(256, MB) norm_fast_kernel(const uint16_t* __restrict__ y1, int ldy, + const uint16_t* __restrict__ wq, const uint16_t* __restrict__ wkv, + uint8_t* __restrict__ qq, float* __restrict__ qs, + uint8_t* __restrict__ kq, float* __restrict__ ks, + float eps, int Mp, int rows, int rev, int etrig, + const unsigned* __restrict__ mcnt, unsigned mtgt, + unsigned long long* __restrict__ epoch) { + // mcnt != nullptr (large M, wq bit19): row-block-granular dependency on GEMM1 instead of griddepcontrol.wait on the + // whole GEMM1 grid. GEMM1's store warp release-adds 1 to mcnt[m0/128] after each of its 128-row x 256-col output tiles + // has fully landed in global memory (mtgt = number of n-tiles); this CTA acquire-polls the counter of its 4 rows and + // then reads y1 through L2 (ld.global.cg). So the norm overlaps GEMM1's last-wave tail on the SMs whose GEMM1 + // clusters already retired. Same math, bit-identical outputs. + TLG_S(9); + NTP(8192); +#ifdef TLG_PROBE + unsigned long long nfp_t0 = tlg_now(); int nfp_it = 0; +#endif + // Latency diet: norm-weight slice (model input, not produced by any predecessor) loaded before the PDL wait / + // row-block counter poll, so it is off the GEMM1 -> norm critical path. Same 16 B per thread as before. + const uint4 wv = __ldg((const uint4*)(threadIdx.x < 192 ? wq + threadIdx.x * 8 : wkv + (threadIdx.x * 8 - 1536))); + if (!mcnt) pdl_wait(); + // etrig (mid M, wq bit16): trigger right after the wait (q_b PDL dependent may be scheduled early; it still + // griddepcontrol.wait's for this grid's completion before reading qq / qs). + if (etrig) asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); + // Per-replay epoch (mid M, wq bit18 with the SM-capped side-stream B wquant): one increment per launch; the dependent + // gq launches read it after griddepcontrol.wait (this grid complete) and wait for the wquant counter >= epoch * jobs. + if (epoch && blockIdx.x == 0 && threadIdx.x == 0) { atomicAdd(epoch, 1ull); epoch[2] = 0ull; epoch[3] = 0ull; } // epoch[2] / [3]: GV_DYN claim counters (reset per replay) + const int rb = rev ? (int)(gridDim.x - 1 - blockIdx.x) : (int)blockIdx.x; // rev: high row blocks first + const int row0 = rb * R; + const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31; + if (mcnt) { + if (tid == 0) { + const unsigned* c = mcnt + (row0 >> 7); + unsigned v, ns = 32; + for (;;) { + asm volatile("ld.acquire.gpu.global.u32 %0, [%1];" : "=r"(v) : "l"(c) : "memory"); + if (v >= mtgt) break; +#ifdef TLG_PROBE + ++nfp_it; +#endif + __nanosleep(ns); + } + } + __syncthreads(); + } + TLG_S(12); +#ifdef TLG_PROBE + const unsigned long long nfp_t1 = tlg_now(); +#endif + const int col = tid * 8; + const bool isq = warp < 6; + const int lc = isq ? col : col - 1536; + // Energy diet: full row block (all R rows valid, every CTA but possibly the last) -> no per-row bounds predicates; + // one base pointer advanced by ldy per row. Same loads / math / stores as the guarded path (bit-identical). + const bool full = row0 + R <= rows; + uint4 v[R]; + const uint16_t* yp = y1 + (size_t)row0 * ldy + col; + if (full) { + if (mcnt) { +#pragma unroll + for (int i = 0; i < R; ++i) v[i] = ldcg_u4v((const uint4*)(yp + (size_t)i * ldy)); + } else { +#pragma unroll + for (int i = 0; i < R; ++i) v[i] = ldcg_u4v((const uint4*)(yp + (size_t)i * ldy)); + } + } else { +#pragma unroll + for (int i = 0; i < R; ++i) { + v[i] = make_uint4(0u, 0u, 0u, 0u); + if (row0 + i < rows) + v[i] = ldcg_u4v((const uint4*)(yp + (size_t)i * ldy)); + } + } + __shared__ __align__(16) float partsum[R][8]; + float f[LV ? 1 : R][8]; + constexpr bool TRW = LV != 0 && (R == 2 || R == 4); // transposed row-sum butterfly (see below) + float ssv[R]; + (void)ssv; +#pragma unroll + for (int i = 0; i < R; ++i) { + const uint32_t w[4] = {v[i].x, v[i].y, v[i].z, v[i].w}; + float* fi = f[LV ? 0 : i]; +#pragma unroll + for (int j = 0; j < 4; ++j) { fi[2 * j] = bf2f((uint16_t)(w[j] & 0xffffu)); fi[2 * j + 1] = bf2f((uint16_t)(w[j] >> 16)); } + float ss = 0.f; +#pragma unroll + for (int j = 0; j < 8; ++j) ss += fi[j] * fi[j]; + if constexpr (TRW) { ssv[i] = ss; continue; } // reduced below with the transposed butterfly +#pragma unroll + for (int o = 16; o; o >>= 1) ss += __shfl_xor_sync(0xffffffffu, ss, o); + if (lane == 0) partsum[i][warp] = ss; + } + if constexpr (TRW) { + const int b4 = (lane >> 4) & 1; + float k; + if constexpr (R == 4) { + float k0 = b4 ? ssv[2] : ssv[0], k1 = b4 ? ssv[3] : ssv[1]; + const float s0 = b4 ? ssv[0] : ssv[2], s1 = b4 ? ssv[1] : ssv[3]; + k0 += __shfl_xor_sync(0xffffffffu, s0, 16); + k1 += __shfl_xor_sync(0xffffffffu, s1, 16); + const int b3 = (lane >> 3) & 1; + k = b3 ? k1 : k0; + const float s2 = b3 ? k0 : k1; + k += __shfl_xor_sync(0xffffffffu, s2, 8); +#pragma unroll + for (int o = 4; o; o >>= 1) k += __shfl_xor_sync(0xffffffffu, k, o); + if ((lane & 7) == 0) partsum[lane >> 3][warp] = k; + } else { + k = b4 ? ssv[1] : ssv[0]; + const float s0 = b4 ? ssv[0] : ssv[1]; + k += __shfl_xor_sync(0xffffffffu, s0, 16); +#pragma unroll + for (int o = 8; o; o >>= 1) k += __shfl_xor_sync(0xffffffffu, k, o); + if ((lane & 15) == 0) partsum[lane >> 4][warp] = k; + } + } + __syncthreads(); + const uint32_t ww[4] = {wv.x, wv.y, wv.z, wv.w}; + float wj[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) wj[j] = bf2f((uint16_t)((j & 1) ? (ww[j >> 1] >> 16) : (ww[j >> 1] & 0xffffu))); + const float D = isq ? 1536.f : 512.f; + const float invD = 1.0f / D; + const int blk = lc >> 7; + // hoisted output pointers (q_a or compressed_kv half); advanced by one row per iteration + uint8_t* op = isq ? qq + (size_t)row0 * 1536 + lc : kq + (size_t)row0 * 512 + lc; + const int opitch = isq ? 1536 : 512; + float* sp = (isq ? qs : ks) + (size_t)blk * Mp + row0; + const bool wsc = (lane & 15) == 0; + if constexpr (LV != 0) { + static_assert(R % 2 == 0, "lean norm pairs rows"); + float2 w2[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) w2[j] = make_float2(wj[2 * j], wj[2 * j + 1]); +#pragma unroll + for (int i = 0; i < R; i += 2) { + uint32_t hb[2][4]; + uint32_t am[2]; +#pragma unroll + for (int h = 0; h < 2; ++h) { + const float tot = row_tot8(partsum[i + h], isq); + const float r = rsqrtf(tot * invD + eps); + const float2 r2 = make_float2(r, r); + const uint32_t w[4] = {v[i + h].x, v[i + h].y, v[i + h].z, v[i + h].w}; // re-unpack (same bf16 bits) +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float2 x = make_float2(__uint_as_float(w[j] << 16), __uint_as_float(w[j] & 0xffff0000u)); + const float2 t2 = __fmul2_rn(__fmul2_rn(x, r2), w2[j]); // (x * r) * w per element, IEEE RN + __nv_bfloat162 t = __floats2bfloat162_rn(t2.x, t2.y); + hb[h][j] = *reinterpret_cast(&t); + } + const uint32_t a = mxa2(mxa2(hb[h][0], hb[h][1]), mxa2(hb[h][2], hb[h][3])) & 0x7fff7fffu; + am[h] = a; + } + // per-row max of the two halves, rows i (lo) and i+1 (hi) in one word, then the 16-lane group max + uint32_t pw = mxb2(__byte_perm(am[0], am[1], 0x5410), __byte_perm(am[0], am[1], 0x7632)); +#pragma unroll + for (int o = 8; o; o >>= 1) pw = mxb2(pw, __shfl_xor_sync(0xffffffffu, pw, o)); +#pragma unroll + for (int h = 0; h < 2; ++h) { + const float amax = h ? __uint_as_float(pw & 0xffff0000u) : __uint_as_float(pw << 16); + const float s = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float inv = __fdividef(1.0f, s); + const unsigned long long inv2 = pack2(inv); + uint2 o; + o.x = qword4(hb[h][0], hb[h][1], inv2); + o.y = qword4(hb[h][2], hb[h][3], inv2); + if (full || row0 + i + h < rows) { + *(uint2*)(op + (size_t)(i + h) * opitch) = o; + if (wsc) sp[i + h] = s; + } + } + } + } else { +#pragma unroll + for (int i = 0; i < R; ++i) { + const float tot = row_tot8(partsum[i], isq); + const float r = rsqrtf(tot * invD + eps); + uint32_t hb[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + __nv_bfloat162 t = __floats2bfloat162_rn((f[i][2 * j] * r) * wj[2 * j], (f[i][2 * j + 1] * r) * wj[2 * j + 1]); + hb[j] = *reinterpret_cast(&t); + } + // instruction diet: balanced max.xorsign.abs tree (exact |max| per half, signs garbage) + ONE sign mask + // (3 HMNMX2 + 1 LOP per row instead of 4 LOP + 4 HMNMX2 in a serial chain); same amax value. + const uint32_t am = mxa2(mxa2(hb[0], hb[1]), mxa2(hb[2], hb[3])) & 0x7fff7fffu; + float amax = bf2max_to_f(am); +#pragma unroll + for (int o = 8; o; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); // 16-lane group + const float s = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float inv = __fdividef(1.0f, s); // fast approx reciprocal (MUFU.RCP) + const unsigned long long inv2 = pack2(inv), ns2 = pack2(-s); + uint2 o; + (void)ns2; + o.x = qword4(hb[0], hb[1], inv2); // lean 4-code asm + o.y = qword4(hb[2], hb[3], inv2); + if (full || row0 + i < rows) { + *(uint2*)(op + (size_t)i * opitch) = o; + if (wsc) sp[i] = s; + } + } + } + TLG_E(9); TLG_E(12); + NTP(0); +#ifdef TLG_PROBE + if (tid == 0 && g_tlg) { + const unsigned long long t2 = tlg_now(); + atomicAdd(g_tlg + 80, nfp_t1 - nfp_t0); atomicAdd(g_tlg + 81, t2 - nfp_t1); atomicAdd(g_tlg + 82, 1ull); + if (nfp_it == 0) { atomicAdd(g_tlg + 83, 1ull); atomicAdd(g_tlg + 84, t2 - nfp_t1); } + atomicMax(g_tlg + 85, t2 - nfp_t1); + } +#endif + // Late PDL trigger (after this CTA's last row block): q_b (wq bit7/bit12) may be scheduled; it still + // griddepcontrol.wait's for this grid's completion before reading qq / qs. + asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); +} + +#if defined(TLG_PROBE) || defined(FX_PROBE) +template static void nf_attr(char* b, int n, const char* nm, K k) { + cudaFuncAttributes a; cudaFuncGetAttributes(&a, k); + int nb = 0; cudaOccupancyMaxActiveBlocksPerMultiprocessor(&nb, k, 256, 0); + snprintf(b, n, " %s:%dr/%zuL/%db", nm, a.numRegs, a.localSizeBytes, nb); +} +std::string nf_regs_all() { + std::string r; char b[96]; + nf_attr(b, 96, "4,1", norm_fast_kernel<4, 1>); r += b; nf_attr(b, 96, "4,4", norm_fast_kernel<4, 4>); r += b; nf_attr(b, 96, "4,5", norm_fast_kernel<4, 5>); r += b; + nf_attr(b, 96, "4,6", norm_fast_kernel<4, 6>); r += b; nf_attr(b, 96, "4,8", norm_fast_kernel<4, 8>); r += b; + nf_attr(b, 96, "8,1", norm_fast_kernel<8, 1>); r += b; nf_attr(b, 96, "8,3", norm_fast_kernel<8, 3>); r += b; + nf_attr(b, 96, "8,4", norm_fast_kernel<8, 4>); r += b; nf_attr(b, 96, "2,1", norm_fast_kernel<2, 1>); r += b; + nf_attr(b, 96, "2,8", norm_fast_kernel<2, 8>); r += b; + nf_attr(b, 96, "L4,1", norm_fast_kernel<4, 1, 1>); r += b; nf_attr(b, 96, "L4,4", norm_fast_kernel<4, 4, 1>); r += b; + nf_attr(b, 96, "L4,5", norm_fast_kernel<4, 5, 1>); r += b; nf_attr(b, 96, "L4,6", norm_fast_kernel<4, 6, 1>); r += b; + nf_attr(b, 96, "L8,1", norm_fast_kernel<8, 1, 1>); r += b; nf_attr(b, 96, "L8,3", norm_fast_kernel<8, 3, 1>); r += b; + return r; +} +#endif + +// ---- norm_pers_kernel (large M, row-gated by the GEMM1 tile counters): persistent variant of +// norm_fast_kernel. A fixed grid (<= MB CTAs per SM) claims R-row blocks in ascending order with one atomic +// per block (claim counter zeroed by the A+act quant every replay) and software-pipelines them: while block i is +// normalized / quantized, the counter poll and the y1 loads of block i+1 are already in flight, and there is no +// per-block CTA launch / prologue (norm-weight load once per CTA). Per-row math and reduction order identical to +// norm_fast_kernel: bit-identical outputs. +template +__global__ void __launch_bounds__(256, MB) norm_pers_kernel(const uint16_t* __restrict__ y1, int ldy, + const uint16_t* __restrict__ wq, const uint16_t* __restrict__ wkv, + uint8_t* __restrict__ qq, float* __restrict__ qs, + uint8_t* __restrict__ kq, float* __restrict__ ks, + float eps, int Mp, int rows, + const unsigned* __restrict__ mcnt, unsigned mtgt, + unsigned* __restrict__ claim, int nblk) { + static_assert(R % 2 == 0, "rows paired"); + const uint4 wv = __ldg((const uint4*)(threadIdx.x < 192 ? wq + threadIdx.x * 8 : wkv + (threadIdx.x * 8 - 1536))); + const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31; + __shared__ int s_rb[2]; + __shared__ __align__(16) float partsum[2][R][8]; + auto claim_poll = [&]() -> int { // thread 0 only + const int rb = (int)atomicAdd(claim, 1u); + if (rb < nblk) { + const unsigned* c = mcnt + ((rb * R) >> 7); + unsigned v; + for (;;) { + asm volatile("ld.acquire.gpu.global.u32 %0, [%1];" : "=r"(v) : "l"(c) : "memory"); + if (v >= mtgt) break; + __nanosleep(32); + } + } + return rb; + }; + if (tid == 0) s_rb[0] = claim_poll(); + __syncthreads(); + int rb = s_rb[0]; + const int col = tid * 8; + const bool isq = warp < 6; + const int lc = isq ? col : col - 1536; + uint4 v[R]; + auto load = [&](int b, uint4 (&d)[R]) { + const int r0 = b * R; + const uint16_t* yp = y1 + (size_t)r0 * ldy + col; +#pragma unroll + for (int i = 0; i < R; ++i) { + d[i] = make_uint4(0u, 0u, 0u, 0u); + if (r0 + i < rows) d[i] = ldcg_u4v((const uint4*)(yp + (size_t)i * ldy)); + } + }; + if (rb < nblk) load(rb, v); + const uint32_t ww[4] = {wv.x, wv.y, wv.z, wv.w}; + float2 w2[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) w2[j] = make_float2(bf2f((uint16_t)(ww[j] & 0xffffu)), bf2f((uint16_t)(ww[j] >> 16))); + const float D = isq ? 1536.f : 512.f; + const float invD = 1.0f / D; + const int blk = lc >> 7; + const int opitch = isq ? 1536 : 512; + const bool wsc = (lane & 15) == 0; +#pragma unroll 1 + for (int it = 0; rb < nblk; ++it) { + const int b = it & 1; + if (tid == 0) s_rb[b ^ 1] = claim_poll(); // next block: claim + readiness poll overlap this block's loads +#pragma unroll + for (int i = 0; i < R; ++i) { + const uint32_t w[4] = {v[i].x, v[i].y, v[i].z, v[i].w}; + float ss = 0.f; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float lo = bf2f((uint16_t)(w[j] & 0xffffu)), hi = bf2f((uint16_t)(w[j] >> 16)); + ss += lo * lo; + ss += hi * hi; + } +#pragma unroll + for (int o = 16; o; o >>= 1) ss += __shfl_xor_sync(0xffffffffu, ss, o); + if (lane == 0) partsum[b][i][warp] = ss; + } + __syncthreads(); + const int rn = s_rb[b ^ 1]; + uint4 vn[R]; + if (rn < nblk) load(rn, vn); + const int row0 = rb * R; + uint8_t* op = isq ? qq + (size_t)row0 * 1536 + lc : kq + (size_t)row0 * 512 + lc; + float* sp = (isq ? qs : ks) + (size_t)blk * Mp + row0; +#pragma unroll + for (int i = 0; i < R; i += 2) { + uint32_t hb[2][4]; + uint32_t am[2]; +#pragma unroll + for (int h = 0; h < 2; ++h) { + const float tot = row_tot8(partsum[b][i + h], isq); + const float r = rsqrtf(tot * invD + eps); + const float2 r2 = make_float2(r, r); + const uint32_t w[4] = {v[i + h].x, v[i + h].y, v[i + h].z, v[i + h].w}; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float2 x = make_float2(__uint_as_float(w[j] << 16), __uint_as_float(w[j] & 0xffff0000u)); + const float2 t2 = __fmul2_rn(__fmul2_rn(x, r2), w2[j]); + __nv_bfloat162 t = __floats2bfloat162_rn(t2.x, t2.y); + hb[h][j] = *reinterpret_cast(&t); + } + am[h] = mxa2(mxa2(hb[h][0], hb[h][1]), mxa2(hb[h][2], hb[h][3])) & 0x7fff7fffu; + } + uint32_t pw = mxb2(__byte_perm(am[0], am[1], 0x5410), __byte_perm(am[0], am[1], 0x7632)); +#pragma unroll + for (int o = 8; o; o >>= 1) pw = mxb2(pw, __shfl_xor_sync(0xffffffffu, pw, o)); +#pragma unroll + for (int h = 0; h < 2; ++h) { + const float amax = h ? __uint_as_float(pw & 0xffff0000u) : __uint_as_float(pw << 16); + const float s = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float inv = __fdividef(1.0f, s); + const unsigned long long inv2 = pack2(inv); + uint2 o; + o.x = qword4(hb[h][0], hb[h][1], inv2); + o.y = qword4(hb[h][2], hb[h][3], inv2); + if (row0 + i + h < rows) { + *(uint2*)(op + (size_t)(i + h) * opitch) = o; + if (wsc) sp[i + h] = s; + } + } + } + rb = rn; +#pragma unroll + for (int i = 0; i < R; ++i) v[i] = vn[i]; + } + asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); +} +static const unsigned* g_nf_mcnt = nullptr; static unsigned g_nf_mtgt = 0; +static unsigned* g_nf_claim = nullptr; static int g_nf_pmb = 0; // persistent norm: claim counter, CTAs per SM (0 = off) +void set_nf_pers(unsigned* claim, int mb) { g_nf_claim = claim; g_nf_pmb = mb; } +void set_norm_mcnt(const unsigned* p, unsigned tgt) { g_nf_mcnt = p; g_nf_mtgt = tgt; } +static int g_nf_r = 4; // norm_fast rows per CTA +void set_nf_rows(int r) { g_nf_r = r; } +static int g_nf_mb = 1; // norm_fast __launch_bounds__ min blocks per SM (see norm_fast_kernel) +void set_nf_mb(int m) { g_nf_mb = m; } +static int g_nf_lv = 1; // 1: lean norm_fast (LV = 1, bit-identical register / instruction diet), 0: previous code +void set_nf_lean(int v) { g_nf_lv = v; } +static unsigned long long* g_nq_epoch = nullptr; // see norm_quant_kernel (epoch); also forces the late trigger +void set_norm_epoch(unsigned long long* ep) { g_nq_epoch = ep; } +// early != 0 (M=512 chain, wq bit22): keep the entry trigger even with an epoch (the dependent q_b reads the epoch only +// after its griddepcontrol.wait, i.e. after this grid completed), so q_b's launch + prologue overlap the norm. +static int g_nq_early = 0; // split-K norm: overrides the small-M late chain (g_late) too -> entry trigger, gq launch/prologue overlap the norm +void set_norm_early(int on) { g_nq_early = on; } +void launch_norm_quant(void* y1, int ldy, const float* part, int nsplit, const void* wq, const void* wkv, + void* qq, float* qs, void* kq, float* ks, float eps, int Mp, cudaStream_t st, int rows, int rev, int fast) { + const int grid = rows > 0 ? rows : Mp; // rows: CTAs (one per row); Mp: scale-array row stride +#define NQ_LAUNCH(NSV) \ + launch_pdl(norm_quant_kernel, dim3(grid), dim3(288), 0, st, g_fg_pdl, (uint16_t*)y1, ldy, part, nsplit, \ + (size_t)Mp * ldy, (const uint16_t*)wq, (const uint16_t*)wkv, (uint8_t*)qq, qs, (uint8_t*)kq, ks, eps, Mp, rev, (g_nq_epoch && g_nq_early) ? 0 : ((g_late || g_nq_epoch) ? 1 : 0), g_nq_epoch) + if (nsplit > 0) { + switch (nsplit) { + case 1: NQ_LAUNCH(1); break; + case 2: NQ_LAUNCH(2); break; + case 3: NQ_LAUNCH(3); break; + case 4: NQ_LAUNCH(4); break; + case 5: NQ_LAUNCH(5); break; + case 6: NQ_LAUNCH(6); break; + case 7: NQ_LAUNCH(7); break; + case 8: NQ_LAUNCH(8); break; + default: NQ_LAUNCH(0); break; // generic runtime loop + } + } else if (fast && g_nf_pmb > 0 && g_nf_claim && g_nf_mcnt && !g_nq_epoch && !g_nf_etrig) { + static int nsm_p = 0; + if (!nsm_p) { int dev; cudaGetDevice(&dev); cudaDeviceGetAttribute(&nsm_p, cudaDevAttrMultiProcessorCount, dev); } + const int nblk = (grid + 3) / 4; + const int pg = std::min(nblk, nsm_p * g_nf_pmb); +#define NP_LAUNCH(MBV) launch_pdl(norm_pers_kernel<4, MBV>, dim3(pg), dim3(256), 0, st, g_fg_pdl, (const uint16_t*)y1, ldy, \ + (const uint16_t*)wq, (const uint16_t*)wkv, (uint8_t*)qq, qs, (uint8_t*)kq, ks, eps, Mp, grid, g_nf_mcnt, g_nf_mtgt, g_nf_claim, nblk) + if (g_nf_pmb >= 4) NP_LAUNCH(4); else if (g_nf_pmb == 3) NP_LAUNCH(3); else NP_LAUNCH(2); +#undef NP_LAUNCH + } else if (fast) { + // rows per CTA (g_nf_r: 2 / 4 / 8; same per-row math and reduction order for every R -> bit-identical) +#define NF_LAUNCH(RV, MBV) \ + launch_pdl(g_nf_lv ? norm_fast_kernel : norm_fast_kernel, dim3((grid + RV - 1) / RV), dim3(256), 0, st, g_fg_pdl, (const uint16_t*)y1, ldy, \ + (const uint16_t*)wq, (const uint16_t*)wkv, (uint8_t*)qq, qs, (uint8_t*)kq, ks, eps, Mp, grid, rev, \ + (g_nf_etrig || (g_nq_epoch && g_nq_early)) ? 1 : 0, g_nf_mcnt, g_nf_mtgt, g_nq_epoch) + // g_fg_pdl (large M, wq bit11): PDL dependent of GEMM1 (pdl_wait at entry before reading y1) + if (g_nf_r == 2) { if (g_nf_mb == 8) NF_LAUNCH(2, 8); else if (g_nf_mb == 5) NF_LAUNCH(2, 5); else NF_LAUNCH(2, 1); } + else if (g_nf_r == 8) { if (g_nf_mb == 4) NF_LAUNCH(8, 4); else if (g_nf_mb == 3) NF_LAUNCH(8, 3); else NF_LAUNCH(8, 1); } + else { if (g_nf_mb == 6) NF_LAUNCH(4, 6); else if (g_nf_mb == 8) NF_LAUNCH(4, 8); else if (g_nf_mb == 5) NF_LAUNCH(4, 5); else if (g_nf_mb == 4) NF_LAUNCH(4, 4); else NF_LAUNCH(4, 1); } +#undef NF_LAUNCH + } else + // g_fg_pdl (mid M, wq bit15): PDL dependent of GEMM1 (pdl_wait before reading y1; triggers at entry) + launch_pdl(norm_quant_kernel, dim3(grid), dim3(256), 0, st, g_fg_pdl, (uint16_t*)y1, ldy, (const float*)nullptr, 0, + (size_t)0, (const uint16_t*)wq, (const uint16_t*)wkv, (uint8_t*)qq, qs, (uint8_t*)kq, ks, eps, Mp, rev, (g_nq_epoch && !g_nq_early) ? 1 : 0, g_nq_epoch); +} + +// ------------------------------------------------------------------ 2. CUTLASS FP8 GEMM (GEMM1 only) +using namespace cute; +using ElementA = cutlass::float_e4m3_t; +using LayoutA = cutlass::layout::RowMajor; // A [M,K], K contiguous +using ElementB = cutlass::float_e4m3_t; +using LayoutB = cutlass::layout::ColumnMajor; // B viewed as [K,N] col-major == W[N,K] row-major +using LayoutD = cutlass::layout::RowMajor; +using ElementAcc = float; +constexpr int AlignA = 16, AlignB = 16; + +using MmaTileShape = Shape<_128, _128, _128>; // one tcgen05 128x128 tile per CTA, K=128 = scale block +using ClusterShape = Shape<_1, _1, _1>; +// 1x128 activation scales (granularity M=1), 128x128 weight scales; both MN-major. +using ScaleConfig = cutlass::detail::Sm100BlockwiseScaleConfig<1, 128, 128, UMMA::Major::MN, UMMA::Major::MN>; +using LayoutSFA = decltype(ScaleConfig::deduce_layoutSFA()); +using LayoutSFB = decltype(ScaleConfig::deduce_layoutSFB()); + +// Explicit 128x64 epilogue subtile: the epilogue warps drain TMEM -> regs -> smem -> TMA store +// in 64-column chunks (instead of the auto choice) to cut epilogue register pressure / spills. +using EpilogueTile = Shape<_128, _64>; + +// Sched = void: persistent data-parallel scheduler; cutlass::gemm::StreamKScheduler: stream-K decomposition (GEMM1 at +// mid/large M, where 17*Mp/128 output tiles quantize badly on 148 SMs; the fp32 partial tiles are fixed up by CUTLASS +// in its workspace, so the bf16 output is the same blockwise-scaled GEMM, summation order only differs per K split). +// TK: mainloop tile depth (TK = 256: two 128-deep scale blocks per smem stage, each MMA'd into its own TMEM accumulator +// and promoted in k order by CUTLASS -> bit-identical to TK = 128; half the stage handshakes, 2x larger TMA boxes). +template +struct GemmCfg { + using MmaTileShape = Shape<_128, _128, Int>; + static constexpr int AlignD = 16 / sizeof(ElementD); + using CollectiveEpilogue = typename cutlass::epilogue::collective::CollectiveBuilder< + cutlass::arch::Sm100, cutlass::arch::OpClassTensorOp, MmaTileShape, ClusterShape, + EpiT, ElementAcc, ElementAcc, + void, LayoutD, AlignD, ElementD, LayoutD, AlignD, + cutlass::epilogue::TmaWarpSpecialized1Sm>::CollectiveOp; + using CollectiveMainloop = typename cutlass::gemm::collective::CollectiveBuilder< + cutlass::arch::Sm100, cutlass::arch::OpClassTensorOp, + ElementA, cute::tuple, AlignA, + ElementB, cute::tuple, AlignB, + ElementAcc, MmaTileShape, ClusterShape, + cutlass::gemm::collective::StageCountAutoCarveout(sizeof(typename CollectiveEpilogue::SharedStorage))>, + cutlass::gemm::KernelTmaWarpSpecializedBlockwise1SmSm100>::CollectiveOp; + using GemmKernel = cutlass::gemm::kernel::GemmUniversal, CollectiveMainloop, + CollectiveEpilogue, Sched>; + using Gemm = cutlass::gemm::device::GemmUniversalAdapter; +}; +using GemmBF16 = GemmCfg::Gemm; +using GemmBF16_SK = GemmCfg::Gemm; // 1-SM 128x128 stream-K // final outputs +// Epilogue subtile 128x16 (fp32): frees ~48 KB of epilogue staging so StageCountAutoCarveout fits one more 64 KB +// TK=256 mainloop stage (2 -> 3). Same values stored: bit-identical. +using GemmF32 = GemmCfg>::Gemm; // split-K partials (M=256 GEMM1 only); tile K 256, see GemmCfg + +// GEMM1 candidates for large M (no split-K, Mp % 256 == 0): 2-SM tcgen05 variants over a 2x1 CTA cluster, +// MMA tile 256 x TN (TN = 128 or 256). Each CTA loads its own 128 A rows and half of the TN-row B tile +// (shared through the 2-SM MMA), halving per-CTA B smem traffic vs the 1-SM 128x128 kernel (which is +// smem-read-bound: 32 KB per 128x128x128 MMA block). N = 2176 is ragged for TN = 256 (TMA OOB handling). +// TK: mainloop tile depth. TK = 256 (M=512 GEMM1, 2-SM 256x128): each smem stage holds TWO 128-deep scale blocks; +// CUTLASS issues each scale block's MMAs into its own TMEM accumulator and promotes them in k order +// (full_acc += sa*sb*partial per 128-K block), so the math / order is unchanged (bit-identical) while the mainloop +// pipeline does half the stage handshakes and moves 2x larger TMA boxes per stage. +template +struct Gemm2SmCfg { + using Tile = Shape<_256, Int, Int>; + using Cluster = Shape<_2, _1, _1>; + static constexpr int AlignD = 8; + using CollectiveEpilogue = typename cutlass::epilogue::collective::CollectiveBuilder< + cutlass::arch::Sm100, cutlass::arch::OpClassTensorOp, Tile, Cluster, + EpiT, ElementAcc, ElementAcc, + void, LayoutD, AlignD, cutlass::bfloat16_t, LayoutD, AlignD, + cutlass::epilogue::TmaWarpSpecialized2Sm>::CollectiveOp; + using CollectiveMainloop = typename cutlass::gemm::collective::CollectiveBuilder< + cutlass::arch::Sm100, cutlass::arch::OpClassTensorOp, + ElementA, cute::tuple, AlignA, + ElementB, cute::tuple, AlignB, + ElementAcc, Tile, Cluster, + cutlass::gemm::collective::StageCountAutoCarveout(sizeof(typename CollectiveEpilogue::SharedStorage))>, + cutlass::gemm::KernelTmaWarpSpecializedBlockwise2SmSm100>::CollectiveOp; + using GemmKernel = cutlass::gemm::kernel::GemmUniversal, CollectiveMainloop, + CollectiveEpilogue, Sched>; + using Gemm = cutlass::gemm::device::GemmUniversalAdapter; +}; +// Epilogue subtile 128x32: frees 16 KB of epilogue staging -> one more TK=256 mainloop stage (3 -> 4). Bit-identical. +using GemmBF16_2Sm128 = Gemm2SmCfg<128, void, 256, Shape<_128, _32>>::Gemm; // tile K 256 (see Gemm2SmCfg) +static_assert(GemmCfg>::CollectiveMainloop::DispatchPolicy::Stages >= 3, "F32 stages"); +static_assert(Gemm2SmCfg<128, void, 256, Shape<_128, _32>>::CollectiveMainloop::DispatchPolicy::Stages >= 4, "2SM stages"); +using GemmBF16_2Sm128_SK = Gemm2SmCfg<128, cutlass::gemm::StreamKScheduler>::Gemm; // 2-SM 256x128 stream-K + +// Fake-quant GEMM1 (Mp >= 1024 candidate): plain fp16 x fp16 -> fp32 tcgen05 GEMM of the dequantized +// operands (no per-k-block promotion), 2-SM 2x1 cluster, bf16 output, TMA in / TMA-store out. +template +struct GemmF16Cfg { + using Tile = Shape<_256, Int, _64>; + using Cluster = Shape<_2, _1, _1>; + using CollectiveEpilogue = typename cutlass::epilogue::collective::CollectiveBuilder< + cutlass::arch::Sm100, cutlass::arch::OpClassTensorOp, Tile, Cluster, + cutlass::epilogue::collective::EpilogueTileAuto, ElementAcc, ElementAcc, + void, LayoutD, 8, cutlass::bfloat16_t, LayoutD, 8, + cutlass::epilogue::TmaWarpSpecialized2Sm>::CollectiveOp; + using CollectiveMainloop = typename cutlass::gemm::collective::CollectiveBuilder< + cutlass::arch::Sm100, cutlass::arch::OpClassTensorOp, + cutlass::half_t, LayoutA, 8, cutlass::half_t, LayoutB, 8, + ElementAcc, Tile, Cluster, + cutlass::gemm::collective::StageCountAutoCarveout(sizeof(typename CollectiveEpilogue::SharedStorage))>, + cutlass::gemm::KernelTmaWarpSpecialized2SmSm100>::CollectiveOp; + using GemmKernel = cutlass::gemm::kernel::GemmUniversal, CollectiveMainloop, + CollectiveEpilogue, void>; + using Gemm = cutlass::gemm::device::GemmUniversalAdapter; +}; + +static void* g_ws[2] = {nullptr, nullptr}; +static size_t g_ws_size[2] = {0, 0}; +static int g_sms = 0; +// GEMM1 persistent-grid SM cap (0 = all SMs): set while the chunked large-M pipeline runs the capped act quant +// of the next M-chunk concurrently on the remaining SMs. +static int g_g1_cap = 0; +void set_gemm1_sm_cap(int n) { g_g1_cap = n; } +static int g_g1_sched = 0; // raster*16 + max_swizzle_size (0 = CUTLASS default heuristic, swizzle 1) +void set_gemm1_sched(int v) { g_g1_sched = v; } + +// Generic launcher. Batch l (L = nbatch) of the problem uses A/B offset l*Kb elements along K, +// i.e. with Kb = K_total/S this is split-K over contiguous K chunks (S=1: plain GEMM). +static int g_sk_splits = 0; // stream-K variants: 0 = pure stream-K, > 1 = fixed split-K count via the stream-K scheduler +template +static int run_gemm(const void* A, const void* B, const float* SFA, const float* SFB, void* D, + int M, int N, int Ktot, int nbatch, cudaStream_t st, int slot) { + using StrideA = typename Gemm::GemmKernel::StrideA; + using StrideB = typename Gemm::GemmKernel::StrideB; + using StrideC = typename Gemm::GemmKernel::StrideC; + using StrideD = typename Gemm::GemmKernel::StrideD; + const int Kb = Ktot / nbatch; + StrideA sA = cutlass::make_cute_packed_stride(StrideA{}, cute::make_shape(M, Kb, nbatch)); + StrideB sB = cutlass::make_cute_packed_stride(StrideB{}, cute::make_shape(N, Kb, nbatch)); + cute::get<0>(sA) = Ktot; cute::get<2>(sA) = Kb; // row pitch = full K; batch = next K chunk + cute::get<0>(sB) = Ktot; cute::get<2>(sB) = Kb; + StrideC sC = cutlass::make_cute_packed_stride(StrideC{}, cute::make_shape(M, N, nbatch)); + StrideD sD = cutlass::make_cute_packed_stride(StrideD{}, cute::make_shape(M, N, nbatch)); + // Packed SF layouts: batch stride = M*(Kb/128) (SFA) / (N/128)*(Kb/128) (SFB), which is exactly + // the next K-block chunk of our [kb][m] / [kb][nb] scale arrays. + LayoutSFA lSFA = ScaleConfig::tile_atom_to_shape_SFA(cute::make_shape(M, N, Kb, nbatch)); + LayoutSFB lSFB = ScaleConfig::tile_atom_to_shape_SFB(cute::make_shape(M, N, Kb, nbatch)); + if (g_sms == 0) { + int dev; cudaGetDevice(&dev); + cudaDeviceGetAttribute(&g_sms, cudaDevAttrMultiProcessorCount, dev); + } + cutlass::KernelHardwareInfo hw; + hw.device_id = 0; + hw.sm_count = (g_g1_cap > 0 && g_g1_cap < g_sms) ? g_g1_cap : g_sms; // chunk pipeline: SM partition + typename Gemm::Arguments args{ + cutlass::gemm::GemmUniversalMode::kGemm, + {M, N, Kb, nbatch}, + {(const ElementA*)A, sA, (const ElementB*)B, sB, SFA, lSFA, SFB, lSFB}, + {{}, nullptr, sC, (ElementD*)D, sD}, + hw}; + args.epilogue.thread.alpha = 1.0f; + args.epilogue.thread.beta = 0.0f; + if (g_g1_sched) { + using RO = decltype(args.scheduler.raster_order); + const int ro = g_g1_sched >> 4, sw = g_g1_sched & 15; + args.scheduler.raster_order = ro == 1 ? RO::AlongM : ro == 2 ? RO::AlongN : RO::Heuristic; + args.scheduler.max_swizzle_size = sw > 0 ? sw : 1; + } + if constexpr (SK) { + using DM = decltype(args.scheduler.decomposition_mode); + if (g_sk_splits > 1) { args.scheduler.decomposition_mode = DM::SplitK; args.scheduler.splits = g_sk_splits; } + else args.scheduler.decomposition_mode = DM::StreamK; + } + Gemm gemm; + if (gemm.can_implement(args) != cutlass::Status::kSuccess) return -1; + size_t ws = Gemm::get_workspace_size(args); + if (ws > g_ws_size[slot]) { + cudaMalloc(&g_ws[slot], ws); // old buffer intentionally leaked (see above) + g_ws_size[slot] = ws; + } + if (gemm.initialize(args, g_ws[slot], st) != cutlass::Status::kSuccess) return -2; + if (gemm.run(st, nullptr, g_g1_pdl != 0) != cutlass::Status::kSuccess) return -3; // g_g1_pdl: GDC launch + return 0; +} + +int launch_fp8_gemm(const void* A, const void* B, const float* SFA, const float* SFB, + void* D, int M, int N, int K, cudaStream_t st, int slot) { + return run_gemm(A, B, SFA, SFB, D, M, N, K, 1, st, slot); +} + +// Stream-K GEMM1 (bf16 out): two = 0 -> 1-SM 128x128, two = 1 -> 2-SM 256x128 (M % 256 == 0). splits > 1: fixed split. +int launch_fp8_gemm_sk(const void* A, const void* B, const float* SFA, const float* SFB, void* D, int M, int N, int K, + int two, int splits, cudaStream_t st, int slot) { + g_sk_splits = splits; + if (two) { + if (M % 256) return -4; + return run_gemm(A, B, SFA, SFB, D, M, N, K, 1, st, slot); + } + return run_gemm(A, B, SFA, SFB, D, M, N, K, 1, st, slot); +} + +int launch_fp8_gemm_2sm(const void* A, const void* B, const float* SFA, const float* SFB, + void* D, int M, int N, int K, int tn, cudaStream_t st, int slot) { + if (M % 256) return -4; + if (tn != 128) return -5; // only 256x128 instantiated (256x256 timed out in build/run) + return run_gemm(A, B, SFA, SFB, D, M, N, K, 1, st, slot); +} + +template +static int run_gemm_f16(const void* A, const void* B, void* D, int M, int N, int K, cudaStream_t st, int slot, + const float* alpha_ptr) { + using StrideA = typename Gemm::GemmKernel::StrideA; + using StrideB = typename Gemm::GemmKernel::StrideB; + using StrideC = typename Gemm::GemmKernel::StrideC; + using StrideD = typename Gemm::GemmKernel::StrideD; + StrideA sA = cutlass::make_cute_packed_stride(StrideA{}, cute::make_shape(M, K, 1)); + StrideB sB = cutlass::make_cute_packed_stride(StrideB{}, cute::make_shape(N, K, 1)); + StrideC sC = cutlass::make_cute_packed_stride(StrideC{}, cute::make_shape(M, N, 1)); + StrideD sD = cutlass::make_cute_packed_stride(StrideD{}, cute::make_shape(M, N, 1)); + if (g_sms == 0) { + int dev; cudaGetDevice(&dev); + cudaDeviceGetAttribute(&g_sms, cudaDevAttrMultiProcessorCount, dev); + } + cutlass::KernelHardwareInfo hw; + hw.device_id = 0; + hw.sm_count = g_sms; + typename Gemm::Arguments args{ + cutlass::gemm::GemmUniversalMode::kGemm, + {M, N, K, 1}, + {(const cutlass::half_t*)A, sA, (const cutlass::half_t*)B, sB}, + {{}, nullptr, sC, (cutlass::bfloat16_t*)D, sD}, + hw}; + args.epilogue.thread.alpha = 1.0f; + args.epilogue.thread.alpha_ptr = alpha_ptr; // device scalar 2^-(sA+sW) written by the quant kernel + args.epilogue.thread.beta = 0.0f; + Gemm gemm; + if (gemm.can_implement(args) != cutlass::Status::kSuccess) return -1; + size_t ws = Gemm::get_workspace_size(args); + if (ws > g_ws_size[slot]) { + cudaMalloc(&g_ws[slot], ws); // old buffer intentionally leaked (see above) + g_ws_size[slot] = ws; + } + if (gemm.initialize(args, g_ws[slot], st) != cutlass::Status::kSuccess) return -2; + if (gemm.run(st) != cutlass::Status::kSuccess) return -3; + return 0; +} + +int launch_f16_gemm(const void* A, const void* B, void* D, int M, int N, int K, int variant, cudaStream_t st, int slot, + const float* alpha_ptr) { + if (variant == 2) return run_gemm_f16::Gemm>(A, B, D, M, N, K, st, slot, alpha_ptr); + return run_gemm_f16::Gemm>(A, B, D, M, N, K, st, slot, alpha_ptr); +} + +int launch_fp8_gemm_splitk(const void* A, const void* B, const float* SFA, const float* SFB, + float* D, int M, int N, int K, int S, cudaStream_t st, int slot) { + return run_gemm(A, B, SFA, SFB, D, M, N, K, S, st, slot); +} + +// ------------------------------------------------------------------ 6. tcgen05 / TMA / mbarrier helpers +// (namespace kept as `kvb` for history; used by the custom blockwise GEMM of section 7) +namespace kvb { + +constexpr int BK = 128; // K block = one scale block +constexpr int NUM_EPI_WARPS = 16; // promotion / epilogue warps +constexpr int WSTAGE_BYTES = 32 * 32 * 2; // 2 KB bf16 staging per epilogue warp +constexpr int OUT_BYTES = NUM_EPI_WARPS * WSTAGE_BYTES; // 32 KB +// Scale ring (gq kernel): per k-block slot = 128 activation scales sfa[kb*Mp + m0 .. +127] (512 B) followed by +// the 16-B aligned chunk of weight scales containing sfb[kb*nsb + n0/128 ..] (16 B). Filled by the TMA producer +// with cp.async.bulk, read by the promotion warps from smem (no exposed L2 latency in the promotion loop). +// NSC >= NST + NTB for every gq configuration (static_assert in gq_kernel): slot reuse is then implied by the +// producer's empty-barrier wait (see the producer comment), so the ring needs no scale-empty barrier. +#ifdef GQ_SKEL +constexpr int NSC = 16; // probe build: also runs the scempty-free protocol (needs NSC >= NST + NTB) +#else +constexpr int NSC = 8; +#endif +constexpr int SC_SLOT = 512 + 128; // 128-B multiple: TMA tensor destinations (2-SM scale loads) need 128-B alignment +constexpr int SC_BYTES = NSC * SC_SLOT; +constexpr int SC_TX = 512 + 16; // scale bytes actually loaded per slot (activation 512 B + weight chunk 16 B) + +__device__ __forceinline__ uint32_t su32(const void* p) { return static_cast(__cvta_generic_to_shared(p)); } +__device__ __forceinline__ void bar_init(uint64_t* b, uint32_t c) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(su32(b)), "r"(c)); +} +__device__ __forceinline__ void bar_expect(uint64_t* b, uint32_t bytes) { + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(su32(b)), "r"(bytes) : "memory"); +} +// Energy: the GPU runs power-capped (~1000 W, SM clock ~1.45-1.5 GHz under a hot loop of large-M calls), so the +// waiting roles should not burn issue slots. try_wait with a suspend-time hint parks the waiting thread in hardware +// until the phase completes (or the hint elapses) instead of re-polling at the default short interval. +#ifndef MBAR_SUSPEND_NS +#define MBAR_SUSPEND_NS 20000 +#endif +// un-hinted single-thread wait sites (bits shared with the skeleton probe's switch word) +constexpr int W_MTEMPTY = 8192, W_MFULL = 65536, W_PROD = 131072, W_STORE = 262144; +#ifndef GQ_LSC +// 1: promotion warps issue the k-block's scale ld.shared right AFTER its first tcgen05.ld (latency overlaps the TMEM +// load round trip instead of preceding it on the tfull -> FFMA2 critical path). Same values: bit-identical. +#define GQ_LSC 1 +#endif +#ifndef GQ_V4 +#define GQ_V4 0 +#endif +#ifndef GQ_WNH +#define GQ_WNH 0 // energy diet: all single-thread role waits (producer empty, MMA tempty/full, store stfull) use try_wait with the suspend-time hint +#endif +#ifdef GQ_SKEL +#define OLDP_STATIC false +#else +#define OLDP_STATIC true +#endif +#ifdef GQ_SKEL +__device__ int g_nohint = 0; // probe build only: 1 = plain try_wait (no suspend-time hint) +#define SKEL_NOHINT_WAIT(addr, par) \ + if (g_nohint == 1) { \ + asm volatile("{\n.reg .pred p;\nWAITN_%=:\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n" \ + "@!p bra WAITN_%=;\n}\n" ::"r"(addr), "r"(par) : "memory"); \ + return; \ + } \ + if (g_nohint == 2) { \ + asm volatile("{\n.reg .pred p;\nWAITT_%=:\nmbarrier.test_wait.parity.shared::cta.b64 p, [%0], %1;\n" \ + "@!p bra WAITT_%=;\n}\n" ::"r"(addr), "r"(par) : "memory"); \ + return; \ + } +#else +#define SKEL_NOHINT_WAIT(addr, par) +#endif +__device__ __forceinline__ void bar_wait(uint64_t* b, uint32_t parity) { + SKEL_NOHINT_WAIT(su32(b), parity) + asm volatile( + "{\n.reg .pred p;\nWAIT_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAIT_%=;\n}\n" ::"r"(su32(b)), "r"(parity), "n"(MBAR_SUSPEND_NS) : "memory"); +} +// Same mbarrier ops on a precomputed 32-bit shared address (keeps the generic->shared conversion out of +// the hot loops; the promotion warps are issue-bound). +__device__ __forceinline__ void bar_wait_a(uint32_t a, uint32_t parity) { + SKEL_NOHINT_WAIT(a, parity) + asm volatile( + "{\n.reg .pred p;\nWAIT_%=:\n" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAIT_%=;\n}\n" ::"r"(a), "r"(parity), "n"(MBAR_SUSPEND_NS) : "memory"); +} +// Wait flavours: 0 = try_wait with suspend-time hint (default), 1 = try_wait without hint, 2 = test_wait spin. +template +__device__ __forceinline__ void bar_wait_f(uint32_t a, uint32_t parity) { + if constexpr (F == 0) { + asm volatile("{\n.reg .pred p;\nWAITF0_%=:\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n" + "@!p bra WAITF0_%=;\n}\n" ::"r"(a), "r"(parity), "n"(MBAR_SUSPEND_NS) : "memory"); + } else if constexpr (F == 1) { + asm volatile("{\n.reg .pred p;\nWAITF1_%=:\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n" + "@!p bra WAITF1_%=;\n}\n" ::"r"(a), "r"(parity) : "memory"); + } else { + asm volatile("{\n.reg .pred p;\nWAITF2_%=:\nmbarrier.test_wait.parity.shared::cta.b64 p, [%0], %1;\n" + "@!p bra WAITF2_%=;\n}\n" ::"r"(a), "r"(parity) : "memory"); + } +} +// Single-thread role wait (producer / MMA issuer / store warp): nh = true -> try_wait WITHOUT the suspend-time hint +// (the lone waiting thread re-polls at the hardware default interval and resumes sooner after the phase flips; it +// burns almost no issue slots, unlike 16 polling promotion warps, which keep the hinted bar_wait_a). +__device__ __forceinline__ void bar_wait_1t(uint64_t* b, uint32_t parity, bool nh) { + if (nh) bar_wait_f<1>(su32(b), parity); + else bar_wait(b, parity); +} +__device__ __forceinline__ void bar_arrive_a(uint32_t a) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(a) : "memory"); +} +__device__ __forceinline__ uint64_t wb_pol_ef() { + uint64_t p; asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(p)); return p; +} +__device__ __forceinline__ void tma_ld(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y) { +#ifdef WB_EFL + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3}], [%4], %5;" + ::"r"(su32(dst)), "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(su32(bar)), "l"(wb_pol_ef()) : "memory"); + return; +#endif + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1, {%2, %3}], [%4];" + ::"r"(su32(dst)), "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(su32(bar)) : "memory"); +} +// 2D TMA load with an L2 cache-policy hint (fused GEMM1: the read-once bf16 A weights are loaded evict_first so they +// do not displace the L2-resident fp8 B weights written concurrently by the side-stream wquant (evict_last)). +__device__ __forceinline__ void tma_ld_hint(void* dst, const CUtensorMap* map, uint64_t* bar, int x, int y, 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"(su32(dst)), "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(su32(bar)), "l"(pol) : "memory"); +} +// 1D bulk global -> shared copy completing on an mbarrier (bytes multiple of 16, both addresses 16-B aligned). +__device__ __forceinline__ void bulk_ld(void* dst, const void* src, uint32_t bytes, uint64_t* bar) { +#ifdef WB_EFL + asm volatile("cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1], %2, [%3], %4;" + ::"r"(su32(dst)), "l"(reinterpret_cast(src)), "r"(bytes), "r"(su32(bar)), "l"(wb_pol_ef()) : "memory"); + return; +#endif + asm volatile("cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1], %2, [%3];" + ::"r"(su32(dst)), "l"(reinterpret_cast(src)), "r"(bytes), "r"(su32(bar)) : "memory"); +} +__device__ __forceinline__ uint32_t mapa_u32(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; +} +__device__ __forceinline__ uint32_t cluster_rank() { + uint32_t r; + asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(r)); + return r; +} +__device__ __forceinline__ void cluster_sync() { + asm volatile("barrier.cluster.arrive.release.aligned;\nbarrier.cluster.wait.acquire.aligned;" ::: "memory"); +} +// arrive on a (possibly remote) mbarrier given its shared::cluster address +__device__ __forceinline__ void bar_arrive_cl(uint32_t a) { + asm volatile("mbarrier.arrive.shared::cluster.b64 _, [%0];" ::"r"(a) : "memory"); +} +// 2-SM TMA load: data lands in THIS CTA's smem, complete_tx is signalled on the leader's barrier +// (bar_cl = shared::cluster address of the leader's mbarrier). +__device__ __forceinline__ void tma_ld2(void* dst, const CUtensorMap* map, uint32_t bar_cl, int x, int y) { +#ifdef WB_EFL + 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"(su32(dst)), "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(bar_cl), "l"(wb_pol_ef()) : "memory"); + return; +#endif + asm volatile( + "cp.async.bulk.tensor.2d.cta_group::2.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1, {%2, %3}], [%4];" + ::"r"(su32(dst)), "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(bar_cl) : "memory"); +} +// 2-SM TMA load with an L2 cache-policy hint (same data / barrier as tma_ld2). +__device__ __forceinline__ void tma_ld2_hint(void* dst, const CUtensorMap* map, uint32_t bar_cl, int x, int y, 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"(su32(dst)), "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(bar_cl), "l"(pol) : "memory"); +} +__device__ __forceinline__ void mma2(uint32_t td, uint64_t ad, uint64_t bd, uint32_t idesc, uint32_t acc) { + asm volatile( + "{\n.reg .pred p;\nsetp.ne.b32 p, %4, 0;\n" + "tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], %1, %2, %3, p;\n}\n" + ::"r"(td), "l"(ad), "l"(bd), "r"(idesc), "r"(acc)); +} +// multicast commit: arrive on the barrier at this offset in BOTH CTAs of the pair +__device__ __forceinline__ void commit2(uint64_t* b) { + asm volatile( + "{\n.reg .b16 m;\nmov.b16 m, 3;\n" + "tcgen05.commit.cta_group::2.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%0], m;\n}" + ::"r"(su32(b)) : "memory"); +} +// multicast commit to an explicit cluster-rank mask (GV_MC 4-CTA clusters: pair 1 = ranks 2,3) +__device__ __forceinline__ void commit2m(uint32_t mask, uint64_t* b) { + asm volatile( + "{\n.reg .b16 m;\ncvt.u16.u32 m, %1;\n" + "tcgen05.commit.cta_group::2.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%0], m;\n}" + ::"r"(su32(b)), "r"(mask) : "memory"); +} +// 2-SM TMA load multicast to the CTAs in `mask` (same CTA-relative smem offset in each); complete_tx goes to the +// barrier at bar_cl's offset in the leader (peer bit 0) CTA of each destination's pair. +__device__ __forceinline__ void tma_ld2_mc(void* dst, const CUtensorMap* map, uint32_t bar_cl, int x, int y, uint16_t mask) { + asm volatile( + "cp.async.bulk.tensor.2d.cta_group::2.shared::cluster.global.mbarrier::complete_tx::bytes.multicast::cluster" + " [%0], [%1, {%2, %3}], [%4], %5;" + ::"r"(su32(dst)), "l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(bar_cl), "h"(mask) : "memory"); +} +__device__ __forceinline__ void tma_st(const CUtensorMap* map, const void* src, int x, int y) { +#ifdef WB_EFT + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%1, %2}], [%3], %4;" + ::"l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(su32(src)), "l"(wb_pol_ef()) : "memory"); + return; +#endif + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group [%0, {%1, %2}], [%3];" + ::"l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(su32(src)) : "memory"); +} +// UMMA smem descriptor: K-major, 128B swizzle, 8-row groups 1024 B apart (SBO), version 1, SW128. +__device__ __forceinline__ uint64_t sdesc(uint32_t a) { + uint64_t d = 0; + d |= (uint64_t)((a & 0x3FFFF) >> 4); + d |= (uint64_t)1 << 16; + d |= (uint64_t)(1024 >> 4) << 32; + d |= (uint64_t)1 << 46; + d |= (uint64_t)2 << 61; + return d; +} +__device__ __forceinline__ void mma(uint32_t td, uint64_t ad, uint64_t bd, uint32_t idesc, uint32_t acc) { + asm volatile( + "{\n.reg .pred p;\nsetp.ne.b32 p, %4, 0;\n" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %3, p;\n}\n" + ::"r"(td), "l"(ad), "l"(bd), "r"(idesc), "r"(acc)); +} +__device__ __forceinline__ void commit(uint64_t* b) { + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(su32(b)) : "memory"); +} +// 4 MMAs of one 128-deep k-block (K = 32 each) in ONE asm block: descriptors rebuilt from (lo, hi) words, the k-step +// (+32 B = +2 in the start-address field) as immediate lo adds (field < 2^14: no carry into hi; == the 64-bit add). +// First MMA overwrites the TMEM accumulator (enable-input-d false), the next 3 accumulate. +template +__device__ __forceinline__ void mma4(uint32_t td, uint32_t alo, uint32_t ahi, uint32_t blo, uint32_t bhi, uint32_t idesc) { +#define MMA4_BODY(G) \ + asm volatile("{\n.reg .pred pf, pt;\n.reg .b64 a, b;\n.reg .b32 t, u;\n" \ + "setp.ne.b32 pf, %0, %0;\nsetp.eq.b32 pt, %0, %0;\n" \ + "mov.b64 a, {%1, %2};\nmov.b64 b, {%3, %4};\n" \ + "tcgen05.mma.cta_group::" G ".kind::f8f6f4 [%0], a, b, %5, pf;\n" \ + "add.u32 t, %1, 2;\nadd.u32 u, %3, 2;\nmov.b64 a, {t, %2};\nmov.b64 b, {u, %4};\n" \ + "tcgen05.mma.cta_group::" G ".kind::f8f6f4 [%0], a, b, %5, pt;\n" \ + "add.u32 t, %1, 4;\nadd.u32 u, %3, 4;\nmov.b64 a, {t, %2};\nmov.b64 b, {u, %4};\n" \ + "tcgen05.mma.cta_group::" G ".kind::f8f6f4 [%0], a, b, %5, pt;\n" \ + "add.u32 t, %1, 6;\nadd.u32 u, %3, 6;\nmov.b64 a, {t, %2};\nmov.b64 b, {u, %4};\n" \ + "tcgen05.mma.cta_group::" G ".kind::f8f6f4 [%0], a, b, %5, pt;\n}\n" \ + ::"r"(td), "r"(alo), "r"(ahi), "r"(blo), "r"(bhi), "r"(idesc)) + if constexpr (CG == 2) MMA4_BODY("2"); + else MMA4_BODY("1"); +#undef MMA4_BODY +} +// commits on precomputed shared::cta addresses (same instructions as commit / commit2m) +__device__ __forceinline__ void commit1a(uint32_t a) { + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(a) : "memory"); +} +__device__ __forceinline__ void commit2a(uint32_t mask, uint32_t a) { + asm volatile( + "{\n.reg .b16 m;\ncvt.u16.u32 m, %1;\n" + "tcgen05.commit.cta_group::2.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%0], m;\n}" + ::"r"(a), "r"(mask) : "memory"); +} +__device__ __forceinline__ uint32_t ld_tmem_slot(const uint32_t* p) { + uint32_t v; + asm volatile("ld.shared.u32 %0, [%1];" : "=r"(v) : "r"(su32(p)) : "memory"); + return v; +} +__device__ __forceinline__ void f_after() { asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void f_before() { asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory"); } + +// 32 TMEM lanes x 16 consecutive fp32 columns -> 16 regs per thread (thread = lane = tile row). +#define KVB_TMEM_LD16(taddr, r) \ + 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"(taddr)) + +// 32 TMEM lanes x 32 consecutive fp32 columns -> 32 regs per thread (one instruction; gq promotion loop). +#define KVB_TMEM_LD32(taddr, r) \ + 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)) + +// bf16-pack 32 fp32 accumulators (one row, 64 B) into the warp's 64B-swizzled staging buffer and +// TMA-store it as a 32x32 box at (x, y). First waits until the warp's previous store has read the buffer. +__device__ __forceinline__ void store_rows(const float* acc, uint8_t* wst, const CUtensorMap* map, int x, int y, + int lane) { + if (lane == 0) asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); + __syncwarp(); + // row `lane` = 64 B = 4 x 16B chunks; 64B swizzle: chunk j -> j ^ ((lane >> 1) & 3) +#pragma unroll + for (int j = 0; j < 4; ++j) { + uint4 pk; + __nv_bfloat162 h0 = __floats2bfloat162_rn(acc[j * 8 + 0], acc[j * 8 + 1]); + __nv_bfloat162 h1 = __floats2bfloat162_rn(acc[j * 8 + 2], acc[j * 8 + 3]); + __nv_bfloat162 h2 = __floats2bfloat162_rn(acc[j * 8 + 4], acc[j * 8 + 5]); + __nv_bfloat162 h3 = __floats2bfloat162_rn(acc[j * 8 + 6], acc[j * 8 + 7]); + pk.x = *reinterpret_cast(&h0); + pk.y = *reinterpret_cast(&h1); + pk.z = *reinterpret_cast(&h2); + pk.w = *reinterpret_cast(&h3); + *reinterpret_cast(wst + lane * 64 + ((j ^ ((lane >> 1) & 3)) << 4)) = pk; + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // generic st.shared -> async proxy + __syncwarp(); + if (lane == 0) { + tma_st(map, wst, x, y); + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + } +} + +// bf16-pack 32 fp32 accumulators (one row, 64 B) into a 64B-swizzled 32x32 staging box (no store issued; +// the dedicated store warp TMA-stores the whole tile's staging once all promotion warps have filled it). +__device__ __forceinline__ void pack_rows(const float* acc, uint8_t* box, int lane) { +#pragma unroll + for (int j = 0; j < 4; ++j) { + uint4 pk; + __nv_bfloat162 h0 = __floats2bfloat162_rn(acc[j * 8 + 0], acc[j * 8 + 1]); + __nv_bfloat162 h1 = __floats2bfloat162_rn(acc[j * 8 + 2], acc[j * 8 + 3]); + __nv_bfloat162 h2 = __floats2bfloat162_rn(acc[j * 8 + 4], acc[j * 8 + 5]); + __nv_bfloat162 h3 = __floats2bfloat162_rn(acc[j * 8 + 6], acc[j * 8 + 7]); + pk.x = *reinterpret_cast(&h0); + pk.y = *reinterpret_cast(&h1); + pk.z = *reinterpret_cast(&h2); + pk.w = *reinterpret_cast(&h3); + *reinterpret_cast(box + lane * 64 + ((j ^ ((lane >> 1) & 3)) << 4)) = pk; + } +} + +// bf16-pack 64 fp32 accumulators (one row, 128 B) into a 128B-swizzled 32x64 staging box (1024-B aligned): +// row `lane` at lane*128, 16-B chunk j at j ^ (lane & 7) (8 consecutive lanes hit 8 distinct bank groups). +__device__ __forceinline__ void pack_rows64(const float* acc, uint8_t* box, int lane) { +#pragma unroll + for (int j = 0; j < 8; ++j) { + uint4 pk; + __nv_bfloat162 h0 = __floats2bfloat162_rn(acc[j * 8 + 0], acc[j * 8 + 1]); + __nv_bfloat162 h1 = __floats2bfloat162_rn(acc[j * 8 + 2], acc[j * 8 + 3]); + __nv_bfloat162 h2 = __floats2bfloat162_rn(acc[j * 8 + 4], acc[j * 8 + 5]); + __nv_bfloat162 h3 = __floats2bfloat162_rn(acc[j * 8 + 6], acc[j * 8 + 7]); + pk.x = *reinterpret_cast(&h0); + pk.y = *reinterpret_cast(&h1); + pk.z = *reinterpret_cast(&h2); + pk.w = *reinterpret_cast(&h3); + *reinterpret_cast(box + lane * 128 + ((j ^ (lane & 7)) << 4)) = pk; + } +} +// Cheaper epilogue pack (same bytes / layout as pack_rows64): 4 cvt.rn.bf16x2.f32 + ONE st.shared.v4.b32 per 16-B +// chunk; the swizzled address of chunk j is pbase ^ (j << 4) (pbase = box + 128*lane + 16*(lane&7), box 1024-B +// aligned so the XOR only flips bits 4..6) and the box offset is an immediate. 8 consecutive lanes write 8 distinct +// 16-B bank groups (conflict-free, 4 wavefronts per warp store = minimum for 512 B). +template +__device__ __forceinline__ void st_bf16x8(uint32_t a, const float* v) { + asm volatile("{\n\t.reg .b32 p0, p1, p2, p3;\n\t" + "cvt.rn.bf16x2.f32 p0, %2, %1;\n\t" + "cvt.rn.bf16x2.f32 p1, %4, %3;\n\t" + "cvt.rn.bf16x2.f32 p2, %6, %5;\n\t" + "cvt.rn.bf16x2.f32 p3, %8, %7;\n\t" + "st.shared.v4.b32 [%0+%9], {p0, p1, p2, p3};\n\t}" + ::"r"(a), "f"(v[0]), "f"(v[1]), "f"(v[2]), "f"(v[3]), "f"(v[4]), "f"(v[5]), "f"(v[6]), "f"(v[7]), "n"(OFF) + : "memory"); +} +__device__ __forceinline__ void pack_rows64_fast(const float* acc, uint32_t pbase, int off) { +#pragma unroll + for (int j = 0; j < 8; ++j) { + const uint32_t a = pbase ^ (uint32_t)(j << 4); + if (off == 0) st_bf16x8<0>(a, acc + j * 8); + else st_bf16x8<4096>(a, acc + j * 8); + } +} +// TMA store with an L2 cache-policy hint (evict_first for the streamed-out GEMM outputs). +__device__ __forceinline__ void tma_st_hint(const CUtensorMap* map, const void* src, int x, int y, uint64_t pol) { + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%1, %2}], [%3], %4;" + ::"l"(reinterpret_cast(map)), "r"(x), "r"(y), "r"(su32(src)), "l"(pol) : "memory"); +} + +// bf16 output map: dims {N, Mp}, box {32 cols (64 B), 32 rows}, 64B swizzle. +// wide = true (BN = 256 gq kernels): box {64 cols (128 B = one full L2 line per row), 32 rows}, 128B swizzle. +static bool make_out_map(CUtensorMap* map, void* ptr, uint64_t Mp, uint64_t N, bool wide = false) { + cuuint64_t dims[2] = {N, Mp}; + cuuint64_t strides[1] = {N * 2}; + cuuint32_t box[2] = {wide ? 64u : 32u, 32}; + cuuint32_t estr[2] = {1, 1}; + return cuTensorMapEncodeTiled(map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, ptr, dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, wide ? CU_TENSOR_MAP_SWIZZLE_128B : CU_TENSOR_MAP_SWIZZLE_64B, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE) == CUDA_SUCCESS; +} + + +// ------------------------------------------------------------------ 7. custom blockwise GEMM (q_b, kv_b) +// D[Mp, N] (bf16) = Aq[Mp, K] x Bq[N, K]^T, 1x128 act scales (SFA[kb*Mp+m]) and 128x128 weight +// scales (SFB[kb*(N/128)+nb]); K multiple of 128 (q_b: 1536 -> 12 scale blocks, kv_b: 512 -> 4). +// Persistent, warp-specialized, 1 CTA/SM, 640 threads, output tile 128 x BN (BN = 256, or 128 for +// small M so more CTAs stream the weights): +// warp 0 : TMA producer. Per k-block one ring stage = A box (128 K x 128 rows, 16 KB) + +// B box (128 K x BN rows), 128B swizzle; 4 (BN=256) / 6 (BN=128) stages. +// warp 1 : TMEM alloc (512 cols) + single-thread tcgen05.mma (kind::f8f6f4, 128xBNx32, 4 per +// k-block). Every k-block has its own scale, so it is accumulated FRESH into one +// of 512/BN TMEM buffers (ring over all k-blocks of all tiles); the MMA runs ahead +// of promotion, including into the next tile while the epilogue drains this one. +// warps 4..19 : promotion + epilogue (112 regs via setmaxnreg). Warp w owns TMEM sub-partition (w&3) +// (rows 32*(w&3)..+31) and column group (w-4)>>2 (BN/4 cols, inside one 128-col weight-scale block). +// Per k-block: tcgen05.ld 16 cols at a time, release the buffer, then +// acc += partial * (sa[m,kb]*sb[kb,nb]) in fp32 registers with packed FFMA2 (scales +// for k-block kb+1 are prefetched while kb is promoted). Tile end: bf16 pack -> per-warp +// 2 KB 64B-swizzled staging -> TMA store of 32x32 boxes straight into the output. +constexpr int GQ_THREADS = 640; +// MV_TW : MMA thread waits tempty / full with mbarrier.test_wait spin (no suspend) +// MV_GATE : warp 3 ('gate') waits tempty + full and hands each k-block to the MMA warp via named barrier +// 8 + it % NTB (bar.arrive / bar.sync, 64 threads); the MMA warp never touches an mbarrier wait +// MV_LAG : commits of k-block kb issued after the MMAs of kb+1 (commit lagging by one) +// MV_ELECT: whole warp 1 waits, elect.sync lane issues MMAs/commits; descriptors precomputed per stage +constexpr int MV_TW = 1, MV_GATE = 2, MV_LAG = 4, MV_ELECT = 8; +#ifndef GQ_MV +#define GQ_MV MV_ELECT +#endif +#ifdef GQ_SKEL +__device__ unsigned long long* g_skc = nullptr; // skeleton probe counters +#ifdef GQ_SKEL_NOTIME +#define SKT(v) const long long v = 0 +#define SKA(acc, a, b) +#else +#define SKT(v) const long long v = clock64() +#define SKA(acc, a, b) acc += (b) - (a) +#endif +#define SKF(i, acc) if (g_skc) atomicAdd(g_skc + (i), (unsigned long long)(acc)) +#define SKDECL(...) long long __VA_ARGS__ +#else +#define SKT(v) +#define SKA(acc, a, b) +#define SKF(i, acc) +#define SKDECL(...) +#endif +#ifdef CLK_PROBE +__device__ unsigned long long* g_clk = nullptr; // probe: [sum clock64 delta, sum globaltimer ns delta, count] +#endif +#ifdef GQ_PROF +__device__ unsigned long long* g_prof = nullptr; // per-CTA 16 u64 clock64 counters (probe build only) +#define PCLK(v) const long long v = clock64() +#define PADD(i, v) pacc[i] += (v) +#define PFLUSH(i) if (g_prof) atomicAdd(g_prof + blockIdx.x * 16 + (i), (unsigned long long)pacc[i]) +#else +#define PCLK(v) +#define PADD(i, v) +#define PFLUSH(i) +#endif +// Up to TWO GEMM problems (same Mp / same A-row tiling, own A/B/out maps, scales, N, K) in one persistent +// launch over a combined unit list: units [0, units0) belong to problem 0, [units0, units) to problem 1. +// Small M runs q_b (K=1536) + kv_b (K=512) as ONE launch so all SMs stream weights until the very end +// (no per-kernel tail / fixed SM partition). sched != nullptr: host-built per-CTA unit lists (LPT-balanced +// by k-block cost): sched[c]..sched[c+1] index into sched[G+1 ..]; else round-robin u = c, c+G, ... +struct GQArgs { + const float* sfa[2]; + const float* sfb[2]; + int N[2], K[2]; + int Mp, units0, units; + const int* sched; + int st_hint; // 1: output TMA stores with L2::evict_first (streamed output does not evict the L2-hot operands) + int skel; // GQ_SKEL probe build only: skeleton switches (ignored otherwise) + int rast; // unit -> (m-block, n-block) raster (see gq_map) + int ldsb; // weight-scale pitch per k-block (floats); 0 = N/128. GEMM1 (ragged N): 20 (16-B aligned chunks) + int nout; // output columns actually stored (TMA boxes at x >= nout skipped); 0 = N + int mrev; // 1: m-block index reversed (high rows first) + unsigned* mcnt = nullptr; // GV_G1 (wq bit19): per-128-row tile-completion counters (+1 per finished output tile) + int nowait; // 1: skip griddepcontrol.wait (PDL dependent that does not read its primary's output: kv_b behind q_b) + int trig; // 1: producer issues griddepcontrol.launch_dependents once it has claimed its last tile; 2: right after griddepcontrol.wait + // In-kernel B-weight dependency (small M, wq bit18, replaces the side-stream event join): wcnt != nullptr -> before + // its first TMA the producer acquire-polls *wcnt (wquant completion counter: +jobs per finished group) until it + // reaches (*wep) * wper (wep = per-replay epoch incremented by the norm, read after griddepcontrol.wait). + const unsigned long long* wcnt; + const unsigned long long* wep; + unsigned long long wper; + const unsigned long long* wcnt0 = nullptr; // != nullptr: problem-0 units wait only for wcnt0 >= epoch * wper0 + unsigned long long wper0 = 0; + int mv = 0; // MV_PROBE build only: runtime MMA-issue variant + int lpol = 0; // 2-SM q_b / kv_b: bit0 B (weight) / bit1 A (activation) operand TMA loads with L2::evict_last + // 2-SM (TWO) only: fp32 scale tensor maps. Activation scales SFA[kb][Mp] (box 128 x 1 = one k-block's 512 B for the + // CTA's 128 rows), weight scales SFB[kb][ldsb] (box 4 x 1 = the 16-B chunk holding the tile's weight scales). Loaded + // with cta_group::2 TMA so their bytes complete on the LEADER's full barrier together with the A/B operands. + CUtensorMap smap_a, smap_b; + CUtensorMap smap_a1, smap_b1; // GV_PAIR on the 2-SM kernel: problem 1's scale maps + // GV_G1 early start (wq bit29): per-row-block quant completion counters (see QuantParams::acnt) + const unsigned* acnt = nullptr; const unsigned* wdn = nullptr; unsigned atgt = 0, wtgt = 0; + unsigned* rst = nullptr; int nrst = 0; // first q_b/kv_b launch: zero rst[0..nrst) after its predecessor wait + // Per-tile unit decode without integer division (gq_map's runtime '/' compiled to ~27-65 instruction software divides + // per tile, repeated by the producer, MMA, store and every promotion warp). Per problem p: exact reciprocal multipliers + // dv_m[p][i] = floor(2^40 / d_i) + 1 for d_0 = primary divisor (rast 0: nblk, 1: mblk, >= 2: gm * nblk), d_1 = gm, + // d_2 = tail-group m-blocks; q = (n * M) >> 40 is exact for n, d < 2^20 (host-checked in gq_set_div). + unsigned long long dv_m[2][3] = {{0, 0, 0}, {0, 0, 0}}; int dv_d[2][3] = {{1, 1, 1}, {1, 1, 1}}; + unsigned long long* dctr = nullptr; // GV_DYN: per-replay unit claim counter (zeroed by the norm) + // GV_G1 tiled activation (large M, aqt producer): atk = K/128 > 0 -> the fp8 activation is stored as contiguous + // 16 KB tiles (128 rows x 128 K, already in the SW128 smem byte order) at tile (m0/128)*atk + kb; tmap_a0 is a flat + // {128 B, rows} map (no swizzle), so each k-block's A tile is ONE contiguous 16 KB DRAM/L2 read. Same smem bytes. + int atk = 0; + int g1sl = 0; // GV_G1 (M >= 16384): y1 output TMA stores with L2::evict_last (re-read by the row-gated norm right after) +}; +__device__ __forceinline__ void poll_ge(const unsigned* c, unsigned tgt) { + unsigned v, ns = 32; + for (;;) { + asm volatile("ld.acquire.gpu.global.u32 %0, [%1];" : "=r"(v) : "l"(c) : "memory"); + if (v >= tgt) break; + __nanosleep(ns); + if (ns < 256) ns <<= 1; + } +} +static int g_gq_rast = 0; +static int g_gq_mv = 0; // MV_PROBE: runtime MMA-issue variant of the 2-SM gq launches +static int g_gq_mrev = 0; +static const unsigned long long* g_gq_wcnt = nullptr; +static const unsigned long long* g_gq_wep = nullptr; +static unsigned long long g_gq_wper = 0; +static const unsigned long long* g_gq_wcnt0 = nullptr; static unsigned long long g_gq_wper0 = 0; +static const unsigned* g_gq_acnt = nullptr; static const unsigned* g_gq_wdn = nullptr; static unsigned g_gq_atgt = 0, g_gq_wtgt = 0; +static unsigned* g_gq_rst = nullptr; static int g_gq_nrst = 0; // consumed (cleared) by the next q_b/kv_b gq launch +static int g_gq_nowait = 0, g_gq_trig = 0; // see GQArgs::nowait / trig (set_gq_pdlchain) // launch_gq_gemm (q_b / kv_b) only: reversed m-block traversal +static int g_gq_dyn = 0; // 1: next combined small-M gq launch (BN = 256, wdep) uses the GV_DYN dynamic scheduler +static int g_gq_npw = 16; // promotion warps of the single-problem BN = 256 gq launches (16 or 8) +// Unit lu of a problem with mblk x nblk tiles -> (mb, nb). rast 0: n fastest (consecutive CTAs share an A row-block), +// 1: m fastest (consecutive CTAs share a weight n-block), 2..4: groups of gm = 2/4/8 m-blocks, m fastest inside the +// group, then n, then the next group (L2 tile swizzle; the tail group has fewer m-blocks). +// Per-tile instruction diet: all operands are non-negative, so the mapping uses UNSIGNED division (no signed-division +// sign fix-up sequences) and every remainder is a multiply-subtract of its quotient (one divide per quotient). +__device__ __forceinline__ void gq_map(int lu_, int mblk_, int nblk_, int rast, int& mb, int& nb) { + const unsigned lu = (unsigned)lu_, mblk = (unsigned)mblk_, nblk = (unsigned)nblk_; + if (rast == 1) { const unsigned q = lu / mblk; nb = (int)q; mb = (int)(lu - q * mblk); return; } + if (rast >= 2) { + const unsigned gm = 1u << (rast - 1); + const unsigned span = gm * nblk; + const unsigned grp = lu / span, idx = lu - grp * span; + const unsigned ge = min(gm, mblk - grp * gm); + const unsigned q = idx / ge; + mb = (int)(grp * gm + (idx - q * ge)); nb = (int)q; return; + } + const unsigned q = lu / nblk; + mb = (int)q; nb = (int)(lu - q * nblk); +} +// exact n / d via the host multiplier (see GQArgs::dv_m) +__device__ __forceinline__ int fdiv40(int n, unsigned long long m) { + return (int)(((unsigned long long)(unsigned)n * m) >> 40); +} +// Same mapping as gq_map (problem p of g), divisions replaced by multiply-shift: bit-identical (mb, nb). +__device__ __forceinline__ void gq_map_fast(const GQArgs& g, int p, int lu, int mblk, int rast, int& mb, int& nb) { + if (rast == 1) { nb = fdiv40(lu, g.dv_m[p][0]); mb = lu - nb * g.dv_d[p][0]; return; } + if (rast >= 2) { + const int gm = 1 << (rast - 1); + const int grp = fdiv40(lu, g.dv_m[p][0]), idx = lu - grp * g.dv_d[p][0]; + const bool tail = mblk - grp * gm < gm; + const unsigned long long mg = tail ? g.dv_m[p][2] : g.dv_m[p][1]; + const int ge = tail ? g.dv_d[p][2] : gm; + nb = fdiv40(idx, mg); mb = grp * gm + (idx - nb * ge); return; + } + mb = fdiv40(lu, g.dv_m[p][0]); nb = lu - mb * g.dv_d[p][0]; +} +// host: fill the multipliers of problem p (mblk x nblk units, raster rast); false if out of the exact range +static bool gq_set_div(GQArgs& g, int p, int mblk, int nblk, int rast) { + const int gm = rast >= 2 ? 1 << (rast - 1) : 1; + const int d0 = rast == 1 ? mblk : rast >= 2 ? gm * nblk : nblk; + const int ngrp = (mblk + gm - 1) / gm; + const int dt = rast >= 2 ? mblk - (ngrp - 1) * gm : 1; + const int dd[3] = {d0 > 0 ? d0 : 1, gm, dt > 0 ? dt : 1}; + if ((long long)mblk * nblk >= (1 << 20) || dd[0] >= (1 << 20)) return false; + for (int i = 0; i < 3; ++i) { g.dv_d[p][i] = dd[i]; g.dv_m[p][i] = ((1ull << 40) / (unsigned long long)dd[i]) + 1ull; } + return true; +} +// Compile-time launch variants of gq_kernel (template VF; each launched instantiation contains only its own path): +// GV_PAIR : two problems in one launch (units0 split) + optional host LPT schedule (launch_gq_comb only) +// GV_HINT : output TMA stores with L2::evict_first +// GV_G1 : ragged-N GEMM1 (output boxes at x >= nout skipped, weight-scale pitch ldsb) +// The tile raster (g.rast) stays a runtime value: it is evaluated once per tile in gq_map (not in a k-block loop), +// and the PDL griddepcontrol.wait is unconditional (a no-op for a non-PDL launch, outside every loop). +constexpr int GV_PAIR = 1, GV_HINT = 2, GV_G1 = 4; +// GV_MC (TWO only): 4-CTA cluster = 2 CTA pairs stacked along M (pair p = rank>>1 owns rows +256p of a 512-row +// unit); both pairs need the same 256 B rows, so each CTA TMA-loads 64 of its pair-half's 128 B rows and multicasts +// them to its counterpart in the other pair (halves the L2 -> SM traffic of the B operand). Stage reuse needs both +// pairs' MMAs: empty barriers count 2, MMA commits of the stage multicast to all 4 CTAs. Same MMAs / data / order. +constexpr int GV_MC = 8; +constexpr int GV_SS = 32; +// GV_L3 (BN = 192 GEMM1 only): all 3 x32 TMEM loads of a warp's 96 columns in flight before ONE wait::ld per k-block +// (was 3 load->wait round trips). Same per-column FMUL/FFMA sequence: bit-identical. +constexpr int GV_L3 = 64; +// GV_DYN (1-SM GV_PAIR only, small M): dynamic tile scheduler. The producer warp claims units in ascending order (q_b +// units first = longest first) with one atomicAdd on a per-replay counter g.dctr (zeroed by the norm kernel, which +// completes before any claim) and publishes each unit id through an 8-slot smem ring (ufull / uempty mbarriers) to the +// MMA, store and promotion warps. CTAs that get an SM early (the SMs freed by the A path while the side-stream B wquant +// still occupies the others) therefore process more tiles; the static LPT list cannot adapt to CTA start times. +// Same tiles / MMAs / promotion order per tile: bit-identical outputs. +constexpr int GV_DYN = 128; +// GV_PP (2-SM, BN = 256, 8 promotion warps, single problem; large-M q_b): warpgroup ping-pong. The 256 x 256 pair unit is +// computed as TWO 256 x 128 pair sub-tiles (h = 0: cols n0..+127, h = 1: n0+128..+255); promotion warpgroup cg owns +// sub-tile cg (its full 128 x 128 fp32 accumulators per CTA, all k-blocks). Per k-block the MMA issues sub-tile 0 into +// TMEM cols b*256 (+0) and commits its own tfull[2b], then sub-tile 1 into b*256+128 and tfull[2b+1]: each warpgroup +// has its own tfull / tempty barriers (4 instead of 2), so it drains its partial while the MMA works on the other +// sub-tile and never waits for the other warpgroup's release. B operand: CTA r loads rows n0 + 64r (sub-tile 0) and +// n0 + 128 + 64r (sub-tile 1) as two 64-row boxes, so each N = 128 cta_group::2 MMA sees its 128 B rows split 64/64 +// over the pair. Same TMEM columns, same per-column K=128 products, same promotion order: bit-identical outputs. +constexpr int GV_PP = 256; +// GV_AR (2-SM, BN = 256, 8 promotion warps, single problem, K == 4 * 128; kv_b at mid M): A-operand reuse. A unit is a +// 256-row m-pair x TWO adjacent 256-col n-tiles (h = 0, 1). Each CTA's 128 A rows x 512 K (4 k-blocks, 64 KB) are +// TMA-loaded ONCE into a dedicated smem region during the h = 0 tile (bytes on that k-block's stage full barrier) and +// re-used by the h = 1 tile; the B stage ring carries only B (16 KB per stage, 5 stages). The MMA releases A slot kb +// (aempty[kb], multicast commit to both CTAs) after the h = 1 MMAs of k-block kb, and the producer waits it before +// refilling for the next unit. Tiles / MMAs / promotion per tile unchanged: bit-identical outputs. +constexpr int GV_AR = 512; +constexpr int AR_NKA = 4; // A slots (k-blocks) held per unit +// GV_AR4 (with GV_AR; kv_b at M >= 8192): unit = m-pair x FOUR adjacent 256-col n-tiles (A loaded once by sub-tile 0, +// re-used by sub-tiles 1..3, released after sub-tile 3's MMAs). Same tiles / MMAs / promotion per tile: bit-identical. +constexpr int GV_AR4 = 1024; +// GV_AR8 (with GV_AR; kv_b at M >= 16384): unit = m-pair x EIGHT adjacent 256-col n-tiles (A reused 8x). Bit-identical. +constexpr int GV_AR8 = 2048; +// GV_AR16 (with GV_AR; kv_b at M >= 16384): unit = m-pair x SIXTEEN adjacent 256-col n-tiles (A reused 16x). Bit-identical. +constexpr int GV_AR16 = 4096; +static int g_gq_skel = 0; // host: skeleton switches passed to gq_kernel (probe build only) +void set_gq_skel(int v) { g_gq_skel = v; } +// TWO: the CTA pair (cluster) walks 256-row units u = cluster, cluster + nclusters, ...; this CTA owns rows +// m0 = 256*(m-block) + 128*rank of the unit (single problem, no host schedule). +template +__device__ __forceinline__ bool gq_unit(const GQArgs& g, int i, int& p, int& m0, int& n0, int& nkb, uint32_t rank, + uint8_t* dsm = nullptr, int role = 0) { + int u; + if (TWO) { + constexpr int CL = (VF & GV_MC) ? 4 : 2; // CTAs per cluster + constexpr int UM = (VF & GV_MC) ? 512 : 256; // unit rows + if constexpr ((VF & GV_DYN) != 0) { + uint64_t* uf = reinterpret_cast(dsm); + uint64_t* ue = uf + 8; + int* ring = reinterpret_cast(ue + 8); + const int sl = i & 7; + const uint32_t ph = ((unsigned)i >> 3) & 1u; + const int ln = threadIdx.x & 31; + const bool leader = (rank & 1u) == 0; + if (role == 1 && leader) { + const uint32_t a_ue = su32(ue + sl); + asm volatile("{\n.reg .pred p;\nDYW1_%=:\nmbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 p, [%0], %1;\n" + "@!p bra DYW1_%=;\n}\n" ::"r"(a_ue), "r"(ph ^ 1u) : "memory"); + int v = 0; + if (ln == 0) { + v = (int)atomicAdd(g.dctr, 1ull); + const uint32_t a_r = su32(ring + sl), a_f = su32(uf + sl); + asm volatile("st.shared.u32 [%0], %1;" ::"r"(a_r), "r"(v) : "memory"); + asm volatile("st.shared::cluster.u32 [%0], %1;" ::"r"(mapa_u32(a_r, rank | 1u)), "r"(v) : "memory"); + asm volatile("mbarrier.arrive.release.cluster.shared::cluster.b64 _, [%0];" ::"r"(mapa_u32(a_f, rank)) : "memory"); + asm volatile("mbarrier.arrive.release.cluster.shared::cluster.b64 _, [%0];" ::"r"(mapa_u32(a_f, rank | 1u)) : "memory"); + } + u = __shfl_sync(0xffffffffu, v, 0); + } else { + asm volatile("{\n.reg .pred p;\nDYW0_%=:\nmbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 p, [%0], %1;\n" + "@!p bra DYW0_%=;\n}\n" ::"r"(su32(uf + sl)), "r"(ph) : "memory"); + asm volatile("ld.shared.u32 %0, [%1];" : "=r"(u) : "r"(su32(ring + sl)) : "memory"); + if (role != 2) __syncwarp(); + if (ln == 0) + asm volatile("mbarrier.arrive.release.cluster.shared::cluster.b64 _, [%0];" ::"r"(mapa_u32(su32(ue + sl), rank & ~1u)) : "memory"); + } + } else if constexpr ((VF & GV_AR) != 0) { + constexpr int ARL = (VF & GV_AR16) ? 4 : (VF & GV_AR8) ? 3 : (VF & GV_AR4) ? 2 : 1; // log2(sub-tiles per unit) + u = (int)(blockIdx.x / CL) + (i >> ARL) * (int)(gridDim.x / CL); // logical tile i = unit i/NS, sub-tile i%NS + } else { + u = (int)(blockIdx.x / CL) + i * (int)(gridDim.x / CL); + } + if (u >= g.units) return false; + // GV_PAIR (2-SM): units [0, units0) = problem 0 (q_b), [units0, units) = problem 1 (kv_b); round-robin over clusters + p = (VF & GV_PAIR) ? (u >= g.units0 ? 1 : 0) : 0; + const int lu2 = u - (p ? g.units0 : 0); + int mb, nb; + gq_map_fast(g, p, lu2, (int)((unsigned)g.Mp / UM), g.rast, mb, nb); // == gq_map(lu, Mp/UM, N[p]/BN, rast, ...) + if (g.mrev) mb = (int)((unsigned)g.Mp / UM) - 1 - mb; + m0 = mb * UM + (int)rank * 128; // rank 0..3 (MC): pair rank>>1 at +256, half rank&1 at +128 + constexpr int ARN = (VF & GV_AR16) ? 16 : (VF & GV_AR8) ? 8 : (VF & GV_AR4) ? 4 : 2; // AR: sub-tiles per unit + n0 = (VF & GV_AR) ? nb * (ARN * BN) + (i & (ARN - 1)) * BN : nb * BN; // AR: n-group unit, sub-tile i%ARN + nkb = (int)((unsigned)g.K[p] / BK); + return true; + } + if constexpr ((VF & GV_DYN) != 0) { + // role 1: producer warp (claims), 0: whole consumer warp, 2: single consumer thread + uint64_t* uf = reinterpret_cast(dsm); + uint64_t* ue = uf + 8; + int* ring = reinterpret_cast(ue + 8); + const int sl = i & 7; + const uint32_t ph = ((unsigned)i >> 3) & 1u; + const int ln = threadIdx.x & 31; + if (role == 1) { + bar_wait_f<1>(su32(uf + 8 + sl), ph ^ 1u); // all consumers read slot use i - 8 + int v = 0; + if (ln == 0) { + v = (int)atomicAdd(g.dctr, 1ull); + asm volatile("st.shared.u32 [%0], %1;" ::"r"(su32(ring + sl)), "r"(v) : "memory"); + bar_arrive_a(su32(uf + sl)); + } + u = __shfl_sync(0xffffffffu, v, 0); + } else { + bar_wait_f<1>(su32(uf + sl), ph); + asm volatile("ld.shared.u32 %0, [%1];" : "=r"(u) : "r"(su32(ring + sl)) : "memory"); + if (role == 0) __syncwarp(); + if (ln == 0) bar_arrive_a(su32(ue + sl)); + } + if (u >= g.units) return false; + } else if ((VF & GV_PAIR) && g.sched) { + const int b = __ldg(g.sched + blockIdx.x), e = __ldg(g.sched + blockIdx.x + 1); + if (b + i >= e) return false; + u = __ldg(g.sched + gridDim.x + 1 + b + i); + } else { + u = blockIdx.x + i * gridDim.x; + if (u >= g.units) return false; + } + p = (VF & GV_PAIR) ? (u >= g.units0 ? 1 : 0) : 0; // single-problem variants: p == 0 at compile time + const int lu = u - (p ? g.units0 : 0); + int mb, nb; + gq_map_fast(g, p, lu, (int)((unsigned)g.Mp >> 7), g.rast, mb, nb); // == gq_map(lu, Mp/128, N[p]/BN, rast, ...) + if (g.mrev) mb = (int)((unsigned)g.Mp >> 7) - 1 - mb; + m0 = mb * 128; + n0 = nb * BN; + nkb = (int)((unsigned)g.K[p] / BK); + return true; +} +// TWO (2-SM, cluster 2x1, BN = 256): a CTA pair computes a 256 x 256 tile with tcgen05.mma.cta_group::2 +// (M=256) issued by the leader (rank 0). Each CTA TMA-loads its own 128 A rows and 128 of the 256 B rows into +// its own smem (complete_tx on the LEADER's full barrier, which expects both CTAs' bytes); MMA commits multicast +// to both CTAs' empty / tfull barriers; each CTA's TMEM holds its own 128 rows x 256 cols, so promotion, the +// scale ring (own m0) and the store warp work per CTA exactly as in 1-SM mode; promotion tempty arrivals go to +// the leader's barrier (count 2 x 16). +// NPW = promotion/epilogue warps (16 default; 8: each warp owns 2x the columns = BN/2, CTA of 384 threads, +// promotion warps raised to 232 registers so the 128 fp32 accumulators per thread stay in registers; BN = 256 only). +// Per-column accumulation order is identical for both NPW (bit-identical outputs). +template +__global__ void __launch_bounds__(128 + 32 * NPW, 1) + gq_kernel(const __grid_constant__ CUtensorMap tmap_a0, const __grid_constant__ CUtensorMap tmap_b0, + const __grid_constant__ CUtensorMap tmap_out0, const __grid_constant__ CUtensorMap tmap_a1, + const __grid_constant__ CUtensorMap tmap_b1, const __grid_constant__ CUtensorMap tmap_out1, + const __grid_constant__ GQArgs g) { + constexpr int GBM = 128; + constexpr int A_ST = GBM * BK; // 16 KB + constexpr int B_ROWS = TWO ? BN / 2 : BN; // B rows TMA-loaded by this CTA + constexpr bool AR = (VF & GV_AR) != 0; // A-operand reuse across two n-tiles (see GV_AR) + static_assert(!AR || (TWO && BN == 256 && NPW == 8 && !(VF & (GV_MC | GV_G1 | GV_PAIR | GV_DYN | GV_SS | GV_PP))), "GV_AR config"); + constexpr int A_REG = AR ? AR_NKA * A_ST : 0; // dedicated A region (64 KB) + constexpr int ARL = (VF & GV_AR16) ? 4 : (VF & GV_AR8) ? 3 : (VF & GV_AR4) ? 2 : 1; // AR: log2(sub-tiles per unit) + constexpr int ARM = (1 << ARL) - 1; + (void)ARM; + constexpr int STAGE = (AR ? 0 : A_ST) + B_ROWS * BK; // 48 KB (BN=256) / 32 KB (BN=128 or 2-SM) / 16 KB (AR: B only) + constexpr bool SS = (VF & GV_SS) != 0; // single-buffered half-tile staging (GEMM1) + constexpr int STG = SS ? GBM * BN : GBM * BN * 2; // bf16 staging: whole tile 64 KB (BN=256) / 32 KB (BN=128); SS: half + constexpr int NST = (224 * 1024 - STG - SC_BYTES - A_REG) / STAGE; // 3 / 5 stages (staging + scale ring next to it) + // TBS: TMEM column stride of one k-block buffer (BN = 192 GEMM1 tiles use 256-column slots of the 512 allocation) + constexpr int TBS = BN == 192 ? 256 : BN; + constexpr int NTB = 512 / TBS; // TMEM k-block buffers + constexpr bool PP = (VF & GV_PP) != 0; // warpgroup ping-pong (see GV_PP) + static_assert(!PP || (TWO && BN == 256 && NPW == 8 && !(VF & (GV_MC | GV_G1 | GV_PAIR | GV_DYN | GV_SS))), "GV_PP config"); + constexpr int NTBB = PP ? 2 * NTB : NTB; // tfull / tempty barriers (PP: one per buffer x warpgroup) + // BN = 192 (GEMM1 only): a tile spans up to 5 weight-scale blocks -> 32-B weight-scale chunk (8 floats) + constexpr uint32_t SCTX = BN == 192 ? 512 + 32 : SC_TX; + static_assert(NPW == 16 || (NPW == 8 && (BN == 256 || (BN == 192 && TWO && (VF & GV_G1)))), "8 promotion warps only with BN = 256 (or the 2-SM BN = 192 GEMM1)"); + constexpr int CPW = BN / (NPW / 4); // columns per promotion warp (NPW/4 column groups) + constexpr int NCH = CPW / 16; // 16-col TMEM load chunks per warp + constexpr int BOXES = CPW / 32; + // 32x32 bf16 boxes per promotion warp (2 KB each) + constexpr bool WIDE = CPW % 64 == 0; // CPW/64 32x64 boxes per warp; // BN = 256: one 32x64 SW128 box per warp (full 128-B lines) + // Split staging (CPW = 128, i.e. NPW = 8 with BN = 256): each warp's 2 boxes form two halves (box 0 of every warp = + // half 0, box 1 = half 1) with their own stfull[h] / stempty[h] barriers, so the store warp TMA-stores half 0 while the + // promotion warps still pack half 1. Otherwise one half (= the whole tile). Same bytes / boxes: bit-identical. + constexpr int NH = (WIDE && CPW / 64 == 2) ? 2 : 1; + constexpr int HB = WIDE ? (CPW / 64) / NH : 0; // 32x64 boxes per warp per half + static_assert(!SS || (NH == 2 && HB == 1 && (VF & GV_G1)), "GV_SS: GEMM1 npw8 split staging only"); + extern __shared__ uint8_t smem_raw[]; + uint8_t* sA = reinterpret_cast((reinterpret_cast(smem_raw) + 1023) & ~uintptr_t(1023)); + uint8_t* smem = sA + A_REG; // AR: A region first, then the (B-only) stage ring + (void)sA; + uint8_t* sOut = smem + NST * STAGE; // 16 warps x BOXES x 2 KB staging (one full tile) + uint8_t* sScale = sOut + STG; // NSC scale slots (SC_SLOT bytes each) + uint64_t* full_bar = reinterpret_cast(sScale + SC_BYTES); + uint64_t* empty_bar = full_bar + NST; + uint64_t* tfull = empty_bar + NST; + uint64_t* tempty = tfull + NTBB; + uint64_t* stfull = tempty + NTBB; // staging filled by all 16 promotion warps + uint64_t* stempty = stfull + 2; // staging read out by the TMA stores (2 halves: [0], [1]) + uint64_t* scfull = stempty + 2; // scale slot landed (tx bytes) + uint64_t* scempty = scfull + NSC; // (old protocol, skeleton probe only) scale slot read + uint32_t* tmem_slot = reinterpret_cast(scempty + NSC); + uint8_t* dsm = reinterpret_cast(scempty + NSC + 1); // GV_DYN: ufull[8], uempty[8], unit ring[8] + uint64_t* aempty = reinterpret_cast(dsm); // AR (never with GV_DYN): A slot kb free (count 1) + (void)aempty; + static_assert(OLDP_STATIC || NSC >= NST + NTB, "scale slot reuse must be implied by the empty-barrier chain"); + + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int Mp = g.Mp; + const uint32_t rank = TWO ? cluster_rank() : 0u; + // tcgen05.commit multicast masks: stage-empty -> every CTA whose smem stage the pair's loads touch (MC: all 4), + // tfull -> both CTAs of this pair (ranks 2p, 2p+1) + const uint32_t EMK = (VF & GV_MC) ? 0xFu : 3u; + const uint32_t TMK = (VF & GV_MC) ? (3u << (rank & 2u)) : 3u; + (void)EMK; (void)TMK; + TLG_S(g.nout ? 10 : g.N[0] == 24576 ? 4 : 6); +#ifdef GQ_SKEL + const int SK = g.skel; + const bool LSC = (g.skel >> 29) & 1, V4 = (g.skel >> 30) & 1; + const int NACT = ((g.skel >> 24) & 31) ? ((g.skel >> 24) & 31) : NPW; + const int MV = (g.skel >> 19) & 15; // MMA-issue variant bits (see MV_* below) + const bool OLDP = (g.skel & 1024) != 0; // 1024: previous protocol (per-warp tempty arrives + scempty ring) + const bool AGG = !OLDP && !(g.skel & 2048); // 2048: no scempty, but per-warp tempty arrives + const int WNH = g.skel; // W_* bits: un-hinted single-thread waits + long long skc0 = 0, skg0 = 0; + if (threadIdx.x == 0) { skc0 = clock64(); asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(skg0)); } +#else + constexpr int SK = 0; + constexpr int NACT = NPW; + constexpr bool LSC = GQ_LSC != 0, V4 = GQ_V4 != 0; + // production: scale-slot reuse implied by the empty/tempty chain whenever NSC >= NST + NTB (see the producer), so the + // per-k-block scempty arrive (promotion) + wait (producer) are dropped; only 1-SM BN=128 (NST 5 + NTB 4 > 8) keeps them. + constexpr bool OLDP = NSC < NST + NTB; + constexpr bool AGG = false; + constexpr int WNH = GQ_WNH; // single-thread waits without suspend hint (see bar_wait_1t) +#ifdef MV_PROBE + const int MV = g.mv; // probe build: runtime MMA-issue variant +#else + constexpr int MV = GQ_MV; // 1-SM gq instantiations use the same elect.sync / running-counter issuer +#endif +#endif +#ifdef CLK_PROBE + long long ck0 = 0, gt0 = 0; + if (threadIdx.x == 0) { ck0 = clock64(); asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(gt0)); } +#endif + + if (threadIdx.x == 0) { + for (int i = 0; i < NST; ++i) { bar_init(&full_bar[i], 1); bar_init(&empty_bar[i], (VF & GV_MC) ? 2 : 1); } + if constexpr (AR) for (int i = 0; i < AR_NKA; ++i) bar_init(&aempty[i], 1); + for (int i = 0; i < NTBB; ++i) { bar_init(&tfull[i], 1); bar_init(&tempty[i], (PP ? NACT / 2 : AGG ? NACT / 4 : NACT) * (TWO ? 2 : 1)); } + for (int i = 0; i < 2; ++i) { bar_init(&stfull[i], NACT); bar_init(&stempty[i], 1); } + for (int i = 0; i < NSC; ++i) { bar_init(&scfull[i], 1); bar_init(&scempty[i], NACT); } + if constexpr ((VF & GV_DYN) != 0) { + uint64_t* uf = reinterpret_cast(dsm); + // 1-SM: + MMA warp + store thread; 2-SM (leader's uempty): both CTAs' promotion warps + store threads, leader MMA + // warp, peer producer warp + for (int i = 0; i < 8; ++i) { bar_init(uf + i, 1); bar_init(uf + 8 + i, TWO ? 2 * NACT + 4 : NACT + 2); } + } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_a0)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_b0)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_out0)) : "memory"); + if ((VF & GV_PAIR) && g.units0 < g.units) { + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_a1)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_b1)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&tmap_out1)) : "memory"); + } + if (TWO) { // 2-SM scale tensor maps (kernel params, constant): prefetched in the prologue, before the PDL wait + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&g.smap_a)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&g.smap_b)) : "memory"); + if (VF & GV_PAIR) { + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&g.smap_a1)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&g.smap_b1)) : "memory"); + } + } + } + if (warp == 1) { + if (TWO) { + asm volatile("tcgen05.alloc.cta_group::2.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(su32(tmem_slot)), "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"(su32(tmem_slot)), "r"(512)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + } + f_before(); + if (TWO) cluster_sync(); else __syncthreads(); // both CTAs' barriers initialised before any remote op + f_after(); + const uint32_t tmem_base = *tmem_slot; + // PDL: the prologue above overlapped the predecessor's tail; its outputs (A operand / scales) are now visible. + // nowait (kv_b launched as PDL dependent of q_b): kv_b reads only norm / B-quant outputs, which completed before q_b + // could trigger (q_b triggers after its own griddepcontrol.wait / after stream-ordered events), so no wait is needed. + if (!g.nowait) pdl_wait(); + if (g.rst && blockIdx.x == 0) // end-of-replay reset of the early-start / tile counters (all their readers done) + for (int i = threadIdx.x; i < g.nrst; i += blockDim.x) g.rst[i] = 0u; + // trig == 2 (M=512 chain, wq bit21): the predecessor (norm) is complete -> let the PDL dependent (kv_b, co-running + // on the SMs this grid leaves free) launch right away. + if (g.trig == 2) asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); + TLG_S(g.nout ? 11 : g.N[0] == 24576 ? 5 : 7); + if (!g.nout) NTP(g.N[0] == 24576 ? 16896 : 16640); + + // setmaxnreg sits at the top of each role branch (no control-flow rejoin before the final barrier), + // so ptxas allocates each role's code with its own register budget. + if (warp < 4) { + asm volatile("setmaxnreg.dec.sync.aligned.u32 32;\n" ::: "memory"); + if (warp == 0) { + // ---------------- TMA producer + // Producer diet (SASS audit: per k-block ~75 instr, each TMA wrapped in its own ELECT/uniformity loop because the + // single-lane producer computed coordinates in a divergent region): the WHOLE warp now walks the tile / k-block + // loops (all coordinates warp-uniform), all lanes wait on the stage's empty barrier, and ONE lane (elected once + // per CTA) issues the expect_tx + all TMA ops of the k-block in a single region. Ring stage / phase are a running + // pair (NST is not a power of two), the scale slot is it & (NSC-1), coordinates advance incrementally. + // Same loads / barriers / bytes / order: bit-identical. + if (!(SK & 16)) { +#ifdef GQ_PROF + long long pacc[16] = {0}; +#endif + SKDECL(sk_pe = 0, sk_pt = 0); + SKT(spt0); + uint32_t el; + asm volatile("{\n.reg .pred P;\nelect.sync _|P, 0xffffffff;\nselp.u32 %0, 1, 0, P;\n}" : "=r"(el)); + static_assert((NSC & (NSC - 1)) == 0, "NSC must be a power of two"); + uint32_t it = 0; + int s = 0; // ring stage (== it % NST) + uint32_t ps = 0; // its phase parity (== (it / NST) & 1) + uint32_t soff = 0; // s * STAGE + const uint32_t full_lead = TWO ? mapa_u32(su32(full_bar), rank & ~1u) : 0u; // leader's full barriers (2-SM) + uint64_t lpolicy = 0; // L2 evict_last policy for the operand loads selected by g.lpol (cache policy only) + if (g.lpol) asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(lpolicy)); + const uint32_t a_empty = su32(empty_bar); + // B weights / weight scales come from the side-stream wquant (no graph edge): acquire-wait its completion. + // wcnt0: problem 0 (q_b) has its own segment counter -> wait for it first, the full counter before a problem-1 unit. + auto wwait = [&](const unsigned long long* c, unsigned long long tgt) { + unsigned long long v; + unsigned ns = 32; + for (;;) { + asm volatile("ld.acquire.gpu.global.u64 %0, [%1];" : "=l"(v) : "l"(c) : "memory"); + if (v >= tgt) break; + __nanosleep(ns); + if (ns < 128) ns <<= 1; + } + asm volatile("fence.proxy.async.global;" ::: "memory"); // generic acquire -> async-proxy (TMA) reads + }; + const unsigned long long wep_v = g.wcnt ? ldcg_u64v(g.wep) : 0ull; + bool wfull = g.wcnt == nullptr; + if (g.wcnt) { + if (g.wcnt0) wwait(g.wcnt0, wep_v * g.wper0); + else { wwait(g.wcnt, wep_v * g.wper); wfull = true; } + } + int p, m0, n0, nkb; + int rbw = -1; + if constexpr ((VF & GV_G1) != 0) { + if (g.wdn) { poll_ge(g.wdn, g.wtgt); asm volatile("fence.proxy.async.global;" ::: "memory"); } + } + __syncwarp(); + for (int ui = 0; gq_unit(g, ui, p, m0, n0, nkb, rank, dsm, 1); ++ui) { + if (!wfull && p != 0) { wwait(g.wcnt, wep_v * g.wper); wfull = true; __syncwarp(); } + if constexpr ((VF & GV_G1) != 0) { + // early start: this CTA's 128 A rows (fp8 codes + 1x128 scales) quantized? + if (g.acnt && (m0 >> 7) != rbw) { + rbw = m0 >> 7; + poll_ge(g.acnt + rbw, g.atgt); + asm volatile("fence.proxy.async.global;" ::: "memory"); + __syncwarp(); + } + } + const CUtensorMap* ma = p ? &tmap_a1 : &tmap_a0; + const CUtensorMap* mb = p ? &tmap_b1 : &tmap_b0; + const float* sfa = g.sfa[p]; + const float* sfb = g.sfb[p]; + const int N = g.N[p]; + const size_t sbstep = (size_t)((VF & GV_G1) ? g.ldsb : (N >> 7)); + const float* psa = sfa + m0; + const float* psb = sfb + ((n0 >> 7) & ~3); + const int brow = n0 + (int)rank * B_ROWS; + const int sbx = (n0 >> 7) & ~3; + int kx = 0; // kb * BK +#pragma unroll 1 + for (int kb = 0; kb < nkb; ++kb, ++it, kx += BK, psa += Mp, psb += sbstep) { + // Scale slot it % NSC is refilled without a scale-empty barrier: the wait on empty[s] for k-block it - NST + // means MMA(it - NST) retired, which was issued only after tempty showed that ALL promotion warps finished + // k-block it - NST - NTB >= it - NSC; each warp reads a k-block's scales before its tempty arrival. + PCLK(pw0); + SKT(se0); + if (WNH & W_PROD) bar_wait_f<1>(a_empty + 8 * s, ps ^ 1); + else bar_wait_a(a_empty + 8 * s, ps ^ 1); + // AR, sub-tile 0: A slot kb must have been released by the previous unit's sub-tile-1 MMAs + const bool lda = !AR || (ui & ARM) == 0; + if constexpr (AR) { if (lda) bar_wait_a(su32(&aempty[kb]), (((unsigned)ui >> ARL) & 1u) ^ 1u); } + SKT(se1); SKA(sk_pe, se0, se1); + PCLK(pw1); PADD(3, pw1 - pw0); + const int q = (int)(it & (NSC - 1)); + if (OLDP && !(SK & 1)) bar_wait_1t(&scempty[q], ((it / NSC) & 1) ^ 1, WNH & W_PROD); + if (el) { + uint8_t* st = smem + soff; + uint8_t* sl = sScale + q * SC_SLOT; + if (SK & 1) { // skeleton: handoffs only + if (!TWO || (rank & 1u) == 0) bar_arrive_a(su32(&full_bar[s])); + if (OLDP && !(SK & 32)) bar_wait_1t(&scempty[q], ((it / NSC) & 1) ^ 1, WNH & W_PROD); + if (TWO) bar_arrive_a(su32(&scfull[q])); + } else if (TWO) { + // the leader's barrier expects both CTAs' bytes (operands + scales; the peer's complete_tx may land + // first: allowed, the phase cannot complete before the leader's arrive.expect_tx) + const uint32_t fb = full_lead + 8 * s; + if ((rank & 1u) == 0) bar_expect(&full_bar[s], 2 * (STAGE + SCTX + (AR && lda ? A_ST : 0))); + // this k-block's scales -> own CTA's scale ring slot (bytes complete on the leader's full barrier). + // Issued FIRST: the two tiny (512 B + 16/32 B) scale boxes no longer queue behind the 2 x 16 KB operand + // boxes in the TMA unit, so their L2 round trip overlaps the operand transfer instead of trailing it + // (the full barrier completes on the last byte). Same loads / barrier / bytes: bit-identical. + tma_ld2(sl, p ? &g.smap_a1 : &g.smap_a, fb, m0, kb); + tma_ld2(sl + 512, p ? &g.smap_b1 : &g.smap_b, fb, sbx, kb); + if constexpr (AR) { + if (lda) { // A slot kb (sub-tile 0 only), B into the B-only stage + if (g.lpol & 2) tma_ld2_hint(sA + kb * A_ST, ma, fb, kx, m0, lpolicy); + else tma_ld2(sA + kb * A_ST, ma, fb, kx, m0); + } + if (g.lpol & 1) tma_ld2_hint(st, mb, fb, kx, brow, lpolicy); + else tma_ld2(st, mb, fb, kx, brow); + } else { + int ax = kx, ay = m0; + if constexpr ((VF & GV_G1) != 0) { if (g.atk) { ax = 0; ay = (((m0 >> 7) * g.atk) + kb) << 7; } } + if (g.lpol & 2) tma_ld2_hint(st, ma, fb, ax, ay, lpolicy); + else tma_ld2(st, ma, fb, ax, ay); + if constexpr ((VF & GV_MC) != 0) { + const uint32_t h = rank & 1u, pr = rank >> 1; + tma_ld2_mc(st + A_ST + pr * (B_ROWS / 2) * BK, mb, fb, kx, + n0 + (int)h * B_ROWS + (int)pr * (B_ROWS / 2), (uint16_t)((1u << h) | (1u << (h + 2)))); + } else if constexpr (PP) { + // two 64-row B boxes: sub-tile h rows n0 + 128h + 64*rank -> stage B offset h * 8 KB +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int br = n0 + 128 * h + 64 * (int)(rank & 1u); + if (g.lpol & 1) tma_ld2_hint(st + A_ST + h * 8192, mb, fb, kx, br, lpolicy); + else tma_ld2(st + A_ST + h * 8192, mb, fb, kx, br); + } + } else { + if (g.lpol & 1) tma_ld2_hint(st + A_ST, mb, fb, kx, brow, lpolicy); + else tma_ld2(st + A_ST, mb, fb, kx, brow); + } + } + (void)psa; (void)psb; + } else { + // 1-SM: operands + scales on the SAME full barrier (one expect_tx) + bar_expect(&full_bar[s], STAGE + SC_TX); + // scales FIRST (as the 2-SM path): the tiny 512 B + 16 B bulk copies no longer queue behind the + // 16 KB + BN*128 B operand boxes. Same loads / barrier / bytes: bit-identical. + bulk_ld(sl, psa, 512, &full_bar[s]); // == sfa + kb*Mp + m0 (pointer walk) + bulk_ld(sl + 512, psb, 16, &full_bar[s]); // == sfb + kb*sbstep + ((n0>>7)&~3) + tma_ld(st, ma, &full_bar[s], kx, m0); + tma_ld(st + A_ST, mb, &full_bar[s], kx, n0); + } + } + // (no per-k-block __syncwarp: every lane waits the next stage's empty barrier itself, and the elected lane's + // expect_tx / TMA ops are not .aligned, so no reconvergence point is needed; same loads / order) + if (++s == NST) { s = 0; ps ^= 1u; soff = 0; } else soff += STAGE; + } + } + PFLUSH(3); + // trig: this CTA claimed all its tiles -> allow the PDL dependent (kv_b) grid to launch; its CTAs take SMs as + // the q_b CTAs retire (fills q_b's wave tail). + if (g.trig == 1) asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); + SKT(spt1); SKA(sk_pt, spt0, spt1); SKF(4, sk_pe); SKF(5, sk_pt); + } + } else if (warp == 1) { + // ---------------- MMA issuer (2-SM: only the leader issues, for both CTAs) + if ((rank & 1u) == 0 && (MV & (MV_GATE | MV_ELECT))) { + // whole-warp issuer: waits (gate: named barrier from warp 3; elect: all lanes poll the mbarriers), then one + // elect.sync lane issues the 4 MMAs + commits. Stage descriptors precomputed (sdesc is linear in the address). + const uint32_t idesc = (1u << 4) | ((uint32_t)(BN >> 3) << 17) | ((uint32_t)((TWO ? 2 * GBM : GBM) >> 4) << 24); + // AR: A descriptor base = A region (slot kb), B descriptor base = B-only stage ring + const uint64_t ad0 = sdesc(AR ? su32(sA) : su32(smem)), bd0 = sdesc(su32(smem) + (AR ? 0 : A_ST)); + // instruction diet: ring position (stage s / phase ps, TMEM buffer b / phase pb) and the stage's descriptor + // offset are carried as running counters (no per-k-block it % NST, it / NST, s * STAGE); barrier addresses are + // one base + 8 * index; the issuing lane is elected ONCE per CTA (whole warp converged here). + constexpr uint64_t DST = (uint64_t)(STAGE >> 4); + const uint32_t a_full = su32(full_bar), a_tempty = su32(tempty); + uint32_t el; + asm volatile("{\n.reg .pred P;\nelect.sync _|P, 0xffffffff;\nselp.u32 %0, 1, 0, P;\n}" : "=r"(el)); + // MMA-issue diet (SASS audit: ~14 64-bit descriptor adds + ~18 ring-counter USEL/UISETP per k-block): ONE k-block + // counter `it`; for power-of-two rings (2-SM: NST = 4, NTB = 2) stage / buffer / phases are bit-extracts of it, + // non-power-of-two stage rings keep a running (s, ps) pair. Descriptors are split into a constant hi word and a + // lo word (start-address field, < 2^14 -> no carry, bit-identical to the 64-bit add): stage lo = base + + // s * (STAGE >> 4), k-step +2 as immediates inside ONE asm block issuing the 4 MMAs; commits take precomputed + // shared addresses. + constexpr bool P2S = (NST & (NST - 1)) == 0; + constexpr uint32_t LNTB = NTB == 1 ? 0 : NTB == 2 ? 1 : NTB == 4 ? 2 : 3; + static_assert((1 << LNTB) == NTB, "NTB power of two"); + const uint32_t alo0 = (uint32_t)ad0, ahi = (uint32_t)(ad0 >> 32), blo0 = (uint32_t)bd0, bhi = (uint32_t)(bd0 >> 32); + const uint32_t a_empty = su32(empty_bar), a_tfull = su32(tfull); + uint32_t it = 0; + uint32_t s_r = 0, ps_r = 0, so_r = 0; // non-power-of-two stage ring only + (void)DST; + SKDECL(sk_mt = 0, sk_mf = 0, sk_mtot = 0, sk_mc = 0); + SKT(smt0); + int p, m0, n0, nkb; + for (int ui = 0; gq_unit(g, ui, p, m0, n0, nkb, rank, dsm, 0); ++ui) { + const uint32_t ite = it + (uint32_t)nkb; +#pragma unroll 1 + for (; it != ite; ++it) { + uint32_t s, ps, so; + if constexpr (P2S) { s = it & (NST - 1); ps = (it / NST) & 1u; so = s * (uint32_t)(STAGE >> 4); } + else { s = s_r; ps = ps_r; so = so_r; } + const uint32_t b = it & (NTB - 1), pb = (it >> LNTB) & 1u; + SKT(sm0); + if constexpr (PP) { + static_assert(P2S, "PP: power-of-two stage ring (loop tail skipped by continue)"); + // ping-pong: sub-tile 0 (warpgroup 0) then sub-tile 1 (warpgroup 1), each N = 128 into its TMEM half, + // each with its own tempty wait / tfull commit; the stage is released after both. + constexpr uint32_t idesc_h = (1u << 4) | ((uint32_t)(128 >> 3) << 17) | ((uint32_t)((2 * GBM) >> 4) << 24); + bar_wait_f<0>(a_full + 8 * s, ps); +#pragma unroll + for (uint32_t h = 0; h < 2; ++h) { + bar_wait_f<0>(a_tempty + 8 * (2 * b + h), pb ^ 1); + f_after(); + if (el) { + mma4<2>(tmem_base + b * TBS + h * 128, alo0 + so, ahi, blo0 + so + h * (8192 >> 4), bhi, idesc_h); + commit2a(TMK, a_tfull + 8 * (2 * b + h)); + } + } + if (el) commit2a(EMK, a_empty + 8 * s); + continue; + } + if (MV & MV_GATE) { + asm volatile("bar.sync %0, 64;" ::"r"(8 + b) : "memory"); + } else { + if (MV & MV_TW) { + if (!(SK & 32)) bar_wait_f<2>(a_tempty + 8 * b, pb ^ 1); + if (!(SK & 16)) bar_wait_f<2>(a_full + 8 * s, ps); + } else { + // operands first, then the TMEM buffer's tempty right before the k-block's first MMA (the buffer of + // k-block it-NTB is the last dependency to clear; waiting it last keeps it off the operand-wait path) + if (!(SK & 16)) bar_wait_f<0>(a_full + 8 * s, ps); + if (!(SK & 32)) bar_wait_f<0>(a_tempty + 8 * b, pb ^ 1); // hinted try_wait (energy diet) + } + } + SKT(sm1); SKA(sk_mt, sm0, sm1); + f_after(); + SKT(sc0); + if (el) { + const uint32_t td = tmem_base + b * TBS; + if (SK & 2) {} + else if constexpr (AR) { + const uint32_t kbl = it - (ite - (uint32_t)nkb); // k-block inside this tile + mma4<2>(td, alo0 + kbl * (uint32_t)(A_ST >> 4), ahi, blo0 + so, bhi, idesc); + if ((ui & ARM) == ARM) commit2a(3u, su32(&aempty[kbl])); // A slot kb free once the last sub-tile's MMAs retire + } + else mma4(td, alo0 + so, ahi, blo0 + so, bhi, idesc); + if (TWO) { commit2a(EMK, a_empty + 8 * s); commit2a(TMK, a_tfull + 8 * b); } + else { commit1a(a_empty + 8 * s); commit1a(a_tfull + 8 * b); } + } + // (dropped the per-k-block __syncwarp: the next iteration's mbarrier waits are per-lane and the elected + // lane's MMAs/commits are not .aligned, so no warp reconvergence point is needed here) + SKT(sc1); SKA(sk_mc, sc0, sc1); + if constexpr (!P2S) { if (++s_r == NST) { s_r = 0; ps_r ^= 1u; so_r = 0; } else so_r += (uint32_t)(STAGE >> 4); } + } + } + SKT(smt1); SKA(sk_mtot, smt0, smt1); + if (lane == 0) { SKF(6, sk_mt); SKF(7, sk_mf); SKF(8, sk_mtot); SKF(11, sk_mc); } + } else if (lane == 0 && (rank & 1u) == 0) { + // instr descriptor: D=f32 (bit 4), A=B=e4m3, both K-major, N>>3 @ bit 17, M>>4 @ bit 24 + const uint32_t idesc = (1u << 4) | ((uint32_t)(BN >> 3) << 17) | ((uint32_t)((TWO ? 2 * GBM : GBM) >> 4) << 24); +#ifdef GQ_PROF + long long pacc[16] = {0}; +#endif + uint32_t it = 0; + SKDECL(sk_mt = 0, sk_mf = 0, sk_mtot = 0); + SKT(smt0); + PCLK(mt0); + int p, m0, n0, nkb; + for (int ui = 0; gq_unit(g, ui, p, m0, n0, nkb, rank, dsm, 2); ++ui) { +#pragma unroll 1 // keep the single-thread producer / MMA loops rolled (small register budget) + for (int kb = 0; kb < nkb; ++kb, ++it) { + const int s = ((unsigned)it % NST); + const int b = ((unsigned)it % NTB); + PCLK(mw0); + SKT(sm0); + if (!(SK & 32)) { // promotion drained this TMEM buffer + if ((SK & 4096) || (MV & MV_TW)) bar_wait_f<2>(su32(&tempty[b]), ((((unsigned)it / NTB)) & 1) ^ 1); + else bar_wait_1t(&tempty[b], ((((unsigned)it / NTB)) & 1) ^ 1, WNH & W_MTEMPTY); + } + PCLK(mw1); + SKT(sm1); + if (!(SK & 16)) { // operands landed + if (MV & MV_TW) bar_wait_f<2>(su32(&full_bar[s]), (((unsigned)it / NST)) & 1); + else bar_wait_1t(&full_bar[s], (((unsigned)it / NST)) & 1, WNH & W_MFULL); + } + SKT(sm2); SKA(sk_mt, sm0, sm1); SKA(sk_mf, sm1, sm2); + PCLK(mw2); PADD(1, mw1 - mw0); PADD(2, mw2 - mw1); + if (!(SK & 512)) f_after(); + PCLK(mi0); + const uint32_t sa_addr = su32(smem + s * STAGE); + const uint64_t ad = sdesc(sa_addr), bd = sdesc(sa_addr + A_ST); + const uint32_t td = tmem_base + b * TBS; +#pragma unroll + for (int k = 0; k < BK / 32; ++k) // +32 B along K inside the 128B swizzle atom + if (SK & 2) {} + else if (TWO) mma2(td, ad + 2 * k, bd + 2 * k, idesc, k > 0 ? 1u : 0u); + else mma(td, ad + 2 * k, bd + 2 * k, idesc, k > 0 ? 1u : 0u); + if (SK & 128) { // skeleton: plain mbarrier arrives instead of tcgen05.commit + if (TWO) { + bar_arrive_cl(mapa_u32(su32(&empty_bar[s]), 0)); bar_arrive_cl(mapa_u32(su32(&empty_bar[s]), 1)); + if (!(SK & 64)) { bar_arrive_cl(mapa_u32(su32(&tfull[b]), 0)); bar_arrive_cl(mapa_u32(su32(&tfull[b]), 1)); } + } else { + bar_arrive_a(su32(&empty_bar[s])); + if (!(SK & 64)) bar_arrive_a(su32(&tfull[b])); + } + } else if (SK & 64) { if (TWO) commit2m(EMK, &empty_bar[s]); else commit(&empty_bar[s]); } + else if (MV & MV_LAG) { // commit of the PREVIOUS k-block after this k-block's MMAs + if (it > 0) { + const int sp = ((unsigned)(it - 1) % NST), bp = ((unsigned)(it - 1) % NTB); + if (TWO) { commit2m(EMK, &empty_bar[sp]); commit2m(TMK, &tfull[bp]); } + else { commit(&empty_bar[sp]); commit(&tfull[bp]); } + } + } + else if (TWO) { commit2m(EMK, &empty_bar[s]); commit2m(TMK, &tfull[b]); } // multicast to both CTAs of the pair + else { + commit(&empty_bar[s]); // smem stage free once these MMAs retire + commit(&tfull[b]); // partial ready for promotion + } + PCLK(mi1); PADD(11, mi1 - mi0); + } + } + if ((MV & MV_LAG) && !(SK & (64 | 128)) && it > 0) { // last k-block's commits + const int sp = ((unsigned)(it - 1) % NST), bp = ((unsigned)(it - 1) % NTB); + if (TWO) { commit2m(EMK, &empty_bar[sp]); commit2m(TMK, &tfull[bp]); } + else { commit(&empty_bar[sp]); commit(&tfull[bp]); } + } + SKT(smt1); SKA(sk_mtot, smt0, smt1); SKF(6, sk_mt); SKF(7, sk_mf); SKF(8, sk_mtot); + PCLK(mt1); PADD(0, mt1 - mt0); PADD(10, it); PFLUSH(0); PFLUSH(1); PFLUSH(2); PFLUSH(10); PFLUSH(11); + } + } else if (warp == 2) { + // ---------------- output store warp: per tile, wait until the 16 promotion warps filled the staging, + // issue all 32x32 TMA stores, wait until they have READ the staging, then hand it back. Promotion + // warps never wait on bulk-store completion (they go straight on to the next tile's k-blocks). + if (lane == 0 && !(SK & 32)) { +#ifdef GQ_PROF + long long pacc[16] = {0}; +#endif + uint32_t t = 0; + uint64_t spol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(spol)); + if ((VF & GV_G1) && g.g1sl) asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(spol)); + PCLK(st0); + int p, m0, n0, nkb; + for (int ui = 0; gq_unit(g, ui, p, m0, n0, nkb, rank, dsm, 2); ++ui, ++t) { + const CUtensorMap* mo = p ? &tmap_out1 : &tmap_out0; +#pragma unroll + for (int hh = 0; hh < NH; ++hh) { + PCLK(sw0); + bar_wait_1t(&stfull[hh], t & 1, WNH & W_STORE); + PCLK(sw1); PADD(7, sw1 - sw0); +#pragma unroll // energy diet: constant staging offsets / (sub, cg) per box, no loop counter math + for (int i = 0; i < NPW; ++i) { + const int sub = (i + 4) & 3, cg = i >> 2; // promotion warp 4+i -> rows / column group + if (SK & 8) {} + else if constexpr (WIDE) { // CPW/64 32 x 64 boxes (4 KB each) per promotion warp +#pragma unroll + for (int h = hh * HB; h < (hh + 1) * HB; ++h) { + if ((VF & GV_G1) && n0 + cg * CPW + h * 64 >= g.nout) continue; // ragged N (GEMM1): box fully past the output + if constexpr (SS) { tma_st(mo, sOut + i * 4096, n0 + cg * CPW + h * 64, m0 + sub * 32); continue; } + if ((VF & GV_HINT) || ((VF & GV_G1) && g.g1sl)) tma_st_hint(mo, sOut + i * BOXES * WSTAGE_BYTES + h * 4096, n0 + cg * CPW + h * 64, m0 + sub * 32, spol); + else tma_st(mo, sOut + i * BOXES * WSTAGE_BYTES + h * 4096, n0 + cg * CPW + h * 64, m0 + sub * 32); + } + } else { +#pragma unroll 1 + for (int ch = 0; ch < BOXES; ++ch) { + if (VF & GV_HINT) tma_st_hint(mo, sOut + (i * BOXES + ch) * WSTAGE_BYTES, n0 + cg * CPW + ch * 32, m0 + sub * 32, spol); + else tma_st(mo, sOut + (i * BOXES + ch) * WSTAGE_BYTES, n0 + cg * CPW + ch * 32, m0 + sub * 32); + } + } + } + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + if constexpr (SS) { // this half's stores have read the (single) staging -> hand it back + asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); + bar_arrive_a(su32(&stempty[0])); + } + } + PCLK(sr0); + if constexpr (SS) {} + else { + if constexpr (NH == 2) { // half 0's stores have read the staging -> hand it back first + asm volatile("cp.async.bulk.wait_group.read 1;" ::: "memory"); + bar_arrive_a(su32(&stempty[0])); + } + asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); + PCLK(sr1); PADD(8, sr1 - sr0); + bar_arrive_a(su32(&stempty[NH - 1])); + } + if ((VF & GV_G1) && g.mcnt) { + // tile's global writes complete -> publish (release) to the row-block counter polled by norm_fast + asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); + asm volatile("fence.proxy.async.global;" ::: "memory"); + asm volatile("red.release.gpu.global.add.u32 [%0], %1;" ::"l"(g.mcnt + (m0 >> 7)), "r"(1u) : "memory"); + } + } + asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); // global writes complete before exit + PCLK(st1); PADD(9, st1 - st0); PFLUSH(7); PFLUSH(8); PFLUSH(9); + } + } else if (warp == 3) { + // ---------------- gate warp (MV_GATE): waits the MMA's mbarriers, hands k-block `it` to the MMA warp via named + // barrier 8 + it % NTB. Reusing an id for k-block it + NTB requires tempty of that buffer, i.e. promotion of k-block + // it, i.e. the MMA warp already passed its bar.sync for it -> no phase aliasing. + if ((rank & 1u) == 0 && (MV & MV_GATE)) { + uint32_t it = 0; + int p, m0, n0, nkb; + for (int ui = 0; gq_unit(g, ui, p, m0, n0, nkb, rank, dsm, 0); ++ui) { +#pragma unroll 1 + for (int kb = 0; kb < nkb; ++kb, ++it) { + const int s = ((unsigned)it % NST); + const int b = ((unsigned)it % NTB); + if (lane == 0) { + if (!(SK & 32)) bar_wait_f<1>(su32(&tempty[b]), ((((unsigned)it / NTB)) & 1) ^ 1); + if (!(SK & 16)) bar_wait_f<1>(su32(&full_bar[s]), (((unsigned)it / NST)) & 1); + } + __syncwarp(); + asm volatile("bar.arrive %0, 64;" ::"r"(8 + b) : "memory"); + } + } + } + } + } else { + // 16 warps: launch 96, WG0 dec 32 frees 128x64 = 512x16 -> 112. 8 warps (384 threads): launch 168, WG0 dec 32 + // frees 128x136 = 17408 >= 256x64 -> 232. + asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;\n" ::"n"(NPW == 16 ? 112 : 232) : "memory"); + // ---------------- promotion + epilogue (NPW warps, 4..3+NPW) + const int sub = warp & 3; // TMEM sub-partition -> rows 32*sub..32*sub+31 + const int cg = (warp - 4) >> 2; // column group of CPW columns + const int row = sub * 32 + lane; + uint32_t tl = 0; // local tile counter (staging barrier parity) + // Register diet (the promotion loop sat at the 112-register cap and spilled): every shared-memory address of + // the loop is ONE base register + a compile-time offset (folded into the instruction's immediate) instead of + // one hoisted register per barrier array / buffer. + const uint32_t sbase = su32(smem); + constexpr uint32_t O_SC = NST * STAGE + STG; // scale ring + constexpr uint32_t O_BAR = O_SC + SC_BYTES; // full_bar + constexpr uint32_t O_TFULL = O_BAR + 8 * (2 * NST); + constexpr uint32_t O_TEMPTY = O_TFULL + 8 * NTBB; + constexpr uint32_t O_STFULL = O_TEMPTY + 8 * NTBB; + constexpr uint32_t O_STEMPTY = O_STFULL + 16; + constexpr uint32_t O_SCFULL = O_STEMPTY + 16; + constexpr uint32_t O_SCEMPTY = O_SCFULL + 8 * NSC; + // tempty barriers (8 B apart): local (1-SM) or the leader's copy (2-SM, shared::cluster address) + const uint32_t tempty_cl = TWO ? mapa_u32(sbase + O_TEMPTY, rank & ~1u) : 0u; + const uint32_t tm_warp = tmem_base + ((uint32_t)(sub * 32) << 16) + cg * CPW; + // TMEM buffer release: the 4 warps of a column group (= one warpgroup, warps 4+4cg..7+4cg, same TMEM + // columns, all 4 sub-partitions) meet on named barrier 1+cg after their tcgen05.ld's completed; ONE elected + // lane then arrives on tempty (count 4 per CTA instead of 16 per-warp arrivals on one mbarrier per k-block). + auto release_tb = [&](uint32_t bo) { // bo = 8 * TMEM buffer index (barrier byte offset) + f_before(); + if (!AGG) { + __syncwarp(); + if (lane == 0) { + if (TWO) bar_arrive_cl(tempty_cl + bo); + else bar_arrive_a(sbase + O_TEMPTY + bo); + } + } else { + asm volatile("bar.sync %0, 128;" ::"r"(1 + cg) : "memory"); + if (sub == 0 && lane == 0) { + if (TWO) bar_arrive_cl(tempty_cl + bo); + else bar_arrive_a(sbase + O_TEMPTY + bo); + } + } + }; + uint32_t it = 0; + // Instruction diet (SASS audit, 1-SM gq<256,false,16,GV_PAIR> promotion loop, cuobjdump on the eval node): per + // k-block ~34 non-FFMA2 instructions, the largest category being the loop tail (14: kb++, rb_b/rb_pb ring with + // ISETP+SEL+SEL+LOP3, rb_q/rb_sa ring with UISETP+USEL+predicated reset, TMEM LOP3, loop compare). The ring + // positions are now DERIVED from the single k-block counter `it` (NTB, NSC are powers of two): b = it & (NTB-1), + // parity = (it / NTB) & 1, scale slot = it & (NSC-1) (smem address base + slot * SC_SLOT), and the k-block loop + // runs on `it` itself (kb == 0 <=> it == tile start), so the tail is one IADD + the running TMEM address + compare. + static_assert((NTB & (NTB - 1)) == 0 && (NSC & (NSC - 1)) == 0, "ring sizes must be powers of two"); + // Running TMEM address of the current k-block buffer (== tm_warp + b * BN). SASS audit (npw8 2-SM gq): the + // per-k-block tm_warp + b * BN was rematerialized from %tid every k-block; carried instead as one loop register. + // The 512-column allocation is the whole TMEM, so its base column is 0 and the buffer offset wraps modulo 512 + // columns (column field = low 16 bits; NTB * BN == 512). + uint32_t rb_tb = tm_warp; + // Ring diet (NTB == 2, every BN = 256 instantiation incl. the 2-SM npw8 q_b / kv_b / GEMM1): the TMEM buffer ring + // is a pair of XOR toggles instead of per-k-block derivations: rb_tb ^= BN (== the 512-column wrap of +BN since + // BN = 256 is bit 8 of the column field) and rb_bo ^= 8 (byte offset of the buffer's tfull / tempty barrier). Only + // the phase parity is still derived from it. NTB != 2 keeps the generic derivation. Same addresses: bit-identical. + uint32_t rb_bo = PP ? 8u * (uint32_t)cg : 0u; // PP: warpgroup cg's barrier of buffer b at 8 * (2b + cg) + static_assert(NTB * TBS == 512, "TMEM ring must span the 512-column allocation"); + const uint32_t sc_base = sbase + O_SC; + (void)it; +#ifdef GQ_PROF + long long pr_tf = 0, pr_se = 0, pr_ld = 0, pr_pre = 0, pr_post = 0, pr_epi = 0; +#endif + PCLK(pt0); + SKDECL(sk_pf = 0, sk_ptot = 0, sk_sl = 0, sk_rl = 0, sk_ep = 0, sk_ld = 0, sk_fm = 0); + SKT(spp0); + int p, m0, n0, nkb; + const bool pact = !(SK & 32) && (warp - 4) < NACT; // skeleton: active promotion warps (always true in production) + for (int ui = 0; pact && gq_unit(g, ui, p, m0, n0, nkb, rank, dsm, 0); ++ui) { + const int c0 = n0 + cg * CPW; + // float index of this warp's (first) weight scale inside a slot. BN = 192: the slot holds the 8 scales from block + // (n0>>7)&~3; a warp's 96 columns may cross one 128-col scale block boundary, after bndp 32-col pairs (c0 % 32 == 0). + const int sbi = BN == 192 ? 128 + ((c0 >> 7) - ((n0 >> 7) & ~3)) : 128 + ((c0 >> 7) & 3); + const int bndp = BN == 192 ? (128 - (c0 & 127)) >> 5 : 1 << 20; + float2 acc2[CPW / 2]; // column pairs -> packed FFMA2 (sm_100) + const uint32_t it0 = it, ite = it + (uint32_t)nkb; + for (; it != ite; ++it, rb_bo ^= (PP ? 16u : 8u), + rb_tb = NTB == 2 ? (rb_tb ^ (uint32_t)TBS) : ((rb_tb & 0xFFFFFE00u) | ((rb_tb + (uint32_t)TBS) & 0x1FFu))) { +#ifdef GQ_PROF + const long long pp0 = clock64(); +#endif + const bool kb0 = it == it0; // first k-block of this tile + const uint32_t bo = NTB == 2 ? rb_bo : 8u * (it & (NTB - 1)); // 8 * TMEM buffer (barrier offset) + const uint32_t rb_pb = (((unsigned)it / NTB)) & 1u; // its phase parity + const int rb_q = (int)(it & (NSC - 1)); // scale slot + const uint32_t rb_sa = sc_base + (uint32_t)rb_q * SC_SLOT; + float sa_, sb_, sbh_ = 0.f; + PCLK(pw0); +#ifdef GQ_PROF + pr_pre += pw0 - pp0; +#endif + SKT(sp0); + if (SK & 32768) bar_wait_f<2>(sbase + O_TFULL + bo, rb_pb); + else if (SK & 16384) bar_wait_f<1>(sbase + O_TFULL + bo, rb_pb); + // NTB = 2 k-blocks ahead, so every tfull -> TMEM ld wake-up delay is directly on the per-k-block critical + // path of the large-M q_b / kv_b GEMMs. Same barrier / phase / data: bit-identical. + else if constexpr (NPW == 8) bar_wait_f<1>(sbase + O_TFULL + bo, rb_pb); + else bar_wait_a(sbase + O_TFULL + bo, rb_pb); + SKT(sp1); SKA(sk_pf, sp0, sp1); +#ifdef GQ_PROF + pr_tf += clock64() - pw0; +#endif + f_after(); + { + // scales arrived with this k-block's full barrier (2-SM: the leader's, which counts both CTAs' scale + // TMA bytes), which the MMA waited on before tfull; no scale-full wait; slot reuse is implied by the + // empty/tempty chain (see the producer). + const int q = rb_q; + if (!LSC) { + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(sa_) : "r"(rb_sa + row * 4) : "memory"); + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(sb_) : "r"(rb_sa + sbi * 4) : "memory"); + if constexpr (BN == 192) asm volatile("ld.shared.f32 %0, [%1];" : "=f"(sbh_) : "r"(rb_sa + sbi * 4 + 4) : "memory"); + } + if (OLDP) { __syncwarp(); if (lane == 0) bar_arrive_a(sbase + O_SCEMPTY + 8 * q); } + } + // LSC: the scale ld.shared are issued right after this k-block's first TMEM loads (their latency overlaps the + // tcgen05.ld round trip instead of preceding it). Same values, bit-identical. + auto ld_scales = [&]() { + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(sa_) : "r"(rb_sa + row * 4) : "memory"); + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(sb_) : "r"(rb_sa + sbi * 4) : "memory"); + if constexpr (BN == 192) asm volatile("ld.shared.f32 %0, [%1];" : "=f"(sbh_) : "r"(rb_sa + sbi * 4 + 4) : "memory"); + }; + const uint32_t tb = rb_tb; // == tm_warp + b * BN (running counter) + SKT(sq1); SKA(sk_sl, sp1, sq1); + if (SK & 4) { // skeleton: hand the buffer straight back + if (LSC) ld_scales(); + SKT(sr0); release_tb(bo); SKT(sr1); SKA(sk_rl, sr0, sr1); + if (sa_ * sb_ == 12345.f) acc2[0].x += 1.f; // keep sc live + continue; + } + // TMEM -> regs: LG x (32x32b.x32) loads in flight before ONE wait::ld. NPW = 8 (232-register promotion + // warps, 128 accumulators): LG = 2 -> 2 waits per k-block instead of 4; NPW = 16 (112 regs): LG = 1. + // Same per-column FMUL/FFMA sequence (bit-identical). + constexpr int LG = (BN == 192 && (VF & GV_L3)) ? 3 : (NPW == 8 && NCH % 4 == 0) ? 2 : 1; + if constexpr (NPW == 8 && NCH == 8 && BN == 256) { + if (V4) { + // V4 (progressive TMEM drain, same FMUL/FFMA per column as below: bit-identical): two 32-col register sets; + // chunk c+2's tcgen05.ld is issued into the set chunk c just consumed, so its latency overlaps chunk c+1's + // FFMA2 instead of being exposed by a second load->wait round trip. + uint32_t ra[32], rbx[32]; + auto fchunk = [&](int c, const uint32_t* r, float2 s2) { + if (kb0) { +#pragma unroll + for (int j = 0; j < 16; ++j) + acc2[c * 16 + j] = __fmul2_rn(make_float2(__uint_as_float(r[2 * j]), __uint_as_float(r[2 * j + 1])), s2); + } else { +#pragma unroll + for (int j = 0; j < 16; ++j) + acc2[c * 16 + j] = __ffma2_rn(make_float2(__uint_as_float(r[2 * j]), __uint_as_float(r[2 * j + 1])), s2, acc2[c * 16 + j]); + } + }; + KVB_TMEM_LD32(tb, ra); + KVB_TMEM_LD32(tb + 32, rbx); + if (LSC) ld_scales(); + asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); + const float scv = sa_ * sb_; + const float2 s2 = make_float2(scv, scv); + fchunk(0, ra, s2); + KVB_TMEM_LD32(tb + 64, ra); + fchunk(1, rbx, s2); + KVB_TMEM_LD32(tb + 96, rbx); + asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); + release_tb(bo); + fchunk(2, ra, s2); + fchunk(3, rbx, s2); + continue; + } + } +#pragma unroll + for (int cp = 0; cp < NCH; cp += 2 * LG) { + uint32_t r[LG][32]; +#pragma unroll + SKT(sl0); + for (int l = 0; l < LG; ++l) KVB_TMEM_LD32(tb + (cp + 2 * l) * 16, r[l]); + if (LSC && cp == 0) ld_scales(); + asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); + SKT(sl1); SKA(sk_ld, sl0, sl1); + if (cp + 2 * LG >= NCH) { // whole slice read -> hand the buffer back to the MMA + SKT(sr0); release_tb(bo); SKT(sr1); SKA(sk_rl, sr0, sr1); + } + const float sc = sa_ * sb_; + const float2 sc2 = make_float2(sc, sc); + const float sch = sa_ * sbh_; // BN = 192: next scale block's factor (same sa * sb product form) + const float2 sch2 = make_float2(sch, sch); + (void)sch2; +#pragma unroll + for (int l = 0; l < LG; ++l) { + const float2 s2 = (BN == 192 && (cp + 2 * l) / 2 >= bndp) ? sch2 : sc2; // this 32-col pair's scale + if (kb0) { +#pragma unroll + for (int j = 0; j < 16; ++j) + acc2[(cp + 2 * l) * 8 + j] = __fmul2_rn(make_float2(__uint_as_float(r[l][2 * j]), __uint_as_float(r[l][2 * j + 1])), s2); + } else { +#pragma unroll + for (int j = 0; j < 16; ++j) + acc2[(cp + 2 * l) * 8 + j] = + __ffma2_rn(make_float2(__uint_as_float(r[l][2 * j]), __uint_as_float(r[l][2 * j + 1])), s2, acc2[(cp + 2 * l) * 8 + j]); + } + } + SKT(sl2); SKA(sk_fm, sl1, sl2); + } + } + const float* acc = reinterpret_cast(acc2); +#pragma unroll + // epilogue: wait until the previous tile's staging was read by its TMA stores (normally long done), + // pack bf16 into this warp's boxes, publish to the async proxy and signal the store warp. + PCLK(pe0); + SKT(se0); +#ifdef GQ_PROF + const long long pe00 = pe0; +#endif + uint8_t* wst = sOut + (warp - 4) * (SS ? 4096 : BOXES * WSTAGE_BYTES); + if constexpr (NH == 2) { + // split staging: pack + publish half h (box h of this warp) after its previous store read it + const uint32_t pbase = su32(wst) + (uint32_t)lane * 128u + ((uint32_t)(lane & 7) << 4); +#pragma unroll + for (int h = 0; h < 2; ++h) { + // SS: one 4 KB box per warp reused by both halves; stempty[0] completes once per half (phase 2*tl + h) + // Un-hinted try_wait: at large M kv_b is output-store + // bound and in GV_SS the half-1 pack waits for half 0's stores, so promotion warps resume right after the store + // thread's stempty arrive. Same barrier / phase: bit-identical. + if constexpr (SS) bar_wait_f<1>(sbase + O_STEMPTY, (uint32_t)(h & 1) ^ 1u); // ((2*tl + h) & 1) ^ 1 + else bar_wait_f<1>(sbase + O_STEMPTY + 8 * h, (tl & 1) ^ 1); + if (!(SK & 4)) pack_rows64_fast(acc + 64 * h, pbase, SS ? 0 : h * 4096); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + if (lane == 0) bar_arrive_a(sbase + O_STFULL + 8 * h); + } + } else { + bar_wait_a(sbase + O_STEMPTY, (tl & 1) ^ 1); +#ifdef GQ_PROF + pr_se += clock64() - pe0; +#endif +#pragma unroll + if (SK & 4) {} + else if constexpr (WIDE) { +#pragma unroll + // one swizzled base address per thread (box 1024-B aligned, row lane at +128*lane, chunk XOR lane&7); + // chunk j / box h then = base ^ (j<<4) + h*4096 (LOP3 + immediate offset), see pack_rows64_fast + const uint32_t pbase = su32(wst) + (uint32_t)lane * 128u + ((uint32_t)(lane & 7) << 4); +#pragma unroll + for (int h = 0; h < CPW / 64; ++h) pack_rows64_fast(acc + 64 * h, pbase, h * 4096); + } + else + for (int ch = 0; ch < BOXES; ++ch) pack_rows(acc + ch * 32, wst + ch * WSTAGE_BYTES, lane); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // generic st.shared -> async proxy + __syncwarp(); + if (lane == 0) bar_arrive_a(sbase + O_STFULL); + } +#ifdef GQ_PROF + pr_epi += clock64() - pe00; +#endif + SKT(se1); SKA(sk_ep, se0, se1); + ++tl; + } + PCLK(pt1); + SKT(spp1); SKA(sk_ptot, spp0, spp1); + if (lane == 0 && warp == 4) { SKF(9, sk_pf); SKF(10, sk_ptot); SKF(12, sk_sl); SKF(13, sk_rl); SKF(14, sk_ep); SKF(15, sk_ld); SKF(16, sk_fm); } + #ifdef GQ_PROF + if (lane == 0 && g_prof) { unsigned long long* gp = g_prof + blockIdx.x * 16; + atomicAdd(gp + 4, (unsigned long long)pr_tf); atomicAdd(gp + 5, (unsigned long long)pr_se); + atomicAdd(gp + 12, (unsigned long long)pr_ld); atomicAdd(gp + 13, (unsigned long long)pr_pre); atomicAdd(gp + 14, (unsigned long long)pr_post); atomicAdd(gp + 15, (unsigned long long)pr_epi); atomicAdd(gp + 6, (unsigned long long)(pt1 - pt0)); } +#endif + } + + f_before(); + if (TWO) cluster_sync(); else __syncthreads(); // peer finished its remote arrivals / MMAs before dealloc + TLG_E(g.nout ? 10 : g.N[0] == 24576 ? 4 : 6); TLG_E(g.nout ? 11 : g.N[0] == 24576 ? 5 : 7); + if (g.nout) NTP(16384); + if (warp == 1) { + f_after(); + if (TWO) asm volatile("tcgen05.dealloc.cta_group::2.sync.aligned.b32 %0, %1;" ::"r"(tmem_base), "r"(512)); + else asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tmem_base), "r"(512)); + } +#ifdef GQ_SKEL + if (threadIdx.x == 0 && g_skc) { // [sum clk, max clk, sum ns, count] + long long g1_; const long long c1 = clock64(); asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(g1_)); + atomicAdd(g_skc + 0, (unsigned long long)(c1 - skc0)); atomicMax(g_skc + 1, (unsigned long long)(c1 - skc0)); + atomicAdd(g_skc + 2, (unsigned long long)(g1_ - skg0)); atomicAdd(g_skc + 3, 1ull); + } +#endif +#ifdef CLK_PROBE + if (threadIdx.x == 0 && g_clk) { + long long gt1; const long long ck1 = clock64(); asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(gt1)); + atomicAdd(g_clk + 0, (unsigned long long)(ck1 - ck0)); atomicAdd(g_clk + 1, (unsigned long long)(gt1 - gt0)); + atomicAdd(g_clk + 2, 1ull); + } +#endif +} + +// fp8 K-major operand map: dims {K, rows}, box {128 K, box_rows}, 128B swizzle. +static bool make_op_map(CUtensorMap* map, const void* ptr, uint64_t rows, uint64_t K, uint32_t box_rows) { + cuuint64_t dims[2] = {K, rows}; + cuuint64_t strides[1] = {K}; + cuuint32_t box[2] = {BK, box_rows}; + cuuint32_t estr[2] = {1, 1}; + return cuTensorMapEncodeTiled(map, CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, const_cast(ptr), dims, strides, box, + estr, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, + CU_TENSOR_MAP_L2_PROMOTION_L2_256B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE) == CUDA_SUCCESS; +} + +template +static int launch_gq_bn(const void* A, const void* B, const float* SFA, const float* SFB, void* D, int Mp, int N, + int K, int nsm, int cap, cudaStream_t st, int hint, int mrev = 0) { + constexpr int STAGE = (128 + BN) * BK; + constexpr int STG = 128 * BN * 2; + constexpr int SMEM = ((224 * 1024 - STG - SC_BYTES) / STAGE) * STAGE + STG + SC_BYTES + 1024 + 512; + static bool attr = false; + if (!attr) { + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + if constexpr (BN == 256) { + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + } + attr = true; + } + CUtensorMap ta, tb, to; + if (!make_op_map(&ta, A, (uint64_t)Mp, (uint64_t)K, 128) || !make_op_map(&tb, B, (uint64_t)N, (uint64_t)K, BN) || + !make_out_map(&to, D, (uint64_t)Mp, (uint64_t)N, BN == 256)) + return -11; + const int units = (Mp / 128) * (N / BN); + int grid = units < nsm ? units : nsm; + if (cap > 0 && grid > cap) grid = cap; // SM partition when co-running with the other gq GEMM + GQArgs g; + g.sfa[0] = g.sfa[1] = SFA; g.sfb[0] = g.sfb[1] = SFB; + g.N[0] = g.N[1] = N; g.K[0] = g.K[1] = K; + g.Mp = Mp; g.units0 = units; g.units = units; g.sched = nullptr; g.st_hint = hint; g.skel = g_gq_skel; g.rast = g_gq_rast; g.ldsb = 0; g.nout = 0; g.mrev = mrev; g.nowait = g_gq_nowait; g.trig = g_gq_trig; g.wcnt = g_gq_wcnt; g.wep = g_gq_wep; g.wper = g_gq_wper; + g.rst = g_gq_rst; g.nrst = g_gq_nrst; g_gq_rst = nullptr; g_gq_nrst = 0; + if (!gq_set_div(g, 0, Mp / 128, N / BN, g.rast) || !gq_set_div(g, 1, Mp / 128, N / BN, g.rast)) return -15; + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3(grid, 1, 1); cfg.blockDim = dim3(GQ_THREADS, 1, 1); cfg.dynamicSmemBytes = SMEM; cfg.stream = st; + cudaLaunchAttribute at[1]; + at[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; // PDL (see g_pdl) + at[0].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = at; cfg.numAttrs = g_pdl ? 1 : 0; + cudaError_t le; + if constexpr (BN == 256) { + if (g_gq_npw == 8) { + cfg.blockDim = dim3(128 + 32 * 8, 1, 1); + le = hint ? cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g) + : cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g); + return le == cudaSuccess && cudaPeekAtLastError() == cudaSuccess ? 0 : -12; + } + } + le = hint ? cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g) + : cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g); + return le == cudaSuccess && cudaPeekAtLastError() == cudaSuccess ? 0 : -12; +} + +template +static int launch_gq_comb(const void* A0, const void* B0, const float* SFA0, const float* SFB0, void* D0, int N0, int K0, + const void* A1, const void* B1, const float* SFA1, const float* SFB1, void* D1, int N1, int K1, + int Mp, int nsm, int epi, cudaStream_t st, int hint = 0) { + constexpr int STAGE = (128 + BN) * BK; + constexpr int STG = 128 * BN * 2; + constexpr int SMEM = ((224 * 1024 - STG - SC_BYTES) / STAGE) * STAGE + STG + SC_BYTES + 1024 + 512; + static bool attr = false; + if (!attr) { + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + if constexpr (BN == 256) { // 8 promotion warps (128 cols each, 232 regs): same per-column math, bit-identical + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + } + attr = true; + } + CUtensorMap ta0, tb0, to0, ta1, tb1, to1; + if (!make_op_map(&ta0, A0, (uint64_t)Mp, (uint64_t)K0, 128) || !make_op_map(&tb0, B0, (uint64_t)N0, (uint64_t)K0, BN) || + !make_out_map(&to0, D0, (uint64_t)Mp, (uint64_t)N0, BN == 256) || + !make_op_map(&ta1, A1, (uint64_t)Mp, (uint64_t)K1, 128) || !make_op_map(&tb1, B1, (uint64_t)N1, (uint64_t)K1, BN) || + !make_out_map(&to1, D1, (uint64_t)Mp, (uint64_t)N1, BN == 256)) + return -11; + const int u0 = (Mp / 128) * (N0 / BN), u1 = (Mp / 128) * (N1 / BN), units = u0 + u1; + const int grid = units < nsm ? units : nsm; + GQArgs g; + g.sfa[0] = SFA0; g.sfa[1] = SFA1; g.sfb[0] = SFB0; g.sfb[1] = SFB1; + g.N[0] = N0; g.N[1] = N1; g.K[0] = K0; g.K[1] = K1; + g.Mp = Mp; g.units0 = u0; g.units = units; g.sched = nullptr; g.st_hint = hint; g.skel = g_gq_skel; g.rast = g_gq_rast; g.ldsb = 0; g.nout = 0; g.mrev = 0; g.nowait = 0; g.trig = 0; g.wcnt = g_gq_wcnt; g.wep = g_gq_wep; g.wper = g_gq_wper; + if (g.wcnt) { g.wcnt0 = g_gq_wcnt0; g.wper0 = g_gq_wper0; } + if (!gq_set_div(g, 0, Mp / 128, N0 / BN, g.rast) || !gq_set_div(g, 1, Mp / 128, N1 / BN, g.rast)) return -15; + if constexpr (BN == 256) { + if (g_gq_dyn && hint && g.wep) { + // GV_DYN: claim counter = epoch[2] (zeroed by the norm each replay, before this grid's griddepcontrol.wait returns) + g.dctr = const_cast(g.wep) + 2; + if (g_gq_npw == 8) launch_pdl(gq_kernel, dim3(grid), dim3(128 + 32 * 8), SMEM, st, g_pdl, ta0, tb0, to0, ta1, tb1, to1, g); + else launch_pdl(gq_kernel, dim3(grid), dim3(GQ_THREADS), SMEM, st, g_pdl, ta0, tb0, to0, ta1, tb1, to1, g); + return cudaPeekAtLastError() == cudaSuccess ? 0 : -12; + } + } + if (epi >= 0) { + static std::map, int*>& cache = *new std::map, int*>(); + const std::array key = {Mp, epi, grid, u0, K0 * 4 + BN / 128, K1}; + auto itc = cache.find(key); + if (itc == cache.end()) { + // LPT: units by descending cost, each to the currently least-loaded CTA (ties -> lowest index). + std::vector order(units); + for (int u = 0; u < units; ++u) order[u] = u; + auto cost = [&](int u) { return (u < u0 ? K0 / BK : K1 / BK) + epi; }; + std::stable_sort(order.begin(), order.end(), [&](int a, int b) { return cost(a) > cost(b); }); + std::vector load(grid, 0); + std::vector> lists(grid); + for (int u : order) { + int best = 0; + for (int c = 1; c < grid; ++c) if (load[c] < load[best]) best = c; + load[best] += cost(u); + lists[best].push_back(u); + } + std::vector h(grid + 1 + units); + int o = 0; + for (int c = 0; c < grid; ++c) { + h[c] = o; + for (int u : lists[c]) h[grid + 1 + o++] = u; + } + h[grid] = o; + int* d = nullptr; + if (cudaMalloc(&d, h.size() * sizeof(int)) != cudaSuccess) return -13; // never freed + cudaMemcpy(d, h.data(), h.size() * sizeof(int), cudaMemcpyHostToDevice); + itc = cache.emplace(key, d).first; + } + g.sched = itc->second; + } + // g_pdl: programmatic dependent launch after the split-K norm (prologue overlaps the norm; pdl_wait in gq_kernel) + if constexpr (BN == 256) { + if (g_gq_npw == 8) { // combined small-M launch with 8 promotion warps (384 threads) + if (hint) launch_pdl(gq_kernel, dim3(grid), dim3(128 + 32 * 8), SMEM, st, g_pdl, ta0, tb0, to0, ta1, tb1, to1, g); + else launch_pdl(gq_kernel, dim3(grid), dim3(128 + 32 * 8), SMEM, st, g_pdl, ta0, tb0, to0, ta1, tb1, to1, g); + return cudaPeekAtLastError() == cudaSuccess ? 0 : -12; + } + } + if (hint) launch_pdl(gq_kernel, dim3(grid), dim3(GQ_THREADS), SMEM, st, g_pdl, ta0, tb0, to0, ta1, tb1, to1, g); + else launch_pdl(gq_kernel, dim3(grid), dim3(GQ_THREADS), SMEM, st, g_pdl, ta0, tb0, to0, ta1, tb1, to1, g); + return cudaPeekAtLastError() == cudaSuccess ? 0 : -12; +} + +static unsigned* g_gq_mcnt = nullptr; // launch_gq_g1 only (see GQArgs::mcnt) +static int g_gq_maxcl = 0; // max co-resident 2x1 clusters of the 2-SM gq kernel (cudaOccupancyMaxActiveClusters) +// 2-SM launcher (BN = 256, Mp % 256 == 0): persistent 2x1 clusters, one cluster per 256 x 256 unit; grid = +// co-resident clusters (the GPC layout may not fit nsm/2), capped by the SM partition (cap/2 clusters). +// Ragged-N use (GEMM1): N = padded tile width (multiple of 256), brows = rows of B (TMA zero-fills rows >= brows), +// nout = output columns (D pitch; TMA store clips / skips columns >= nout), ldsb = weight-scale pitch (multiple of 4). +static int g_gq_g1sl = 0; // GQArgs::g1sl of the next gq GEMM1 launch (set_g1_sl) +static int g_gq_g1lp = 0; // GQArgs::lpol of the gq GEMM1 launches (set_g1_lpol; bit0 B weights, bit1 A act evict_last) +static int g_gq_g1ss = 0; // 1: GEMM1 gq launches use GV_SS (5-stage ring, single staging); see set_g1_ss +static int g_gq_lpol = 0; // GQArgs::lpol of the next 2-SM q_b / kv_b launches (set_gq_lpol) +static int g_gq_mc = 0; // 1: next 2-SM npw8 q_b / kv_b launches use the 4-CTA B-multicast clusters (GV_MC) +static int g_gq_maxcl4 = 0; +static int g_gq_ar = 0; // 2: GV_AR4 (four n-tiles per unit) + // 1: next single-problem 2-SM npw8 K=512 gq launches use GV_AR (set_gq_ar) +static int g_gq_pp = 0; // 1: next single-problem 2-SM npw8 gq launches use GV_PP (set_gq_pp) // max co-resident 4-CTA clusters of the GV_MC kernel +static int launch_gq_two(const void* A, const void* B, const float* SFA, const float* SFB, void* D, int Mp, int N, + int K, int nsm, int cap, cudaStream_t st, int hint, int brows = 0, int nout = 0, int ldsb = 0, + int mrev = 0, const void* A1 = nullptr, const void* B1 = nullptr, const float* SFA1 = nullptr, + const float* SFB1 = nullptr, void* D1 = nullptr, int N1 = 0, int K1 = 0) { + const bool pair = A1 != nullptr; // GV_PAIR: second problem (same Mp) appended to the unit list + constexpr int BN = 256; + constexpr int STAGE = (128 + BN / 2) * BK; + constexpr int STG = 128 * BN * 2; + constexpr int SMEM = ((224 * 1024 - STG - SC_BYTES) / STAGE) * STAGE + STG + SC_BYTES + 1024 + 512; + int& maxcl = g_gq_maxcl; + if (maxcl == 0) { + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + // GV_SS: 5 x 32 KB stages + 32 KB staging == 4 x 32 KB + 64 KB -> same dynamic smem size + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaLaunchConfig_t qc = {}; + qc.gridDim = dim3(nsm & ~1, 1, 1); + qc.blockDim = dim3(GQ_THREADS, 1, 1); + qc.dynamicSmemBytes = SMEM; + 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; + if (cudaOccupancyMaxActiveClusters(&maxcl, gq_kernel, &qc) != cudaSuccess || maxcl <= 0) { + cudaGetLastError(); + maxcl = nsm / 2; + } + if (maxcl > nsm / 2) maxcl = nsm / 2; + } + // GV_MC: q_b / kv_b only (not the ragged GEMM1), 8 promotion warps, Mp % 512 == 0 + const bool mc = !pair && g_gq_mc && !nout && g_gq_npw == 8 && Mp % 512 == 0; + if (mc && g_gq_maxcl4 == 0) { + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaLaunchConfig_t qc = {}; + qc.gridDim = dim3(nsm & ~3, 1, 1); + qc.blockDim = dim3(128 + 32 * 8, 1, 1); + qc.dynamicSmemBytes = SMEM; + cudaLaunchAttribute qa[1]; + qa[0].id = cudaLaunchAttributeClusterDimension; + qa[0].val.clusterDim.x = 4; qa[0].val.clusterDim.y = 1; qa[0].val.clusterDim.z = 1; + qc.attrs = qa; + qc.numAttrs = 1; + if (cudaOccupancyMaxActiveClusters(&g_gq_maxcl4, gq_kernel, &qc) != cudaSuccess || g_gq_maxcl4 <= 0) { + cudaGetLastError(); + g_gq_maxcl4 = nsm / 4; + } + if (g_gq_maxcl4 > nsm / 4) g_gq_maxcl4 = nsm / 4; + } + const int CLS = mc ? 4 : 2; + const bool pp = !pair && !nout && !mc && g_gq_npw == 8 && g_gq_pp; // GV_PP warpgroup ping-pong (large-M q_b) + // GV_AR A-operand reuse (kv_b, K = 512 = 4 k-blocks, N % 512 == 0): unit = m-pair x two 256-col n-tiles + const bool ar16 = g_gq_ar == 4 && N % (16 * BN) == 0; + const bool ar8 = !ar16 && g_gq_ar >= 3 && N % (8 * BN) == 0; + const bool ar4 = !ar8 && g_gq_ar >= 2 && N % (4 * BN) == 0; + const bool ar = !pair && !nout && !mc && !pp && g_gq_npw == 8 && g_gq_ar && K == AR_NKA * BK && N % (2 * BN) == 0; + constexpr int SMEM_AR = AR_NKA * 128 * BK + ((224 * 1024 - STG - SC_BYTES - AR_NKA * 128 * BK) / (BN / 2 * BK)) * (BN / 2 * BK) + + STG + SC_BYTES + 1024 + 512; + static_assert(SMEM_AR <= 232448, "GV_AR smem"); + static bool ar_attr = false; + if (ar && !ar_attr) { + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_AR); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_AR); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_AR); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_AR); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_AR); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_AR); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_AR); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_AR); + ar_attr = true; + } + const int UBN = ar ? (ar16 ? 16 : ar8 ? 8 : ar4 ? 4 : 2) * BN : BN; // unit width in columns + CUtensorMap ta, tb, to; + if (!make_op_map(&ta, A, (uint64_t)Mp, (uint64_t)K, 128) || + !make_op_map(&tb, B, (uint64_t)(brows ? brows : N), (uint64_t)K, (mc || pp) ? BN / 4 : BN / 2) || // MC / PP: 64-row pieces + !make_out_map(&to, D, (uint64_t)Mp, (uint64_t)(nout ? nout : N), BN == 256)) + return -11; + const int units0 = (Mp / (128 * CLS)) * (N / UBN); + const int units = units0 + (pair ? (Mp / (128 * CLS)) * (N1 / BN) : 0); + CUtensorMap ta1 = ta, tb1 = tb, to1 = to; + if (pair && (!make_op_map(&ta1, A1, (uint64_t)Mp, (uint64_t)K1, 128) || !make_op_map(&tb1, B1, (uint64_t)N1, (uint64_t)K1, BN / 2) || + !make_out_map(&to1, D1, (uint64_t)Mp, (uint64_t)N1, true))) + return -11; + const int mxc = mc ? g_gq_maxcl4 : maxcl; + int ncl = units < mxc ? units : mxc; + if (cap > 0 && ncl > cap / CLS) ncl = cap / CLS > 0 ? cap / CLS : 1; + GQArgs g; + g.sfa[0] = g.sfa[1] = SFA; g.sfb[0] = g.sfb[1] = SFB; + g.N[0] = g.N[1] = N; g.K[0] = g.K[1] = K; + g.Mp = Mp; g.units0 = units0; g.units = units; g.sched = nullptr; g.st_hint = hint; g.skel = g_gq_skel; g.rast = g_gq_rast; g.ldsb = ldsb ? ldsb : N / BN * (BN / 128); g.nout = nout; + if (pair) { g.sfa[1] = SFA1; g.sfb[1] = SFB1; g.N[1] = N1; g.K[1] = K1; } g.mrev = mrev; g.nowait = g_gq_nowait; g.trig = g_gq_trig; g.wcnt = g_gq_wcnt; g.wep = g_gq_wep; g.wper = g_gq_wper; + // single-problem q_b/kv_b launch: optional wait on the B-wquant segment-0 counter only (problem 0 == segment 0) + if (!pair && !nout && g.wcnt && g_gq_wcnt0) { g.wcnt0 = g_gq_wcnt0; g.wper0 = g_gq_wper0; } + g.mcnt = nout ? g_gq_mcnt : nullptr; + g.g1sl = nout ? g_gq_g1sl : 0; + g.mv = g_gq_mv; + g.lpol = nout ? g_gq_g1lp : g_gq_lpol; + if (!gq_set_div(g, 0, Mp / (128 * CLS), N / UBN, g.rast)) return -15; + if (pair && !gq_set_div(g, 1, Mp / (128 * CLS), N1 / BN, g.rast)) return -15; + { + auto smap = [](CUtensorMap* m, const float* p, uint64_t w, uint64_t h, uint32_t bx) { + cuuint64_t dims[2] = {w, h}; + cuuint64_t strides[1] = {w * 4}; + cuuint32_t box[2] = {bx, 1}; + cuuint32_t estr[2] = {1, 1}; + return cuTensorMapEncodeTiled(m, CU_TENSOR_MAP_DATA_TYPE_FLOAT32, 2, const_cast(p), dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, CU_TENSOR_MAP_L2_PROMOTION_NONE, + CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE) == CUDA_SUCCESS; + }; + if (!smap(&g.smap_a, SFA, (uint64_t)Mp, (uint64_t)(K / BK), 128) || + !smap(&g.smap_b, SFB, (uint64_t)g.ldsb, (uint64_t)(K / BK), 4)) + return -11; + g.smap_a1 = g.smap_a; g.smap_b1 = g.smap_b; + if (pair && (!smap(&g.smap_a1, SFA1, (uint64_t)Mp, (uint64_t)(K1 / BK), 128) || + !smap(&g.smap_b1, SFB1, (uint64_t)(N1 / 128), (uint64_t)(K1 / BK), 4))) + return -11; + } + if (nout) { + if (g_gq_acnt) { g.acnt = g_gq_acnt; g.wdn = g_gq_wdn; g.atgt = g_gq_atgt; g.wtgt = g_gq_wtgt; g.nowait = 1; } + } else { + g.rst = g_gq_rst; g.nrst = g_gq_nrst; g_gq_rst = nullptr; g_gq_nrst = 0; + } + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3(CLS * ncl, 1, 1); + cfg.blockDim = dim3(g_gq_npw == 8 ? 128 + 32 * 8 : GQ_THREADS, 1, 1); + cfg.dynamicSmemBytes = SMEM; + cfg.stream = st; + cudaLaunchAttribute at[2]; + at[0].id = cudaLaunchAttributeClusterDimension; + at[0].val.clusterDim.x = CLS; at[0].val.clusterDim.y = 1; at[0].val.clusterDim.z = 1; + at[1].id = cudaLaunchAttributeProgrammaticStreamSerialization; // PDL (see g_pdl) + at[1].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = at; + cfg.numAttrs = g_pdl ? 2 : 1; + cudaError_t le; + if (nout) { // ragged-N GEMM1 variant: only instantiated with 8 promotion warps and plain stores + if (g_gq_npw != 8 || hint) return -14; + le = g_gq_g1ss ? cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g) + : cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g); + } else if (pair) { // 2-SM q_b + kv_b in one persistent launch (8 promotion warps only) + if (g_gq_npw != 8) return -14; + le = hint ? cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta1, tb1, to1, g) + : cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta1, tb1, to1, g); + } else if (mc) { + le = hint ? cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g) + : cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g); + } else if (ar) { + cfg.dynamicSmemBytes = SMEM_AR; + if (ar16) + le = hint ? cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g) + : cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g); + else if (ar8) + le = hint ? cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g) + : cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g); + else if (ar4) + le = hint ? cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g) + : cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g); + else + le = hint ? cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g) + : cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g); + } else if (pp) { + le = hint ? cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g) + : cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g); + } else if (g_gq_npw == 8) { + le = hint ? cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g) + : cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g); + } else { + le = hint ? cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g) + : cudaLaunchKernelEx(&cfg, gq_kernel, ta, tb, to, ta, tb, to, g); + } + if (le != cudaSuccess) return -13; + return cudaPeekAtLastError() == cudaSuccess ? 0 : -12; +} + +// GEMM1 with 2-SM 256 x 192 pair tiles (N = 2112 = 11 x 192: no ragged tile, every MMA column is a used output column; +// vs 256 x 256 tiles the 9th n-tile of each m-block only had 64 valid columns). Same per-column promotion math (each +// 32-col pair uses its own 128-col weight-scale block): bit-identical y1. 8 promotion warps (96 cols each), 32x32 64B- +// swizzled output boxes, 32-B weight-scale chunk per k-block. Requires nout % 192 == 0, Mp % 256 == 0. +static int g_g1_bn192 = 0; +static int g_g1_l3 = 1; // BN = 192 GEMM1: GV_L3 single-wait TMEM promotion +static int g_gq_maxcl192 = 0; +// GEMM1 BN = 192 with 4-CTA clusters (GV_MC, M >= 8192 rows): 2 CTA pairs stacked along M (unit = 512 rows x 192 cols); +// each CTA TMA-loads 48 of its pair-half's 96 B rows and multicasts them to its counterpart in the other pair, halving the +// L2 -> SM traffic of the weight operand. Same MMAs / data / promotion order: bit-identical y1. +static int g_g1_mc = 0; +int g_act_tiled = 0; // set_act_tiled: aqt stores tiled fp8 act, BN=192 gq GEMM1 loads it (both or neither) +static int g_gq_maxcl192mc = 0; +static int launch_gq_g1_192(const void* A, const void* B, const float* SFA, const float* SFB, void* D, int Mp, int nout, + int brows, int K, int ldsb, int nsm, int cap, cudaStream_t st) { + constexpr int BN = 192; + constexpr int STAGE = (128 + BN / 2) * BK; + constexpr int STG = 128 * BN * 2; + constexpr int SMEM = ((224 * 1024 - STG - SC_BYTES) / STAGE) * STAGE + STG + SC_BYTES + 1024 + 512; + auto kfn = g_g1_l3 ? gq_kernel : gq_kernel; + const bool mc = g_g1_mc && Mp % 512 == 0; + if (mc) kfn = gq_kernel; + if (mc && g_gq_maxcl192mc == 0) { + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaLaunchConfig_t qc = {}; + qc.gridDim = dim3(nsm & ~3, 1, 1); + qc.blockDim = dim3(128 + 32 * 8, 1, 1); + qc.dynamicSmemBytes = SMEM; + cudaLaunchAttribute qa[1]; + qa[0].id = cudaLaunchAttributeClusterDimension; + qa[0].val.clusterDim.x = 4; qa[0].val.clusterDim.y = 1; qa[0].val.clusterDim.z = 1; + qc.attrs = qa; qc.numAttrs = 1; + if (cudaOccupancyMaxActiveClusters(&g_gq_maxcl192mc, kfn, &qc) != cudaSuccess || g_gq_maxcl192mc <= 0) { + cudaGetLastError(); + g_gq_maxcl192mc = nsm / 4; + } + if (g_gq_maxcl192mc > nsm / 4) g_gq_maxcl192mc = nsm / 4; + } + const int CLS = mc ? 4 : 2; + if (g_gq_maxcl192 == 0) { + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaFuncSetAttribute(gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaLaunchConfig_t qc = {}; + qc.gridDim = dim3(nsm & ~1, 1, 1); + qc.blockDim = dim3(128 + 32 * 8, 1, 1); + qc.dynamicSmemBytes = SMEM; + 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; + if (cudaOccupancyMaxActiveClusters(&g_gq_maxcl192, gq_kernel, &qc) != cudaSuccess || g_gq_maxcl192 <= 0) { + cudaGetLastError(); + g_gq_maxcl192 = nsm / 2; + } + if (g_gq_maxcl192 > nsm / 2) g_gq_maxcl192 = nsm / 2; + } + CUtensorMap ta, tb, to; + bool aok; + if (g_act_tiled) { // tiled activation (see GQArgs::atk): flat {128 B, Mp*K/128 rows} map, box 128 x 128, no swizzle + cuuint64_t dims[2] = {128, (cuuint64_t)Mp * (cuuint64_t)(K / BK)}; + cuuint64_t strides[1] = {128}; + cuuint32_t box[2] = {128, 128}; + cuuint32_t estr[2] = {1, 1}; + aok = cuTensorMapEncodeTiled(&ta, CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, const_cast(A), dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, CU_TENSOR_MAP_L2_PROMOTION_L2_256B, + CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE) == CUDA_SUCCESS; + } else aok = make_op_map(&ta, A, (uint64_t)Mp, (uint64_t)K, 128); + if (!aok || !make_op_map(&tb, B, (uint64_t)brows, (uint64_t)K, mc ? BN / 4 : BN / 2) || + !make_out_map(&to, D, (uint64_t)Mp, (uint64_t)nout, false)) + return -11; + const int units = (Mp / (128 * CLS)) * (nout / BN); + const int mxc = mc ? g_gq_maxcl192mc : g_gq_maxcl192; + int ncl = units < mxc ? units : mxc; + if (cap > 0 && ncl > cap / CLS) ncl = cap / CLS > 0 ? cap / CLS : 1; + GQArgs g; + g.sfa[0] = g.sfa[1] = SFA; g.sfb[0] = g.sfb[1] = SFB; + g.N[0] = g.N[1] = nout; g.K[0] = g.K[1] = K; + g.Mp = Mp; g.units0 = units; g.units = units; g.sched = nullptr; g.st_hint = 0; g.skel = g_gq_skel; g.rast = g_gq_rast; + g.ldsb = ldsb; g.nout = nout; g.mrev = 0; g.nowait = g_gq_nowait; g.trig = g_gq_trig; + g.wcnt = g_gq_wcnt; g.wep = g_gq_wep; g.wper = g_gq_wper; + g.mcnt = g_gq_mcnt; g.mv = g_gq_mv; g.lpol = g_gq_g1lp; + g.atk = g_act_tiled ? K / BK : 0; + if (!gq_set_div(g, 0, Mp / (128 * CLS), nout / BN, g.rast)) return -15; + { + auto smap = [](CUtensorMap* m, const float* p, uint64_t w, uint64_t h, uint32_t bx) { + cuuint64_t dims[2] = {w, h}; + cuuint64_t strides[1] = {w * 4}; + cuuint32_t box[2] = {bx, 1}; + cuuint32_t estr[2] = {1, 1}; + return cuTensorMapEncodeTiled(m, CU_TENSOR_MAP_DATA_TYPE_FLOAT32, 2, const_cast(p), dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, CU_TENSOR_MAP_L2_PROMOTION_NONE, + CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE) == CUDA_SUCCESS; + }; + // weight scales: box 8 x 1 (32 B) = the 8 scales from block (n0>>7)&~3 (a 192-col tile spans <= 5 blocks) + if (!smap(&g.smap_a, SFA, (uint64_t)Mp, (uint64_t)(K / BK), 128) || !smap(&g.smap_b, SFB, (uint64_t)ldsb, (uint64_t)(K / BK), 8)) + return -11; + g.smap_a1 = g.smap_a; g.smap_b1 = g.smap_b; + } + if (g_gq_acnt) { g.acnt = g_gq_acnt; g.wdn = g_gq_wdn; g.atgt = g_gq_atgt; g.wtgt = g_gq_wtgt; g.nowait = 1; } + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3(CLS * ncl, 1, 1); + cfg.blockDim = dim3(128 + 32 * 8, 1, 1); + cfg.dynamicSmemBytes = SMEM; + cfg.stream = st; + cudaLaunchAttribute at[2]; + at[0].id = cudaLaunchAttributeClusterDimension; + at[0].val.clusterDim.x = CLS; at[0].val.clusterDim.y = 1; at[0].val.clusterDim.z = 1; + at[1].id = cudaLaunchAttributeProgrammaticStreamSerialization; + at[1].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = at; + cfg.numAttrs = g_pdl ? 2 : 1; + if (cudaLaunchKernelEx(&cfg, kfn, ta, tb, to, ta, tb, to, g) != cudaSuccess) return -13; + return cudaPeekAtLastError() == cudaSuccess ? 0 : -12; +} + +} // namespace kvb + +void set_gq_raster(int r) { kvb::g_gq_rast = r; } +void set_g1_ss(int on) { kvb::g_gq_g1ss = on ? 1 : 0; } +void set_g1_lpol(int v) { kvb::g_gq_g1lp = v & 3; } +void set_g1_sl(int on) { kvb::g_gq_g1sl = on ? 1 : 0; } +void set_gq_lpol(int v) { kvb::g_gq_lpol = v & 3; } +void set_gq_mc(int on) { kvb::g_gq_mc = on ? 1 : 0; } +void set_gq_pp(int on) { kvb::g_gq_pp = on ? 1 : 0; } +void set_gq_ar(int on) { kvb::g_gq_ar = on >= 2 && on <= 4 ? on : on ? 1 : 0; } +int gq_max_clusters4() { return kvb::g_gq_maxcl4; } +void set_gq_mrev(int on) { kvb::g_gq_mrev = on ? 1 : 0; } +void set_gq_dyn(int on) { kvb::g_gq_dyn = on; } // 0 off, 1 / 2: GV_DYN claim counter epoch[2] / epoch[3] +void set_gq_wdep0(const unsigned long long* cnt0, unsigned long long per0) { kvb::g_gq_wcnt0 = cnt0; kvb::g_gq_wper0 = per0; } +void set_gq_wdep(const unsigned long long* cnt, const unsigned long long* ep, unsigned long long per) { + kvb::g_gq_wcnt = cnt; kvb::g_gq_wep = ep; kvb::g_gq_wper = per; +} +void set_g1_early(const unsigned* acnt, unsigned atgt, const unsigned* wdn, unsigned wtgt) { + kvb::g_gq_acnt = acnt; kvb::g_gq_atgt = atgt; kvb::g_gq_wdn = wdn; kvb::g_gq_wtgt = wtgt; +} +void set_gq_rst(unsigned* p, int n) { kvb::g_gq_rst = p; kvb::g_gq_nrst = n; } +void set_gq_pdlchain(int nowait, int trig) { kvb::g_gq_nowait = nowait; kvb::g_gq_trig = trig; } + +// GEMM1 on the 2-SM gq kernel (256x256 pair tiles, 8 promotion warps): y1[Mp, nout] = xq[Mp,K] x Wa[brows,K]^T. +// Tiles cover ceil(nout/256)*256 columns; B rows >= brows are TMA zero-filled, output boxes past nout are skipped / +// clipped; weight scales at SFB[kb*ldsb + nb] (ldsb % 4 == 0 so every 16-B scale chunk is aligned). +int launch_gq_g1(const void* A, const void* B, const float* SFA, const float* SFB, void* D, int Mp, int nout, int brows, + int K, int ldsb, cudaStream_t st, int max_ctas, int rast) { + static int nsm = 0; + if (nsm == 0) { + int dev; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&nsm, cudaDevAttrMultiProcessorCount, dev); + } + if (kvb::g_g1_bn192 && Mp % 256 == 0 && K % 128 == 0 && nout % 192 == 0 && ldsb % 4 == 0 && + (((nout - 192) >> 7) & ~3) + 8 <= ldsb) { + const int sr2 = kvb::g_gq_rast; + if (rast >= 0) kvb::g_gq_rast = rast; + const int r2 = kvb::launch_gq_g1_192(A, B, SFA, SFB, D, Mp, nout, brows, K, ldsb, nsm, max_ctas, st); + kvb::g_gq_rast = sr2; + return r2; + } + if (Mp % 256 || K % 128 || nout % 64 || ldsb % 4 || ldsb * 128 < (nout + 255) / 256 * 256) return -10; + const int Nt = (nout + 255) / 256 * 256; + const int sv = kvb::g_gq_npw; + const int sr = kvb::g_gq_rast; + kvb::g_gq_npw = 8; + if (rast >= 0) kvb::g_gq_rast = rast; // rast < 0: the global gq raster (set_gq_raster) + const int r = kvb::launch_gq_two(A, B, SFA, SFB, D, Mp, Nt, K, nsm, max_ctas, st, 0, brows, nout, ldsb); + kvb::g_gq_npw = sv; + kvb::g_gq_rast = sr; + return r; +} +void set_g1_mcnt(unsigned* p) { kvb::g_gq_mcnt = p; } +void set_g1_bn192(int on) { kvb::g_g1_bn192 = on ? 1 : 0; } +void set_g1_mc(int on) { kvb::g_g1_mc = on ? 1 : 0; } +void set_act_tiled(int on) { kvb::g_act_tiled = on ? 1 : 0; } +void set_g1_l3(int on) { kvb::g_g1_l3 = on ? 1 : 0; } +int get_g1_bn192() { return kvb::g_g1_bn192; } +// Large M: q_b (problem 0) + kv_b (problem 1) on ONE persistent 2-SM npw8 launch (combined 256x256 unit list, +// q_b units first, round-robin over clusters): kv_b's short units fill q_b's last wave; same tiles / math (bit-identical). +int launch_gq_two_pair(const void* A0, const void* B0, const float* SFA0, const float* SFB0, void* D0, int N0, int K0, + const void* A1, const void* B1, const float* SFA1, const float* SFB1, void* D1, int N1, int K1, + int Mp, int hint, cudaStream_t st) { + static int nsm = 0; + if (nsm == 0) { int dev; cudaGetDevice(&dev); cudaDeviceGetAttribute(&nsm, cudaDevAttrMultiProcessorCount, dev); } + if (Mp % 256 || N0 % 512 || N1 % 512 || K0 % 128 || K1 % 128) return -10; + const int sv = kvb::g_gq_npw; + kvb::g_gq_npw = 8; + const int r = kvb::launch_gq_two(A0, B0, SFA0, SFB0, D0, Mp, N0, K0, nsm, 0, st, hint, 0, 0, 0, kvb::g_gq_mrev, + A1, B1, SFA1, SFB1, D1, N1, K1); + kvb::g_gq_npw = sv; + return r; +} +void set_gq_mv(int v) { kvb::g_gq_mv = v; } +void set_gq_npw(int n) { kvb::g_gq_npw = n == 8 ? 8 : 16; } +// Max co-resident 2x1 clusters of the 2-SM gq kernel on an idle GPU (computed once; GPC layout can leave SMs unpaired). +int gq_max_clusters() { + if (kvb::g_gq_maxcl == 0) { + int dev, nsm; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&nsm, cudaDevAttrMultiProcessorCount, dev); + constexpr int BN = 256; + constexpr int STAGE = (128 + BN / 2) * kvb::BK; + constexpr int STG = 128 * BN * 2; + constexpr int SMEM = ((224 * 1024 - STG - kvb::SC_BYTES) / STAGE) * STAGE + STG + kvb::SC_BYTES + 1024 + 512; + cudaFuncSetAttribute(kvb::gq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + cudaLaunchConfig_t qc = {}; + qc.gridDim = dim3(nsm & ~1, 1, 1); + qc.blockDim = dim3(kvb::GQ_THREADS, 1, 1); + qc.dynamicSmemBytes = SMEM; + 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 mc = 0; + if (cudaOccupancyMaxActiveClusters(&mc, kvb::gq_kernel, &qc) != cudaSuccess || mc <= 0) { + cudaGetLastError(); + mc = nsm / 2; + } + if (mc > nsm / 2) mc = nsm / 2; + return mc; // launch_gq_two still performs its own (identical) one-time init with all attributes + } + return kvb::g_gq_maxcl; +} + +// 128x256 tiles when they give >= 2 waves, else 128x128 (more CTAs streaming the weights). +// max_ctas > 0 caps the persistent grid (q_b and kv_b co-run on disjoint SM sets; 1 CTA/SM each). +#ifdef GQ_PROF +void gq_set_prof(void* p) { cudaMemcpyToSymbol(kvb::g_prof, &p, sizeof(p)); } +#endif +#ifdef GQ_SKEL +void gq_skel_set(int skel, void* cnt, int nohint) { + kvb::set_gq_skel(skel); + cudaMemcpyToSymbol(kvb::g_skc, &cnt, sizeof(cnt)); + cudaMemcpyToSymbol(kvb::g_nohint, &nohint, sizeof(int)); +} +#endif +int launch_gq_gemm(const void* A, const void* B, const float* SFA, const float* SFB, void* D, int Mp, int N, int K, + cudaStream_t st, int max_ctas, int two, int hint) { + static int nsm = 0; + if (nsm == 0) { + int dev; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&nsm, cudaDevAttrMultiProcessorCount, dev); + } + if (Mp % 128 || N % 512 || K % 128) return -10; // N % 512: 16-B weight-scale chunk stays inside a row + // two != 0 (chosen per M and per GEMM by whole-graph timing in main.cpp): 2-SM 256x256 pair tiles. + if (two && Mp % 256 == 0 && N % 256 == 0) + return kvb::launch_gq_two(A, B, SFA, SFB, D, Mp, N, K, nsm, max_ctas, st, hint, 0, 0, 0, kvb::g_gq_mrev); + if (N % 256 == 0 && (Mp / 128) * (N / 256) >= 2 * nsm) + return kvb::launch_gq_bn<256>(A, B, SFA, SFB, D, Mp, N, K, nsm, max_ctas, st, hint, kvb::g_gq_mrev); + return kvb::launch_gq_bn<128>(A, B, SFA, SFB, D, Mp, N, K, nsm, max_ctas, st, hint, kvb::g_gq_mrev); +} + + +// ------------------------------------------------------------------ 8. persistent TMA-ring quant (small M) +// One persistent launch quantizes ALL weights (q_a|kv_a concatenated, q_b, kv_b) plus the activation. +// Same job decomposition and math as quant_kernel (job = one 128x128 weight block or 128 contiguous 1x128 +// activation groups = 32 KB bf16), but data movement is decoupled from math: +// warp 8 (lane 0) : producer. Per job one TMA load into a 3-stage 32 KB smem ring: 2D tensor-map box +// {128 cols, 128 rows} (no swizzle, row r at r*256 B) for weights, a 1D bulk copy of +// the valid bytes for activation chunks. L2 evict_first hint (bf16 is read once). +// warps 0-7 : consumers. Read the stage into registers (same tid -> (row, 16-col chunk) mapping as +// quant_kernel), release it immediately, then amax (CTA-wide via a named barrier for +// weights, 8-lane shuffles for 1x128 act groups), correctly rounded x/scale, e4m3 +// satfinite, 16 B st.global with L2 evict_last (the 70 MB fp8 weights stay L2-resident +// for the GEMMs that follow). +// 2 CTAs/SM (96 KB ring each) -> up to 192 KB of bf16 loads in flight per SM, no per-CTA launch/exit tail. +struct PQParams { + CUtensorMap map[4]; // bf16 [N,K] maps, one per weight segment + WSeg s[4]; + int nseg, nwblk, nablk; + ActJob a; + int late; // 1: consumers trigger PDL launch_dependents after their last job's stores + int ptrig; // 1: producer triggers launch_dependents after its last job claim (mid M, wq bit14) +}; +// Two configurations (template NG = consumer groups of 8 warps): +// NG=1: 3-stage ring, 288 threads, 2 CTAs/SM (single fused launch over the whole GPU). +// NG=2: 6-stage ring (192 KB), 544 threads, exactly 1 CTA/SM -> a grid-capped launch owns a fixed set of +// SMs (used to SM-partition A-weight quant | B-weight quant | GEMM1). Group g handles the jobs +// it = g, g+NG, ... of this CTA; since NST % NG == 0 every ring stage belongs to one group. +constexpr int PQ_STAGE = 32768; +template struct PQCfg { + static constexpr int NST = 3 * NG; + static constexpr int THREADS = 256 * NG + 32; // NG x 8 consumer warps + 1 producer warp + static constexpr int SMEM = NST * PQ_STAGE + 128 + 128; + static constexpr int MINB = NG == 1 ? 2 : 1; +}; + +template +__global__ void __launch_bounds__(PQCfg::THREADS, PQCfg::MINB) pquant_kernel(const __grid_constant__ PQParams P) { + TLG_S(0); + constexpr int PQ_NST = PQCfg::NST; + extern __shared__ uint8_t pq_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(pq_raw) + 127) & ~uintptr_t(127)); + uint64_t* full = reinterpret_cast(smem + PQ_NST * PQ_STAGE); + uint64_t* empty = full + PQ_NST; + __shared__ float red_all[NG][2][8]; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int njobs = P.nwblk + P.nablk; + if (threadIdx.x == 0) { + for (int i = 0; i < PQ_NST; ++i) { kvb::bar_init(&full[i], 1); kvb::bar_init(&empty[i], 8); } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + } + // prologue: prefetch this CTA's TMA descriptors (one producer-warp lane per map; overlaps barrier init) + if (warp == 8 * NG) { + const CUtensorMap* pm = nullptr; + if (lane < P.nseg) pm = &P.map[lane]; + if (pm) asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(pm)) : "memory"); + } + __syncthreads(); + + if (warp == 8 * NG) { + // ---------------- producer + if (lane == 0) { + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + int it = 0; + for (int job = blockIdx.x; job < njobs; job += gridDim.x, ++it) { + const int s = ((unsigned)it % PQ_NST); + kvb::bar_wait_f<1>(kvb::su32(&empty[s]), ((((unsigned)it / PQ_NST)) & 1) ^ 1); // un-hinted (ring handoff latency) + uint8_t* dst = smem + s * PQ_STAGE; + if (job < P.nwblk) { + int si = 0; +#pragma unroll + for (int i = 1; i < 4; ++i) if (i < P.nseg && job >= P.s[i].nblk_start) si = i; + const WSeg& sg = P.s[si]; + const int lb = job - sg.nblk_start, nkb = sg.K >> 7; + const int nb = udiv40(lb, sg.dvm), kb = lb - nb * nkb; + kvb::bar_expect(&full[s], PQ_STAGE); + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5;" + ::"r"(kvb::su32(dst)), "l"(reinterpret_cast(&P.map[si])), "r"(kb * 128), "r"(nb * 128), + "r"(kvb::su32(&full[s])), "l"(pol) : "memory"); + } else { + const int ab = job - P.nwblk; + const long valid = (long)P.a.M * (P.a.K >> 7); // groups backed by real rows + long ng = valid - (long)ab * ACT_GROUPS_PER_CTA; + if (ng > ACT_GROUPS_PER_CTA) ng = ACT_GROUPS_PER_CTA; + const uint32_t bytes = ng > 0 ? (uint32_t)ng * 256u : 0u; + kvb::bar_expect(&full[s], bytes); // 0 bytes: plain arrive (pad chunk) + if (bytes) + asm volatile( + "cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1], %2, [%3], %4;" + ::"r"(kvb::su32(dst)), "l"((const uint8_t*)P.a.x + (size_t)ab * PQ_STAGE), "r"(bytes), + "r"(kvb::su32(&full[s])), "l"(pol) : "memory"); + } + } + // ptrig: this CTA claimed its last job -> a PDL dependent (mid M: CUTLASS GEMM1) may be scheduled; it + // griddepcontrol.wait's for this grid's completion before reading any output. + if (P.ptrig) PDL_TRIGGER(); + } + return; + } + + // ---------------- consumers (group g = warps 8g..8g+7, 256 threads each) + const int grp = warp >> 3; + const int tid = threadIdx.x & 255; // thread index inside the group + float (*red)[8] = red_all[grp]; + uint64_t pst; + asm volatile("createpolicy.fractional.L2::" KPOL_LAST ".b64 %0, 1.0;" : "=l"(pst)); + const int r0 = tid >> 3, sub = tid & 7, c = sub * 16; + int it = grp, li = 0; // it: CTA-wide job counter, li: this group's local counter + for (int job = blockIdx.x + grp * gridDim.x; job < njobs; job += NG * gridDim.x, it += NG, ++li) { + const int s = ((unsigned)it % PQ_NST); + kvb::bar_wait_f<1>(kvb::su32(&full[s]), (((unsigned)it / PQ_NST)) & 1); // un-hinted try_wait: resume right after the TMA lands + const uint8_t* st = smem + s * PQ_STAGE + r0 * 256 + sub * 32; // row r0 (+32 per pass), 32 B chunk + // Bank-conflict-free 16 B smem reads: a quarter-warp (8 lanes, sub 0..7) covers 256 B of one row; lanes + // with sub >= 4 read their high 16 B first, so each 16 B load instruction hits 8 distinct 16 B bank groups. + const int hsw = (sub >> 2) & 1; + uint4 va[4], vb[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) { + va[i] = *reinterpret_cast(st + i * 8192 + hsw * 16); + vb[i] = *reinterpret_cast(st + i * 8192 + (hsw ^ 1) * 16); + } + __syncwarp(); + if (lane == 0) kvb::bar_arrive_a(kvb::su32(&empty[s])); // stage consumed -> producer refills + if (job < P.nwblk) { + int si = 0; +#pragma unroll + for (int i = 1; i < 4; ++i) if (i < P.nseg && job >= P.s[i].nblk_start) si = i; + const WSeg& sg = P.s[si]; + const int lb = job - sg.nblk_start, nkb = sg.K >> 7; + const int nb = udiv40(lb, sg.dvm), kb = lb - nb * nkb; + uint32_t acc = 0u; +#pragma unroll + for (int i = 0; i < 4; ++i) acc = amax16(va[i], vb[i], acc); + // shuffle diet: warp |max| via ONE redux.sync.max.u32 (non-negative non-NaN fp32 bits order like u32; exact) + uint32_t amu = __float_as_uint(bf2max_to_f(acc)); + asm volatile("redux.sync.max.u32 %0, %0, 0xffffffff;" : "+r"(amu)); + float amax = __uint_as_float(amu); + if (lane == 0) red[li & 1][warp & 7] = amax; // double-buffered across jobs + asm volatile("bar.sync %0, 256;" ::"r"(1 + grp) : "memory"); // group-wide named barrier + amax = red[li & 1][0]; +#pragma unroll + for (int i = 1; i < 8; ++i) amax = fmaxf(amax, red[li & 1][i]); + const float sc = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float inv = __fdividef(1.0f, sc); // fast approx reciprocal (MUFU.RCP) + uint8_t* dst = (uint8_t*)sg.dst + (size_t)(sg.row_off + nb * 128 + r0) * sg.K + kb * 128 + c; + const size_t rstep = (size_t)32 * sg.K; +#pragma unroll + for (int i = 0; i < 4; ++i) { + if (sg.vrows && nb * 128 + r0 + 32 * i >= sg.vrows) continue; // pad rows: amax only + const uint4 q = quant16_fast(va[i], vb[i], inv, hsw); + asm volatile("st.global.L2::cache_hint.v4.b32 [%0], {%1,%2,%3,%4}, %5;" + ::"l"(dst + i * rstep), "r"(q.x), "r"(q.y), "r"(q.z), "r"(q.w), "l"(pst) : "memory"); + } + if (tid == 0) sg.sf[kb * sg.ld_sf + (sg.row_off >> 7) + nb] = sc; + } else { + const ActJob& A = P.a; + const int ab = job - P.nwblk; + const int nkb = A.K >> 7; + const int total = A.Mp * nkb, valid = A.M * nkb; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int g = ab * ACT_GROUPS_PER_CTA + i * 32 + r0; + if (g >= valid) { va[i] = make_uint4(0u, 0u, 0u, 0u); vb[i] = va[i]; } // padding rows -> zeros + } + // shuffle diet (as act_block / aqt): the 1x128 |max| is an exact bf16 value, so passes i (even) and i+1 share + // ONE bf16x2 word (lo = pass i, hi = pass i+1) -> 3 SHFL + 3 HMNMX2 per pass PAIR. Same max: bit-identical. + uint32_t pwp = 0u; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int g = ab * ACT_GROUPS_PER_CTA + i * 32 + r0; + if ((i & 1) == 0) { + const uint32_t a2 = amax16(va[i], vb[i], 0u), b2 = amax16(va[i + 1], vb[i + 1], 0u); + uint32_t pw = mxb2(__byte_perm(a2, b2, 0x5410), __byte_perm(a2, b2, 0x7632)); +#pragma unroll + for (int o = 4; o; o >>= 1) pw = mxb2(pw, __shfl_xor_sync(0xffffffffu, pw, o)); // 8-lane group + pwp = pw; + } + const float amax = (i & 1) ? __uint_as_float(pwp & 0xffff0000u) : __uint_as_float(pwp << 16); + const float sc = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float inv = __fdividef(1.0f, sc); // fast approx reciprocal (MUFU.RCP) + if (g < total) { + const uint4 q = quant16_fast(va[i], vb[i], inv, hsw); + asm volatile("st.global.L2::cache_hint.v4.b32 [%0], {%1,%2,%3,%4}, %5;" + ::"l"((uint8_t*)A.q + (size_t)g * 128 + c), "r"(q.x), "r"(q.y), "r"(q.z), "r"(q.w), "l"(pst) + : "memory"); + if (sub == 0) { + const int m = udiv40(g, A.dvm), kb = g - m * nkb; + A.sf[(size_t)kb * A.Mp + m] = sc; + } + } + } + } + } + if (P.late) PDL_TRIGGER(); // this consumer's last job claimed and stored + TLG_E(0); +} + +// ------------------------------------------------------------------ 8b. register-direct weight quant (SM-capped) +// Replaces the smem/TMA-ring pquant_kernel<2> for the weights-only SM-capped launch (B-weight quant co-running +// with the A path at small M). No shared-memory round trip: 1 CTA/SM, 512 threads = 2 independent groups of +// 256 threads; a group owns one 128x128 bf16 block at a time with the weight_block() mapping (thread -> row +// r0 = tid>>3 (+32*i), 16-col chunk c = (tid&7)*16; 4 x 32 B ld.global.nc.L1::no_allocate.L2::256B v8 loads, +// L2 evict_first). Three register buffers rotate so the NEXT TWO blocks of the group's job list are already +// in flight while the current one is reduced/quantized (2 groups x 2 blocks x 32 KB = 128 KB in flight per SM). +// amax: bf16x2 max -> redux.sync over the warp -> one named barrier per block over the group's 8 warps +// (3-slot smem scratch). Quant: x * (1/scale) (same fast math as pquant), e4m3 satfinite, 16 B st.global with +// L2 evict_last (the fp8 weights stay L2-resident for the GEMMs). +struct RQParams { WSeg s[4]; int nseg, nwblk; }; +static int g_rq_mode = 1; // 1: register-direct kernel for weights-only capped launches, 0: pquant_kernel<2> +void set_rquant(int on) { g_rq_mode = on; } + +__device__ __forceinline__ void ld32_ef(const void* p, uint4& a, uint4& b, uint64_t pol) { + asm volatile("ld.global.nc.L1::no_allocate.L2::cache_hint.L2::256B.v8.b32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8], %9;" + : "=r"(a.x), "=r"(a.y), "=r"(a.z), "=r"(a.w), "=r"(b.x), "=r"(b.y), "=r"(b.z), "=r"(b.w) + : "l"(p), "l"(pol)); +} + +__global__ void __launch_bounds__(512, 1) rquant_kernel(const __grid_constant__ RQParams P) { + TLG_S(15); + __shared__ float red[2][3][8]; + const int grp = threadIdx.x >> 8, tid = threadIdx.x & 255, wg = tid >> 5, lane = threadIdx.x & 31; + const int r0 = tid >> 3, c = (tid & 7) * 16; + const int ng = gridDim.x * 2; + const int nw = P.nwblk; + uint64_t pld, pst; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pld)); + asm volatile("createpolicy.fractional.L2::" KPOL_LAST ".b64 %0, 1.0;" : "=l"(pst)); + // job -> (segment, n-block, k-block) + auto decode = [&](int job, int& si, int& nb, int& kb) { + si = 0; +#pragma unroll + for (int i = 1; i < 4; ++i) if (i < P.nseg && job >= P.s[i].nblk_start) si = i; + const int lb = job - P.s[si].nblk_start, nkb = P.s[si].K >> 7; + nb = udiv40(lb, P.s[si].dvm); kb = lb - nb * nkb; + }; + auto issue = [&](int job, uint4 (&va)[4], uint4 (&vb)[4]) { + if (job >= nw) return; + int si, nb, kb; + decode(job, si, nb, kb); + const WSeg& sg = P.s[si]; + const uint16_t* src = (const uint16_t*)sg.src + (size_t)(nb * 128 + r0) * sg.K + kb * 128 + c; + const size_t rstep = (size_t)32 * sg.K; +#pragma unroll + for (int i = 0; i < 4; ++i) ld32_ef(src + i * rstep, va[i], vb[i], pld); + }; + auto process = [&](int job, const uint4 (&va)[4], const uint4 (&vb)[4], int slot) { + int si, nb, kb; + decode(job, si, nb, kb); + const WSeg& sg = P.s[si]; + uint32_t acc = 0u; +#pragma unroll + for (int i = 0; i < 4; ++i) acc = amax16(va[i], vb[i], acc); + uint32_t am = __float_as_uint(bf2max_to_f(acc)); // >= 0, non-NaN: u32 order == float order + asm volatile("redux.sync.max.u32 %0, %0, 0xffffffff;" : "+r"(am)); + if (lane == 0) red[grp][slot][wg] = __uint_as_float(am); + asm volatile("bar.sync %0, 256;" ::"r"(1 + grp) : "memory"); + float amax = red[grp][slot][0]; +#pragma unroll + for (int i = 1; i < 8; ++i) amax = fmaxf(amax, red[grp][slot][i]); + const float sc = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float inv = __fdividef(1.0f, sc); // fast approx reciprocal (MUFU.RCP) + uint8_t* dst = (uint8_t*)sg.dst + (size_t)(sg.row_off + nb * 128 + r0) * sg.K + kb * 128 + c; + const size_t rstep = (size_t)32 * sg.K; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const uint4 q = quant16_fast(va[i], vb[i], inv, 0); + asm volatile("st.global.L2::cache_hint.v4.b32 [%0], {%1,%2,%3,%4}, %5;" + ::"l"(dst + i * rstep), "r"(q.x), "r"(q.y), "r"(q.z), "r"(q.w), "l"(pst) : "memory"); + } + if (tid == 0) sg.sf[kb * sg.ld_sf + (sg.row_off >> 7) + nb] = sc; + }; + uint4 a0[4], b0[4], a1[4], b1[4], a2[4], b2[4]; + int j = blockIdx.x * 2 + grp; // group-uniform job index + issue(j, a0, b0); + issue(j + ng, a1, b1); +#pragma unroll 1 + for (;;) { + if (j >= nw) break; + issue(j + 2 * ng, a2, b2); process(j, a0, b0, 0); j += ng; + if (j >= nw) break; + issue(j + 2 * ng, a0, b0); process(j, a1, b1, 1); j += ng; + if (j >= nw) break; + issue(j + 2 * ng, a1, b1); process(j, a2, b2, 2); j += ng; + } + TLG_E(15); +} + +// ------------------------------------------------------------------ 8c. activation-only 1x128 quant (register-direct) +// Many small CTAs (256 threads = 32 groups of 1x128, 8 KB of bf16 per CTA; M=128 -> 224 CTAs) so the whole +// activation is in flight at once: one 32 B ld.global.nc per thread, 8-lane shuffle amax, x * (1/scale) (same fast +// math as pquant's act path), e4m3 satfinite 16 B store, scales MN-major [kb][m]; padding rows -> zeros. +constexpr int AQ_GROUPS = 32; +__global__ void __launch_bounds__(256) aquant_kernel(const __grid_constant__ ActJob A) { + TLG_S(13); + // PDL: let the dependent fused GEMM1 launch now (it griddepcontrol.wait's before touching xq / xs). + if (!A.late) PDL_TRIGGER(); // late: trigger after the final stores below instead + const int tid = threadIdx.x, sub = tid & 7; + const int nkb = A.K >> 7; + const int blk = A.rev ? (int)(gridDim.x - 1 - blockIdx.x) : (int)blockIdx.x; // rev: high rows first + const int g = blk * AQ_GROUPS + (tid >> 3); + const int total = A.Mp * nkb, valid = A.M * nkb; + // Energy diet fast path: every group of this CTA backed by a real row -> no load / store predicates. + // Same load / math / stores as the guarded path below (bit-identical). + if ((blk + 1) * AQ_GROUPS <= valid) { + const size_t eo = (size_t)g * 128 + sub * 16; + uint4 fa, fb; + // cache policy only (bit-identical): read-once bf16 x -> L2 evict_first; fp8 xq (re-read by every fused-GEMM1 + // n-block CTA) -> L2 evict_last, as act_block does + uint64_t pef_, pel_; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pef_)); + asm volatile("createpolicy.fractional.L2::" KPOL_LAST ".b64 %0, 1.0;" : "=l"(pel_)); + ld32_hint((const uint16_t*)A.x + eo, fa, fb, pef_); + float am = bf2max_to_f(amax16(fa, fb, 0u)); +#pragma unroll + for (int o = 4; o; o >>= 1) am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, o)); + const float s2 = fmaxf(am * (1.0f / FP8_MAX), 1e-12f); + st16_hint((uint8_t*)A.q + eo, quant16_fast(fa, fb, __fdividef(1.0f, s2), 0), pel_); + if (sub == 0) { + const int m = udiv40(g, A.dvm); + A.sf[(size_t)(g - m * nkb) * A.Mp + m] = s2; + } + if (A.late) PDL_TRIGGER(); + TLG_E(13); + pdl_wait(); + return; + } + uint4 va = make_uint4(0u, 0u, 0u, 0u), vb = va; + if (g < valid) ld32((const uint16_t*)A.x + (size_t)g * 128 + sub * 16, va, vb); + float amax = bf2max_to_f(amax16(va, vb, 0u)); +#pragma unroll + for (int o = 4; o; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); // 8-lane group + const float sc = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float inv = __fdividef(1.0f, sc); // fast approx reciprocal (MUFU.RCP) + if (g < total) { + *(uint4*)((uint8_t*)A.q + (size_t)g * 128 + sub * 16) = quant16_fast(va, vb, inv, 0); + if (sub == 0) { + const int m = udiv40(g, A.dvm), kb = g - m * nkb; + A.sf[(size_t)kb * A.Mp + m] = sc; + } + } + if (A.late) PDL_TRIGGER(); // final stores issued + TLG_E(13); + // PDL dependent (wq bit17: behind the A-weight wquant): it reads only x, so the wait sits at the very end, which + // makes this grid's completion imply its predecessor's (GEMM1 behind it waits only for this grid). No-op otherwise. + pdl_wait(); +} + +void launch_pquant(const WSeg* segs, int nseg, int total_wblocks, const ActJob* act, cudaStream_t st, int max_sms) { + static int nsm = 0; + if (nsm == 0) { + int dev; cudaGetDevice(&dev); + cudaDeviceGetAttribute(&nsm, cudaDevAttrMultiProcessorCount, dev); + cudaFuncSetAttribute(pquant_kernel<1>, cudaFuncAttributeMaxDynamicSharedMemorySize, PQCfg<1>::SMEM); + cudaFuncSetAttribute(pquant_kernel<2>, cudaFuncAttributeMaxDynamicSharedMemorySize, PQCfg<2>::SMEM); + } + if (act && total_wblocks == 0 && !act->f16) { // activation only: many-CTA register-direct kernel + const long groups = (long)act->Mp * (act->K / 128); + ActJob a2 = *act; + a2.dvm = dvm40((unsigned)(act->K >> 7)); + a2.late = g_late && !g_aq_early; // aq_early: entry trigger (fused GEMM1 dependent streams its weights early) + launch_pdl(aquant_kernel, dim3((int)((groups + AQ_GROUPS - 1) / AQ_GROUPS)), dim3(256), 0, st, g_aq_pdl, a2); + return; + } + if (g_rq_mode && !act && max_sms > 0 && total_wblocks > 0) { // weights-only SM-capped: register-direct kernel + RQParams R; + memset(&R, 0, sizeof(R)); + R.nseg = nseg; R.nwblk = total_wblocks; + for (int i = 0; i < nseg; ++i) { R.s[i] = segs[i]; R.s[i].dvm = dvm40((unsigned)(segs[i].K >> 7)); } + int grid = max_sms < nsm ? max_sms : nsm; + if (grid * 2 > total_wblocks) grid = (total_wblocks + 1) / 2; + rquant_kernel<<>>(R); + return; + } + PQParams P; + memset(&P, 0, sizeof(P)); + P.nseg = nseg; + for (int i = 0; i < nseg; ++i) { + P.s[i] = segs[i]; + P.s[i].dvm = dvm40((unsigned)(segs[i].K >> 7)); + cuuint64_t dims[2] = {(cuuint64_t)segs[i].K, (cuuint64_t)segs[i].N}; + cuuint64_t strides[1] = {(cuuint64_t)segs[i].K * 2}; + cuuint32_t box[2] = {128, 128}; + cuuint32_t estr[2] = {1, 1}; + cuTensorMapEncodeTiled(&P.map[i], CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, const_cast(segs[i].src), dims, + strides, box, estr, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, + CU_TENSOR_MAP_L2_PROMOTION_L2_256B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + } + P.nwblk = total_wblocks; + P.late = g_late; + P.ptrig = g_pq_ptrig; + P.nablk = 0; + if (act) { + P.a = *act; + P.a.dvm = dvm40((unsigned)(act->K >> 7)); + long groups = (long)act->Mp * (act->K / 128); + P.nablk = (int)((groups + ACT_GROUPS_PER_CTA - 1) / ACT_GROUPS_PER_CTA); + } + const int njobs = P.nwblk + P.nablk; + if (max_sms <= 0) { // whole GPU, 2 CTAs/SM + int grid = 2 * nsm; + if (grid > njobs) grid = njobs; + pquant_kernel<1><<::THREADS, PQCfg<1>::SMEM, st>>>(P); + } else { // SM-capped: 1 CTA/SM on max_sms SMs + int grid = max_sms < nsm ? max_sms : nsm; + if (grid > njobs) grid = njobs; + pquant_kernel<2><<::THREADS, PQCfg<2>::SMEM, st>>>(P); + } +} + +// ------------------------------------------------------------------ 8d. high-bandwidth TMA-in / TMA-out weight quant +// SM-capped B-weight quant that co-runs with GEMM1 at mid/large M (it must finish on few SMs, so per-SM +// bandwidth is what matters). 1 CTA/SM, 544 threads: +// warp 16 (lane 0) : producer. One 2D TMA box {128 cols, 128 rows} of bf16 (32 KB, no swizzle, row r at r*256 B) +// per 128x128 weight block into a 4-stage smem ring (128 KB in flight per SM), L2 evict_first. +// warps 0-15 : 4 consumer groups of 4 warps; group g takes jobs it = g, g+4, ... of this CTA (stage it%4 == +// g, so a stage is always consumed by the same group). Per job: conflict-free 16 B smem reads +// (8 passes of 16 rows), tree-reduced bf16x2 amax, release the stage, 128x128 amax (warp redux + group named barrier), +// q = x*(1/scale) e4m3 satfinite (pquant math), write the 16 KB of fp8 codes into the group's +// smem out-buffer (row r at r*128 B), fence.proxy.async, then ONE thread issues a 2D TMA bulk +// store (cp.async.bulk.tensor, L2 evict_last so the GEMMs read the fp8 weights from L2). +// The out-buffer is reused only after cp.async.bulk.wait_group.read 0 by that same thread. +struct WQParams { CUtensorMap in[4]; CUtensorMap out[4]; WSeg s[4]; int nseg, nwblk, dry; int ptrig; unsigned long long* done; unsigned long long* done0; + int spol; int lastj; int jc; int rev0; }; // rev0: segment-0 jobs quantized in reverse block order (see wquant_kernel decode) // lastj: jobs >= lastj store with L2 evict_normal (others: spol policy). spol: L2 policy of the fp8 stores (0 evict_last, 1 evict_normal, 2 evict_first, 3 evict_unchanged) +// CTA-local job sequence of wquant_kernel: iteration it -> job. jc = 1: job = blockIdx.x + it * gridDim.x (round +// robin). jc = 4 (M=128 row): every CTA owns runs of 4 ADJACENT k-block jobs = one 128-row x 512-col bf16 chunk +// (1 KB contiguous per row instead of 256 B) -> superjob s = blockIdx.x + (it / 4) * gridDim.x, job = 4 s + it % 4. +// Strictly increasing in it, so the first job >= nj ends the CTA's sequence. Same per-job math: bit-identical. +__device__ __forceinline__ int wq_job(int jc, int it) { + if (jc == 4) return (int)(((unsigned)blockIdx.x + ((unsigned)it >> 2) * gridDim.x) * 4u + ((unsigned)it & 3u)); + return (int)blockIdx.x + it * (int)gridDim.x; +} +__device__ __forceinline__ uint64_t wq_spol(int v) { + uint64_t p; + if (v == 1) asm volatile("createpolicy.fractional.L2::evict_normal.b64 %0, 1.0;" : "=l"(p)); + else if (v == 2) asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(p)); + else if (v == 3) asm volatile("createpolicy.fractional.L2::evict_unchanged.b64 %0, 1.0;" : "=l"(p)); + else asm volatile("createpolicy.fractional.L2::" KPOL_LAST ".b64 %0, 1.0;" : "=l"(p)); + return p; +} +static int g_wq_spol = 0; +void set_wq_spol(int v) { g_wq_spol = v; } +// Small M: only the first g_wq_lastj 128x128 jobs (the q_b + first kv_b units, consumed first by the gq launch) are +// stored with the evict_last policy; later jobs evict_normal (cache policy only, bit-identical). 0 = all jobs. +static int g_wq_lastj = 0; +static int g_wq_rev0 = 0; +void set_wq_rev0(int v) { g_wq_rev0 = v; } +static int g_wq_jc = 1; // wquant_kernel job chunk (1 or 4, see wq_job) +void set_wq_jc(int v) { g_wq_jc = v == 4 ? 4 : 1; } +void set_wq_lastj(int v) { g_wq_lastj = v; } +// plain (no suspend-time hint) mbarrier wait: the ring roles here must react immediately +__device__ __forceinline__ void wq_wait(uint64_t* b, uint32_t parity) { + asm volatile("{\n.reg .pred p;\nWQW_%=:\nmbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n@!p bra WQW_%=;\n}\n" + ::"r"(kvb::su32(b)), "r"(parity) : "memory"); +} +// Energy: hinted wait for the non-critical store-thread / out-buffer handoffs (ofull / oempty) of wquant / aqt: the +// waiting thread is suspended in hardware until the phase completes (or the hint elapses) instead of re-polling. +// Same barrier / phase: bit-identical. +__device__ __forceinline__ void wq_wait_h(uint64_t* b, uint32_t parity) { kvb::bar_wait(b, parity); } +// Ring stages, consumer groups, warps per group. NST % NG == 0 is REQUIRED: stage it % NST is then always consumed by +// the same group (it % NG), so no waiter can be two mbarrier phases ahead (parity waits would pass spuriously). +#ifndef WQ_NST_ +#define WQ_NST_ 4 +#define WQ_NG_ 4 +#define WQ_GW_ 4 +#endif +static_assert(WQ_NST_ % WQ_NG_ == 0, "each ring stage must belong to one consumer group"); +constexpr int WQ_NST = WQ_NST_, WQ_NG = WQ_NG_, WQ_GW = WQ_GW_; +constexpr int WQ_GT = 32 * WQ_GW; // threads per group +constexpr int WQ_RP = WQ_GT / 8; // block rows per pass (8 threads x 32 B per 256 B row) +constexpr int WQ_NP = 128 / WQ_RP; // passes per 128x128 block +constexpr int WQ_THREADS = WQ_GT * WQ_NG + 32; +constexpr int WQ_OUT = 16384; +constexpr int WQ_SMEM = WQ_NST * PQ_STAGE + WQ_NG * WQ_OUT + 128 + 128 + 1024; // +1024: QV 7 1024-B alignment + +// ---- quant16 variants (same math, different bf16 -> fp32 unpack instruction mix; probe-selected): +// QV 0: shl / and (quant16_fast) 1: lo via mul.lo.u32 (IMAD, FMA pipe), hi via and +// 2: both via prmt 3: lo via IMAD, hi via IMAD.HI + IMAD (all FMA pipe) +template +__device__ __forceinline__ void unpack_bf2(uint32_t w, float& lo, float& hi) { + uint32_t l, h; + if constexpr (QV == 0) { l = w << 16; h = w & 0xffff0000u; } + else if constexpr (QV == 1) { asm("mul.lo.u32 %0, %1, 65536;" : "=r"(l) : "r"(w)); h = w & 0xffff0000u; } + else if constexpr (QV == 2) { + asm("prmt.b32 %0, %1, 0, 0x1044;" : "=r"(l) : "r"(w)); + asm("prmt.b32 %0, %1, 0, 0x3244;" : "=r"(h) : "r"(w)); + } else { + uint32_t t; + asm("mul.lo.u32 %0, %1, 65536;" : "=r"(l) : "r"(w)); + asm("mul.hi.u32 %0, %1, 65536;" : "=r"(t) : "r"(w)); + asm("mul.lo.u32 %0, %1, 65536;" : "=r"(h) : "r"(t)); + } + lo = __uint_as_float(l); hi = __uint_as_float(h); +} +template +__device__ __forceinline__ uint16_t quant_pair_v(uint32_t w, unsigned long long inv2) { + float lo, hi; + unpack_bf2(w, lo, hi); + uint16_t r; + asm("{\n\t.reg .b64 x, q;\n\t.reg .f32 a, b;\n\t" + "mov.b64 x, {%1, %2};\n\t" + "mul.rn.f32x2 q, x, %3;\n\t" + "mov.b64 {a, b}, q;\n\t" + "cvt.rn.satfinite.e4m3x2.f32 %0, b, a;\n\t}" + : "=h"(r) : "f"(lo), "f"(hi), "l"(inv2)); + return r; +} +template +__device__ __forceinline__ uint2 quant8_v(const uint4& a, unsigned long long inv2) { + uint2 o; + o.x = (uint32_t)quant_pair_v(a.x, inv2) | ((uint32_t)quant_pair_v(a.y, inv2) << 16); + o.y = (uint32_t)quant_pair_v(a.z, inv2) | ((uint32_t)quant_pair_v(a.w, inv2) << 16); + return o; +} +// two bf16x2 words -> one 32-bit word of 4 e4m3 codes in ONE asm block (no 16-bit zero-extend / shift-or merge) +__device__ __forceinline__ uint32_t quant_word2(uint32_t w0, uint32_t w1, unsigned long long inv2) { + const float l0 = __uint_as_float(w0 << 16), h0 = __uint_as_float(w0 & 0xffff0000u); + const float l1 = __uint_as_float(w1 << 16), h1 = __uint_as_float(w1 & 0xffff0000u); + uint32_t r; + asm("{\n\t.reg .b64 x0, x1, q0, q1;\n\t.reg .f32 a0, b0, a1, b1;\n\t.reg .b16 c0, c1;\n\t" + "mov.b64 x0, {%1, %2};\n\t" + "mov.b64 x1, {%3, %4};\n\t" + "mul.rn.f32x2 q0, x0, %5;\n\t" + "mul.rn.f32x2 q1, x1, %5;\n\t" + "mov.b64 {a0, b0}, q0;\n\t" + "mov.b64 {a1, b1}, q1;\n\t" + "cvt.rn.satfinite.e4m3x2.f32 c0, b0, a0;\n\t" + "cvt.rn.satfinite.e4m3x2.f32 c1, b1, a1;\n\t" + "mov.b32 %0, {c0, c1};\n\t}" + : "=r"(r) : "f"(l0), "f"(h0), "f"(l1), "f"(h1), "l"(inv2)); + return r; +} +template +__device__ __forceinline__ uint4 quant16_v(const uint4& first, const uint4& second, float inv, int hsw) { + if constexpr (QV == 0) return quant16_fast(first, second, inv, hsw); + if constexpr (QV >= 4) { + const unsigned long long inv2 = pack2(inv); + const uint32_t f0 = quant_word2(first.x, first.y, inv2), f1 = quant_word2(first.z, first.w, inv2); + const uint32_t s0 = quant_word2(second.x, second.y, inv2), s1 = quant_word2(second.z, second.w, inv2); + return hsw ? make_uint4(s0, s1, f0, f1) : make_uint4(f0, f1, s0, s1); + } + const unsigned long long inv2 = pack2(inv); + const uint2 qa = quant8_v(first, inv2), qb = quant8_v(second, inv2); + return hsw ? make_uint4(qb.x, qb.y, qa.x, qa.y) : make_uint4(qa.x, qa.y, qb.x, qb.y); +} + +// Balanced max.xorsign.abs tree over the 8*NP words of va[0..NP) / vb[0..NP) (word order va[i].xyzw, vb[i].xyzw), in +// the SAME topology as the breadth-first stride-doubling tree over t[64] (levels 1-3 = one pass's 8 words, levels 4-6 = +// across passes), but evaluated depth-first: each pass is reduced to one word right away, so at most NP partial words +// are live next to the 64 input words (the breadth-first form held 32 extra temporaries -> spills at the 112-register +// cap of the 576-thread wquant / aqt kernels). Same operations on the same operand pairs: bit-identical. +template +__device__ __forceinline__ uint32_t amax_tree(const uint4 (&va)[NP], const uint4 (&vb)[NP]) { + static_assert((NP & (NP - 1)) == 0, "power-of-two pass count"); + uint32_t p[NP]; +#pragma unroll + for (int i = 0; i < NP; ++i) + p[i] = mxa2(mxa2(mxa2(va[i].x, va[i].y), mxa2(va[i].z, va[i].w)), mxa2(mxa2(vb[i].x, vb[i].y), mxa2(vb[i].z, vb[i].w))); +#pragma unroll + for (int w = 1; w < NP; w <<= 1) +#pragma unroll + for (int i = 0; i + w < NP; i += 2 * w) p[i] = mxa2(p[i], p[i + w]); + return p[0]; +} +template +__global__ void __launch_bounds__(WQ_THREADS + (QV >= 6 ? 32 : 0), 1) wquant_kernel(const __grid_constant__ WQParams P) { + TLG_S(1); + extern __shared__ uint8_t wq_raw[]; + // QV 7: the fp8 out-buffers are TMA-stored through a SWIZZLE_128B map -> 1024-B aligned base + constexpr uintptr_t WQA = QV == 7 ? 1023 : 127; + uint8_t* smem = reinterpret_cast((reinterpret_cast(wq_raw) + WQA) & ~WQA); + uint8_t* sout = smem + WQ_NST * PQ_STAGE; + uint64_t* full = reinterpret_cast(sout + WQ_NG * WQ_OUT); + uint64_t* empty = full + WQ_NST; + // DS (QV 5): decoupled output store. ofull[g]: group g's fp8 tile written (GW warp arrivals); oempty[g]: its TMA + // store has read the out-buffer (store thread). 2 x WQ_NG barriers fit the 128-B barrier carve-out. + constexpr bool DS = QV >= 5; // 6/7: store thread in its own warp (lane 0 of warp WQ_GW*WQ_NG+1) + uint64_t* ofull = empty + WQ_NST; + uint64_t* oempty = ofull + WQ_NG; + __shared__ float red_all[WQ_NG][2][WQ_GW]; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int nj = P.nwblk; + if (threadIdx.x == 0) { + for (int i = 0; i < WQ_NST; ++i) { kvb::bar_init(&full[i], 1); kvb::bar_init(&empty[i], WQ_GW); } + if (DS) for (int i = 0; i < WQ_NG; ++i) { kvb::bar_init(&ofull[i], WQ_GW); kvb::bar_init(&oempty[i], 1); } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + } + // prologue: prefetch this CTA's TMA descriptors (one producer-warp lane per map; overlaps barrier init) + if (warp == WQ_GW * WQ_NG) { + const CUtensorMap* pm = nullptr; + if (lane < P.nseg) pm = &P.in[lane]; + else if (lane >= 4 && lane - 4 < P.nseg) pm = &P.out[lane - 4]; + if (pm) asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(pm)) : "memory"); + } + __syncthreads(); + // rev0 (M=128): segment-0 (q_b) job j is remapped to block seg1-1-j, so the q_b blocks the combined gq launch claims + // FIRST (low n-blocks, ascending GV_DYN claims) are quantized LAST (most recently written fp8 lines in L2). Every + // job still maps to exactly one block of the same segment (segment counters unchanged): bit-identical outputs. + auto decode = [&](int job, int& si, int& nb, int& kb) { + if (P.rev0 && job < P.s[1].nblk_start) job = P.s[1].nblk_start - 1 - job; + si = 0; +#pragma unroll + for (int i = 1; i < 4; ++i) if (i < P.nseg && job >= P.s[i].nblk_start) si = i; + const int lb = job - P.s[si].nblk_start, nkb = P.s[si].K >> 7; + nb = udiv40(lb, P.s[si].dvm); kb = lb - nb * nkb; + }; + if (warp >= WQ_GW * WQ_NG) { + // ---------------- producer + if (warp == WQ_GW * WQ_NG && lane == 0) { + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + int it = 0; + for (int job = wq_job(P.jc, 0); job < nj; ++it, job = wq_job(P.jc, it)) { + const int s = ((unsigned)it % WQ_NST); + wq_wait(&empty[s], ((((unsigned)it / WQ_NST)) & 1) ^ 1); + int si, nb, kb; + decode(job, si, nb, kb); + kvb::bar_expect(&full[s], PQ_STAGE); + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5;" + ::"r"(kvb::su32(smem + s * PQ_STAGE)), "l"(reinterpret_cast(&P.in[si])), "r"(kb * 128), + "r"(nb * 128), "r"(kvb::su32(&full[s])), "l"(pol) : "memory"); + } + // ptrig: last job claimed -> PDL dependent (mid M: CUTLASS GEMM1 / aquant) may be scheduled (it waits for us). + if (P.ptrig) PDL_TRIGGER(); + } else if (DS && lane == (QV >= 6 ? 0 : 1) && warp == WQ_GW * WQ_NG + (QV >= 6 ? 1 : 0) && P.dry != 1) { + // ---------------- store thread (DS): CTA job it belongs to group it % WQ_NG (its li = it / WQ_NG-th job). + // Waits for the group's tile, issues the 16 KB TMA store (L2 evict_last); once a store has READ its buffer + // (wait_group.read 1 after the next store is issued) the buffer is handed back via oempty. + uint64_t pst, pnm; + pst = wq_spol(P.spol); + pnm = wq_spol(1); // evict_normal for jobs past the L2-resident prefix (lastj) + int it = 0; + // done0 (small M): segment-0 completion counter. Before this CTA's first store of a job past segment 0, all its + // segment-0 stores are drained (wait_group 0) and published with ONE release add of their count, so a consumer of + // segment 0 only (q_b units of the combined gq launch) can start before the other segments are quantized. + const int seg1 = P.nseg > 1 ? P.s[1].nblk_start : nj; + int n0 = 0; bool pub0 = P.done0 == nullptr; + for (int job = wq_job(P.jc, 0); job < nj; ++it, job = wq_job(P.jc, it)) { + const int g = ((unsigned)it % WQ_NG), l = ((unsigned)it / WQ_NG); + wq_wait_h(&ofull[g], l & 1); + if (!pub0 && job >= seg1) { + asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); + asm volatile("fence.proxy.async.global;" ::: "memory"); + if (n0 > 0) asm volatile("red.release.gpu.global.add.u64 [%0], %1;" ::"l"(P.done0), "l"((unsigned long long)n0) : "memory"); + pub0 = true; + } + if (job < seg1) ++n0; + if (P.dry != 2) { + int si, nb, kb; + decode(job, si, nb, kb); + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%1, %2}], [%3], %4;" + ::"l"(reinterpret_cast(&P.out[si])), "r"(kb * 128), "r"(P.s[si].row_off + nb * 128), + "r"(kvb::su32(sout + g * WQ_OUT)), "l"(job < P.lastj ? pst : pnm) : "memory"); + } + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + asm volatile("cp.async.bulk.wait_group.read 1;" ::: "memory"); // all but the newest store have read smem + if (it > 0) kvb::bar_arrive_a(kvb::su32(&oempty[((unsigned)(it - 1) % WQ_NG)])); + } + asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); // global writes done before exit + if (it > 0) kvb::bar_arrive_a(kvb::su32(&oempty[((unsigned)(it - 1) % WQ_NG)])); + if (P.done && it > 0) { + // completion signal (gq in-kernel wait, wq bit18): all fp8 TMA stores of this CTA complete; the scale stores + // were made before the consumers' ofull arrivals (release) that this thread acquired. + asm volatile("fence.proxy.async.global;" ::: "memory"); + asm volatile("red.release.gpu.global.add.u64 [%0], %1;" ::"l"(P.done), "l"((unsigned long long)it) : "memory"); + } + if (!pub0 && n0 > 0) { // CTA had segment-0 jobs only + asm volatile("fence.proxy.async.global;" ::: "memory"); + asm volatile("red.release.gpu.global.add.u64 [%0], %1;" ::"l"(P.done0), "l"((unsigned long long)n0) : "memory"); + } + } + return; + } + // ---------------- consumers + const int grp = warp / WQ_GW; + const int tid = threadIdx.x % WQ_GT, wg = tid >> 5; + float (*red)[WQ_GW] = red_all[grp]; + uint8_t* ob = sout + grp * WQ_OUT; + uint64_t pst, pnm; + pst = wq_spol(P.spol); + pnm = wq_spol(1); + // QV 7 (production; SASS audit of QV 6: 35 SEL of 513 instructions per thread per 128x128 job came from the + // per-lane half swap `hsw` that made QV 6's 32-B-per-thread LDS.128 reads bank-conflict free and then re-ordered every + // quantized uint4). QV 7 drops the swap without bank conflicts by a different thread -> element mapping: + // * thread (t = tid>>3, sub = tid&7) owns row r0 (+16 per pass) and the TWO 8-column pieces cols sub*8..+7 (va) and + // 64+sub*8..+7 (vb): each LDS.128 of 8 lanes reads 128 contiguous bytes (conflict-free), nothing to re-order; + // * its 2 x 8 fp8 codes go out as two st.shared.v2 into a SWIZZLE_128B out-buffer (16-B unit u of row r at + // u ^ (r&7), TMA-stored with a SWIZZLE_128B map, so global bytes are unchanged). Rows are permuted so that the two + // 8-lane groups of every 16-lane store phase have (r ^ r') & 4 != 0 -> their units fall into disjoint bank halves + // (conflict-free 64-bit stores). Address math is one base per piece + i*2048 immediates. + // Same amax set / scale / x*(1/scale) / codes / positions: bit-identical. + const int r0 = QV == 7 ? ((((tid >> 3) & 1) << 2) + ((tid >> 4) & 3) + ((tid >> 6) << 3)) : tid >> 3; + const int sub = tid & 7; + const int hsw = (sub >> 2) & 1; + static_assert(QV != 7 || (WQ_GT == 128 && WQ_RP == 16), "QV 7 row permutation assumes 128-thread groups"); + const uint32_t so1 = kvb::su32(ob) + (uint32_t)r0 * 128u + ((uint32_t)((sub >> 1) ^ (r0 & 7)) << 4) + (uint32_t)(sub & 1) * 8u; + const uint32_t so2 = so1 ^ 64u; // unit u+4 of the same row + (void)so1; (void)so2; + int it = grp, li = 0; + for (int job = wq_job(P.jc, grp); job < nj; it += WQ_NG, ++li, job = wq_job(P.jc, it)) { + const int s = ((unsigned)it % WQ_NST); + wq_wait(&full[s], (((unsigned)it / WQ_NST)) & 1); + if (P.dry == 1) { __syncwarp(); if (lane == 0) kvb::bar_arrive_a(kvb::su32(&empty[s])); continue; } // probe only + const uint8_t* st = smem + s * PQ_STAGE + r0 * 256 + sub * (QV == 7 ? 16 : 32); + uint4 va[WQ_NP], vb[WQ_NP]; +#pragma unroll + for (int i = 0; i < WQ_NP; ++i) { + if constexpr (QV == 7) { // cols sub*8..+7 and 64+sub*8..+7 of row r0 + 16i + va[i] = *reinterpret_cast(st + i * WQ_RP * 256); + vb[i] = *reinterpret_cast(st + i * WQ_RP * 256 + 128); + } else { + va[i] = *reinterpret_cast(st + i * WQ_RP * 256 + hsw * 16); + vb[i] = *reinterpret_cast(st + i * WQ_RP * 256 + (hsw ^ 1) * 16); + } + } +#ifdef WQ_PROBE + if (P.dry == 5) { // probe: second pass of LDS (smem-bandwidth sensitivity) +#pragma unroll + for (int i = 0; i < WQ_NP; ++i) { + uint4 x, y; + asm volatile("ld.shared.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(x.x), "=r"(x.y), "=r"(x.z), "=r"(x.w) : "r"(kvb::su32(st + i * WQ_RP * 256 + hsw * 16))); + asm volatile("ld.shared.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(y.x), "=r"(y.y), "=r"(y.z), "=r"(y.w) : "r"(kvb::su32(st + i * WQ_RP * 256 + (hsw ^ 1) * 16))); + va[i].x |= x.x & y.y & 0x80008000u & x.w & y.z & x.y & y.x & x.z & y.w & 0u; + } + } +#endif + __syncwarp(); + if (lane == 0) kvb::bar_arrive_a(kvb::su32(&empty[s])); + int si, nb, kb; + decode(job, si, nb, kb); + // amax: independent bf16x2 max chains per pass (short dependency chains), then a tree + uint32_t acc[WQ_NP]; +#pragma unroll + uint32_t amw; + if constexpr (QV >= 4) { + // one balanced max.xorsign.abs tree over all 8*WQ_NP words (magnitude exact at every level, signs garbage), + // a single sign mask at the end: 8*WQ_NP - 1 HMNMX2 + 1 LOP (was 9 per pass + the pass tree) + amw = amax_tree(va, vb) & 0x7fff7fffu; // depth-first, same tree (register diet) + } else { +#pragma unroll + for (int i = 0; i < WQ_NP; ++i) acc[i] = amax16(va[i], vb[i], 0u); +#pragma unroll + for (int w = 1; w < WQ_NP; w <<= 1) +#pragma unroll + for (int i = 0; i + w < WQ_NP; i += 2 * w) asm("max.bf16x2 %0, %0, %1;" : "+r"(acc[i]) : "r"(acc[i + w])); + amw = acc[0]; + } + uint32_t am = __float_as_uint(bf2max_to_f(amw)); // >= 0, non-NaN: u32 order == float order + asm volatile("redux.sync.max.u32 %0, %0, 0xffffffff;" : "+r"(am)); + if (lane == 0) red[li & 1][wg] = __uint_as_float(am); + if (DS) { if (tid == 0 && li > 0) wq_wait_h(&oempty[grp], (li - 1) & 1); } // previous store read the buffer + else if (tid == 0) asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); // out-buffer free again + asm volatile("bar.sync %0, %1;" ::"r"(1 + grp), "n"(WQ_GT) : "memory"); + float amax = red[li & 1][0]; +#pragma unroll + for (int i = 1; i < WQ_GW; ++i) amax = fmaxf(amax, red[li & 1][i]); + const float sc = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float inv = __fdividef(1.0f, sc); // fast approx reciprocal (MUFU.RCP) + if (DS && tid == 0 && P.dry != 2) { const WSeg& sg = P.s[si]; sg.sf[kb * sg.ld_sf + (sg.row_off >> 7) + nb] = sc; } +#ifdef WQ_PROBE + if (P.dry == 6) { // probe: quant math twice (ALU/issue sensitivity) + uint32_t x = 0; +#pragma unroll + for (int i = 0; i < WQ_NP; ++i) { const uint4 q = quant16_v(va[i], vb[i], inv * 1.0001f, hsw); x ^= q.x ^ q.y ^ q.z ^ q.w; } + if (x == 0x9e3779b9u) red[0][0] = 0.f; + } +#endif + if constexpr (QV == 7) { + const unsigned long long inv2 = pack2(inv); +#pragma unroll + for (int i = 0; i < WQ_NP; ++i) { + const uint32_t a0 = quant_word2(va[i].x, va[i].y, inv2), a1 = quant_word2(va[i].z, va[i].w, inv2); + const uint32_t b0 = quant_word2(vb[i].x, vb[i].y, inv2), b1 = quant_word2(vb[i].z, vb[i].w, inv2); + asm volatile("st.shared.v2.b32 [%0], {%1, %2};" ::"r"(so1 + (uint32_t)(i * WQ_RP * 128)), "r"(a0), "r"(a1) : "memory"); + asm volatile("st.shared.v2.b32 [%0], {%1, %2};" ::"r"(so2 + (uint32_t)(i * WQ_RP * 128)), "r"(b0), "r"(b1) : "memory"); + } + } else { +#pragma unroll + for (int i = 0; i < WQ_NP; ++i) + *reinterpret_cast(ob + (r0 + WQ_RP * i) * 128 + sub * 16) = quant16_v(va[i], vb[i], inv, hsw); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // generic st.shared -> async proxy + if (DS) { // hand the tile to the store thread (no second group barrier) + __syncwarp(); + if (lane == 0) kvb::bar_arrive_a(kvb::su32(&ofull[grp])); + continue; + } + asm volatile("bar.sync %0, %1;" ::"r"(1 + grp), "n"(WQ_GT) : "memory"); + if (tid == 0 && P.dry != 2) { + const WSeg& sg = P.s[si]; + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%1, %2}], [%3], %4;" + ::"l"(reinterpret_cast(&P.out[si])), "r"(kb * 128), "r"(sg.row_off + nb * 128), + "r"(kvb::su32(ob)), "l"(job < P.lastj ? pst : pnm) : "memory"); + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + sg.sf[kb * sg.ld_sf + (sg.row_off >> 7) + nb] = sc; + } + } + if (!DS && tid == 0) { + asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); // global writes done before exit + if (P.done && li > 0) { + // completion signal for the in-kernel consumer (gq, wq bit18): this group's TMA stores + scale stores done + asm volatile("fence.proxy.async.global;" ::: "memory"); + asm volatile("red.release.gpu.global.add.u64 [%0], %1;" ::"l"(P.done), "l"((unsigned long long)li) : "memory"); + } + } + TLG_E(1); +} + +struct AQTParams { + WQParams w; // weight segments (in/out maps, WSeg) + CUtensorMap ain, aout; // act bf16 [M, K] (box 128x128), fp8 [Mp, K] (box 128x128, SW128) + float* asf; // act scales [K/128][Mp] + uint8_t* aq; // act fp8 base (tiled store) + int Mp, nkb, nact, rev; + unsigned long long dvm; // dvm40(nkb) + unsigned* g1cnt; int ng1cnt; + unsigned* dyn; // [0] job claim counter, [1] finished-producer counter (both 0 at entry; last CTA resets) + int apol; // fp8 act tile TMA-store L2 policy: 0 evict_last (default), 1 evict_normal + int atiled; // 1: act fp8 tiles stored contiguously (16 KB at tile mb*nkb+kb, SW128 byte order), see GQArgs::atk + int pf; // 1 (M >= 8192): producer claims one job ahead and L2-prefetches its bf16 box (more DRAM bytes in flight) +}; +// Dynamic job scheduling (aqt): the producer of each CTA claims jobs with one atomicAdd on dyn[0] (ascending: weight +// blocks, then act tiles) instead of the static job = blockIdx.x + k*gridDim.x split, so SMs that get more DRAM +// bandwidth take more jobs. The claimed job id travels +// with its ring stage (sjob[s], written before the stage's release arrive) to the consumer group, which forwards it +// to the store thread (ojob[g], before its ofull arrive). A claim >= nj ends the CTA: the producer pushes a -1 +// sentinel through the next WQ_NG stages (one per group); groups forward it to the store thread. Same per-job math +// / stores: bit-identical outputs. +// aqt ring depth: 5 x 32 KB bf16 stages (was 4; one more 128x128 box in flight per SM toward the DRAM floor). Since +// NST = 5 is not a multiple of the 4 consumer groups, stage it % 5 is reused by different groups; the FULL barrier is +// therefore indexed by it % 20 (lcm(5, 4)): barrier it % 20 is only ever waited by group it % 4, which observes its +// phases in order (no parity aliasing), and the producer re-arms it for job it only after the empty-barrier chain of +// stage it % 5 (jobs it-5, it-10, it-15, it-20) showed that job it-20 was consumed. Same jobs / math: bit-identical. +constexpr int AQ_NST = 5, AQ_NFB = 20; +static_assert(AQ_NFB % AQ_NST == 0 && AQ_NFB % WQ_NG == 0, "full barrier ring = lcm(stages, groups)"); +constexpr int AQ_SMEM = AQ_NST * PQ_STAGE + WQ_NG * WQ_OUT + 8 * (AQ_NFB + AQ_NST + 2 * WQ_NG) + 4 * (AQ_NST + WQ_NG) + 64 + 1024; +__global__ void __launch_bounds__(WQ_THREADS + 32, 1) aqt_kernel(const __grid_constant__ AQTParams Q) { + TLG_S(8); + const WQParams& P = Q.w; + extern __shared__ uint8_t wq_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(wq_raw) + 1023) & ~uintptr_t(1023)); + uint8_t* sout = smem + AQ_NST * PQ_STAGE; + uint64_t* full = reinterpret_cast(sout + WQ_NG * WQ_OUT); + uint64_t* empty = full + AQ_NFB; + uint64_t* ofull = empty + AQ_NST; + uint64_t* oempty = ofull + WQ_NG; + volatile int* sjob = reinterpret_cast(oempty + WQ_NG); // job id per ring stage + volatile int* ojob = sjob + AQ_NST; // job id per group out-buffer + __shared__ float red_all[WQ_NG][2][WQ_GW]; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int nw = P.nwblk, nj = P.nwblk + Q.nact; + if (threadIdx.x == 0) { + for (int i = 0; i < AQ_NFB; ++i) kvb::bar_init(&full[i], 1); + for (int i = 0; i < AQ_NST; ++i) kvb::bar_init(&empty[i], WQ_GW); + for (int i = 0; i < WQ_NG; ++i) { kvb::bar_init(&ofull[i], WQ_GW); kvb::bar_init(&oempty[i], 1); } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + } + // Prologue: prefetch every TMA descriptor this CTA uses (bf16 weight / act load maps, fp8 store maps) into the + // descriptor cache, so the producer's first TMA load and the store thread's first TMA store do not pay the + // param-space descriptor fetch on the critical path (one lane per map, overlaps barrier init). Data path unchanged. + if (warp == WQ_GW * WQ_NG) { + const CUtensorMap* pm = nullptr; + if (lane < P.nseg) pm = &P.in[lane]; + else if (lane >= 4 && lane - 4 < P.nseg) pm = &P.out[lane - 4]; + else if (lane == 8) pm = &Q.ain; + else if (lane == 9) pm = &Q.aout; + if (pm) asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(pm)) : "memory"); + } + if (Q.g1cnt && blockIdx.x == 0) + for (int i = threadIdx.x; i < Q.ng1cnt; i += blockDim.x) Q.g1cnt[i] = 0u; // reset per replay (as quant_kernel) + __syncthreads(); + auto decode = [&](int job, int& si, int& nb, int& kb) { + si = 0; +#pragma unroll + for (int i = 1; i < 4; ++i) if (i < P.nseg && job >= P.s[i].nblk_start) si = i; + const int lb = job - P.s[si].nblk_start, nkb = P.s[si].K >> 7; + nb = udiv40(lb, P.s[si].dvm); kb = lb - nb * nkb; + }; + auto adec = [&](int job, int& mb, int& kb) { // act job -> (128-row block, k-block); rev: high rows first + int ab = job - nw; + if (Q.rev) ab = Q.nact - 1 - ab; + mb = udiv40(ab, Q.dvm); kb = ab - mb * Q.nkb; + }; + if (warp >= WQ_GW * WQ_NG) { + if (warp == WQ_GW * WQ_NG && lane == 0) { + // ---------------- producer + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + int it = 0; + // Q.pf (large M): the next job is claimed one iteration early and its bf16 box is L2-prefetched + // (cp.async.bulk.prefetch.tensor, no smem), so one more 32 KB DRAM read per SM is in flight beyond the 5-stage + // ring. Same jobs / loads / math: bit-identical. Each CTA still makes exactly one claim >= nj. + // Q.pf = claim-ahead depth (1 at M >= 8192, 2 at M >= 16384): jobs claimed early + L2-prefetched (FIFO q[]). + // Claims are monotonic, so q[0] >= nj implies every later queued claim >= nj too. + int qj[2] = {nj, nj}; + // register diet (ptxas: aqt had a 24 B local frame from the runtime-indexed qj[]): constant-trip unrolled loops so + // qj stays in registers; same claims in the same order (bit-identical). +#pragma unroll + for (int k2 = 0; k2 < 2; ++k2) if (k2 < Q.pf) qj[k2] = (int)atomicAdd(Q.dyn, 1u); + auto pfetch = [&](int job) { + if (job < nw) { + int si, nb, kb; decode(job, si, nb, kb); + asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile [%0, {%1, %2}];" + ::"l"(reinterpret_cast(&P.in[si])), "r"(kb * 128), "r"(nb * 128) : "memory"); + } else { + int mb, kb; adec(job, mb, kb); + asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile [%0, {%1, %2}];" + ::"l"(reinterpret_cast(&Q.ain)), "r"(kb * 128), "r"(mb * 128) : "memory"); + } + }; +#pragma unroll + for (int k2 = 0; k2 < 2; ++k2) + if (k2 < Q.pf && qj[k2] < nj) pfetch(qj[k2]); + for (;; ++it) { + const int s = ((unsigned)it % AQ_NST), fb = ((unsigned)it % AQ_NFB); + wq_wait(&empty[s], ((((unsigned)it / AQ_NST)) & 1) ^ 1); + int job; + if (Q.pf) { + job = qj[0]; + if (job >= nj) break; + const int nxt = (int)atomicAdd(Q.dyn, 1u); + if (Q.pf == 2) { qj[0] = qj[1]; qj[1] = nxt; } else qj[0] = nxt; + if (nxt < nj) pfetch(nxt); + } else { + job = (int)atomicAdd(Q.dyn, 1u); // dynamic claim (stage s is free: its old id was consumed) + if (job >= nj) break; + } + sjob[s] = job; // published by the release arrive.expect_tx below + const CUtensorMap* map; + int x, y; + if (job < nw) { int si, nb, kb; decode(job, si, nb, kb); map = &P.in[si]; x = kb * 128; y = nb * 128; } + else { int mb, kb; adec(job, mb, kb); map = &Q.ain; x = kb * 128; y = mb * 128; } + kvb::bar_expect(&full[fb], PQ_STAGE); + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5;" + ::"r"(kvb::su32(smem + s * PQ_STAGE)), "l"(reinterpret_cast(map)), "r"(x), "r"(y), + "r"(kvb::su32(&full[fb])), "l"(pol) : "memory"); + } + PDL_TRIGGER(); // last job claimed: the GEMM1 PDL dependent may be scheduled (it waits for this grid) + // end-of-work sentinels: iterations it .. it+WQ_NG-1 (one per consumer group); stage of `it` already free + for (int k = 0; k < WQ_NG; ++k) { + const unsigned i2 = (unsigned)(it + k); + const int s = (int)(i2 % AQ_NST); + if (k > 0) wq_wait(&empty[s], ((i2 / AQ_NST) & 1) ^ 1); + sjob[s] = -1; + kvb::bar_arrive_a(kvb::su32(&full[i2 % AQ_NFB])); // plain arrive (count 1): completes the phase, no tx + } + // this producer's claims are over: the last CTA to get here resets both counters for the next launch + __threadfence(); + if (atomicAdd(Q.dyn + 1, 1u) == gridDim.x - 1) { atomicExch(Q.dyn, 0u); atomicExch(Q.dyn + 1, 0u); } + } else if (warp == WQ_GW * WQ_NG + 1 && lane == 0) { + // ---------------- store thread + uint64_t pst; + asm volatile("createpolicy.fractional.L2::" KPOL_LAST ".b64 %0, 1.0;" : "=l"(pst)); + const uint64_t pnm = wq_spol(1); // evict_normal (act tiles when Q.apol) + int it = 0; + for (;; ++it) { + const int g = ((unsigned)it % WQ_NG), l = ((unsigned)it / WQ_NG); + wq_wait_h(&ofull[g], l & 1); + const int job = ojob[g]; + if (job < 0) break; // sentinel: this CTA's job stream ended + if (job < nw) { + int si, nb, kb; + decode(job, si, nb, kb); + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%1, %2}], [%3], %4;" + ::"l"(reinterpret_cast(&P.out[si])), "r"(kb * 128), "r"(P.s[si].row_off + nb * 128), + "r"(kvb::su32(sout + g * WQ_OUT)), "l"(pst) : "memory"); + } else { + int mb, kb; + adec(job, mb, kb); + // fp8 act tile: read by all GEMM1 n-tiles within a short window (n-fastest raster) -> L2 evict_last by + // default; apol = 1 (very large M: 117 MB of act > L2) evict_normal so stale act lines do not stay pinned + // against the co-running B wquant's evict_last fp8 weights (cache policy only, bit-identical) + if (Q.atiled) { // tiled: the 16 KB SW128 out-buffer as-is, one contiguous 1D bulk store + uint8_t* gdst = Q.aq + ((size_t)mb * Q.nkb + kb) * 16384; + asm volatile("cp.async.bulk.global.shared::cta.bulk_group.L2::cache_hint [%0], [%1], %2, %3;" + ::"l"(gdst), "r"(kvb::su32(sout + g * WQ_OUT)), "r"(16384), "l"(Q.apol ? pnm : pst) : "memory"); + } else + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%1, %2}], [%3], %4;" + ::"l"(reinterpret_cast(&Q.aout)), "r"(kb * 128), "r"(mb * 128), + "r"(kvb::su32(sout + g * WQ_OUT)), "l"(Q.apol ? pnm : pst) : "memory"); + } + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + asm volatile("cp.async.bulk.wait_group.read 1;" ::: "memory"); + if (it > 0) kvb::bar_arrive_a(kvb::su32(&oempty[((unsigned)(it - 1) % WQ_NG)])); + } + asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); + if (it > 0) kvb::bar_arrive_a(kvb::su32(&oempty[((unsigned)(it - 1) % WQ_NG)])); + } + return; + } + // ---------------- consumers + const int grp = warp / WQ_GW; + const int tid = threadIdx.x % WQ_GT, wg = tid >> 5; + float (*red)[WQ_GW] = red_all[grp]; + uint8_t* ob = sout + grp * WQ_OUT; + static_assert(WQ_GT == 128 && WQ_RP == 16 && WQ_NP == 8, "aqt mapping assumes 128-thread groups"); + // row permutation of wquant_kernel<7> (conflict-free 64-bit SW128 stores); the 8 lanes tid&~7..+7 share row r0 + const int r0 = (((tid >> 3) & 1) << 2) + ((tid >> 4) & 3) + ((tid >> 6) << 3); + const int sub = tid & 7; + const uint32_t so1 = kvb::su32(ob) + (uint32_t)r0 * 128u + ((uint32_t)((sub >> 1) ^ (r0 & 7)) << 4) + (uint32_t)(sub & 1) * 8u; + const uint32_t so2 = so1 ^ 64u; + int it = grp, li = 0; + for (;; it += WQ_NG, ++li) { + const int s = ((unsigned)it % AQ_NST); + // energy: 16 consumer warps park on the full barrier with the suspend-time hint (hardware sleep until the TMA + // completes) instead of re-polling; same barrier / phase: bit-identical. + kvb::bar_wait_f<1>(kvb::su32(&full[(unsigned)it % AQ_NFB]), (((unsigned)it / AQ_NFB)) & 1); // un-hinted try_wait: consumer resumes right after the TMA lands + const int job = sjob[s]; // read before this stage's empty arrive (group-uniform) + if (job < 0) { + // sentinel: forward to the store thread once its previous store of this group has read the out-buffer + if (tid == 0) { if (li > 0) wq_wait_h(&oempty[grp], (li - 1) & 1); ojob[grp] = -1; } + asm volatile("bar.sync %0, %1;" ::"r"(1 + grp), "n"(WQ_GT) : "memory"); + __syncwarp(); + if (lane == 0) kvb::bar_arrive_a(kvb::su32(&ofull[grp])); + break; + } + const uint8_t* st = smem + s * PQ_STAGE + r0 * 256 + sub * 16; + uint4 va[WQ_NP], vb[WQ_NP]; +#pragma unroll + for (int i = 0; i < WQ_NP; ++i) { // cols sub*8..+7 and 64+sub*8..+7 of row r0 + 16i + va[i] = *reinterpret_cast(st + i * WQ_RP * 256); + vb[i] = *reinterpret_cast(st + i * WQ_RP * 256 + 128); + } + __syncwarp(); + if (lane == 0) kvb::bar_arrive_a(kvb::su32(&empty[s])); + if (job < nw) { + int si, nb, kb; + decode(job, si, nb, kb); + // register diet (as wquant_kernel<7>): same max.xorsign.abs tree topology evaluated depth-first (amax_tree), + // so only WQ_NP partials stay live next to the 64 input words instead of 32 breadth-first temporaries. Bit-identical. + const uint32_t t0 = amax_tree(va, vb); + uint32_t am = __float_as_uint(bf2max_to_f(t0 & 0x7fff7fffu)); + asm volatile("redux.sync.max.u32 %0, %0, 0xffffffff;" : "+r"(am)); + if (lane == 0) red[li & 1][wg] = __uint_as_float(am); + if (tid == 0) { if (li > 0) wq_wait_h(&oempty[grp], (li - 1) & 1); ojob[grp] = job; } // previous store read the out-buffer + asm volatile("bar.sync %0, %1;" ::"r"(1 + grp), "n"(WQ_GT) : "memory"); + float amax = red[li & 1][0]; +#pragma unroll + for (int i = 1; i < WQ_GW; ++i) amax = fmaxf(amax, red[li & 1][i]); + const float sc = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float inv = __fdividef(1.0f, sc); + if (tid == 0) { const WSeg& sg = P.s[si]; sg.sf[kb * sg.ld_sf + (sg.row_off >> 7) + nb] = sc; } + const unsigned long long inv2 = pack2(inv); +#pragma unroll + for (int i = 0; i < WQ_NP; ++i) { + const uint32_t a0 = quant_word2(va[i].x, va[i].y, inv2), a1 = quant_word2(va[i].z, va[i].w, inv2); + const uint32_t b0 = quant_word2(vb[i].x, vb[i].y, inv2), b1 = quant_word2(vb[i].z, vb[i].w, inv2); + asm volatile("st.shared.v2.b32 [%0], {%1, %2};" ::"r"(so1 + (uint32_t)(i * WQ_RP * 128)), "r"(a0), "r"(a1) : "memory"); + asm volatile("st.shared.v2.b32 [%0], {%1, %2};" ::"r"(so2 + (uint32_t)(i * WQ_RP * 128)), "r"(b0), "r"(b1) : "memory"); + } + } else { + int mb, kb; + adec(job, mb, kb); + // the group barrier also orders the red[] double buffer of the surrounding weight jobs + if (tid == 0) { if (li > 0) wq_wait_h(&oempty[grp], (li - 1) & 1); ojob[grp] = job; } + asm volatile("bar.sync %0, %1;" ::"r"(1 + grp), "n"(WQ_GT) : "memory"); + float* sfp = Q.asf + (size_t)kb * Q.Mp + mb * 128 + r0; + uint32_t pwp = 0u; +#pragma unroll + for (int i = 0; i < WQ_NP; ++i) { + // Shuffle diet: the 1x128 amax is an exact bf16 value, so rows i (even) and i+1 share ONE 32-bit word + // (lo = row i, hi = row i+1) -> 3 SHFL + 3 HMNMX2 per row PAIR instead of 3 SHFL + 3 FMNMX per row. + // Same per-row max over the 8 lanes (non-negative, exact): bit-identical scales / codes. + uint32_t pw; + if ((i & 1) == 0) { + const uint32_t a2 = amax16(va[i], vb[i], 0u), b2 = amax16(va[i + 1], vb[i + 1], 0u); + pw = mxb2(__byte_perm(a2, b2, 0x5410), __byte_perm(a2, b2, 0x7632)); +#pragma unroll + for (int o = 4; o; o >>= 1) pw = mxb2(pw, __shfl_xor_sync(0xffffffffu, pw, o)); // 8 lanes of rows r0+16i, +16 + pwp = pw; + } + const float am = (i & 1) ? __uint_as_float(pwp & 0xffff0000u) : __uint_as_float(pwp << 16); + const float sc = fmaxf(am * (1.0f / FP8_MAX), 1e-12f); + const unsigned long long inv2 = pack2(__fdividef(1.0f, sc)); + const uint32_t a0 = quant_word2(va[i].x, va[i].y, inv2), a1 = quant_word2(va[i].z, va[i].w, inv2); + const uint32_t b0 = quant_word2(vb[i].x, vb[i].y, inv2), b1 = quant_word2(vb[i].z, vb[i].w, inv2); + asm volatile("st.shared.v2.b32 [%0], {%1, %2};" ::"r"(so1 + (uint32_t)(i * WQ_RP * 128)), "r"(a0), "r"(a1) : "memory"); + asm volatile("st.shared.v2.b32 [%0], {%1, %2};" ::"r"(so2 + (uint32_t)(i * WQ_RP * 128)), "r"(b0), "r"(b1) : "memory"); + if (sub == 0) sfp[16 * i] = sc; + } + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // generic st.shared -> async proxy + __syncwarp(); + if (lane == 0) kvb::bar_arrive_a(kvb::su32(&ofull[grp])); + } + TLG_E(8); +} + +static unsigned* g_aqt_dyn = nullptr; // aqt dynamic job claim counters (2 x u32, zero-initialised workspace) +void set_aqt_dyn(unsigned* p) { g_aqt_dyn = p; } +static int g_aqt_apol = 0; +void set_aqt_apol(int v) { g_aqt_apol = v; } +static int g_aqt = 1; // 1: large-M A+act quant via aqt_kernel (else quant_kernel) +void set_aqt(int on) { g_aqt = on; } +int get_aqt() { return g_aqt; } +void launch_quant_tma(const WSeg* segs, int nseg, int total_wblocks, const ActJob* act, int ctas, cudaStream_t st) { + static bool attr = false; + if (!attr) { cudaFuncSetAttribute(aqt_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, AQ_SMEM); attr = true; } + AQTParams Q; + memset(&Q, 0, sizeof(Q)); + WQParams& P = Q.w; + P.nseg = nseg; P.nwblk = total_wblocks; + cuuint32_t box[2] = {128, 128}; + cuuint32_t estr[2] = {1, 1}; + for (int i = 0; i < nseg; ++i) { + P.s[i] = segs[i]; + P.s[i].dvm = dvm40((unsigned)(segs[i].K >> 7)); + cuuint64_t dims[2] = {(cuuint64_t)segs[i].K, (cuuint64_t)segs[i].N}; + cuuint64_t strides[1] = {(cuuint64_t)segs[i].K * 2}; + cuTensorMapEncodeTiled(&P.in[i], CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, const_cast(segs[i].src), dims, + strides, box, estr, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, + CU_TENSOR_MAP_L2_PROMOTION_L2_256B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + cuuint64_t odims[2] = {(cuuint64_t)segs[i].K, (cuuint64_t)(segs[i].row_off + (segs[i].vrows ? segs[i].vrows : segs[i].N))}; // TMA store clips pad rows + cuuint64_t ostr[1] = {(cuuint64_t)segs[i].K}; + cuTensorMapEncodeTiled(&P.out[i], CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, segs[i].dst, odims, ostr, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + } + { + cuuint64_t dims[2] = {(cuuint64_t)act->K, (cuuint64_t)act->M}; // rows >= M: TMA zero fill (padding rows) + cuuint64_t strides[1] = {(cuuint64_t)act->K * 2}; + cuTensorMapEncodeTiled(&Q.ain, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, const_cast(act->x), dims, strides, box, + estr, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, + CU_TENSOR_MAP_L2_PROMOTION_L2_256B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + cuuint64_t odims[2] = {(cuuint64_t)act->K, (cuuint64_t)act->Mp}; + cuuint64_t ostr[1] = {(cuuint64_t)act->K}; + cuTensorMapEncodeTiled(&Q.aout, CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, act->q, odims, ostr, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + } + Q.asf = act->sf; Q.Mp = act->Mp; Q.nkb = act->K >> 7; Q.nact = (act->Mp >> 7) * Q.nkb; Q.rev = act->rev; + Q.dvm = dvm40((unsigned)Q.nkb); + Q.g1cnt = g_q_g1cnt; Q.ng1cnt = g_q_ng1cnt; + Q.dyn = g_aqt_dyn; + Q.apol = g_aqt_apol; + Q.pf = act->Mp >= 16384 ? 2 : act->Mp >= 8192 ? 1 : 0; // claim-ahead / L2 prefetch depth + Q.atiled = kvb::g_act_tiled; Q.aq = (uint8_t*)act->q; + if (!Q.dyn) { fprintf(stderr, "launch_quant_tma: no claim counter (set_aqt_dyn)\n"); return; } + const int nj = total_wblocks + Q.nact; + int grid = ctas; + if (grid * WQ_NG > nj) grid = (nj + WQ_NG - 1) / WQ_NG; + if (grid < 1) grid = 1; + aqt_kernel<<>>(Q); +} + +// ---- wquant2_kernel: same job decomposition / ring / math as wquant_kernel, but the fp8 codes go +// straight from registers to global (16 B st.global.v4 per thread, 8 consecutive lanes = one 128-B fp8 row segment, +// L2 evict_last) instead of st.shared -> out-buffer -> TMA store. Shared-memory traffic per element drops from 6 B +// (TMA fill 2 + LDS 2 + STS 1 + TMA-store read 1) to 4 B; the consumers of wquant_kernel were smem-bandwidth bound +// (~128 B/clk/SM -> ~21 elem/clk). One group barrier per job (amax) instead of two. Bit-identical codes / scales. +// NST % NG == 0: stage it % NST is always consumed by group it % NG (parity waits never two phases ahead). +template +struct WQ2Cfg { + static_assert(NST % NG == 0, "each ring stage must belong to one consumer group"); + static constexpr int GT = 32 * GW, RP = GT / 8, NP = 128 / RP, THREADS = GT * NG + 32; + static constexpr int SMEM = NST * PQ_STAGE + 128 + 128; +}; +template +__global__ void __launch_bounds__(WQ2Cfg::THREADS, 1) wquant2_kernel(const __grid_constant__ WQParams P) { + using C = WQ2Cfg; + constexpr int GT = C::GT, RP = C::RP, NP = C::NP; + TLG_S(1); + extern __shared__ uint8_t wq_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(wq_raw) + 127) & ~uintptr_t(127)); + uint64_t* full = reinterpret_cast(smem + NST * PQ_STAGE); + uint64_t* empty = full + NST; + __shared__ float red_all[NG][2][GW]; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int nj = P.nwblk; + if (threadIdx.x == 0) { + for (int i = 0; i < NST; ++i) { kvb::bar_init(&full[i], 1); kvb::bar_init(&empty[i], GW); } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + } + // prologue: prefetch this CTA's TMA descriptors (one producer-warp lane per map; overlaps barrier init) + if (warp == GW * NG) { + const CUtensorMap* pm = nullptr; + if (lane < P.nseg) pm = &P.in[lane]; + if (pm) asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(pm)) : "memory"); + } + __syncthreads(); + auto decode = [&](int job, int& si, int& nb, int& kb) { + si = 0; +#pragma unroll + for (int i = 1; i < 4; ++i) if (i < P.nseg && job >= P.s[i].nblk_start) si = i; + const int lb = job - P.s[si].nblk_start, nkb = P.s[si].K >> 7; + nb = udiv40(lb, P.s[si].dvm); kb = lb - nb * nkb; + }; + if (warp == GW * NG) { + // ---------------- producer: one 32 KB TMA box per 128x128 bf16 block, L2 evict_first + if (lane == 0) { + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + int it = 0; + for (int job = blockIdx.x; job < nj; job += gridDim.x, ++it) { + const int s = ((unsigned)it % NST); + wq_wait(&empty[s], ((((unsigned)it / NST)) & 1) ^ 1); + int si, nb, kb; + decode(job, si, nb, kb); + kvb::bar_expect(&full[s], PQ_STAGE); + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint" + " [%0], [%1, {%2, %3}], [%4], %5;" + ::"r"(kvb::su32(smem + s * PQ_STAGE)), "l"(reinterpret_cast(&P.in[si])), "r"(kb * 128), + "r"(nb * 128), "r"(kvb::su32(&full[s])), "l"(pol) : "memory"); + } + if (P.ptrig) PDL_TRIGGER(); + } + return; + } + // ---------------- consumers (group grp = warps GW*grp .. +GW-1) + const int grp = warp / GW; + const int tid = threadIdx.x % GT, wg = tid >> 5; + float (*red)[GW] = red_all[grp]; + uint64_t pst; + asm volatile("createpolicy.fractional.L2::" KPOL_LAST ".b64 %0, 1.0;" : "=l"(pst)); + const int r0 = tid >> 3, sub = tid & 7; + const int hsw = (sub >> 2) & 1; + int it = grp, li = 0; + for (int job = blockIdx.x + grp * gridDim.x; job < nj; job += NG * gridDim.x, it += NG, ++li) { + const int s = ((unsigned)it % NST); + wq_wait(&full[s], (((unsigned)it / NST)) & 1); + if (P.dry == 1) { __syncwarp(); if (lane == 0) kvb::bar_arrive_a(kvb::su32(&empty[s])); continue; } // probe only + const uint8_t* st = smem + s * PQ_STAGE + r0 * 256 + sub * 32; + uint4 va[NP], vb[NP]; +#pragma unroll + for (int i = 0; i < NP; ++i) { // conflict-free: lanes with sub >= 4 read their high 16 B first + va[i] = *reinterpret_cast(st + i * RP * 256 + hsw * 16); + vb[i] = *reinterpret_cast(st + i * RP * 256 + (hsw ^ 1) * 16); + } + __syncwarp(); + if (lane == 0) kvb::bar_arrive_a(kvb::su32(&empty[s])); // stage consumed -> producer refills + int si, nb, kb; + decode(job, si, nb, kb); + uint32_t acc[NP]; + uint32_t am; +#ifdef WQ_PROBE + if (P.dry == 4) am = __float_as_uint(fabsf(__uint_as_float(va[0].x << 16)) + 1.f); + else +#endif + { +#pragma unroll + for (int i = 0; i < NP; ++i) acc[i] = amax16(va[i], vb[i], 0u); +#pragma unroll + for (int w = 1; w < NP; w <<= 1) +#pragma unroll + for (int i = 0; i + w < NP; i += 2 * w) asm("max.bf16x2 %0, %0, %1;" : "+r"(acc[i]) : "r"(acc[i + w])); + am = __float_as_uint(bf2max_to_f(acc[0])); // >= 0, non-NaN: u32 order == float order + } + asm volatile("redux.sync.max.u32 %0, %0, 0xffffffff;" : "+r"(am)); + if (lane == 0) red[li & 1][wg] = __uint_as_float(am); // double-buffered: next write to this slot is 2 jobs later + asm volatile("bar.sync %0, %1;" ::"r"(1 + grp), "n"(GT) : "memory"); + float amax = red[li & 1][0]; +#pragma unroll + for (int i = 1; i < GW; ++i) amax = fmaxf(amax, red[li & 1][i]); + const float sc = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float inv = __fdividef(1.0f, sc); // fast approx reciprocal (MUFU.RCP) + const WSeg& sg = P.s[si]; + uint8_t* dst = (uint8_t*)sg.dst + (size_t)(sg.row_off + nb * 128 + r0) * sg.K + kb * 128 + sub * 16; + const size_t rstep = (size_t)RP * sg.K; +#ifdef WQ_PROBE + if (P.dry == 3) { // probe: no quant math (keep the loaded data live) + uint32_t x = 0; +#pragma unroll + for (int i = 0; i < NP; ++i) x ^= va[i].x ^ va[i].y ^ va[i].z ^ va[i].w ^ vb[i].x ^ vb[i].y ^ vb[i].z ^ vb[i].w; + if (x == 0x12345678u && inv == 3.f) sg.sf[0] = 0.f; + continue; + } +#endif +#pragma unroll + for (int i = 0; i < NP; ++i) { + const uint4 q = quant16_fast(va[i], vb[i], inv, hsw); + if (P.dry != 2 && P.dry != 4) + asm volatile("st.global.L2::cache_hint.v4.b32 [%0], {%1,%2,%3,%4}, %5;" + ::"l"(dst + i * rstep), "r"(q.x), "r"(q.y), "r"(q.z), "r"(q.w), "l"(pst) : "memory"); + } + if (tid == 0 && P.dry == 0) sg.sf[kb * sg.ld_sf + (sg.row_off >> 7) + nb] = sc; + } + if (P.done) { + // completion signal (gq in-kernel wait, wq bit18): every thread's fp8 / scale stores made gpu-visible, then one + // release add per group (bar.sync orders the group's fenced stores before thread 0's release). + __threadfence(); + asm volatile("bar.sync %0, %1;" ::"r"(1 + grp), "n"(GT) : "memory"); + if (tid == 0 && li > 0) { + __threadfence(); + asm volatile("red.release.gpu.global.add.u64 [%0], %1;" ::"l"(P.done), "l"((unsigned long long)li) : "memory"); + } + } + TLG_E(1); +} +template +static void launch_wq2(const WQParams& P, int total_wblocks, int ctas, cudaStream_t st) { + using C = WQ2Cfg; + static bool attr = false; + if (!attr) { + cudaFuncSetAttribute(wquant2_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, C::SMEM); + attr = true; + } + int grid = ctas; + if (grid * NG > total_wblocks) grid = (total_wblocks + NG - 1) / NG; + if (grid < 1) grid = 1; + wquant2_kernel<<>>(P); +} +// ---- wquant3_kernel: register-direct loads (no smem round trip for the bf16 input), TMA-store output. +// 1 CTA/SM, G groups of 128 threads; group g owns jobs blockIdx.x*G + g + k*(G*gridDim.x). Thread (r0 = tid>>3, +// sub = tid&7) loads rows r0 + 16i (i < 8), 32 B (16 bf16) at column sub*16 with ld.global.nc.v8 (L2 evict_first, +// 256-B L2 prefetch): 8 lanes = one 256-B row segment (fully coalesced). Two register buffers: the next job's loads +// are in flight while the current one is reduced / quantized. Then the same math as wquant_kernel (bf16x2 amax +// tree, warp redux, group named barrier, x * (1/scale), e4m3 satfinite) into the group's 16 KB smem out-buffer and +// one 2D TMA store (L2 evict_last). Bit-identical codes / scales. +template +__global__ void __launch_bounds__(128 * G, 1) wquant3_kernel(const __grid_constant__ WQParams P) { + TLG_S(1); + extern __shared__ uint8_t wq_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(wq_raw) + 127) & ~uintptr_t(127)); + __shared__ float red_all[G][2][4]; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int grp = warp >> 2, tid = threadIdx.x & 127, wg = tid >> 5; + const int r0 = tid >> 3, sub = tid & 7; + const int nj = P.nwblk; + float (*red)[4] = red_all[grp]; + uint8_t* ob = smem + grp * 16384; + uint64_t pld, pst; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pld)); + asm volatile("createpolicy.fractional.L2::" KPOL_LAST ".b64 %0, 1.0;" : "=l"(pst)); + auto decode = [&](int job, int& si, int& nb, int& kb) { + si = 0; +#pragma unroll + for (int i = 1; i < 4; ++i) if (i < P.nseg && job >= P.s[i].nblk_start) si = i; + const int lb = job - P.s[si].nblk_start, nkb = P.s[si].K >> 7; + nb = udiv40(lb, P.s[si].dvm); kb = lb - nb * nkb; + }; + auto issue = [&](int job, uint4 (&va)[8], uint4 (&vb)[8]) { + if (job >= nj) return; + int si, nb, kb; + decode(job, si, nb, kb); + const WSeg& sg = P.s[si]; + const uint16_t* src = (const uint16_t*)sg.src + (size_t)(nb * 128 + r0) * sg.K + kb * 128 + sub * 16; + const size_t rstep = (size_t)16 * sg.K; +#pragma unroll + for (int i = 0; i < 8; ++i) ld32_ef(src + i * rstep, va[i], vb[i], pld); + }; + int li = 0; + auto process = [&](int job, const uint4 (&va)[8], const uint4 (&vb)[8]) { + int si, nb, kb; + decode(job, si, nb, kb); + uint32_t acc[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) acc[i] = amax16(va[i], vb[i], 0u); +#pragma unroll + for (int w = 1; w < 8; w <<= 1) +#pragma unroll + for (int i = 0; i + w < 8; i += 2 * w) asm("max.bf16x2 %0, %0, %1;" : "+r"(acc[i]) : "r"(acc[i + w])); + uint32_t am = __float_as_uint(bf2max_to_f(acc[0])); // >= 0, non-NaN: u32 order == float order + asm volatile("redux.sync.max.u32 %0, %0, 0xffffffff;" : "+r"(am)); + if (lane == 0) red[li & 1][wg] = __uint_as_float(am); + if (tid == 0) asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); // out-buffer free again + asm volatile("bar.sync %0, 128;" ::"r"(1 + grp) : "memory"); + const float amax = fmaxf(fmaxf(red[li & 1][0], red[li & 1][1]), fmaxf(red[li & 1][2], red[li & 1][3])); + const float sc = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float inv = __fdividef(1.0f, sc); // fast approx reciprocal (MUFU.RCP) + if (P.dry != 2) { +#pragma unroll + for (int i = 0; i < 8; ++i) + *reinterpret_cast(ob + (r0 + 16 * i) * 128 + sub * 16) = quant16_fast(va[i], vb[i], inv, 0); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // generic st.shared -> async proxy + } else { + uint32_t x = 0; +#pragma unroll + for (int i = 0; i < 8; ++i) { const uint4 q = quant16_fast(va[i], vb[i], inv, 0); x ^= q.x ^ q.y ^ q.z ^ q.w; } + if (x == 0x9e3779b9u) red[0][0] = 0.f; + } + asm volatile("bar.sync %0, 128;" ::"r"(1 + grp) : "memory"); + if (tid == 0 && P.dry != 2) { + const WSeg& sg = P.s[si]; + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%1, %2}], [%3], %4;" + ::"l"(reinterpret_cast(&P.out[si])), "r"(kb * 128), "r"(sg.row_off + nb * 128), + "r"(kvb::su32(ob)), "l"(pst) : "memory"); + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + sg.sf[kb * sg.ld_sf + (sg.row_off >> 7) + nb] = sc; + } + ++li; + }; + const int step = G * gridDim.x; + int j = blockIdx.x * G + grp; + uint4 a0[8], b0[8], a1[8], b1[8]; + issue(j, a0, b0); +#pragma unroll 1 + for (;;) { + if (j >= nj) break; + issue(j + step, a1, b1); process(j, a0, b0); j += step; + if (j >= nj) break; + issue(j + step, a0, b0); process(j, a1, b1); j += step; + } + if (tid == 0) { + asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); // global writes done before exit + if (P.done && li > 0) { + asm volatile("fence.proxy.async.global;" ::: "memory"); + asm volatile("red.release.gpu.global.add.u64 [%0], %1;" ::"l"(P.done), "l"((unsigned long long)li) : "memory"); + } + } + TLG_E(1); +} +template +static void launch_wq3(const WQParams& P, int total_wblocks, int ctas, cudaStream_t st) { + static bool attr = false; + if (!attr) { + cudaFuncSetAttribute(wquant3_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, G * 16384 + 128); + attr = true; + } + int grid = ctas; + if (grid * G > total_wblocks) grid = (total_wblocks + G - 1) / G; + if (grid < 1) grid = 1; + wquant3_kernel<<>>(P); +} +// 3 (default): wquant_kernel<7> (= <6> without the hsw half swap); 4: wquant_kernel<6>; 0: legacy wquant_kernel<0>; 1/2/9: probe variants (see launch_wquant) +static int g_wq_ver = 3; +void set_wq_ver(int v) { g_wq_ver = v; } +void launch_wquant(const WSeg* segs, int nseg, int total_wblocks, int ctas, cudaStream_t st, int dry, + unsigned long long* done, unsigned long long* done0) { + static bool attr = false; + if (!attr) { + cudaFuncSetAttribute(wquant_kernel<0>, cudaFuncAttributeMaxDynamicSharedMemorySize, WQ_SMEM); + attr = true; + } + WQParams P; + memset(&P, 0, sizeof(P)); + P.nseg = nseg; P.nwblk = total_wblocks; P.dry = dry; P.ptrig = g_pq_ptrig; P.done = done; P.spol = g_wq_spol; + P.jc = g_wq_jc; + P.rev0 = (g_wq_rev0 && nseg > 1) ? 1 : 0; + P.lastj = g_wq_lastj > 0 && g_wq_lastj < total_wblocks ? g_wq_lastj : total_wblocks; + P.done0 = (g_wq_ver == 3 || g_wq_ver == 4) ? done0 : nullptr; // DS store-thread versions only + for (int i = 0; i < nseg; ++i) { + P.s[i] = segs[i]; + P.s[i].dvm = dvm40((unsigned)(segs[i].K >> 7)); + cuuint64_t dims[2] = {(cuuint64_t)segs[i].K, (cuuint64_t)segs[i].N}; + cuuint64_t strides[1] = {(cuuint64_t)segs[i].K * 2}; + cuuint32_t box[2] = {128, 128}; + cuuint32_t estr[2] = {1, 1}; + cuTensorMapEncodeTiled(&P.in[i], CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, const_cast(segs[i].src), dims, + strides, box, estr, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, + CU_TENSOR_MAP_L2_PROMOTION_L2_256B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + cuuint64_t odims[2] = {(cuuint64_t)segs[i].K, (cuuint64_t)(segs[i].row_off + (segs[i].vrows ? segs[i].vrows : segs[i].N))}; // TMA store clips pad rows + cuuint64_t ostr[1] = {(cuuint64_t)segs[i].K}; + // ver 3 (wquant_kernel<7>): the fp8 out-buffer is in the 128B-swizzled layout + cuTensorMapEncodeTiled(&P.out[i], CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, segs[i].dst, odims, ostr, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, g_wq_ver == 3 ? CU_TENSOR_MAP_SWIZZLE_128B : CU_TENSOR_MAP_SWIZZLE_NONE, + CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); + } + if (g_wq_ver == 9) { launch_wq2<4, 4, 4>(P, total_wblocks, ctas, st); return; } + int grid = ctas; + if (grid * WQ_NG > total_wblocks) grid = (total_wblocks + WQ_NG - 1) / WQ_NG; + if (grid < 1) grid = 1; + static bool attr2 = false; + if (!attr2) { + cudaFuncSetAttribute(wquant_kernel<1>, cudaFuncAttributeMaxDynamicSharedMemorySize, WQ_SMEM); + cudaFuncSetAttribute(wquant_kernel<4>, cudaFuncAttributeMaxDynamicSharedMemorySize, WQ_SMEM); + cudaFuncSetAttribute(wquant_kernel<6>, cudaFuncAttributeMaxDynamicSharedMemorySize, WQ_SMEM); + cudaFuncSetAttribute(wquant_kernel<7>, cudaFuncAttributeMaxDynamicSharedMemorySize, WQ_SMEM); + attr2 = true; + } + switch (g_wq_ver) { + case 1: wquant_kernel<1><<>>(P); return; // QV 1 == codegen of QV 0 + case 2: wquant_kernel<4><<>>(P); return; + case 3: wquant_kernel<7><<>>(P); return; // production (no hsw swap) + case 4: wquant_kernel<6><<>>(P); return; + default: break; + } + wquant_kernel<0><<>>(P); +} + +// q_b + kv_b (or any two problems with the same Mp) as ONE persistent BN=128 launch (see kvb::launch_gq_comb). +int launch_gq_pair(const void* A0, const void* B0, const float* SFA0, const float* SFB0, void* D0, int N0, int K0, + const void* A1, const void* B1, const float* SFA1, const float* SFB1, void* D1, int N1, int K1, + int Mp, int epi, int bn, cudaStream_t st) { + static int nsm = 0; + if (nsm == 0) { + int dev; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&nsm, cudaDevAttrMultiProcessorCount, dev); + } + if (Mp % 128 || N0 % 512 || K0 % 128 || N1 % 512 || K1 % 128) return -10; + if (bn == 256) + // hint = 1: output TMA stores with L2::evict_first, so the streamed-out q/kv tiles do not evict the fp8 B weights + // still to be read by this launch (small-M CTA timeline probe: kv_b tail CTAs were waiting on B loads). + return kvb::launch_gq_comb<256>(A0, B0, SFA0, SFB0, D0, N0, K0, A1, B1, SFA1, SFB1, D1, N1, K1, Mp, nsm, epi, st, 1); + return kvb::launch_gq_comb<128>(A0, B0, SFA0, SFB0, D0, N0, K0, A1, B1, SFA1, SFB1, D1, N1, K1, Mp, nsm, epi, st); +} + +// ------------------------------------------------------------------ 9. fused A-weight quant + split-K GEMM1 (small M) +// Replaces (A-weight quant -> split-K CUTLASS GEMM1) for Mp <= 512. Grid = 17 n-blocks x G m-groups x S splits; +// CTA (nb, gi, sp) owns weight rows nb*128..+127 of [q_a|kv_a], act rows gi*256..+255 (mcnt = 1 or 2 m-tiles) +// and k-blocks [sp*56/S, (sp+1)*56/S). Per k-block: +// warp 0 (1 thread) : TMA producer -> 3-stage ring; stage = bf16 weight block 128x128 (32 KB, no swizzle, +// row r at r*256 B) + mcnt fp8 act tiles 128x128 (16 KB each, SW128, from the act quant). +// warps 4..19 (512) : (a) quantize the bf16 block in-CTA exactly like pquant_kernel (128x128 amax, scale = +// max(amax/448,1e-12), x * (1/scale), e4m3 satfinite) and write the codes into a +// SW128 K-major smem tile (2-slot ring) = the MMA B operand; (b) promote the previous k-block: +// tcgen05.ld the fresh fp32 partial, acc += partial * (sa[m,kb] * sb[kb,nb]) in registers. +// warp 1 (1 thread) : TMEM alloc (512 cols = 2 buffers x 2 m-tiles x 128) + tcgen05.mma kind::f8f6f4 +// 128x128x32 (4 per k-block per m-tile), commits free the ring stage / fp8 slot / signal. +namespace kvb { +struct FGArgs { const float* xs; float* part; int Mp, S, G, MT, NKB, NY; int late; int whint; unsigned long long Gm, Sm; }; // whint: bf16 weight TMA loads with L2::evict_first // late: PDL trigger after the partial stores // NY: used GEMM1 columns (2112) = partial row stride +constexpr int FG_NST = 3; +constexpr int FG_STAGE = 65536; // 32 KB bf16 weight block + 2 x 16 KB fp8 act tiles +constexpr int FG_WQ = 16384; // one quantized fp8 128x128 SW128 weight tile +constexpr int FG_SMEM = FG_NST * FG_STAGE + 2 * FG_WQ + 1024 + 256; +#ifdef GQ_PROBE +__device__ unsigned long long* g_fgp = nullptr; // probe: 8 u64 counters per CTA +#define FGC(v) const long long v = clock64() +#define FGA(i, val) if (g_fgp) atomicAdd(g_fgp + blockIdx.x * 8 + (i), (unsigned long long)(val)) +#else +#define FGC(v) +#define FGA(i, x) +#endif + +__global__ void __launch_bounds__(GQ_THREADS, 1) + fg1_kernel(const __grid_constant__ CUtensorMap map_wqa, const __grid_constant__ CUtensorMap map_wkva, + const __grid_constant__ CUtensorMap map_act, const __grid_constant__ FGArgs g) { + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(smem_raw) + 1023) & ~uintptr_t(1023)); + uint8_t* sWq = smem + FG_NST * FG_STAGE; + uint64_t* full = reinterpret_cast(sWq + 2 * FG_WQ); + uint64_t* empty = full + FG_NST; + uint64_t* wqf = empty + FG_NST; // fp8 weight tile written (16 worker warps) + uint64_t* wqe = wqf + 2; // fp8 weight tile consumed by the MMAs + uint64_t* tfull = wqe + 2; + uint64_t* tempty = tfull + 2; + uint32_t* tmem_slot = reinterpret_cast(tempty + 2); + __shared__ __align__(16) float red[2][16]; + + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + TLG_S(14); + const int u = blockIdx.x; + const int rem = (int)((unsigned)u / 17u), nb = u - rem * 17; + const int sp = udiv40(rem, g.Gm), gi = rem - sp * g.G; + const int m0 = gi * 256; + const int mcnt = min(2, g.MT - 2 * gi); + const int kb0 = udiv40(sp * g.NKB, g.Sm), nk = udiv40((sp + 1) * g.NKB, g.Sm) - kb0; + const int Mp = g.Mp; + + if (threadIdx.x == 0) { + for (int i = 0; i < FG_NST; ++i) { bar_init(&full[i], 1); bar_init(&empty[i], 1); } + for (int i = 0; i < 2; ++i) { + bar_init(&wqf[i], NUM_EPI_WARPS); bar_init(&wqe[i], 1); + bar_init(&tfull[i], 1); bar_init(&tempty[i], NUM_EPI_WARPS); + } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&map_wqa)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&map_wkva)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&map_act)) : "memory"); + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(su32(tmem_slot)), "r"(512)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + f_before(); + __syncthreads(); + f_after(); + const uint32_t tmem_base = *tmem_slot; + + if (warp < 4) { + asm volatile("setmaxnreg.dec.sync.aligned.u32 32;\n" ::: "memory"); + if (warp == 0 && lane == 0) { + // ---------------- TMA producer + const CUtensorMap* mw = nb < 12 ? &map_wqa : &map_wkva; + const int wrow = (nb < 12 ? nb : nb - 12) * 128; + uint64_t wpol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(wpol)); +#pragma unroll 1 + for (int i = 0; i < nk; ++i) { + const int s = ((unsigned)i % FG_NST), kb = kb0 + i; + FGC(e0); + bar_wait(&empty[s], ((((unsigned)i / FG_NST)) & 1) ^ 1); + FGC(e1); FGA(0, e1 - e0); + uint8_t* st = smem + s * FG_STAGE; + bar_expect(&full[s], 32768u + (uint32_t)mcnt * 16384u); + if (g.whint) tma_ld_hint(st, mw, &full[s], kb * BK, wrow, wpol); + else tma_ld(st, mw, &full[s], kb * BK, wrow); + for (int mt = 0; mt < mcnt; ++mt) tma_ld(st + 32768 + mt * 16384, &map_act, &full[s], kb * BK, m0 + mt * 128); + } + } else if (warp == 1 && lane == 0) { + // ---------------- MMA issuer: D[act row, weight row] (fp32, TMEM) per k-block, fresh accumulate + const uint32_t idesc = (1u << 4) | ((uint32_t)(128 >> 3) << 17) | ((uint32_t)(128 >> 4) << 24); +#pragma unroll 1 + for (int i = 0; i < nk; ++i) { + const int s = ((unsigned)i % FG_NST), b = i & 1; + bar_wait(&tempty[b], ((i >> 1) & 1) ^ 1); // promotion drained this TMEM buffer + bar_wait(&wqf[b], (i >> 1) & 1); // quantized weight tile ready + bar_wait(&full[s], (((unsigned)i / FG_NST)) & 1); // act tiles landed + f_after(); + const uint64_t bd = sdesc(su32(sWq + b * FG_WQ)); + for (int mt = 0; mt < mcnt; ++mt) { + const uint64_t ad = sdesc(su32(smem + s * FG_STAGE + 32768 + mt * 16384)); + const uint32_t td = tmem_base + b * 256 + mt * 128; +#pragma unroll + for (int k = 0; k < BK / 32; ++k) mma(td, ad + 2 * k, bd + 2 * k, idesc, k > 0 ? 1u : 0u); + } + commit(&empty[s]); + commit(&wqe[b]); + commit(&tfull[b]); + } + } + } else { + asm volatile("setmaxnreg.inc.sync.aligned.u32 112;\n" ::: "memory"); + // ---------------- 16 worker warps: in-CTA weight quant (k-block i) + promotion (k-block i-1) + const int wt = threadIdx.x - 128, ww = warp - 4; + const int r0 = wt >> 3, sub = wt & 7, hsw = (sub >> 2) & 1; + const int q = warp & 3, cg = (warp - 4) >> 2; // TMEM lane quadrant, 32-column group + const int rowA = m0 + q * 32 + lane; // act row (m-tile 0); m-tile 1 = +128 + float2 acc2[32]; // column pairs -> packed FFMA2 +#pragma unroll + for (int j = 0; j < 32; ++j) acc2[j] = make_float2(0.f, 0.f); + FGC(w0); +#ifdef GQ_PROBE + long long wf = 0, we = 0, wt2 = 0, wqt = 0, wpp = 0; +#define FGW(acc, a, b) acc += (b) - (a) +#else +#define FGW(acc, a, b) +#endif + // ping-pong act-scale registers (set p = k-block parity): the __ldg for k-block i completes while k-block i + // is quantized and is consumed only by its promotion one step later (no register move forcing the wait). + float sa00 = 0.f, sa01 = 0.f, sa10 = 0.f, sa11 = 0.f, sb0 = 0.f, sb1 = 0.f; + const uint32_t tm_warp = tmem_base + ((uint32_t)(q * 32) << 16) + cg * 32; + // promotion of k-block j (TMEM buffer b): acc += partial * (sa * sb) + auto promote = [&](int j, float sa0, float sa1, float sb) { + const int b = j & 1; + FGC(t0); + bar_wait(&tfull[b], (j >> 1) & 1); + FGC(t1); FGW(wt2, t0, t1); + f_after(); +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { + if (mt < mcnt) { + uint32_t r[32]; + const uint32_t ta = tm_warp + b * 256 + mt * 128; + KVB_TMEM_LD16(ta, r); + KVB_TMEM_LD16(ta + 16, (r + 16)); + asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); + const float scl = (mt ? sa1 : sa0) * sb; + const float2 sc2 = make_float2(scl, scl); +#pragma unroll + for (int c = 0; c < 16; ++c) + acc2[mt * 16 + c] = __ffma2_rn(make_float2(__uint_as_float(r[2 * c]), __uint_as_float(r[2 * c + 1])), sc2, acc2[mt * 16 + c]); + } + } + f_before(); + __syncwarp(); + if (lane == 0) bar_arrive_a(su32(&tempty[b])); + FGC(t2); FGW(wpp, t1, t2); + }; + // One pipeline step i: (1) amax of k-block i, (2) promotion of k-block i-2 inside the barrier slack (lag 2 + // keeps the MMA latency off the critical path), (3) CTA-wide amax via the named barrier, (4) re-read the bf16 + // block from smem and quantize it into fp8 slot i&1. + auto step = [&](auto PARc, int i) { + constexpr int PAR = decltype(PARc)::value; + // Scale set PAR holds k-block i-2 (loaded two steps ago, so the copies below do not wait) and is then + // refilled for k-block i. + float& saQ0 = PAR ? sa10 : sa00; + float& saQ1 = PAR ? sa11 : sa01; + float& sbQ = PAR ? sb1 : sb0; + const float saP0 = saQ0, saP1 = saQ1, sbP = sbQ; // k-block i-2 + if (i < nk) { + const int kb = kb0 + i, s = ((unsigned)i % FG_NST), w = PAR; + saQ0 = ldcg_f32v(g.xs + (size_t)kb * Mp + rowA); + if (mcnt > 1) saQ1 = ldcg_f32v(g.xs + (size_t)kb * Mp + rowA + 128); + FGC(f0); + bar_wait(&full[s], (((unsigned)i / FG_NST)) & 1); + FGC(f1); FGW(wf, f0, f1); + const uint8_t* st = smem + s * FG_STAGE + r0 * 256 + sub * 32; // row r0 (+64), 32 B = 16 bf16 + { + uint4 va[2], vb[2]; +#pragma unroll + for (int q2 = 0; q2 < 2; ++q2) { // bank-conflict-free: lanes with sub >= 4 read their high half first + va[q2] = *reinterpret_cast(st + q2 * 16384 + hsw * 16); + vb[q2] = *reinterpret_cast(st + q2 * 16384 + (hsw ^ 1) * 16); + } + uint32_t a2 = 0u; +#pragma unroll + for (int q2 = 0; q2 < 2; ++q2) a2 = amax16(va[q2], vb[q2], a2); + // amax >= 0 and never NaN (max.bf16x2 drops NaN) -> fp32 bit patterns order like u32 + uint32_t am = __float_as_uint(bf2max_to_f(a2)); + asm volatile("redux.sync.max.u32 %0, %0, 0xffffffff;" : "+r"(am)); + if (lane == 0) red[PAR][ww] = __uint_as_float(am); // double-buffered across k-blocks + } + if (i >= 2) promote(i - 2, saP0, saP1, sbP); + asm volatile("bar.sync 1, 512;" ::: "memory"); // 16 worker warps + const float4* rv = reinterpret_cast(red[PAR]); + float amax = 0.f; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float4 t = rv[j]; + amax = fmaxf(amax, fmaxf(fmaxf(t.x, t.y), fmaxf(t.z, t.w))); + } + const float sc = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float inv = 1.0f / sc; + FGC(q0); + bar_wait(&wqe[w], ((i >> 1) & 1) ^ 1); // MMAs of k-block i-2 done with this slot + FGC(q1); FGW(we, q0, q1); FGW(wqt, f1, q0); + uint8_t* wqs = sWq + w * FG_WQ; +#pragma unroll + for (int q2 = 0; q2 < 2; ++q2) { + const uint4 va = *reinterpret_cast(st + q2 * 16384 + hsw * 16); + const uint4 vb = *reinterpret_cast(st + q2 * 16384 + (hsw ^ 1) * 16); + const int r = r0 + 64 * q2; + const uint4 qv = quant16_fast(va, vb, inv, hsw); // same quant as pquant (current small-M path) + // SW128 K-major: 8-row groups 1024 B apart, row 128 B, 16-B chunk j stored at j ^ (r & 7) + *reinterpret_cast(wqs + (r >> 3) * 1024 + (r & 7) * 128 + ((sub ^ (r & 7)) << 4)) = qv; + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + if (lane == 0) bar_arrive_a(su32(&wqf[w])); + sbQ = sc; + } else if (i >= 2 && i <= nk + 1) { + promote(i - 2, saP0, saP1, sbP); // drain the last two k-blocks + } + }; +#pragma unroll 1 + for (int i = 0; i <= nk + 1; i += 2) { + step(std::integral_constant{}, i); + step(std::integral_constant{}, i + 1); + } + FGC(w1); + #ifdef GQ_PROBE + if (threadIdx.x == 128) { FGA(1, w1 - w0); FGA(2, wf); FGA(3, we); FGA(4, wt2); FGA(5, wqt); FGA(6, nk); FGA(7, wpp); } +#endif + // fp32 split-K partial: part[sp][m][n], 32 contiguous columns per thread per m-tile + // columns >= NY (kv_a padding outputs 576..639) are never stored (warp-uniform skip) + float* pbase = g.part + (size_t)sp * Mp * g.NY + nb * 128 + cg * 32; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { + if (mt < mcnt && nb * 128 + cg * 32 < g.NY) { + float4* dst = reinterpret_cast(pbase + (size_t)(rowA + mt * 128) * g.NY); +#pragma unroll + for (int v = 0; v < 8; ++v) + dst[v] = make_float4(acc2[mt * 16 + 2 * v].x, acc2[mt * 16 + 2 * v].y, acc2[mt * 16 + 2 * v + 1].x, acc2[mt * 16 + 2 * v + 1].y); + } + } + } + + f_before(); + __syncthreads(); + TLG_E(14); + if (warp == 1) { + f_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tmem_base), "r"(512)); + } +} + +// ------------------------------------------------------------------ 9b. fg2_kernel: decoupled quant front end +// Same job as fg1_kernel (CTA (nb, gi, sp): weight rows nb*128..+127 of [q_a|kv_a], act rows gi*256..+255, k-blocks +// [kb0, kb0+nk)), same math (bit-identical partials), but the in-CTA weight quant is rebuilt on the wquant design so +// quantization of k-blocks k+1..k+A overlaps the MMA / promotion of k-block k (no CTA-wide lockstep barrier): +// warp 0 (1 thread) : TMA producer of the bf16 weight ring (4 x 32 KB 128x128 boxes, row r at r*256 B; stage g +// belongs to quant group g). +// warp 2 (1 thread) : TMA producer of the fp8 act ring (NA slots x MC 128x128 SW128 tiles). +// warp 1 (1 thread) : TMEM alloc (512 cols = NT buffers x MC m-tiles x 128) + tcgen05.mma kind::f8f6f4 128x128x32; +// per k-block commits free the act slot, the fp8 weight tile and signal tfull. +// warps 4..19 : 4 groups x 4 warps. Group g quantizes the k-blocks j with j % 4 == g (128 threads per 32 KB +// block, 8 passes of 16 rows): conflict-free 16 B smem reads, bf16x2 amax, warp redux, one +// 128-thread named barrier (group only), scale -> smem scale ring (mbarrier scf), then e4m3 +// codes written straight into a SW128 K-major fp8 tile (NQ-slot ring, wqf/wqeG mbarriers) = MMA +// B operand; bf16 stage released (wempty). ALL 16 warps promote every k-block (lag D = 2): +// tcgen05.ld the fresh fp32 partial, acc += partial * (sa[m,kb] * sb[kb]) in registers. +// Per warp, step i = promote(i-2) then (its turn) quant(i+A); A <= NQ + NT - 2 keeps every dependency of a warp's +// work on its own earlier steps (deadlock free). Partials stored exactly like fg1_kernel. +// SR = 1 (production): the activation scales of k-block j (xs[kb*Mp + m0 .. +MC*128), written by the act quant) are +// bulk-copied by the act producer into an 8-slot smem scale ring on the act slot's afull barrier (the MMA waits afull +// before tfull, the promotion reads them after tfull) instead of one volatile ld.global.cg per k-block per worker +// thread: role clocks (M=128, 68 CTAs x 14 k-blocks) showed that load path stalling each worker warp ~600 clk per step +//. NA drops 3 -> 2 to make room. Slot j & 7 is +// refilled for k-block j only after aempty of MMA(j - NA), which required tempty, i.e. every warp's promote(j - NA - +// NT) (and its scale read) done; NSS >= NA + NT. Same scale values / math: bit-identical partials. +template struct FG2Cfg { + // Every mbarrier must have, per phase, waiters that observe ALL its phases in order (a parity wait cannot tell + // phase k from k-2): bf16 stage s is therefore owned by quant group s (NWS == 4), and the "fp8 tile free" signal is + // a per-group barrier wqeG[j % 4] (MMA(j) commits there; quant(j+NQ), always group (j+NQ) % 4, waits on it). + static constexpr int NWS = 4; // bf16 weight stages (32 KB), stage g <-> quant group g + static constexpr int NQ = MC == 2 ? 2 : 3; // fp8 SW128 weight tiles (16 KB) + static constexpr int NA = (MC == 2 || SR) ? 2 : 3; // act slots (MC x 16 KB) + static constexpr int NT = MC == 2 ? 2 : 4; // TMEM buffers of MC*128 columns + static constexpr int A = MC == 2 ? 2 : 3; // quant lookahead (steps) + static constexpr int D = 2; // promotion lag (== ping-pong period of the act-scale registers) + static constexpr int NSB = 16; // weight-scale ring + static constexpr int ASZ = MC * 16384; + static constexpr int OFF_Q = NWS * 32768; + static constexpr int OFF_A = OFF_Q + NQ * 16384; + static constexpr int NSS = SR ? 8 : 0; // act-scale ring slots (SR) + static constexpr int SSZ = MC * 512; // bytes per scale slot + static constexpr int OFF_S = OFF_A + NA * ASZ; + static constexpr int OFF_B = OFF_S + NSS * SSZ; + static_assert(!SR || (NSS >= NA + NT && (NSS & (NSS - 1)) == 0), "scale ring reuse must be implied by aempty"); + static constexpr int NBAR = 2 * NWS + NQ + 4 + 2 * NA + 2 * NT + NSB; + static_assert(NWS == 4, "bf16 stage must be owned by one quant group"); + static_assert(OFF_B <= 229376, "smem"); + static constexpr int SMEM = OFF_B + 8 * NBAR + 4 * NSB + 16 + 1024; + static_assert(A <= NQ + NT - D, "quant lookahead would make a warp wait on its own future work"); + static_assert(D == 2, "act-scale ping-pong assumes lag 2"); + static_assert(NT * MC * 128 <= 512, "TMEM"); +}; + +#ifdef FG_ROLE +__device__ unsigned long long* g_fgr = nullptr; // probe: role clocks (sum over CTAs) +#define FRT(v) const long long v = clock64() +#define FRD(acc, a, b) acc += (b) - (a) +#define FRF(i, acc) if (g_fgr) atomicAdd(g_fgr + (i), (unsigned long long)(acc)) +#define FRDECL(...) long long __VA_ARGS__ +#else +#define FRT(v) +#define FRD(acc, a, b) +#define FRF(i, acc) +#define FRDECL(...) +#endif +template +__global__ void __launch_bounds__(GQ_THREADS, 1) + fg2_kernel(const __grid_constant__ CUtensorMap map_wqa, const __grid_constant__ CUtensorMap map_wkva, + const __grid_constant__ CUtensorMap map_act, const __grid_constant__ FGArgs g) { + using C = FG2Cfg; + constexpr int NWS = C::NWS, NQ = C::NQ, NA = C::NA, NT = C::NT, NSB = C::NSB; + uint8_t* sS; // act-scale ring (SR) + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(smem_raw) + 1023) & ~uintptr_t(1023)); + uint8_t* sW = smem; + uint8_t* sQ = smem + C::OFF_Q; + uint8_t* sA = smem + C::OFF_A; + sS = smem + C::OFF_S; + uint64_t* wfull = reinterpret_cast(smem + C::OFF_B); + uint64_t* wempty = wfull + NWS; + uint64_t* wqf = wempty + NWS; // fp8 tile written (4 warps of the quant group) + uint64_t* wqeG = wqf + NQ; // [4]: MMAs of k-block j (j % 4 == index) retired -> its fp8 tile is free + uint64_t* afull = wqeG + 4; + uint64_t* aempty = afull + NA; + uint64_t* tfull = aempty + NA; + uint64_t* tempty = tfull + NT; + uint64_t* scf = tempty + NT; // weight scale of k-block j landed in sbv[j % NSB] + float* sbv = reinterpret_cast(scf + NSB); + uint32_t* tmem_slot = reinterpret_cast(sbv + NSB); + __shared__ float red[4][2][4]; // per group, double-buffered warp amaxes + + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + TLG_S(14); + FRT(fr_k0); + const int u = blockIdx.x; + const int rem = (int)((unsigned)u / 17u), nb = u - rem * 17; + const int sp = udiv40(rem, g.Gm), gi = rem - sp * g.G; + const int m0 = gi * 256; + const int mcnt = min(MC, g.MT - 2 * gi); + const int kb0 = udiv40(sp * g.NKB, g.Sm), nk = udiv40((sp + 1) * g.NKB, g.Sm) - kb0; + const int Mp = g.Mp; + + if (threadIdx.x == 0) { + for (int i = 0; i < NWS; ++i) { bar_init(&wfull[i], 1); bar_init(&wempty[i], 4); } + for (int i = 0; i < NQ; ++i) bar_init(&wqf[i], 4); + for (int i = 0; i < 4; ++i) bar_init(&wqeG[i], 1); + for (int i = 0; i < NA; ++i) { bar_init(&afull[i], 1); bar_init(&aempty[i], 1); } + for (int i = 0; i < NT; ++i) { bar_init(&tfull[i], 1); bar_init(&tempty[i], NUM_EPI_WARPS); } + for (int i = 0; i < NSB; ++i) bar_init(&scf[i], 1); + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&map_wqa)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&map_wkva)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&map_act)) : "memory"); + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(su32(tmem_slot)), "r"(512)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + f_before(); + __syncthreads(); + f_after(); + // tmem_base is re-read from tmem_slot inside each role (register diet: a value live across the setmaxnreg + // role split was spilled to local memory, ptxas 4 B store / 12-24 B loads) + FRT(fr_k1); + if (threadIdx.x == 0) { FRF(0, fr_k1 - fr_k0); FRF(1, 1); } + + // PDL: the split-K norm may be scheduled now (it griddepcontrol.wait's for our completion before reading partials). + // late: only after the final partial stores (end of kernel). + if (!g.late) PDL_TRIGGER(); + + if (warp < 4) { + asm volatile("setmaxnreg.dec.sync.aligned.u32 32;\n" ::: "memory"); + const uint32_t tmem_base = ld_tmem_slot(tmem_slot); // re-read per role: not live across the setmaxnreg split + if (warp == 0 || warp == 2) { + // Producer diet (port of the gq producer diet): the WHOLE warp walks the k-block loop (warp-uniform ring + // position / phase as running counters, barrier addresses base + 8 * index), all lanes wait on the empty + // barrier, and ONE lane (elected once) issues the expect_tx + all TMA ops of the k-block in a single region. + // Same loads / barriers / bytes / order as the single-lane form: bit-identical. + uint32_t el; + asm volatile("{\n.reg .pred P;\nelect.sync _|P, 0xffffffff;\nselp.u32 %0, 1, 0, P;\n}" : "=r"(el)); + if (warp == 0) { + // ---------------- bf16 weight ring producer (stage freed by the quant group after its last smem read) + const CUtensorMap* mw = nb < 12 ? &map_wqa : &map_wkva; + const int wrow = (nb < 12 ? nb : nb - 12) * 128; + uint64_t wpol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(wpol)); + const uint32_t a_wempty = su32(wempty); + int s = 0; uint32_t ps = 0; int kx = kb0 * BK; + FRDECL(fr_pw = 0); + FRT(fr_p0); +#pragma unroll 1 + for (int j = 0; j < nk; ++j, kx += BK) { + FRT(fr_a); + bar_wait_a(a_wempty + 8 * s, ps ^ 1); + FRT(fr_b); FRD(fr_pw, fr_a, fr_b); + if (el) { + bar_expect(&wfull[s], 32768u); + if (g.whint) tma_ld_hint(sW + s * 32768, mw, &wfull[s], kx, wrow, wpol); + else tma_ld(sW + s * 32768, mw, &wfull[s], kx, wrow); + } + // (no per-k-block __syncwarp: per-lane mbarrier waits; the elected lane issues non-.aligned TMA/MMA/commit) + if (++s == NWS) { s = 0; ps ^= 1u; } + } + FRT(fr_p1); + if (lane == 0) { FRF(2, fr_pw); FRF(3, fr_p1 - fr_p0); FRF(4, fr_p1 - fr_k0); } + } else { + // ---------------- fp8 act ring producer (slot freed by the MMA commit) + // PDL: the activation quant (previous launch) must have completed before its fp8 tiles are read. + FRT(fr_g0); + asm volatile("griddepcontrol.wait;" ::: "memory"); + FRT(fr_g1); + if (lane == 0) { FRF(5, fr_g1 - fr_g0); FRF(6, fr_g1 - fr_k0); } + const uint32_t a_aempty = su32(aempty); + int a = 0; uint32_t pa = 0; int kx = kb0 * BK; +#pragma unroll 1 + for (int j = 0; j < nk; ++j, kx += BK) { + bar_wait_a(a_aempty + 8 * a, pa ^ 1); + if (el) { + bar_expect(&afull[a], (uint32_t)mcnt * (16384u + (SR ? 512u : 0u))); + for (int mt = 0; mt < mcnt; ++mt) + tma_ld(sA + a * C::ASZ + mt * 16384, &map_act, &afull[a], kx, m0 + mt * 128); + if (SR) // this k-block's activation scales (rows m0 .. m0 + mcnt*128) -> scale slot j & (NSS-1) + bulk_ld(sS + (j & (C::NSS - 1)) * C::SSZ, g.xs + (size_t)(kb0 + j) * Mp + m0, (uint32_t)mcnt * 512u, &afull[a]); + } + // (no per-k-block __syncwarp: per-lane mbarrier waits; the elected lane issues non-.aligned TMA/MMA/commit) + if (++a == NA) { a = 0; pa ^= 1u; } + } + } + } else if (warp == 1) { + // ---------------- MMA issuer: D[act row, weight row] per k-block, fresh accumulate into TMEM buffer j % NT + // Instruction diet (same MMAs / commits / order as the per-k-block modulo form): whole warp waits, ONE lane + // (elected once) issues; ring positions a / b / qs and their phases are running counters, barrier addresses are + // base + 8 * index, descriptors are base + running offsets (sdesc is linear in the smem address). + const uint32_t idesc = (1u << 4) | ((uint32_t)(128 >> 3) << 17) | ((uint32_t)(128 >> 4) << 24); + uint32_t el; + asm volatile("{\n.reg .pred P;\nelect.sync _|P, 0xffffffff;\nselp.u32 %0, 1, 0, P;\n}" : "=r"(el)); + const uint32_t a_tempty = su32(tempty), a_wqf = su32(wqf), a_afull = su32(afull); + const uint64_t ad0 = sdesc(su32(sA)), bd0 = sdesc(su32(sQ)); + constexpr uint64_t ADST = (uint64_t)(C::ASZ >> 4), BDST = (uint64_t)(16384 >> 4); + int a = 0, b = 0, qs = 0; + uint32_t pa = 0, pb = 0, pq = 0; + uint64_t aoff = 0, boff = 0; + FRDECL(fr_mt = 0, fr_mq = 0, fr_ma = 0); + FRT(fr_m0); +#pragma unroll 1 + for (int j = 0; j < nk; ++j) { + FRT(fr_a); + bar_wait_a(a_tempty + 8 * b, pb ^ 1); // promotion drained this TMEM buffer + FRT(fr_b); + bar_wait_a(a_wqf + 8 * qs, pq); // quantized weight tile ready + FRT(fr_c); + bar_wait_a(a_afull + 8 * a, pa); // act tiles landed + FRT(fr_d); FRD(fr_mt, fr_a, fr_b); FRD(fr_mq, fr_b, fr_c); FRD(fr_ma, fr_c, fr_d); + f_after(); + if (el) { + const uint64_t bd = bd0 + boff; + for (int mt = 0; mt < mcnt; ++mt) { + const uint64_t ad = ad0 + aoff + (uint64_t)mt * (16384 >> 4); + const uint32_t td = tmem_base + b * (128 * MC) + mt * 128; +#pragma unroll + for (int k = 0; k < BK / 32; ++k) mma(td, ad + 2 * k, bd + 2 * k, idesc, k > 0 ? 1u : 0u); + } + commit(&aempty[a]); + commit(&wqeG[j & 3]); + commit(&tfull[b]); + } + // (no per-k-block __syncwarp: per-lane mbarrier waits; the elected lane issues non-.aligned TMA/MMA/commit) + if (++a == NA) { a = 0; pa ^= 1u; aoff = 0; } else aoff += ADST; + if (++b == NT) { b = 0; pb ^= 1u; } + if (++qs == NQ) { qs = 0; pq ^= 1u; boff = 0; } else boff += BDST; + } + FRT(fr_m1); + if (lane == 0) { FRF(7, fr_mt); FRF(8, fr_mq); FRF(9, fr_ma); FRF(10, fr_m1 - fr_m0); FRF(11, fr_m1 - fr_k0); } + } + } else { + asm volatile("setmaxnreg.inc.sync.aligned.u32 112;\n" ::: "memory"); + const uint32_t tmem_base = ld_tmem_slot(tmem_slot); // re-read per role: not live across the setmaxnreg split + const int wt = threadIdx.x - 128; + const int grp = wt >> 7; // quant group == promotion column group + const int gt = wt & 127, gw = warp & 3; + const int r0 = gt >> 3, sub = gt & 7, hsw = (sub >> 2) & 1; + const int q = warp & 3, cg = grp; // TMEM lane quadrant, 32-column group + const int rowA = m0 + q * 32 + lane; // act row (m-tile 0); m-tile 1 = +128 + float2 acc2[16 * MC]; +#pragma unroll + for (int j = 0; j < 16 * MC; ++j) acc2[j] = make_float2(0.f, 0.f); + const uint32_t tm_warp = tmem_base + ((uint32_t)(q * 32) << 16) + cg * 32; + const float* xs = g.xs; + FRDECL(fr_ws = 0, fr_wt = 0, fr_wp = 0, fr_wf = 0, fr_we = 0, fr_wq = 0, fr_wg = 0, fr_wf0 = 0, fr_wl = 0, fr_wst = 0, fr_wqa = 0); + + auto promote = [&](int j, float sa0, float sa1) { + FRT(fr_a); + const int b = ((unsigned)j % NT); + bar_wait_f<1>(su32(&scf[((unsigned)j % NSB)]), (((unsigned)j / NSB)) & 1); // un-hinted: worker wake-up on the per-k-block critical path + FRT(fr_b); + const float sb = sbv[((unsigned)j % NSB)]; + bar_wait_f<1>(su32(&tfull[b]), (((unsigned)j / NT)) & 1); // un-hinted: worker wake-up on the per-k-block critical path + FRT(fr_c); FRD(fr_ws, fr_a, fr_b); FRD(fr_wt, fr_b, fr_c); + f_after(); + // Latency reorder (bit-identical): the act-scale ld.shared (SR) is issued right AFTER the first tcgen05.ld so its + // latency overlaps the TMEM load round trip, and the TMEM buffer is handed back (tempty) right after the last + // wait::ld, before the FFMA2 accumulate, so the MMA of k-block j + NT can start earlier. Same values / order. + const uint32_t sa_ad = su32(sS) + (uint32_t)((j & (C::NSS - 1)) * C::SSZ) + (uint32_t)(q * 32 + lane) * 4u; +#pragma unroll + for (int mt = 0; mt < MC; ++mt) { + if (mt < mcnt) { + uint32_t r[32]; + KVB_TMEM_LD32(tm_warp + b * (128 * MC) + mt * 128, r); + if (SR && mt == 0) { // scales landed with k-block j's act tiles (afull, waited by the MMA before tfull) + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(sa0) : "r"(sa_ad) : "memory"); + if (MC > 1 && mcnt > 1) asm volatile("ld.shared.f32 %0, [%1];" : "=f"(sa1) : "r"(sa_ad + 512u) : "memory"); + } + asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); + if (mt == mcnt - 1) { // all TMEM reads of this buffer done -> release it to the MMA + f_before(); + __syncwarp(); + if (lane == 0) bar_arrive_a(su32(&tempty[b])); + } + const float scl = (mt ? sa1 : sa0) * sb; + const float2 sc2 = make_float2(scl, scl); +#pragma unroll + for (int c = 0; c < 16; ++c) + acc2[mt * 16 + c] = __ffma2_rn(make_float2(__uint_as_float(r[2 * c]), __uint_as_float(r[2 * c + 1])), sc2, acc2[mt * 16 + c]); + } + } + FRT(fr_e); FRD(fr_wp, fr_c, fr_e); + }; + // Address diet (loop-invariant per thread): bf16 read offsets (row r0, 32-B chunk sub, conflict-free half order) + // and the SW128 fp8 write offset of row r0; pass p adds p*4096 (read) / p*2048 (write: r0+16p -> 8-row group + // (r0>>3)+2p, r&7 unchanged). Same addresses as the per-pass formula, so bit-identical. + const uint32_t q_rlo = (uint32_t)(r0 * 256 + sub * 32 + hsw * 16), q_rhi = q_rlo ^ 16u; + const uint32_t q_wo = (uint32_t)((r0 >> 3) * 1024 + (r0 & 7) * 128 + ((sub ^ (r0 & 7)) << 4)); + auto quant = [&](int j) { + FRT(fr_a); + const int s = ((unsigned)j % NWS); + bar_wait_f<1>(su32(&wfull[s]), (((unsigned)j / NWS)) & 1); // un-hinted: worker wake-up on the per-k-block critical path + FRT(fr_b); FRD(fr_wf, fr_a, fr_b); + if (j < 4) FRD(fr_wf0, fr_a, fr_b); + const uint8_t* stl = sW + s * 32768 + q_rlo; // row r0 + 16p: first-read 16-B half + const uint8_t* sth = sW + s * 32768 + q_rhi; // second-read 16-B half + uint32_t a0 = 0u, a1 = 0u; +#pragma unroll + for (int p = 0; p < 8; p += 2) { // bank-conflict-free: lanes with sub >= 4 read their high half first + const uint4 va = *reinterpret_cast(stl + p * 4096); + const uint4 vb = *reinterpret_cast(sth + p * 4096); + const uint4 vc = *reinterpret_cast(stl + (p + 1) * 4096); + const uint4 vd = *reinterpret_cast(sth + (p + 1) * 4096); + a0 = amax16(va, vb, a0); + a1 = amax16(vc, vd, a1); + } + asm("max.bf16x2 %0, %0, %1;" : "+r"(a0) : "r"(a1)); + // amax >= 0 and never NaN (max.bf16x2 drops NaN) -> fp32 bit patterns order like u32 + uint32_t am = __float_as_uint(bf2max_to_f(a0)); + asm volatile("redux.sync.max.u32 %0, %0, 0xffffffff;" : "+r"(am)); + const int par = (j >> 2) & 1; + if (lane == 0) red[grp][par][gw] = __uint_as_float(am); + asm volatile("bar.sync %0, 128;" ::"r"(1 + grp) : "memory"); // quant group only + const float amax = fmaxf(fmaxf(red[grp][par][0], red[grp][par][1]), fmaxf(red[grp][par][2], red[grp][par][3])); + const float sc = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float inv = 1.0f / sc; + if (gt == 0) { sbv[((unsigned)j % NSB)] = sc; bar_arrive_a(su32(&scf[((unsigned)j % NSB)])); } + const int qs = ((unsigned)j % NQ); + FRT(fr_c); + if (j >= NQ) { // MMAs of k-block j-NQ done with this tile + const int jp = j - NQ; + bar_wait_f<1>(su32(&wqeG[jp & 3]), (jp >> 2) & 1); // un-hinted: worker wake-up on the per-k-block critical path + } + FRT(fr_d); FRD(fr_we, fr_c, fr_d); + uint8_t* wqs = sQ + qs * 16384; +#pragma unroll + for (int p = 0; p < 8; ++p) { + const uint4 va = *reinterpret_cast(stl + p * 4096); + const uint4 vb = *reinterpret_cast(sth + p * 4096); + const uint4 qv = quant16_fast(va, vb, inv, hsw); // same quant as pquant / fg1 + // SW128 K-major: 8-row groups 1024 B apart, row 128 B, 16-B chunk j stored at j ^ (r & 7) (r = r0 + 16p) + *reinterpret_cast(wqs + q_wo + p * 2048) = qv; + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + if (lane == 0) { bar_arrive_a(su32(&wqf[qs])); bar_arrive_a(su32(&wempty[s])); } + FRT(fr_e); FRD(fr_wq, fr_b, fr_c); FRD(fr_wq, fr_d, fr_e); + }; + // act-scale ping-pong registers: loaded for k-block i at step i, consumed by promote(i) at step i + 2 + float saA0 = 0.f, saA1 = 0.f, saB0 = 0.f, saB1 = 0.f; + auto step = [&](auto PARc, int i) { + constexpr int PAR = decltype(PARc)::value; + float& s0 = PAR ? saB0 : saA0; + float& s1 = PAR ? saB1 : saA1; + FRT(fr_s0); + const int j = i - C::D; + // PDL: act scales xs come from the previous (activation quant) launch; the weight quants of steps < 0 overlap it. + if (i == 0) { FRT(fr_a); asm volatile("griddepcontrol.wait;" ::: "memory"); FRT(fr_b); FRD(fr_wg, fr_a, fr_b); } + if (j >= 0 && j < nk) promote(j, s0, s1); + FRT(fr_l0); + if (!SR && i >= 0 && i < nk) { + s0 = ldcg_f32v(xs + (size_t)(kb0 + i) * Mp + rowA); + if (mcnt > 1) s1 = ldcg_f32v(xs + (size_t)(kb0 + i) * Mp + rowA + 128); + } + FRT(fr_l1); FRD(fr_wl, fr_l0, fr_l1); + const int jq = i + C::A; + if (jq >= 0 && jq < nk && (jq & 3) == grp) { quant(jq); FRT(fr_l2); FRD(fr_wqa, fr_l1, fr_l2); } + FRT(fr_l3); FRD(fr_wst, fr_s0, fr_l3); + }; + FRT(fr_w0); +#pragma unroll 1 + for (int i = -C::A; i < nk + C::D; i += 2) { + step(std::integral_constant{}, i); + step(std::integral_constant{}, i + 1); + } + FRT(fr_w1); + if (lane == 0) { FRF(12, fr_ws); FRF(13, fr_wt); FRF(14, fr_wp); FRF(15, fr_wf); FRF(16, fr_we); FRF(17, fr_wq); + FRF(18, fr_wg); FRF(19, fr_w1 - fr_w0); FRF(20, fr_w1 - fr_k0); FRF(21, fr_wf0); FRF(24, fr_wl); FRF(25, fr_wst); FRF(26, fr_wqa); } + // fp32 split-K partial: part[sp][m][n], 32 contiguous columns per thread per m-tile + // columns >= NY (kv_a padding outputs 576..639) are never stored (warp-uniform skip) + float* pbase = g.part + (size_t)sp * Mp * g.NY + nb * 128 + cg * 32; +#pragma unroll + for (int mt = 0; mt < MC; ++mt) { + if (mt < mcnt && nb * 128 + cg * 32 < g.NY) { + // 256-bit stores (4 x st.global.v8 instead of 8 x v4; 32-B aligned: NY*4, col*4 are multiples of 32) with an + // L2 evict_last policy: the split-K norm re-reads these partials right after this grid. Same bytes: bit-identical. + float* dst = pbase + (size_t)(rowA + mt * 128) * g.NY; + uint64_t ppol; + asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(ppol)); +#pragma unroll + for (int v = 0; v < 4; ++v) { + const float2 a0 = acc2[mt * 16 + 4 * v], a1 = acc2[mt * 16 + 4 * v + 1]; + const float2 a2 = acc2[mt * 16 + 4 * v + 2], a3 = acc2[mt * 16 + 4 * v + 3]; + asm volatile("st.global.L2::cache_hint.v8.b32 [%0], {%1,%2,%3,%4,%5,%6,%7,%8}, %9;" + ::"l"(dst + 8 * v), "r"(__float_as_uint(a0.x)), "r"(__float_as_uint(a0.y)), "r"(__float_as_uint(a1.x)), + "r"(__float_as_uint(a1.y)), "r"(__float_as_uint(a2.x)), "r"(__float_as_uint(a2.y)), + "r"(__float_as_uint(a3.x)), "r"(__float_as_uint(a3.y)), "l"(ppol) : "memory"); + } + } + } + } + + f_before(); + __syncthreads(); + TLG_E(14); + { FRT(fr_k2); if (threadIdx.x == 0) { FRF(22, fr_k2 - fr_k0); FRF(23, nk); } } + if (g.late) PDL_TRIGGER(); // late: all partial stores of this CTA issued + if (warp == 1) { + f_after(); + const uint32_t tmem_base = ld_tmem_slot(tmem_slot); // re-read per role: not live across the setmaxnreg split + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tmem_base), "r"(512)); + } +} + +// ------------------------------------------------------------------ 9c. fq_kernel: quantize-on-load q_b GEMM (small M) +// D[Mp, N] (bf16) = A[Mp, K](fp8, 1x128 scales sa[kb*Mp + m]) x quant128x128(W[N, K] bf16)^T. The bf16 q_b weight is +// NOT pre-quantized: each 128x128 bf16 block is TMA-loaded into a 4-stage bf16 ring and quantized in-CTA with the exact +// wquant<7> math (|max| over the block, scale = max(amax*(1/448), 1e-12), q = x * __fdividef(1, scale) RN e4m3x2 +// satfinite) straight into a SW128 K-major fp8 B tile; the scale goes to a smem scale slot. Same fp8 codes / scales as +// the side-stream wquant -> the MMA / promotion below are those of the gq kernel: bit-identical outputs. +// Persistent: unit u = (m-block, 128-row weight n-block), n fastest; CTA c walks u = c, c+G, ... (every unit has the +// same nkb = K/128 k-blocks; the CTA's k-block iterations form one flat sequence j). +// warp 0 (elect lane) : bf16 weight ring producer (stage j % 4 owned by quant group j % 4). Weights do not depend on +// the PDL predecessor, so this runs (and the quant groups quantize) before griddepcontrol.wait. +// warp 2 (elect lane) : griddepcontrol.wait, then fp8 act ring (2 slots: 128x128 SW128 tile + the 512 B of act scales). +// warp 1 (elect lane) : TMEM alloc (4 x 128 columns) + tcgen05.mma kind::f8f6f4 128x128x32 (4 per k-block, fresh +// accumulate per k-block); commits free the act slot, the fp8 B tile and signal tfull. +// warps 4..19 : 4 quant groups x 4 warps (group g quantizes k-blocks j % 4 == g, fg2 ring protocol) and ALL 16 +// promote every k-block (lag 2): acc = partial * (sa*sb) (first k-block) / FFMA2 accumulate, then +// at a unit's last k-block the bf16 row segment (32 cols = 64 B per thread) is stored to D. +struct FQArgs { int Mp, N, nkb, nblk, units; unsigned long long dvk, dvn; uint16_t* out; const float* sa; }; +__global__ void __launch_bounds__(GQ_THREADS, 1) + fq_kernel(const __grid_constant__ CUtensorMap map_w, const __grid_constant__ CUtensorMap map_act, + const __grid_constant__ FQArgs g) { + using C = FG2Cfg<1, 1>; + constexpr int NWS = C::NWS, NQ = C::NQ, NA = C::NA, NT = C::NT, NSB = C::NSB; + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(smem_raw) + 1023) & ~uintptr_t(1023)); + uint8_t* sW = smem; + uint8_t* sQ = smem + C::OFF_Q; + uint8_t* sA = smem + C::OFF_A; + uint8_t* sS = smem + C::OFF_S; + uint64_t* wfull = reinterpret_cast(smem + C::OFF_B); + uint64_t* wempty = wfull + NWS; + uint64_t* wqf = wempty + NWS; + uint64_t* wqeG = wqf + NQ; + uint64_t* afull = wqeG + 4; + uint64_t* aempty = afull + NA; + uint64_t* tfull = aempty + NA; + uint64_t* tempty = tfull + NT; + uint64_t* scf = tempty + NT; + float* sbv = reinterpret_cast(scf + NSB); + uint32_t* tmem_slot = reinterpret_cast(sbv + NSB); + __shared__ float red[4][2][4]; + + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int Mp = g.Mp, nkb = g.nkb; + const int nu = (int)blockIdx.x < g.units ? (g.units - 1 - (int)blockIdx.x) / (int)gridDim.x + 1 : 0; + const int T = nu * nkb; // flat k-block iterations of this CTA + // flat iteration j -> (m0, n0, kb) + auto dec = [&](int j, int& m0, int& n0, int& kb) { + const int ui = udiv40(j, g.dvk); + kb = j - ui * nkb; + const int u = (int)blockIdx.x + ui * (int)gridDim.x; + const int mb = udiv40(u, g.dvn); + m0 = mb * 128; n0 = (u - mb * g.nblk) * 128; + }; + + if (threadIdx.x == 0) { + for (int i = 0; i < NWS; ++i) { bar_init(&wfull[i], 1); bar_init(&wempty[i], 4); } + for (int i = 0; i < NQ; ++i) bar_init(&wqf[i], 4); + for (int i = 0; i < 4; ++i) bar_init(&wqeG[i], 1); + for (int i = 0; i < NA; ++i) { bar_init(&afull[i], 1); bar_init(&aempty[i], 1); } + for (int i = 0; i < NT; ++i) { bar_init(&tfull[i], 1); bar_init(&tempty[i], NUM_EPI_WARPS); } + for (int i = 0; i < NSB; ++i) bar_init(&scf[i], 1); + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&map_w)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&map_act)) : "memory"); + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(su32(tmem_slot)), "r"(512)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + f_before(); + __syncthreads(); + f_after(); + // tmem_base is re-read from tmem_slot inside each role (register diet: a value live across the setmaxnreg + // role split was spilled to local memory, ptxas 4 B store / 12-24 B loads) + + if (warp < 4) { + asm volatile("setmaxnreg.dec.sync.aligned.u32 32;\n" ::: "memory"); + const uint32_t tmem_base = ld_tmem_slot(tmem_slot); // re-read per role: not live across the setmaxnreg split + uint32_t el; + asm volatile("{\n.reg .pred P;\nelect.sync _|P, 0xffffffff;\nselp.u32 %0, 1, 0, P;\n}" : "=r"(el)); + if (warp == 0) { + // ---------------- bf16 weight ring producer (read-once weights: L2 evict_first) + uint64_t wpol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(wpol)); + const uint32_t a_wempty = su32(wempty); + int s = 0; uint32_t ps = 0; +#pragma unroll 1 + for (int j = 0; j < T; ++j) { + int m0, n0, kb; + dec(j, m0, n0, kb); + bar_wait_a(a_wempty + 8 * s, ps ^ 1); + if (el) { + bar_expect(&wfull[s], 32768u); + tma_ld_hint(sW + s * 32768, &map_w, &wfull[s], kb * BK, n0, wpol); + } + // (no per-k-block __syncwarp: per-lane mbarrier waits; the elected lane issues non-.aligned TMA/MMA/commit) + if (++s == NWS) { s = 0; ps ^= 1u; } + } + } else if (warp == 2) { + // ---------------- fp8 act ring producer (+ this k-block's 128 act scales); act = PDL predecessor output + asm volatile("griddepcontrol.wait;" ::: "memory"); + PDL_TRIGGER(); // predecessor complete: dependents may launch (they still wait for this grid themselves) + const uint32_t a_aempty = su32(aempty); + int a = 0; uint32_t pa = 0; +#pragma unroll 1 + for (int j = 0; j < T; ++j) { + int m0, n0, kb; + dec(j, m0, n0, kb); + bar_wait_a(a_aempty + 8 * a, pa ^ 1); + if (el) { + bar_expect(&afull[a], 16384u + 512u); + tma_ld(sA + a * C::ASZ, &map_act, &afull[a], kb * BK, m0); + bulk_ld(sS + (j & (C::NSS - 1)) * C::SSZ, g.sa + (size_t)kb * Mp + m0, 512u, &afull[a]); + } + // (no per-k-block __syncwarp: per-lane mbarrier waits; the elected lane issues non-.aligned TMA/MMA/commit) + if (++a == NA) { a = 0; pa ^= 1u; } + } + } else if (warp == 1) { + // ---------------- MMA issuer + const uint32_t idesc = (1u << 4) | ((uint32_t)(128 >> 3) << 17) | ((uint32_t)(128 >> 4) << 24); + const uint32_t a_tempty = su32(tempty), a_wqf = su32(wqf), a_afull = su32(afull); + const uint64_t ad0 = sdesc(su32(sA)), bd0 = sdesc(su32(sQ)); + constexpr uint64_t ADST = (uint64_t)(C::ASZ >> 4), BDST = (uint64_t)(16384 >> 4); + int a = 0, b = 0, qs = 0; + uint32_t pa = 0, pb = 0, pq = 0; + uint64_t aoff = 0, boff = 0; +#pragma unroll 1 + for (int j = 0; j < T; ++j) { + bar_wait_a(a_tempty + 8 * b, pb ^ 1); // promotion drained this TMEM buffer + bar_wait_a(a_wqf + 8 * qs, pq); // quantized weight tile ready + bar_wait_a(a_afull + 8 * a, pa); // act tile + scales landed + f_after(); + if (el) { + const uint64_t ad = ad0 + aoff, bd = bd0 + boff; + const uint32_t td = tmem_base + b * 128; +#pragma unroll + for (int k = 0; k < BK / 32; ++k) mma(td, ad + 2 * k, bd + 2 * k, idesc, k > 0 ? 1u : 0u); + commit(&aempty[a]); + commit(&wqeG[j & 3]); + commit(&tfull[b]); + } + // (no per-k-block __syncwarp: per-lane mbarrier waits; the elected lane issues non-.aligned TMA/MMA/commit) + if (++a == NA) { a = 0; pa ^= 1u; aoff = 0; } else aoff += ADST; + if (++b == NT) { b = 0; pb ^= 1u; } + if (++qs == NQ) { qs = 0; pq ^= 1u; boff = 0; } else boff += BDST; + } + } + } else { + asm volatile("setmaxnreg.inc.sync.aligned.u32 112;\n" ::: "memory"); + const uint32_t tmem_base = ld_tmem_slot(tmem_slot); // re-read per role: not live across the setmaxnreg split + const int wt = threadIdx.x - 128; + const int grp = wt >> 7; // quant group == promotion column group + const int gt = wt & 127, gw = warp & 3; + const int r0 = gt >> 3, sub = gt & 7, hsw = (sub >> 2) & 1; + const int q = warp & 3, cg = grp; // TMEM lane quadrant, 32-column group + float2 acc2[16]; + const uint32_t tm_warp = tmem_base + ((uint32_t)(q * 32) << 16) + cg * 32; + auto promote = [&](int j) { + const int b = ((unsigned)j % NT); + bar_wait_f<1>(su32(&scf[((unsigned)j % NSB)]), (((unsigned)j / NSB)) & 1); // un-hinted: worker wake-up on the per-k-block critical path + const float sb = sbv[((unsigned)j % NSB)]; + bar_wait_f<1>(su32(&tfull[b]), (((unsigned)j / NT)) & 1); // un-hinted: worker wake-up on the per-k-block critical path + f_after(); + float sa0; + const uint32_t sa = su32(sS) + (uint32_t)((j & (C::NSS - 1)) * C::SSZ) + (uint32_t)(q * 32 + lane) * 4u; + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(sa0) : "r"(sa) : "memory"); + int m0, n0, kb; + dec(j, m0, n0, kb); + uint32_t r[32]; + KVB_TMEM_LD32(tm_warp + b * 128, r); + asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); + f_before(); + __syncwarp(); + if (lane == 0) bar_arrive_a(su32(&tempty[b])); + const float scl = sa0 * sb; // == gq: sc = sa * sb + const float2 sc2 = make_float2(scl, scl); + if (kb == 0) { +#pragma unroll + for (int c = 0; c < 16; ++c) acc2[c] = __fmul2_rn(make_float2(__uint_as_float(r[2 * c]), __uint_as_float(r[2 * c + 1])), sc2); + } else { +#pragma unroll + for (int c = 0; c < 16; ++c) + acc2[c] = __ffma2_rn(make_float2(__uint_as_float(r[2 * c]), __uint_as_float(r[2 * c + 1])), sc2, acc2[c]); + } + if (kb == nkb - 1) { // unit done: bf16 row segment (64 B) -> D + uint4* dst = reinterpret_cast(g.out + (size_t)(m0 + q * 32 + lane) * g.N + n0 + cg * 32); +#pragma unroll + for (int v = 0; v < 4; ++v) { + uint32_t w[4]; +#pragma unroll + for (int h = 0; h < 4; ++h) { + __nv_bfloat162 t = __floats2bfloat162_rn(acc2[4 * v + h].x, acc2[4 * v + h].y); + w[h] = *reinterpret_cast(&t); + } + dst[v] = make_uint4(w[0], w[1], w[2], w[3]); + } + } + }; + // per-thread bf16 read offsets (row r0 + 16p, conflict-free half order) and SW128 fp8 write offset (as fg2) + const uint32_t q_rlo = (uint32_t)(r0 * 256 + sub * 32 + hsw * 16), q_rhi = q_rlo ^ 16u; + const uint32_t q_wo = (uint32_t)((r0 >> 3) * 1024 + (r0 & 7) * 128 + ((sub ^ (r0 & 7)) << 4)); + auto quant = [&](int j) { + const int s = ((unsigned)j % NWS); + bar_wait_f<1>(su32(&wfull[s]), (((unsigned)j / NWS)) & 1); // un-hinted: worker wake-up on the per-k-block critical path + const uint8_t* stl = sW + s * 32768 + q_rlo; + const uint8_t* sth = sW + s * 32768 + q_rhi; + uint32_t a0 = 0u, a1 = 0u; +#pragma unroll + for (int p = 0; p < 8; p += 2) { + const uint4 va = *reinterpret_cast(stl + p * 4096); + const uint4 vb = *reinterpret_cast(sth + p * 4096); + const uint4 vc = *reinterpret_cast(stl + (p + 1) * 4096); + const uint4 vd = *reinterpret_cast(sth + (p + 1) * 4096); + a0 = amax16(va, vb, a0); + a1 = amax16(vc, vd, a1); + } + asm("max.bf16x2 %0, %0, %1;" : "+r"(a0) : "r"(a1)); + uint32_t am = __float_as_uint(bf2max_to_f(a0)); // >= 0: u32 order == float order + asm volatile("redux.sync.max.u32 %0, %0, 0xffffffff;" : "+r"(am)); + const int par = (j >> 2) & 1; + if (lane == 0) red[grp][par][gw] = __uint_as_float(am); + asm volatile("bar.sync %0, 128;" ::"r"(1 + grp) : "memory"); // quant group only + const float amax = fmaxf(fmaxf(red[grp][par][0], red[grp][par][1]), fmaxf(red[grp][par][2], red[grp][par][3])); + const float sc = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float inv = __fdividef(1.0f, sc); // == wquant_kernel<7> + if (gt == 0) { sbv[((unsigned)j % NSB)] = sc; bar_arrive_a(su32(&scf[((unsigned)j % NSB)])); } + const int qs = ((unsigned)j % NQ); + if (j >= NQ) { // MMAs of k-block j-NQ done with this tile + const int jp = j - NQ; + bar_wait_f<1>(su32(&wqeG[jp & 3]), (jp >> 2) & 1); // un-hinted: worker wake-up on the per-k-block critical path + } + uint8_t* wqs = sQ + qs * 16384; +#pragma unroll + for (int p = 0; p < 8; ++p) { + const uint4 va = *reinterpret_cast(stl + p * 4096); + const uint4 vb = *reinterpret_cast(sth + p * 4096); + *reinterpret_cast(wqs + q_wo + p * 2048) = quant16_fast(va, vb, inv, hsw); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + if (lane == 0) { bar_arrive_a(su32(&wqf[qs])); bar_arrive_a(su32(&wempty[s])); } + }; +#pragma unroll 1 + for (int i = -C::A; i < T + C::D; ++i) { + const int j = i - C::D; + if (j >= 0 && j < T) promote(j); + const int jq = i + C::A; + if (jq >= 0 && jq < T && (jq & 3) == grp) quant(jq); + } + } + + f_before(); + __syncthreads(); + if (warp == 1) { + f_after(); + const uint32_t tmem_base = ld_tmem_slot(tmem_slot); // re-read per role: not live across the setmaxnreg split + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tmem_base), "r"(512)); + } +} + +} // namespace kvb + + +// fused quantize-on-load q_b GEMM (see fq_kernel): D[Mp,N] = A x quant(W bf16 [N,K])^T on `grid` persistent CTAs. +int launch_fq_gemm(const void* W, const void* A, const float* SA, void* D, int Mp, int N, int K, int grid, cudaStream_t st, + int pdl) { + static bool attr = false; + if (!attr) { + cudaFuncSetAttribute(kvb::fq_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, kvb::FG2Cfg<1, 1>::SMEM); + attr = true; + } + if (Mp % 128 || N % 128 || K % 128 || grid < 1) return -40; + CUtensorMap mw, ma; + cuuint64_t dims[2] = {(cuuint64_t)K, (cuuint64_t)N}; + cuuint64_t strides[1] = {(cuuint64_t)K * 2}; + cuuint32_t box[2] = {128, 128}; + cuuint32_t estr[2] = {1, 1}; + if (cuTensorMapEncodeTiled(&mw, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, const_cast(W), dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, CU_TENSOR_MAP_L2_PROMOTION_L2_256B, + CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE) != CUDA_SUCCESS || + !kvb::make_op_map(&ma, A, (uint64_t)Mp, (uint64_t)K, 128)) + return -41; + kvb::FQArgs g; + g.Mp = Mp; g.N = N; g.nkb = K / 128; g.nblk = N / 128; g.units = (Mp / 128) * (N / 128); + g.dvk = dvm40((unsigned)g.nkb); g.dvn = dvm40((unsigned)g.nblk); g.out = (uint16_t*)D; g.sa = SA; + if (grid > g.units) grid = g.units; + launch_pdl(kvb::fq_kernel, dim3(grid), dim3(kvb::GQ_THREADS), kvb::FG2Cfg<1, 1>::SMEM, st, pdl, mw, ma, g); + return cudaPeekAtLastError() == cudaSuccess ? 0 : -42; +} +static int g_fg_whint = 0; // fused GEMM1: bf16 weight TMA loads with L2::evict_first +void set_fg_whint(int on) { g_fg_whint = on; } +#ifdef SR_PROBE +static int g_fg_sr = 1; +void set_fg_sr(int v) { g_fg_sr = v; } +#endif +// Small-M fused GEMM1 (fg2): 1 = trigger launch_dependents at ENTRY even under the late-trigger chain (wq bit10), so the +// split-K norm grid (PDL dependent, tiny CTAs that co-reside with fg2 / B-wquant CTAs) is launched and parked in +// griddepcontrol.wait while fg2 runs, instead of being launched only after fg2's last partial stores. The norm still +// waits for fg2's full completion before reading partials: same data, bit-identical. +static int g_fg_early = 0; +void set_fg_early(int on) { g_fg_early = on; } +static int g_fg_ver = 2; // 2: fg2_kernel (decoupled quant front end), 1: fg1_kernel (probe comparison only) +void set_fg_ver(int v) { g_fg_ver = v; } + +int fused_g1_splits(int Mp, int avail, int K) { + const int G = (Mp / 128 + 1) / 2; + int S = avail / (17 * G); + if (S < 1) S = 1; + if (S > K / 128) S = K / 128; + return S; +} + +int launch_fused_g1(const void* wqa, const void* wkva, const void* xq, const float* xs, float* part, int Mp, int K, + int S, cudaStream_t st) { + static bool attr = false; + if (!attr) { + cudaFuncSetAttribute(kvb::fg1_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, kvb::FG_SMEM); + cudaFuncSetAttribute(kvb::fg2_kernel<1, 1>, cudaFuncAttributeMaxDynamicSharedMemorySize, kvb::FG2Cfg<1, 1>::SMEM); +#ifdef SR_PROBE + cudaFuncSetAttribute(kvb::fg2_kernel<1, 0>, cudaFuncAttributeMaxDynamicSharedMemorySize, kvb::FG2Cfg<1, 0>::SMEM); +#endif + attr = true; + } + if (Mp % 128 || K % 128) return -20; + CUtensorMap mq, mk, ma; + auto wmap = [&](CUtensorMap* m, const void* p, uint64_t rows) { + cuuint64_t dims[2] = {(cuuint64_t)K, rows}; + cuuint64_t strides[1] = {(cuuint64_t)K * 2}; + cuuint32_t box[2] = {128, 128}; + cuuint32_t estr[2] = {1, 1}; + return cuTensorMapEncodeTiled(m, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, const_cast(p), dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, + CU_TENSOR_MAP_L2_PROMOTION_L2_256B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE) == CUDA_SUCCESS; + }; + if (!wmap(&mq, wqa, 1536) || !wmap(&mk, wkva, 640) || !kvb::make_op_map(&ma, xq, (uint64_t)Mp, (uint64_t)K, 128)) + return -21; + kvb::FGArgs g; + g.xs = xs; g.part = part; g.Mp = Mp; g.S = S; g.MT = Mp / 128; g.G = (g.MT + 1) / 2; g.NKB = K / 128; g.NY = 1536 + 576; g.late = g_late && !g_fg_early; g.whint = g_fg_whint; g.Gm = dvm40((unsigned)g.G); g.Sm = dvm40((unsigned)S); + const int grid = 17 * g.G * S; + if (g_fg_ver == 1 || g.MT >= 2) kvb::fg1_kernel<<>>(mq, mk, ma, g); +#ifdef SR_PROBE + else if (!g_fg_sr) launch_pdl(kvb::fg2_kernel<1, 0>, dim3(grid), dim3(kvb::GQ_THREADS), kvb::FG2Cfg<1, 0>::SMEM, st, g_fg_pdl, mq, mk, ma, g); +#endif + else launch_pdl(kvb::fg2_kernel<1, 1>, dim3(grid), dim3(kvb::GQ_THREADS), kvb::FG2Cfg<1, 1>::SMEM, st, g_fg_pdl, mq, mk, ma, g); + return cudaPeekAtLastError() == cudaSuccess ? 0 : -22; +} + +#ifdef FG_ROLE +void fgr_set(void* p) { cudaMemcpyToSymbol(kvb::g_fgr, &p, sizeof(p)); } +#endif +#ifdef GQ_PROBE +void fg_set_prof(void* p) { cudaMemcpyToSymbol(kvb::g_fgp, &p, sizeof(p)); } +#endif + +// ------------------------------------------------------------------ 10. fused B-weight quant + q_b/kv_b GEMM (small M) +// Replaces (B-weight pquant -> fp8 weights in global -> gq GEMMs) for Mp <= 512: the bf16 q_b / kv_b weights are +// read ONCE and quantized in-CTA (no 55 MB fp8 write + re-read). Persistent grid (1 CTA/SM) over a combined unit +// list: unit = (n-block of 128 weight rows of q_b (problem 0) or kv_b (problem 1), m-group gi of 256 act rows); +// a host LPT schedule (cost = nkb + 1) assigns units to CTAs. Each CTA walks a flat k-block iteration sequence over +// all its units, with the same pipeline as fg1_kernel (section 9): +// warp 0 (1 thread) : TMA producer -> 3-stage ring; stage = bf16 weight block 128x128 (32 KB, no swizzle) + +// mcnt fp8 act tiles 128x128 (16 KB each, SW128) of the normed activation (qq / kq). +// warps 4..19 (512) : quantize the bf16 block exactly like pquant_kernel (128x128 amax, x * (1/scale), e4m3 +// satfinite) into a SW128 K-major smem tile (2-slot ring) = MMA B operand; promote k-block +// i-2: acc += partial * (sa[m,kb] * sb); at a unit's last k-block store the bf16 tile +// (each thread: 32 contiguous output columns of one row per m-tile, 64 B) and reset acc. +// warp 1 (1 thread) : TMEM alloc (2 buffers x 2 m-tiles x 128 cols) + tcgen05.mma kind::f8f6f4 128x128x32. +namespace kvb { +struct FBArgs { + const float* sa[2]; // act scales, MN-major [kb][Mp] + uint16_t* out[2]; // bf16 outputs [Mp, N_p] + int N[2], nkb[2]; + int nb0; // n-blocks of problem 0 + int Mp, G, MT; + unsigned long long Gm; // dvm40(G) + const int* sched; // [grid+1] offsets, then unit lists +}; +struct FBCur { int li, end, kb, nkb, p, nb, gi, mcnt; }; +__device__ __forceinline__ void fb_load(const FBArgs& g, FBCur& c) { + c.kb = 0; + if (c.li >= c.end) { c.nkb = 0; return; } + const int u = __ldg(g.sched + gridDim.x + 1 + c.li); + const int nbc = udiv40(u, g.Gm); + c.gi = u - nbc * g.G; + c.p = nbc >= g.nb0 ? 1 : 0; + c.nb = c.p ? nbc - g.nb0 : nbc; + c.nkb = c.p ? g.nkb[1] : g.nkb[0]; + c.mcnt = min(2, g.MT - 2 * c.gi); +} +__device__ __forceinline__ void fb_init(const FBArgs& g, FBCur& c) { + c.li = __ldg(g.sched + blockIdx.x); + c.end = __ldg(g.sched + blockIdx.x + 1); + fb_load(g, c); +} +__device__ __forceinline__ void fb_adv(const FBArgs& g, FBCur& c) { + if (++c.kb >= c.nkb) { ++c.li; fb_load(g, c); } +} + +__global__ void __launch_bounds__(GQ_THREADS, 1) + fb_kernel(const __grid_constant__ CUtensorMap map_w0, const __grid_constant__ CUtensorMap map_w1, + const __grid_constant__ CUtensorMap map_a0, const __grid_constant__ CUtensorMap map_a1, + const __grid_constant__ FBArgs g) { + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = reinterpret_cast((reinterpret_cast(smem_raw) + 1023) & ~uintptr_t(1023)); + uint8_t* sWq = smem + FG_NST * FG_STAGE; + uint64_t* full = reinterpret_cast(sWq + 2 * FG_WQ); + uint64_t* empty = full + FG_NST; + uint64_t* wqf = empty + FG_NST; + uint64_t* wqe = wqf + 2; + uint64_t* tfull = wqe + 2; + uint64_t* tempty = tfull + 2; + uint32_t* tmem_slot = reinterpret_cast(tempty + 2); + __shared__ __align__(16) float red[2][16]; + + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int Mp = g.Mp; + + if (threadIdx.x == 0) { + for (int i = 0; i < FG_NST; ++i) { bar_init(&full[i], 1); bar_init(&empty[i], 1); } + for (int i = 0; i < 2; ++i) { + bar_init(&wqf[i], NUM_EPI_WARPS); bar_init(&wqe[i], 1); + bar_init(&tfull[i], 1); bar_init(&tempty[i], NUM_EPI_WARPS); + } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&map_w0)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&map_w1)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&map_a0)) : "memory"); + asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast(&map_a1)) : "memory"); + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(su32(tmem_slot)), "r"(512)); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); + } + f_before(); + __syncthreads(); + f_after(); + const uint32_t tmem_base = *tmem_slot; + + if (warp < 4) { + asm volatile("setmaxnreg.dec.sync.aligned.u32 32;\n" ::: "memory"); + if (warp == 0 && lane == 0) { + // ---------------- TMA producer: flat k-block sequence over this CTA's units + FBCur c; + fb_init(g, c); +#pragma unroll 1 + for (int i = 0; c.nkb > 0; ++i, fb_adv(g, c)) { + const int s = ((unsigned)i % FG_NST); + bar_wait(&empty[s], ((((unsigned)i / FG_NST)) & 1) ^ 1); + uint8_t* st = smem + s * FG_STAGE; + bar_expect(&full[s], 32768u + (uint32_t)c.mcnt * 16384u); + tma_ld(st, c.p ? &map_w1 : &map_w0, &full[s], c.kb * BK, c.nb * 128); + for (int mt = 0; mt < c.mcnt; ++mt) + tma_ld(st + 32768 + mt * 16384, c.p ? &map_a1 : &map_a0, &full[s], c.kb * BK, c.gi * 256 + mt * 128); + } + } else if (warp == 1 && lane == 0) { + // ---------------- MMA issuer: D[act row, weight row] per k-block, fresh accumulate into TMEM buffer i&1 + const uint32_t idesc = (1u << 4) | ((uint32_t)(128 >> 3) << 17) | ((uint32_t)(128 >> 4) << 24); + FBCur c; + fb_init(g, c); +#pragma unroll 1 + for (int i = 0; c.nkb > 0; ++i, fb_adv(g, c)) { + const int s = ((unsigned)i % FG_NST), b = i & 1; + bar_wait(&tempty[b], ((i >> 1) & 1) ^ 1); + bar_wait(&wqf[b], (i >> 1) & 1); + bar_wait(&full[s], (((unsigned)i / FG_NST)) & 1); + f_after(); + const uint64_t bd = sdesc(su32(sWq + b * FG_WQ)); + for (int mt = 0; mt < c.mcnt; ++mt) { + const uint64_t ad = sdesc(su32(smem + s * FG_STAGE + 32768 + mt * 16384)); + const uint32_t td = tmem_base + b * 256 + mt * 128; +#pragma unroll + for (int k = 0; k < BK / 32; ++k) mma(td, ad + 2 * k, bd + 2 * k, idesc, k > 0 ? 1u : 0u); + } + commit(&empty[s]); + commit(&wqe[b]); + commit(&tfull[b]); + } + } + } else { + asm volatile("setmaxnreg.inc.sync.aligned.u32 112;\n" ::: "memory"); + // ---------------- 16 worker warps: in-CTA weight quant (iteration i) + promotion / epilogue (iteration i-2) + const int wt = threadIdx.x - 128, ww = warp - 4; + const int r0 = wt >> 3, sub = wt & 7, hsw = (sub >> 2) & 1; + const int q = warp & 3, cg = (warp - 4) >> 2; // TMEM lane quadrant, 32-column group + const int rl = q * 32 + lane; // act row inside an m-tile + float2 acc2[32]; +#pragma unroll + for (int j = 0; j < 32; ++j) acc2[j] = make_float2(0.f, 0.f); + FBCur cq, cp; // cursors of the quant (i) and promotion (i-2) iterations + fb_init(g, cq); + fb_init(g, cp); + int T = 0; // total k-block iterations of this CTA + { + FBCur c = cq; + while (c.nkb > 0) { T += c.nkb; ++c.li; fb_load(g, c); } + } + float sa00 = 0.f, sa01 = 0.f, sa10 = 0.f, sa11 = 0.f, sb0 = 0.f, sb1 = 0.f; + const uint32_t tm_warp = tmem_base + ((uint32_t)(q * 32) << 16) + cg * 32; + auto promote = [&](int j, float sa0, float sa1, float sb) { + const int b = j & 1; + bar_wait(&tfull[b], (j >> 1) & 1); + f_after(); + const int mcnt = cp.mcnt; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { + if (mt < mcnt) { + uint32_t r[32]; + const uint32_t ta = tm_warp + b * 256 + mt * 128; + KVB_TMEM_LD16(ta, r); + KVB_TMEM_LD16(ta + 16, (r + 16)); + asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); + const float scl = (mt ? sa1 : sa0) * sb; + const float2 sc2 = make_float2(scl, scl); +#pragma unroll + for (int c = 0; c < 16; ++c) + acc2[mt * 16 + c] = __ffma2_rn(make_float2(__uint_as_float(r[2 * c]), __uint_as_float(r[2 * c + 1])), sc2, acc2[mt * 16 + c]); + } + } + f_before(); + __syncwarp(); + if (lane == 0) bar_arrive_a(su32(&tempty[b])); + if (cp.kb == cp.nkb - 1) { + // unit done: bf16 tile rows -> global (64 contiguous bytes per thread per m-tile), reset accumulators + const int N = cp.p ? g.N[1] : g.N[0]; + uint16_t* D = cp.p ? g.out[1] : g.out[0]; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { + if (mt < mcnt) { + uint4* dst = reinterpret_cast(D + (size_t)(cp.gi * 256 + mt * 128 + rl) * N + cp.nb * 128 + cg * 32); +#pragma unroll + for (int v = 0; v < 4; ++v) { + uint32_t w[4]; +#pragma unroll + for (int h = 0; h < 4; ++h) { + const float2 a = acc2[mt * 16 + 4 * v + h]; + __nv_bfloat162 t = __floats2bfloat162_rn(a.x, a.y); + w[h] = *reinterpret_cast(&t); + } + dst[v] = make_uint4(w[0], w[1], w[2], w[3]); + } + } + } +#pragma unroll + for (int j2 = 0; j2 < 32; ++j2) acc2[j2] = make_float2(0.f, 0.f); + } + fb_adv(g, cp); + }; + auto step = [&](auto PARc, int i) { + constexpr int PAR = decltype(PARc)::value; + float& saQ0 = PAR ? sa10 : sa00; + float& saQ1 = PAR ? sa11 : sa01; + float& sbQ = PAR ? sb1 : sb0; + const float saP0 = saQ0, saP1 = saQ1, sbP = sbQ; // iteration i-2 + if (i < T) { + const int s = ((unsigned)i % FG_NST), w = PAR; + const float* xs = cq.p ? g.sa[1] : g.sa[0]; + const int rowA = cq.gi * 256 + rl; + saQ0 = ldcg_f32v(xs + (size_t)cq.kb * Mp + rowA); + if (cq.mcnt > 1) saQ1 = ldcg_f32v(xs + (size_t)cq.kb * Mp + rowA + 128); + bar_wait(&full[s], (((unsigned)i / FG_NST)) & 1); + const uint8_t* st = smem + s * FG_STAGE + r0 * 256 + sub * 32; + { + uint4 va[2], vb[2]; +#pragma unroll + for (int q2 = 0; q2 < 2; ++q2) { + va[q2] = *reinterpret_cast(st + q2 * 16384 + hsw * 16); + vb[q2] = *reinterpret_cast(st + q2 * 16384 + (hsw ^ 1) * 16); + } + uint32_t a2 = 0u; +#pragma unroll + for (int q2 = 0; q2 < 2; ++q2) a2 = amax16(va[q2], vb[q2], a2); + uint32_t am = __float_as_uint(bf2max_to_f(a2)); + asm volatile("redux.sync.max.u32 %0, %0, 0xffffffff;" : "+r"(am)); + if (lane == 0) red[PAR][ww] = __uint_as_float(am); + } + if (i >= 2) promote(i - 2, saP0, saP1, sbP); + asm volatile("bar.sync 1, 512;" ::: "memory"); + const float4* rv = reinterpret_cast(red[PAR]); + float amax = 0.f; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float4 t = rv[j]; + amax = fmaxf(amax, fmaxf(fmaxf(t.x, t.y), fmaxf(t.z, t.w))); + } + const float sc = fmaxf(amax * (1.0f / FP8_MAX), 1e-12f); + const float inv = 1.0f / sc; + bar_wait(&wqe[w], ((i >> 1) & 1) ^ 1); + uint8_t* wqs = sWq + w * FG_WQ; +#pragma unroll + for (int q2 = 0; q2 < 2; ++q2) { + const uint4 va = *reinterpret_cast(st + q2 * 16384 + hsw * 16); + const uint4 vb = *reinterpret_cast(st + q2 * 16384 + (hsw ^ 1) * 16); + const int r = r0 + 64 * q2; + const uint4 qv = quant16_fast(va, vb, inv, hsw); + *reinterpret_cast(wqs + (r >> 3) * 1024 + (r & 7) * 128 + ((sub ^ (r & 7)) << 4)) = qv; + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + if (lane == 0) bar_arrive_a(su32(&wqf[w])); + sbQ = sc; + fb_adv(g, cq); + } else if (i >= 2 && i <= T + 1) { + promote(i - 2, saP0, saP1, sbP); + } + }; +#pragma unroll 1 + for (int i = 0; i <= T + 1; i += 2) { + step(std::integral_constant{}, i); + step(std::integral_constant{}, i + 1); + } + } + + f_before(); + __syncthreads(); + if (warp == 1) { + f_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tmem_base), "r"(512)); + } +} +} // namespace kvb + +int launch_fused_b(const void* w0, const void* w1, const void* a0, const float* sa0, const void* a1, const float* sa1, + void* d0, void* d1, int N0, int K0, int N1, int K1, int Mp, cudaStream_t st) { + static int nsm = 0; + if (nsm == 0) { + int dev; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&nsm, cudaDevAttrMultiProcessorCount, dev); + cudaFuncSetAttribute(kvb::fb_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, kvb::FG_SMEM); + } + if (Mp % 128 || N0 % 128 || N1 % 128 || K0 % 128 || K1 % 128) return -30; + auto wmap = [&](CUtensorMap* m, const void* p, uint64_t rows, uint64_t K) { + cuuint64_t dims[2] = {(cuuint64_t)K, rows}; + cuuint64_t strides[1] = {(cuuint64_t)K * 2}; + cuuint32_t box[2] = {128, 128}; + cuuint32_t estr[2] = {1, 1}; + return cuTensorMapEncodeTiled(m, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, const_cast(p), dims, strides, box, estr, + CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, + CU_TENSOR_MAP_L2_PROMOTION_L2_256B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE) == CUDA_SUCCESS; + }; + CUtensorMap mw0, mw1, ma0, ma1; + if (!wmap(&mw0, w0, N0, K0) || !wmap(&mw1, w1, N1, K1) || + !kvb::make_op_map(&ma0, a0, (uint64_t)Mp, (uint64_t)K0, 128) || !kvb::make_op_map(&ma1, a1, (uint64_t)Mp, (uint64_t)K1, 128)) + return -31; + kvb::FBArgs g; + g.sa[0] = sa0; g.sa[1] = sa1; + g.out[0] = (uint16_t*)d0; g.out[1] = (uint16_t*)d1; + g.N[0] = N0; g.N[1] = N1; g.nkb[0] = K0 / 128; g.nkb[1] = K1 / 128; + g.nb0 = N0 / 128; + g.Mp = Mp; g.MT = Mp / 128; g.G = (g.MT + 1) / 2; g.Gm = dvm40((unsigned)g.G); + const int units = (N0 / 128 + N1 / 128) * g.G; + const int grid = units < nsm ? units : nsm; + // LPT schedule (cached per shape, device buffer never freed): unit cost = k-blocks + 1 (epilogue) + static std::map, int*>& cache = *new std::map, int*>(); + const std::array key = {Mp, grid, N0, K0, N1, K1}; + auto itc = cache.find(key); + if (itc == cache.end()) { + auto cost = [&](int u) { return (u / g.G < g.nb0 ? g.nkb[0] : g.nkb[1]) + 1; }; + std::vector order(units); + for (int u = 0; u < units; ++u) order[u] = u; + std::stable_sort(order.begin(), order.end(), [&](int a, int b) { return cost(a) > cost(b); }); + std::vector load(grid, 0); + std::vector> lists(grid); + for (int u : order) { + int best = 0; + for (int c = 1; c < grid; ++c) if (load[c] < load[best]) best = c; + load[best] += cost(u); + lists[best].push_back(u); + } + std::vector h(grid + 1 + units); + int o = 0; + for (int c = 0; c < grid; ++c) { + h[c] = o; + for (int u : lists[c]) h[grid + 1 + o++] = u; + } + h[grid] = o; + int* d = nullptr; + if (cudaMalloc(&d, h.size() * sizeof(int)) != cudaSuccess) return -32; + cudaMemcpy(d, h.data(), h.size() * sizeof(int), cudaMemcpyHostToDevice); + itc = cache.emplace(key, d).first; + } + g.sched = itc->second; + kvb::fb_kernel<<>>(mw0, mw1, ma0, ma1, g); + return cudaPeekAtLastError() == cudaSuccess ? 0 : -33; +} + +// ------------------------------------------------------------------ 11. L2 prefetch of the B weights (small M) +// Issued on a side stream at the start of the small-M fused graph: while act quant -> fused GEMM1 -> norm run, +// the first `bytes` of the bf16 B weights (q_b rows first, then kv_b = exactly the order in which fb_kernel's +// LPT schedule first touches its units: q_b n-blocks ascending, each 384 KB contiguous) are pulled into L2 with +// cp.async.bulk.prefetch.L2 (fire-and-forget, no smem / registers). One thread per 16 KB chunk. +// hint = 1: L2::evict_last cache policy on the prefetch. +constexpr uint32_t PF_CHUNK = 16384; +__global__ void __launch_bounds__(256) l2_prefetch_kernel(const uint8_t* __restrict__ p0, size_t n0, + const uint8_t* __restrict__ p1, size_t n1, int hint) { + const size_t off = ((size_t)blockIdx.x * blockDim.x + threadIdx.x) * PF_CHUNK; + const uint8_t* p; + size_t rem; + if (off < n0) { p = p0 + off; rem = n0 - off; } + else if (off - n0 < n1) { p = p1 + (off - n0); rem = n1 - (off - n0); } + else return; + const uint32_t bytes = (uint32_t)(rem < PF_CHUNK ? rem : PF_CHUNK) & ~15u; // multiple of 16 + if (!bytes) return; + if (hint) { + uint64_t pol; + asm volatile("createpolicy.fractional.L2::" KPOL_LAST ".b64 %0, 1.0;" : "=l"(pol)); + asm volatile("cp.async.bulk.prefetch.L2.global.L2::cache_hint [%0], %1, %2;" ::"l"(p), "r"(bytes), "l"(pol) : "memory"); + } else { + asm volatile("cp.async.bulk.prefetch.L2.global [%0], %1;" ::"l"(p), "r"(bytes) : "memory"); + } +} + +void launch_l2_prefetch(const void* p0, size_t n0, const void* p1, size_t n1, size_t bytes, int hint, cudaStream_t st) { + if (bytes < n0) { n0 = bytes; n1 = 0; } + else if (bytes - n0 < n1) n1 = bytes - n0; + const size_t chunks = (n0 + n1 + PF_CHUNK - 1) / PF_CHUNK; + if (!chunks) return; + const int grid = (int)((chunks + 255) / 256); + l2_prefetch_kernel<<>>((const uint8_t*)p0, n0, (const uint8_t*)p1, n1, hint); +} + +#ifdef CLK_PROBE +void clk_set(void* p) { cudaMemcpyToSymbol(kvb::g_clk, &p, sizeof(p)); } +__global__ void clk_spin(unsigned long long* o) { + long long g0, g1; asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(g0)); + const long long c0 = clock64(); + do { asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(g1)); } while (g1 - g0 < 2000000); + const long long c1 = clock64(); + if (threadIdx.x == 0 && blockIdx.x == 0) { o[0] = c1 - c0; o[1] = g1 - g0; } +} +void clk_spin_launch(unsigned long long* o, cudaStream_t s) { clk_spin<<<148, 32, 0, s>>>(o); } +#endif +#ifdef NPW_PROBE +// probe: registers / local memory (spills) of the gq kernel instantiations +void gq_attr_report(char* buf, int n) { + cudaFuncAttributes a[4]; + cudaFuncGetAttributes(&a[0], kvb::gq_kernel<256, false>); + cudaFuncGetAttributes(&a[1], kvb::gq_kernel<256, false, 8>); + cudaFuncGetAttributes(&a[2], kvb::gq_kernel<256, true>); + cudaFuncGetAttributes(&a[3], kvb::gq_kernel<256, true, 8>); + snprintf(buf, n, " ATTR(regs/local B): 1sm16 %d/%zu 1sm8 %d/%zu 2sm16 %d/%zu 2sm8 %d/%zu", a[0].numRegs, a[0].localSizeBytes, + a[1].numRegs, a[1].localSizeBytes, a[2].numRegs, a[2].localSizeBytes, a[3].numRegs, a[3].localSizeBytes); +} +#endif + +#ifdef WQ_PROBE +__global__ void __launch_bounds__(512, 1) ubench_kernel(int op, int iters, unsigned long long* out, uint32_t seed) { + uint32_t r[8]; float f[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) { r[j] = seed * (threadIdx.x + 7 * j + 1); f[j] = __uint_as_float((r[j] & 0x007fffffu) | 0x3f800000u); } + const unsigned long long inv2 = pack2(1.37f); + __syncthreads(); + const long long c0 = clock64(); + for (int i = 0; i < iters; ++i) { +#pragma unroll + for (int j = 0; j < 8; ++j) { + if (op == 0) { // cvt e4m3x2.f32 + uint16_t h; asm volatile("cvt.rn.satfinite.e4m3x2.f32 %0, %1, %2;" : "=h"(h) : "f"(f[j]), "f"(f[(j + 1) & 7])); + r[j] += h; + } else if (op == 1) { // mul f32x2 + unsigned long long x; asm volatile("mov.b64 %0, {%1, %2};" : "=l"(x) : "f"(f[j]), "f"(f[(j + 3) & 7])); + asm volatile("mul.rn.f32x2 %0, %0, %1;" : "+l"(x) : "l"(inv2)); + float a, b; asm volatile("mov.b64 {%0, %1}, %2;" : "=f"(a), "=f"(b) : "l"(x)); f[j] = a; f[(j + 3) & 7] = b; + } else if (op == 2) { // max.xorsign.abs.bf16x2 + asm volatile("max.xorsign.abs.bf16x2 %0, %0, %1;" : "+r"(r[j]) : "r"(r[(j + 5) & 7])); + } else if (op == 3) { // quant_pair_fast + r[j] = r[j] * 3u + quant_pair_fast(r[j], inv2); + } else { + asm volatile("add.u32 %0, %0, %1;" : "+r"(r[j]) : "r"(r[(j + 1) & 7])); + } + } + } + const long long c1 = clock64(); + uint32_t x = 0; for (int j = 0; j < 8; ++j) x ^= r[j] ^ __float_as_uint(f[j]); + if (threadIdx.x == 0) { atomicMax(out, (unsigned long long)(c1 - c0)); } + if (x == 0x9e3779b9u) out[1] = x; +} +void ubench(int op, int iters, unsigned long long* out, cudaStream_t st) { ubench_kernel<<<148, 512, 0, st>>>(op, iters, out, 12345u); } +#endif +#ifdef WB_PROBE +__global__ void rdflush_kernel(const uint4* __restrict__ p, size_t n16, unsigned* out) { + uint32_t a = 0; + for (size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x; i < n16; i += (size_t)gridDim.x * blockDim.x) { + uint4 v; asm volatile("ld.global.cg.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(v.x), "=r"(v.y), "=r"(v.z), "=r"(v.w) : "l"(p + i)); + a ^= v.x ^ v.y ^ v.z ^ v.w; + } + if (a == 0x9e3779b9u) *out = a; +} +void wb_rdflush(const void* p, size_t bytes, unsigned* out, cudaStream_t s) { rdflush_kernel<<<148 * 8, 256, 0, s>>>((const uint4*)p, bytes / 16, out); } +#endif + +#ifdef BW_PROBE +__global__ void bwp_rd_kernel(const uint4* __restrict__ p, size_t n16, unsigned* out) { + uint32_t a = 0; + for (size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x; i < n16; i += (size_t)gridDim.x * blockDim.x) { + uint4 v; asm volatile("ld.global.nc.L1::no_allocate.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(v.x), "=r"(v.y), "=r"(v.z), "=r"(v.w) : "l"(p + i)); + a ^= v.x ^ v.y ^ v.z ^ v.w; + } + if (a == 0x9e3779b9u) *out = a; +} +__global__ void bwp_rd8_kernel(const uint4* __restrict__ p, size_t n16, unsigned* out) { // 8 x 16 B in flight / thread + uint32_t a = 0; + const size_t st = (size_t)gridDim.x * blockDim.x; + for (size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x; i + 7 * st < n16; i += 8 * st) { + uint4 v[8]; +#pragma unroll + for (int k = 0; k < 8; ++k) asm volatile("ld.global.nc.L1::no_allocate.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(v[k].x), "=r"(v[k].y), "=r"(v[k].z), "=r"(v[k].w) : "l"(p + i + k * st)); +#pragma unroll + for (int k = 0; k < 8; ++k) a ^= v[k].x ^ v[k].y ^ v[k].z ^ v[k].w; + } + if (a == 0x9e3779b9u) *out = a; +} +void bwp_flush(const void* p, size_t bytes, unsigned* out, cudaStream_t s) { bwp_rd_kernel<<<148 * 8, 256, 0, s>>>((const uint4*)p, bytes / 16, out); } +void bwp_read(const void* p, size_t bytes, unsigned* out, int grid, int v8, cudaStream_t s) { + if (v8) bwp_rd8_kernel<<>>((const uint4*)p, bytes / 16, out); + else bwp_rd_kernel<<>>((const uint4*)p, bytes / 16, out); +} +#endif diff --git a/kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/src/kernel.h b/kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/src/kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e0282900b884977aae6ce2e520100ac2fd3618af --- /dev/null +++ b/kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/src/kernel.h @@ -0,0 +1,153 @@ +// Host-callable launchers implemented in kernel.cu (raw pointers; no torch types). +#pragma once +#include +#include +#include + +struct WSeg { // one bf16 weight [N,K] to quantize 128x128-blockwise + const void* src; // bf16 [N,K] row-major + void* dst; // fp8 base of destination (row offset applied via row_off) + float* sf; // SFB base, MN-major: sf[kb * ld_sf + nb] + int N, K, row_off, ld_sf; // row_off = destination row offset (concatenation) + int nblk_start; // prefix sum of 128x128 blocks (for flat grid) + int vrows = 0; // > 0: only rows < vrows get fp8 codes stored (kv_a pad rows 576..639 feed the amax only) + int f16 = 0; // 1: dst is fp16 [.,K]: DEQUANTIZED values fp8code*scale*2^s (quant_kernel only) + const unsigned* amax = nullptr; // f16: per-tensor |max| (fp32 bits) -> power-of-two prescale 2^s, s = pre_exp(amax) + unsigned long long dvm = 0; // exact multiply-shift reciprocal of K/128 (dvm40), filled by the launchers +}; + +struct ActJob { // optional 1x128 activation quant fused into the same launch + const void* x; // bf16 [M,K] + void* q; // fp8 [Mp,K] (rows >= M written as zeros) + float* sf; // MN-major [K/128][Mp] + int M, Mp, K; + int f16 = 0; // 1: q is fp16 [Mp,K]: DEQUANTIZED values fp8code*scale*2^s (quant_kernel only) + const unsigned* amax = nullptr; // f16: per-tensor |max| bits (prescale exponent source) + int rev = 0; // 1: CTAs walk the row blocks high -> low (last-written rows = lowest, L2-hot for GEMM1) + int late = 0; // 1: PDL launch_dependents after the final stores (aquant) instead of at entry + unsigned long long dvm = 0; // exact multiply-shift reciprocal of K/128 (dvm40), filled by the launchers +}; +// Exact unsigned division by a small divisor without a software divide: n / d == (n * dvm40(d)) >> 40 for +// d < 2^20 and n * d < 2^40 (m = floor(2^40/d) + 1 overshoots 2^40/d by e/d with e <= d, so the error n*e/(d*2^40) < 1/d). +inline unsigned long long dvm40(unsigned d) { return ((1ull << 40) / (unsigned long long)(d ? d : 1u)) + 1ull; } + +// One launch: quantizes nseg weights (128x128 blocks) and, if act != nullptr, the activation. +void launch_quant(const WSeg* segs, int nseg, int total_wblocks, const ActJob* act, cudaStream_t s, + float* alpha = nullptr); // alpha != nullptr (f16 path): writes 2^-(sA+sW) for the fp16 GEMM1 epilogue +// fp16 fake-quant path: out[0] = max|x[0:n0]|, out[1] = max(|w0[0:n1]|, |w1[0:n2]|) as fp32 bits (bf16 inputs, n* % 16 == 0). +void launch_amax(const void* x, size_t n0, const void* w0, size_t n1, const void* w1, size_t n2, unsigned* out, cudaStream_t s); +// Small-M variant: one persistent TMA-ring launch (2 CTAs/SM) over all weight segments + the activation. +// max_sms > 0: 1 CTA/SM variant on at most max_sms SMs (SM partitioning for concurrent launches). +void launch_pquant(const WSeg* segs, int nseg, int total_wblocks, const ActJob* act, cudaStream_t s, int max_sms = 0); +// RMSNorm + 1x128 requant. If nsplit > 0, y1 is produced here by summing nsplit fp32 split-K +// partials (part, stride Mp*ldy each) and rounding to bf16 (k_pe columns written to y1). +void launch_norm_quant(void* y1, int ldy, const float* part, int nsplit, + const void* wq, const void* wkv, + void* qq, float* qs, void* kq, float* ks, float eps, int Mp, cudaStream_t s, int rows = 0, + int rev = 0, int fast = 0); // fast: norm_fast_kernel<4> (non-split only); rev: rows processed high -> low (reverse of GEMM1's write order) // rows: grid (0 = Mp) +// Chunked large-M pipeline helpers. +void set_gemm1_sm_cap(int n); // CUTLASS GEMM1 persistent sm_count cap (0 = all) +void launch_act_capped(const ActJob* act, int ctas, cudaStream_t s); // act-only quant, persistent, <= ctas CTAs +// D[M,N](bf16,row-major) = blockwise-scaled FP8 GEMM of A[M,K] x B[N,K]^T +int launch_fp8_gemm(const void* A, const void* B, const float* SFA, const float* SFB, + void* D, int M, int N, int K, cudaStream_t s, int ws_slot); // ws_slot: per-stream workspace +int launch_fp8_gemm_sk(const void* A, const void* B, const float* SFA, const float* SFB, void* D, int M, int N, int K, + int two, int splits, cudaStream_t s, int ws_slot); // stream-K GEMM1 (see kernel.cu) +// 2-SM (2x1 cluster) variant, MMA tile 256 x tn (tn = 128 / 256); requires M % 256 == 0. +int launch_fp8_gemm_2sm(const void* A, const void* B, const float* SFA, const float* SFB, + void* D, int M, int N, int K, int tn, cudaStream_t s, int ws_slot); +// Split-K variant: D[S][M][N] fp32 partials, split s covers K range [s*K/S, (s+1)*K/S). +int launch_fp8_gemm_splitk(const void* A, const void* B, const float* SFA, const float* SFB, + float* D, int M, int N, int K, int S, cudaStream_t s, int ws_slot); +// Fake-quant GEMM1 path: D[M,N] bf16 = A[M,K](fp16) x B[N,K](fp16)^T, fp32 accumulate (CUTLASS SM100 +// tcgen05 f16 kernel, 2-SM cluster). variant 1: 256x128 tile, 2: 256x256 tile. +int launch_f16_gemm(const void* A, const void* B, void* D, int M, int N, int K, int variant, cudaStream_t s, int ws_slot, + const float* alpha_ptr); // D = (*alpha_ptr) * A x B^T (undoes the power-of-two operand prescales exactly) +// Custom persistent tcgen05 blockwise FP8 GEMM (used for q_b and kv_b): D[Mp,N] bf16 = A[Mp,K] x B[N,K]^T, +// SFA[kb*Mp + m], SFB[kb*(N/128) + nb]; Mp, N, K multiples of 128. +int launch_gq_gemm(const void* A, const void* B, const float* SFA, const float* SFB, void* D, int Mp, int N, int K, + cudaStream_t s, int max_ctas, int two = 0, + int hint = 0); // hint: 1 = output TMA stores with L2::evict_first // max_ctas: grid cap (0 = all SMs); two: 2-SM cta_group::2 256x256 (Mp%256==0) +// Two GEMMs (same Mp) in ONE persistent launch over a combined 128 x bn (128/256) tile list. epi >= 0: host LPT schedule +// with unit cost = K/128 + epi; epi < 0: round-robin. +int launch_gq_pair(const void* A0, const void* B0, const float* SFA0, const float* SFB0, void* D0, int N0, int K0, + const void* A1, const void* B1, const float* SFA1, const float* SFB1, void* D1, int N1, int K1, + int Mp, int epi, int bn, cudaStream_t st); +// Small M: fused [q_a|kv_a] weight quant (in-CTA, bit-identical 128x128 scheme) + split-K fp8 GEMM1 against the +// quantized activation xq/xs ([Mp,K] fp8, MN-major scales). Writes fp32 partials part[S][Mp][2176]. +int launch_fused_g1(const void* wqa, const void* wkva, const void* xq, const float* xs, float* part, int Mp, int K, + int S, cudaStream_t s); +void set_fg_pdl(int on); +// Late PDL trigger (small M): aquant / fg2 / split-K norm / pquant trigger launch_dependents after their final stores. +void set_late_trig(int on); +// small M: act-only aquant triggers its PDL dependent (fused GEMM1) at entry even under the late-trigger chain +void set_aq_early(int on); +// CUTLASS GEMM1 launched as a PDL dependent (GDC, CUTLASS_ENABLE_GDC_FOR_SM100) of its in-stream predecessor. +void set_g1_pdl(int on); // small-M fused path: PDL launch of fused GEMM1 + split-K norm (set around capture) +void set_fg_ver(int v); +void set_fg_whint(int on); // fused GEMM1: bf16 A-weight TMA loads with L2::evict_first (small M) +// Mid-M late-trigger PDL chain (wq bits 14-17): producer triggers of pquant/wquant, norm_fast early trigger, aquant PDL. +void set_pq_ptrig(int on); +void set_nf_etrig(int on); +void set_aq_pdl(int on); // fused GEMM1 kernel version: 2 (default) decoupled quant front end, 1 old lockstep +int fused_g1_splits(int Mp, int avail_sms, int K); // S so 17*G*S CTAs fit avail_sms (G = ceil(Mp/256)) +// Small M: fused B-weight quant (in-CTA, same scheme as pquant) + q_b (problem 0) / kv_b (problem 1) GEMMs in ONE +// persistent launch. w*: bf16 weights [N,K]; a*: fp8 normed activations [Mp,K] with scales sa*[kb*Mp+m]; d*: bf16 [Mp,N]. +int launch_fused_b(const void* w0, const void* w1, const void* a0, const float* sa0, const void* a1, const float* sa1, + void* d0, void* d1, int N0, int K0, int N1, int K1, int Mp, cudaStream_t st); +// Small M: L2 prefetch (cp.async.bulk.prefetch.L2) of the first `bytes` of [p0 (n0 bytes) | p1 (n1 bytes)]. +void launch_l2_prefetch(const void* p0, size_t n0, const void* p1, size_t n1, size_t bytes, int hint, cudaStream_t st); +// 1 (default): weights-only SM-capped launch_pquant uses the register-direct rquant_kernel; 0: pquant_kernel<2>. +void set_rquant(int on); +// wquant kernel version (probe / table): 0 = wquant_kernel +void set_wq_ver(int v); +// Mid/large M: TMA-in / TMA-store weight quant on `ctas` SMs (1 CTA/SM, 6x32 KB ring), co-runs with capped GEMM1. +void launch_wquant(const WSeg* segs, int nseg, int total_wblocks, int ctas, cudaStream_t s, int dry = 0, + unsigned long long* done = nullptr, unsigned long long* done0 = nullptr); // done: += jobs per finished consumer group (release, after stores) +// gq launches: in-kernel wait for *cnt >= (*ep) * per before the first TMA (nullptr = off) +void set_gq_wdep(const unsigned long long* cnt, const unsigned long long* ep, unsigned long long per); +// norm_quant_kernel: ep != nullptr -> one atomic increment per launch (replay epoch) + end-of-kernel PDL trigger +void set_norm_epoch(unsigned long long* ep); +void set_norm_early(int on); // with set_norm_epoch: entry (not late) PDL trigger +// Tunable kernel-internal knobs (offline-autotuned per M, see main.cpp kCfg): +void set_gq_raster(int r); // gq tile raster: 0 n-fastest (row-major), 1 m-fastest (N-major), 2/3/4 grouped gm = 2/4/8 m-blocks +void set_gemm1_sched(int v); // CUTLASS GEMM1 tile scheduler: 0 default, else raster*16 + max_swizzle (raster 1 AlongM, 2 AlongN) +void set_gq_npw(int n); +// 1: following 2-SM npw8 q_b/kv_b gq launches (Mp % 512 == 0) use 4-CTA clusters with B-operand TMA multicast (mode bit5 q_b, bit6 kv_b) +void set_gq_mc(int on); // promotion warps of the single-problem BN = 256 gq kernels: 16 (default) or 8 +// PDL (programmatic stream serialization) on the following gq GEMM launches (q_b after the norm); see g_pdl in kernel.cu. +void set_pdl(int on); +// gq q_b/kv_b: 1 = m-blocks traversed high -> low (start on the rows the norm wrote last); applied to launch_gq_gemm only. +void set_gq_mrev(int on); +// q_b -> kv_b PDL chain on one stream: nowait = skip griddepcontrol.wait, trig = early launch_dependents (next gq launches). +void set_gq_pdlchain(int nowait, int trig); +// GEMM1 on the 2-SM gq kernel (ragged N = nout used columns, B rows brows, weight-scale pitch ldsb; Mp % 256 == 0). +int launch_gq_g1(const void* A, const void* B, const float* SFA, const float* SFB, void* D, int Mp, int nout, int brows, + int K, int ldsb, cudaStream_t st, int max_ctas, int rast = -1); // rast >= 0 overrides the gq raster +// Max co-resident 2x1 clusters of the 2-SM gq kernel (idle GPU). +int gq_max_clusters(); + +// Large M (wq bit19): GEMM1 row-block completion counters -> norm_fast row-granular dependency (see kernel.cu). +void set_quant_g1cnt(unsigned* p, int n); // quant_kernel block 0 zeroes p[0..n) each replay +void set_g1_mcnt(unsigned* p); +void set_g1_ss(int on); // gq GEMM1: 1 = GV_SS variant (5-stage operand ring, single-buffered output staging) // gq GEMM1 store warp: +1 per finished tile at p[m0/128] +void set_norm_mcnt(const unsigned* p, unsigned tgt); // norm_fast waits p[row/128] >= tgt instead of griddepcontrol.wait + +// Large M (wq bit29): quant_kernel early PDL trigger + per-row-block completion counters -> GEMM1 (gq) starts on +// quantized rows while the quant grid drains (see kernel.cu QuantParams::acnt). +void set_quant_early(unsigned* acnt, unsigned* wdn); +void set_g1_early(const unsigned* acnt, unsigned atgt, const unsigned* wdn, unsigned wtgt); +void set_gq_rst(unsigned* p, int n); // next q_b/kv_b gq launch zeroes p[0..n) after its predecessor wait + +// Large M: A-weight 128x128 + activation 1x128 quant in one persistent TMA-in / TMA-store launch (aqt_kernel). +void launch_quant_tma(const WSeg* segs, int nseg, int total_wblocks, const ActJob* act, int ctas, cudaStream_t s); +void set_aqt(int on); +int get_aqt(); +// Small M: fused quantize-on-load q_b GEMM (bf16 weights quantized in-CTA, wquant<7> math), grid persistent CTAs. +int launch_fq_gemm(const void* W, const void* A, const float* SA, void* D, int Mp, int N, int K, int grid, cudaStream_t st, + int pdl); + +// combined small-M gq launch: q_b (problem 0) units wait for the wquant segment-0 counter (nullptr = off) +void set_gq_wdep0(const unsigned long long* cnt0, unsigned long long per0); +// combined small-M gq launch: GV_DYN dynamic unit claiming (claim counter = epoch[2], zeroed by the norm) +void set_gq_dyn(int on); diff --git a/kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/src/main.cpp b/kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/src/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..793aa063e7f8d3363cfdff8b3d0c00344907326e --- /dev/null +++ b/kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/src/main.cpp @@ -0,0 +1,1049 @@ +// M128: aq 0-3 | fg2 GEMM1 4-27/30 | B wquant 0-36 | split norm 29-34 | combined gq 34-48 (Bq + gq critical) +// M256: pquant(A+act) 0-20 | CUTLASS split-K GEMM1 20-38 | norm 38-40 | B wquant 0-41 | q_b 40-58, kv_b 44-60 +// M512: pquant 0-20 | CUTLASS 2-SM GEMM1 20-37 | norm_fast 38-41 | B wquant 0-41 | kv_b 42-71, q_b 45-73 +// +// Two-stream schedule (events for dependencies): +// main : [quant Wa (q_a|kv_a) + act] [GEMM1 (split-K if small M)] [norm(+split reduce)+requant] ev_norm +// (wait ev_wb)[q_b GEMM] (wait ev_kv) +// side : (wait ev_start)[quant W_qb + W_kvb] ev_wb ....... (wait ev_norm)[kv_b GEMM] ev_kv +// The B-weight quantization overlaps the A path / GEMM1, and the kv_b GEMM overlaps the q_b GEMM. +// +#include +#include +#include +#include +#include +#include +#include "kernel.h" +void set_aqt_dyn(unsigned* p); +void set_aqt_apol(int v); // aqt fp8 act stores: 1 = L2 evict_normal (M >= 16384 only) +void set_fg_early(int on); // fused GEMM1 (fg2) early PDL trigger (see kernel.cu) +void set_wq_lastj(int v); +void set_wq_jc(int v); +void set_wq_rev0(int v); // M=128: q_b wquant blocks in reverse order (L2 recency for gq) +void set_wq_ver(int v); +#ifdef BW_PROBE +void bwp_flush(const void* p, size_t bytes, unsigned* out, cudaStream_t s); +void bwp_read(const void* p, size_t bytes, unsigned* out, int grid, int v8, cudaStream_t s); +#endif // wquant job chunk: 4 = 128x512 per-CTA runs (M=128 row) +void set_nf_rows(int r); +void set_nf_mb(int m); +void set_nf_lean(int v); // 1 (default): lean norm_fast (bit-identical register/instruction diet), 0: previous code // norm_fast min blocks per SM (__launch_bounds__): 1 default, 5/6/8 (R=4), 3/4 (R=8), 8 (R=2) +// mode bit11 / bit12: q_b / kv_b weight TMA loads with L2::evict_last; bit13: their activation loads too (2-SM gq) +void set_gq_lpol(int v); +void set_gq_pp(int on); +void set_gq_ar(int on); // mid-M kv_b (K=512): 2-SM gq A-operand reuse over two n-tiles (GV_AR, bit-identical) // large-M q_b: 2-SM gq warpgroup ping-pong (GV_PP, bit-identical) +void set_g1_lpol(int v); +void set_g1_sl(int on); // gq GEMM1 y1 TMA stores L2 evict_last (M >= 16384 row) +void set_g1_bn192(int on); +void set_g1_l3(int on); +void set_g1_mc(int on); // M=8192 row BN=192 GEMM1: 4-CTA clusters with B multicast (bit-identical) // BN = 192 GEMM1: single-wait TMEM promotion (GV_L3) +#include +#include +#include +#include +#include + + +#define TLR(s, n) + +struct Sync { // heap-allocated, never destroyed (no teardown-time CUDA calls) + cudaEvent_t ev_start, ev_wb, ev_norm, ev_kv; + cudaStream_t cs, ss; // capture (origin) stream and side stream + cudaStream_t ss_hi; // highest-priority twin of ss (Entry::prio 1) + cudaStream_t qs; // chunked large-M pipeline: act quant (chunk i+1) + norm (chunk i-1) stream + cudaEvent_t ev_q0, ev_nd, ev_a[8], ev_g[8]; // chunk pipeline dependencies + int nsm = 148; + Sync() { + int dev; cudaGetDevice(&dev); + cudaDeviceGetAttribute(&nsm, cudaDevAttrMultiProcessorCount, dev); + cudaEventCreateWithFlags(&ev_start, cudaEventDisableTiming); + cudaEventCreateWithFlags(&ev_wb, cudaEventDisableTiming); + cudaEventCreateWithFlags(&ev_norm, cudaEventDisableTiming); + cudaEventCreateWithFlags(&ev_kv, cudaEventDisableTiming); + cudaStreamCreateWithFlags(&cs, cudaStreamNonBlocking); + cudaStreamCreateWithFlags(&ss, cudaStreamNonBlocking); + { int lo = 0, hi = 0; cudaDeviceGetStreamPriorityRange(&lo, &hi); // per-M branch priority (Entry::prio) + cudaStreamCreateWithPriority(&ss_hi, cudaStreamNonBlocking, hi); } + cudaStreamCreateWithFlags(&qs, cudaStreamNonBlocking); + cudaEventCreateWithFlags(&ev_q0, cudaEventDisableTiming); + cudaEventCreateWithFlags(&ev_nd, cudaEventDisableTiming); + for (int i = 0; i < 8; ++i) { + cudaEventCreateWithFlags(&ev_a[i], cudaEventDisableTiming); + cudaEventCreateWithFlags(&ev_g[i], cudaEventDisableTiming); + } + } +}; + +using Key = std::array; +struct Entry { // per-M graph + workspace (heap, never freed) + uint8_t* ws = nullptr; + cudaGraphExec_t exec = nullptr; + Key key{}; + int qcta = -1; // q_b CTAs when co-running (kv_b gets nsm-qcta); 0 = full grids; -1 = untuned + int cap_g1 = -1; // GEMM1 variant the current exec was built with + int g1 = 0; // GEMM1 non-split variant: 0 CUTLASS 1-SM 128x128, 1 2-SM 256x128 + int qsp = 0; // small M: SMs given to the B-weight quant (0 = one fused quant launch) + int cap_qsp = -1; // qsp the current exec was built with + int S = 0; // GEMM1 split-K factor (0 = default rule; mid M swept by whole-graph timing) + int cap_S = -1; // split factor the current exec was built with + int f16 = 0; // Mp >= 1024: GEMM1 fake-quant fp16 variant (0 off, 1 2-SM 256x128, 2 2-SM 256x256) + int cap_f16 = -1; // f16 variant the current exec was built with + int fg = 1; // small M: 1 = fused A-weight quant + split-K GEMM1 kernel, 0 = pquant(A) + CUTLASS split-K + int cap_fg = -1; // fg the current exec was built with + int mode = 0; // gq kernel variant: bit0 q_b, bit1 kv_b use the 2-SM cta_group::2 kernel (Mp%256==0), + // bit2: q_b/kv_b output TMA stores with L2::evict_first + // bit3 / bit4: 8 promotion warps for q_b / kv_b (BN = 256 / 2-SM gq kernels; bit-identical) + int cap_mode = -1; // mode the current exec was built with + int fb = 0; // small M: 1 = fused B-weight quant + q_b/kv_b GEMM kernel (implies fg = 1, qsp = 0) + int cap_fb = -1; // fb the current exec was built with + int pf = 0; // fb path: B-weight L2 prefetch, MB | (evict_last hint << 16); 0 = off + int cap_pf = -1; // pf the current exec was built with + int chunks = 0; // large M: M-chunk software pipeline (0/1 = off, else C chunks of Mp/C rows) + int qa = 0; // chunk pipeline: SMs left free of GEMM1 for the next chunk's act quant / norm + int cap_chunks = -1, cap_qa = -1; + int bqs = 0; // non-fused M: SMs for the TMA weight quant of q_b/kv_b co-running with capped GEMM1 (0 = old path) + int cap_bqs = -1; + int wq = 0; // TMA-in/TMA-store wquant_kernel use: bit0 small-M side-stream B quant (qsp SMs), + // bit1 non-fused A-weight quant (+ separate act quant), bit2 non-fused full-GPU side-stream B quant, + // bit3 act quant concurrent with A wquant, bit7 q_b PDL launch after the norm + int cap_wq = -1; + int gqr = 0; // gq tile raster (set_gq_raster) + int g1r = 0; // CUTLASS GEMM1 scheduler raster/swizzle (set_gemm1_sched) + int sk = 0; // small M (Mp <= 512): GEMM1 split-K override (0 = default rule) + int cap_gqr = -1, cap_g1r = -1, cap_sk = -1; + int rv = 0; // producer->consumer L2 reuse by traversal order (non-fused path; bit-identical outputs): + // bit0 act 1x128 quant walks row blocks high -> low (GEMM1 consumes low -> high: starts on + // the L2-hot rows), bit1 RMSNorm+requant rows high -> low (GEMM1's last-written rows first), + // bit2 q_b/kv_b gq m-blocks start where the norm ended (reversed m iff bit1 is off) + int cap_rv = -1; + // Steady-state graph cache: one instantiated exec per pointer set (Key) of this M, LRU-replaced. Outputs are fresh + // at::empty tensors each call, so when the caller keeps previous outputs alive the caching allocator hands out a few + // rotating address sets; each set keeps its own exec (no re-capture / cudaGraphExecUpdate in the timed loop). + int nq = 0; // non-split RMSNorm: 1 = norm_fast_kernel<4> (4 rows/CTA, packed rcp+FMA quant) + int cap_nq = -1; + // Graph-branch priority: 1 = side branch (B-weight quant / kv_b, stream ss) captured on a HIGHEST-priority stream and + // the graph instantiated with cudaGraphInstantiateFlagUseNodePriority (deterministic SM placement of the two + // co-running branches; M=512 row only). 0 = plain. + int prio = 0; + int fgh = 0; // small M fused GEMM1: bf16 A-weight TMA loads with L2::evict_first (first-call head-to-head) + int cap_prio = -1; + int fq = 0; // small M: q_b via the fused quantize-on-load fq kernel on fq CTAs (0 = fp8 gq path) + int cap_fq = -1; + int g1lp = 0; // gq GEMM1 (g1 8/9) operand loads evict_last: bit0 B weights, bit1 A activation + int g1ss = -1; // gq GEMM1 GV_SS override (-1 = default rule Mp <= 4096) + int g1ra = -1; // gq GEMM1 raster override when not forced by g1m_on (-1 = global gqr) + int cap_g1lp = -1, cap_g1ss = -2, cap_g1ra = -2; + // wq bit26 q_b+kv_b pair launch: unit raster override (-1 = global gqr; 2/3/4 = grouped raster, gm = 2/4/8 m-pair + // blocks per group, m fastest inside the group: concurrently running clusters share B column panels while only + // gm*256 A rows are live). Fixed: -1 (table raster; no runtime selection). Bit-identical. + int pgr = -1, cap_pgr = -2; + int nfb = 0; // norm_fast __launch_bounds__ min blocks per SM (0 = default 1; see set_nf_mb) + int cap_nfb = -1; + struct Slot { Key key; cudaGraphExec_t exec; unsigned long long t; }; + std::vector slots; + unsigned long long tick = 0; +}; +static constexpr size_t kMaxSlots = 16; +static constexpr int kMergeTag = 2; // merge re-sample marker (unused) +static constexpr int kFGM = 1 << 20; +static constexpr int kNQE = 1 << 22; // wq bit22: norm keeps its entry PDL trigger under the bit18 epoch +static constexpr int kKVF = 1 << 23; +static constexpr int kG1ET = 1 << 24; // wq bit24 (large M, with bit19): GEMM1 gq triggers launch_dependents right after + // griddepcontrol.wait, so norm_fast CTAs fill GEMM1's last-wave tail (row counters gate them) +static constexpr int kQE = 1 << 29; // wq bit29 (with bit19 + bit10): quant_kernel early trigger + row-block counters -> + // gq GEMM1 starts on already-quantized rows while the quant grid drains +static constexpr int kDYN = 1 << 27; // wq bit27 (small M, combined gq + bit18): GV_DYN dynamic tile claiming +static constexpr int kFGH = 1 << 30; // wq bit30 (small M fused GEMM1): bf16 A-weight TMA loads with L2::evict_first (en.fgh) +static constexpr int kOWQ = 1 << 28; // wq bit28: legacy wquant_kernel<0> (lockstep TMA-store epilogue) instead of <6> +static constexpr int kQET = 1 << 25; // wq bit25 (bit9 chain): first gq triggers early -> second gq fills its tail // wq bit23 (with bit21): kv_b launched first in the chain +static constexpr int kPAIR = 1 << 26; // wq bit26 (large M, full grids, MODE 2-SM npw8 both): q_b + kv_b in ONE 2-SM launch +int launch_gq_two_pair(const void* A0, const void* B0, const float* SFA0, const float* SFB0, void* D0, int N0, int K0, + const void* A1, const void* B1, const float* SFA1, const float* SFB1, void* D1, int N1, int K1, + int Mp, int hint, cudaStream_t st); +static constexpr int kKVCH = 1 << 21; // wq bit21: q_b -> kv_b PDL chain off the norm (with bit18), see gemm_b // wq bit20: mid-M fused A-weight quant + split-K GEMM1 + +struct Cfg { int Mp, qcta, g1, S, bqs, wq, fb, fg, qsp, pf, mode, chunks, qa, gqr, g1r, sk, rv, nq, prio; int fq = 0; int nfb = 0; }; +static const Cfg kCfg[] = { + {128, 2, 0, 0, 0, 263425 | kDYN | kFGH | kNQE, 0, 1, 80, 0, 8, 0, 0, 0, 0, 0, 0, 0, 1}, + {256, 96, 0, 0, 0, (14944257 & ~(1 << 23)) | 16384, 0, 0, 80, 0, 31, 0, 0, 0, 0, 2, 0, 0, 1}, // prio 1: side branch high + {512, 96, 1, 0, 0, 15187969 & ~(1 << 22), 0, 0, 66, 0, 31, 0, 0, 0, 0x12, 1, 0, 2, 1}, // nq 2: lean norm_fast<2> (bit-identical to norm_quant) // prio 1: side branch high + {1024, 100, 8, 1, 76, 17548416 | 2048 | (1 << 18), 0, 1, 0, 0, 27, 0, 0, 1, 0x22, 0, 4, 2, 0, 0, 5}, // nfb 5: norm_fast<2> __launch_bounds__(256,5) + {2048, 0, 8, 1, 60, 17304704 | 65536 | (1 << 18) | (1 << 21) | (1 << 22) | (1 << 26), 0, 1, 0, 0, 31 | (1 << 21), 0, 0, 1, 0x11, 0, 5, 1, 0, 0, 4}, // nfb 4: norm_fast __launch_bounds__(256,4) behind the GEMM1 tail (as 4096+); rv 5: act quant rows high->low (L2-hot for GEMM1 start), gq m reversed + {4096, 0, 8, 0, 30, 32250880 & ~((1 << 18) | (1 << 21) | (1 << 22) | (1 << 23)), 0, 1, 0, 0, 31 | (1 << 21) | (1 << 22), 0, 0, 1, 0x12, 0, 7, 1, 3, 0, 4}, // prio 3: q_b PDL dependent of norm_fast (cs), kv_b on normal side stream; mode bit2 ported from the 8192 row: q_b/kv_b output stores L2 evict_first // nfb 4 (norm_fast 4 CTAs/SM behind GEMM1 tail, as 16384); prio 2: q_b on high-priority side stream, kv_b on main fills its tail (pair launch / norm chain bits dropped so the prio-2 co-run path applies) + {8192, 0, 9, 0, 20, 25713920, 0, 1, 0, 0, 31 | (1 << 21), 0, 0, 1, 0x24, 0, 5, 1, 3, 0, 4}, // prio 3 (q_b PDL off the norm); nfb 4: norm_fast __launch_bounds__(256,4) (64 regs, 4 CTAs/SM), as 16384 + {16384, 0, 9, 0, 20, 17309568 & ~(512 | 128), 0, 1, 0, 0, 31 | 8192, /* GEMM1 on 2-SM 256x256 pair tiles (9 n-tiles: 8 full + ragged tail) instead of 256x192 (11): fewer A re-reads; bit-identical */ 0, 0, 1, 0x22, 0, 7, 1, 3, 0, 4}, + +}; +// Applies the table row nearest (log distance on Mp) WITHIN the same regime (Mp <= 512: fused small-M path; +// else non-fused path) and drops options that the given Mp cannot use. Returns false if the table is empty. +static bool apply_cfg(Entry& en, int Mp, bool mid_split) { + const int n = sizeof(kCfg) / sizeof(kCfg[0]); + int best = -1; double bd = 1e30; + for (int i = 0; i < n; ++i) { + if (kCfg[i].Mp <= 0 || ((kCfg[i].Mp <= 512) != (Mp <= 512))) continue; + const double d = std::fabs(std::log((double)kCfg[i].Mp / (double)Mp)); + if (d < bd) { bd = d; best = i; } + } + if (best < 0) return false; + const Cfg& c = kCfg[best]; + en.qcta = c.qcta; en.g1 = c.g1; en.S = c.S; en.bqs = c.bqs; en.wq = c.wq; en.fb = c.fb; en.fg = c.fg; + en.qsp = c.qsp; en.pf = c.pf; en.mode = c.mode; en.chunks = c.chunks; en.qa = c.qa; + en.gqr = c.gqr; en.g1r = c.g1r; en.sk = Mp <= 512 ? c.sk : 0; + en.rv = Mp <= 512 ? 0 : c.rv; + en.nq = c.nq; // non-split small M (M=512 row) may use norm_fast too + en.prio = c.prio; + en.fq = Mp <= 512 ? c.fq : 0; + en.nfb = Mp <= 512 ? 0 : c.nfb; + // M=16384 brainstorm pick: GEMM1 (gq 256x192) fp8 [q_a|kv_a] weight TMA loads with L2::evict_last (15.6 MB re-read by + // all 64 m-pairs while 117 MB of fp8 activation streams through L2). Cache policy only: bit-identical. + en.g1lp = Mp >= 8192 ? 1 : 0; + if (Mp <= 512 && (en.wq & kFGH)) en.fgh = 1; + if (Mp % 256) { en.g1 = en.g1 >= 8 ? 0 : en.g1 >= 2 ? 2 + (((en.g1 - 2) >> 1) << 1) : 0; en.mode &= 28; en.chunks = 0; } // 2-SM GEMM1 / gq need Mp % 256 == 0 + if (!mid_split && en.S > 1) en.S = 0; // split-K partials sized only for mid M + if (en.S > 1) en.g1 = 0; + if (en.chunks > 1 && Mp % (256 * en.chunks)) en.chunks = 0; + return true; +} +static std::string& g_wqrep = *new std::string(); + +// Output view without a dispatcher call: new TensorImpl on the shared storage of `base` with explicit sizes / strides / +// storage offset (exactly what as_strided produces for these in-bounds, non-grad bf16 outputs). +static int g_fv = 1; +static inline at::Tensor mkview(const at::Tensor& base, c10::IntArrayRef sz, c10::IntArrayRef st, int64_t off) { + at::Tensor t = at::detail::make_tensor(c10::Storage(base.storage()), base.key_set(), base.dtype()); + t.unsafeGetTensorImpl()->set_sizes_and_strides(sz, st, off); + return t; +} + +void set_nf_pers(unsigned* claim, int mb); +void set_act_tiled(int on); // aqt -> BN=192 gq GEMM1: fp8 act stored as contiguous pre-swizzled 16 KB tiles // persistent row-gated norm (kernel.cu norm_pers_kernel) +static std::vector run(at::Tensor hidden_states, at::Tensor q_a_proj_weight, + at::Tensor q_a_layernorm_weight, at::Tensor q_b_proj_weight, + at::Tensor kv_a_proj_weight, at::Tensor kv_a_layernorm_weight, + at::Tensor kv_b_proj_weight, double rms_norm_eps) { + static Sync& sy = *new Sync(); + static std::map& cache = *new std::map(); + + const int64_t B = hidden_states.size(0), L = hidden_states.size(1), H = hidden_states.size(2); + const int M = (int)(B * L); + const int Mp = (M + 127) / 128 * 128; // pad rows to the GEMM tile; pad rows are zeros + const int QR = 1536, KR = 512, NA = 1536 + 640, NY = 1536 + 576, NQ = 24576, NKV = 32768; + // g1 == 8: GEMM1 on the custom 2-SM gq kernel (256x256 pair tiles, 8 promotion warps, ragged N = 2112 over 9 tiles); + // its A-weight scales use a padded per-k-block pitch kG1Ld = 20 (16-B aligned 4-scale chunks); CUTLASS paths use 17. + constexpr int kG1Ld = 20; + int g1cap = 0; // GEMM1 SM cap (BQ co-run) for the gq GEMM1 launch + cudaStream_t ms = at::cuda::getCurrentCUDAStream().stream(); + // Host-latency diet: inputs are normally already contiguous; TensorImpl::is_contiguous() is an inline flag read, + // while Tensor::contiguous() is a dispatcher round trip per tensor (7 per call). Same tensors / pointers. + auto ctg = [](const at::Tensor& t) -> at::Tensor { return t.is_contiguous() ? t : t.contiguous(); }; + const at::Tensor x = ctg(hidden_states); + const at::Tensor wqa = ctg(q_a_proj_weight), wkva = ctg(kv_a_proj_weight); + const at::Tensor wqb = ctg(q_b_proj_weight), wkvb = ctg(kv_b_proj_weight); + const at::Tensor lnq = ctg(q_a_layernorm_weight), lnkv = ctg(kv_a_layernorm_weight); + +#ifdef BW_PROBE + { + const size_t nq = (size_t)24576 * 1536, nkv = (size_t)32768 * 512; + uint8_t *dq, *dkv, *fl; float *sq, *skv; unsigned* junk; + cudaMalloc(&dq, nq); cudaMalloc(&dkv, nkv); cudaMalloc(&sq, 12 * 192 * 4); cudaMalloc(&skv, 4 * 256 * 4); + cudaMalloc(&fl, (size_t)256 << 20); cudaMalloc(&junk, 64); cudaMemset(fl, 1, (size_t)256 << 20); + WSeg sg[2]; memset(sg, 0, sizeof(sg)); + sg[0].src = wqb.data_ptr(); sg[0].dst = dq; sg[0].sf = sq; sg[0].N = 24576; sg[0].K = 1536; sg[0].ld_sf = 192; sg[0].nblk_start = 0; + sg[1].src = wkvb.data_ptr(); sg[1].dst = dkv; sg[1].sf = skv; sg[1].N = 32768; sg[1].K = 512; sg[1].ld_sf = 256; sg[1].nblk_start = 192 * 12; + const int nblk = 192 * 12 + 256 * 4; + cudaStream_t st; cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking); + cudaEvent_t e0, e1; cudaEventCreate(&e0); cudaEventCreate(&e1); + std::string rep = "BWPROBE"; + auto tm = [&](const char* nm, double mb, auto fn) { + std::vector v; + for (int r = 0; r < 10; ++r) { + bwp_flush(fl, (size_t)256 << 20, junk, st); + cudaEventRecord(e0, st); fn(); cudaEventRecord(e1, st); cudaEventSynchronize(e1); + float ms; cudaEventElapsedTime(&ms, e0, e1); if (r) v.push_back(ms); + } + std::sort(v.begin(), v.end()); + const double us = v[v.size() / 2] * 1000.0; + char b[160]; snprintf(b, 160, " |%s %.1fus %.2fTB/s", nm, us, mb / us / 1e6 * 1e6 / 1e6); + rep += b; + }; + const double RB = (double)(nq + nkv) * 2.0, WB = (double)(nq + nkv); + for (int jc = 1; jc <= 4; jc += 3) { + set_wq_ver(3); set_wq_jc(jc); set_wq_lastj(2560); + for (int c : {148, 80, 74}) { + char nm[64]; + snprintf(nm, 64, "wq jc%d c%d rw", jc, c); tm(nm, RB + WB, [&] { launch_wquant(sg, 2, nblk, c, st, 0); }); + snprintf(nm, 64, "wqDRY1(TMAread) jc%d c%d", jc, c); tm(nm, RB, [&] { launch_wquant(sg, 2, nblk, c, st, 1); }); + snprintf(nm, 64, "wqDRY2(nostore) jc%d c%d", jc, c); tm(nm, RB, [&] { launch_wquant(sg, 2, nblk, c, st, 2); }); + } + } + set_wq_jc(1); set_wq_lastj(0); + for (int g : {148 * 2, 148 * 4, 80 * 4}) { + char nm[64]; + snprintf(nm, 64, "ldread g%d", g); tm(nm, (double)nq * 2, [&] { bwp_read(wqb.data_ptr(), nq * 2, junk, g, 0, st); }); + snprintf(nm, 64, "ld8read g%d", g); tm(nm, (double)nq * 2, [&] { bwp_read(wqb.data_ptr(), nq * 2, junk, g, 1, st); }); + } + cudaError_t pe = cudaDeviceSynchronize(); + rep += " err="; rep += cudaGetErrorString(pe); + TORCH_CHECK(false, rep); + } +#endif + + // ---- split-K factor for GEMM1: only 17*(Mp/128) output tiles; split K=7168 (56 k-blocks) so + // ~136 CTAs stream the A-weights. S must divide 56. + const int tiles1 = (Mp / 128) * (NA / 128); + int S = 1; + const int cand[4] = {8, 4, 2, 1}; + for (int c : cand) { if (tiles1 * c <= 148 && ((int)(H / 128)) % c == 0) { S = c; break; } } + // Mid M (Mp in [640, 2048]): 136..272 GEMM1 tiles of 56 k-blocks each -> poor wave fill (0.9-1.8 waves). + // Split-K S in {1, 2, 4} (fp32 partials reduced in the norm kernel) is chosen per M by whole-graph timing. + const bool mid_split = Mp >= 640 && Mp <= 2048 && (int)(H / 128) % 4 == 0; + // small M: the fused quant+GEMM1 kernel uses up to nsm/17 splits (G = 1); size the partials for that + const int Smax = Mp <= 512 ? std::max(1, std::min((int)(H / 128), sy.nsm / 17)) : (mid_split ? 4 : S); + + // ---- workspace layout for all intermediates (256B-aligned carve-outs) + size_t off = 0; + auto carve = [&](size_t bytes) { size_t o = off; off += (bytes + 255) & ~size_t(255); return o; }; + const size_t o_waq = carve((size_t)NA * H), o_was = carve((size_t)(H / 128) * kG1Ld * 4); // pitch 20 >= NA/128 (gq GEMM1 layout) + const size_t o_wqbq = carve((size_t)NQ * QR), o_wqbs = carve((size_t)(QR / 128) * (NQ / 128) * 4); + const size_t o_wkbq = carve((size_t)NKV * KR), o_wkbs = carve((size_t)(KR / 128) * (NKV / 128) * 4); + const size_t o_xq = carve((size_t)Mp * H), o_xs = carve((size_t)(H / 128) * Mp * 4); + const size_t o_qaq = carve((size_t)Mp * QR), o_qas = carve((size_t)(QR / 128) * Mp * 4); + const size_t o_kvq = carve((size_t)Mp * KR), o_kvs = carve((size_t)(KR / 128) * Mp * 4); + // fake-quant GEMM1 operands (dequantized fp16 act [Mp,H] and [q_a|kv_a] weights [NA,H]), Mp >= 1024 only + constexpr bool kF16Gemm1 = false; + const bool f16_ok = kF16Gemm1 && Mp >= 1024; + const size_t o_xh = carve(f16_ok ? (size_t)Mp * H * 2 : 0), o_wah = carve(f16_ok ? (size_t)NA * H * 2 : 0); + const size_t o_part = carve(Smax > 1 ? (size_t)Smax * Mp * NY * 4 : 0); + // fp16 path: [0] = max|x| bits, [1] = max|[q_a|kv_a]| bits, [2] = GEMM1 epilogue alpha = 2^-(sA+sW) (float) + const size_t o_amax = carve(16); + // small-M in-kernel B-quant dependency (wq bit18): [0] wquant completion counter (+jobs), [1] per-replay epoch (norm) + const size_t o_sync = carve(48); // [2]: wquant segment-0 (q_b) completion counter + // large M (wq bit19): per-128-row GEMM1 tile-completion counters (zeroed by quant_kernel every replay) + // [0, nrb) GEMM1 tile counters (norm_fast), [nrb, 2 nrb) quant row-block counters + [2 nrb] weight counter (wq bit29) + const size_t o_g1c = carve((size_t)(2 * (Mp / 128) + 1) * 4); + const size_t o_dyn = carve(16); // aqt dynamic job claim counters (zeroed once; the kernel resets them) + + const bool fused_quant = Mp <= 512; // small M: single persistent quant launch + Entry*& ep = cache[M]; + if (!ep) { + ep = new Entry(); + cudaError_t e = cudaMalloc((void**)&ep->ws, off); + TORCH_CHECK(e == cudaSuccess, "workspace alloc failed"); + cudaMemset(ep->ws + o_sync, 0, 48); + cudaMemset(ep->ws + o_dyn, 0, 16); + cudaMemset(ep->ws + o_g1c, 0, (size_t)(2 * (Mp / 128) + 1) * 4); // early-start counters (reset per replay by q_b/kv_b) // counters start at 0 (then only ever incremented, once per replay / job) + cudaDeviceSynchronize(); + TORCH_CHECK(apply_cfg(*ep, Mp, mid_split), "no schedule table row"); // hardcoded per-M schedule + } + Entry& en = *ep; + if (en.S > 0) S = en.S; + // small-M non-fused GEMM1: split override + if (Mp <= 512 && en.sk > 0 && !en.fg && en.sk <= Smax && ((int)(H / 128)) % en.sk == 0) S = en.sk; + int F16 = en.f16; // used by capture()/gemm1(); F16 > 0 implies S == 1 + int MODE = en.mode; + const int PPQ = (Mp >= 1024 && Mp < 8192) || Mp >= 16384 ? 1 : 0; // M=16384: GV_PP 2x128-col TMEM half slots // M >= 8192: q_b plain 2-SM npw8 (as 16384), bit-identical // M >= 16384: q_b plain 2-SM npw8 (single N=256 MMA per k-step), bit-identical + const int NPERS = 0; // Mp >= 16384: persistent row-gated norm, 4 CTAs/SM (bit-identical) // mid/large-M q_b (2-SM npw8 launches): GV_PP warpgroup ping-pong (bit-identical) // used by gemm_b(): 2-SM gq variant per GEMM + uint8_t* wb = en.ws; + auto P8 = [&](size_t o) { return (void*)(wb + o); }; + auto PF = [&](size_t o) { return (float*)(wb + o); }; + + // ---- outputs (fresh tensors each call) + // Host-latency diet: ONE caching-allocator call for all three outputs (y1 [Mp,NY] | q [Mp,NQ] | kv [Mp,NKV], bf16, + // contiguous, every sub-buffer 256-B aligned since Mp % 128 == 0); the kernels only need raw pointers, and the five + // returned outputs are built with one as_strided each (instead of 3 at::empty + 11 narrow/view dispatcher calls). + struct OutPtr { void* p; void* data_ptr() const { return p; } }; + // Host-latency diet: the output storage comes straight from the CUDA caching allocator (same allocator, same + // current-stream association as at::empty) and is wrapped in a TensorImpl without a dispatcher round trip. + at::Tensor obuf; + { + const size_t nbytes = (size_t)Mp * (NY + NQ + NKV) * sizeof(uint16_t); + c10::Allocator* alloc = c10::cuda::CUDACachingAllocator::get(); + c10::Storage stor(c10::Storage::use_byte_size_t(), nbytes, alloc->allocate(nbytes), alloc, /*resizable=*/false); + obuf = at::detail::make_tensor(std::move(stor), c10::DispatchKeySet(c10::DispatchKey::CUDA), + caffe2::TypeMeta::Make()); + obuf.unsafeGetTensorImpl()->set_sizes_contiguous({(int64_t)Mp * (NY + NQ + NKV)}); + } + uint16_t* obase = (uint16_t*)obuf.data_ptr(); + const OutPtr y1{obase}, q{obase + (size_t)Mp * NY}, kv{obase + (size_t)Mp * (NY + NQ)}; + + float epsf = (float)rms_norm_eps; + uint32_t epsbits; memcpy(&epsbits, &epsf, 4); + Key key = {(uintptr_t)x.data_ptr(), (uintptr_t)wqa.data_ptr(), (uintptr_t)wkva.data_ptr(), + (uintptr_t)wqb.data_ptr(), (uintptr_t)wkvb.data_ptr(), (uintptr_t)lnq.data_ptr(), + (uintptr_t)lnkv.data_ptr(), (uintptr_t)y1.data_ptr(), (uintptr_t)q.data_ptr(), + (uintptr_t)kv.data_ptr(), (uintptr_t)epsbits}; + + cudaStream_t cs = sy.cs, ss = en.prio >= 1 ? sy.ss_hi : sy.ss; // prio 1/2: side branch on the highest-priority stream + bool g1m_on = false; + bool qe_on = false; // set by capture(): wq bit29 early GEMM1 start // set by capture(): wq bit19 GEMM1 -> norm_fast row-block counters (n-fastest GEMM1 raster) + bool fq_on = false; // set by capture(): q_b on the fused quantize-on-load kernel (side-stream wquant: kv_b only) + bool wdep_on = false; + bool seg0_on = false; + bool seg0kv_on = false; // set by capture(): Mp > 256 chain, kv_b waits only on B-wquant segment 0 (kv_b weights) // set by capture(): combined small-M gq, q_b units wait only for the q_b part of the B wquant // set by capture(): q_b/kv_b gq waits in-kernel for the side-stream B wquant (wq bit18) + unsigned long long* const wcnt = (unsigned long long*)(wb + o_sync); + const unsigned long long wper = (unsigned long long)(NQ / 128) * (QR / 128) + (unsigned long long)(NKV / 128) * (KR / 128); + // q_b / kv_b launches for a given SM split: kv_b on the side stream gets (nsm - qcta) CTAs, q_b on + // the main stream gets qcta, so the two persistent kernels (1 CTA/SM each) co-run on disjoint SMs: + // compute-bound q_b (K=1536) overlaps output-bandwidth-bound kv_b (K=512). qcta = 0: both full grid. + // qcta in [1, 4] (small M only): q_b + kv_b as ONE combined persistent launch on the main stream + // (1 = 128x128 tiles, LPT schedule with epilogue cost 2 k-blocks; 2/3 = 128x256 tiles, LPT epilogue cost 0/1; + // 4 = 128x256 round-robin); side stream just joins. + auto gemm_b = [&](int qcta, int& rc2, int& rc3) { + if (fq_on) { + // q_b: fused quantize-on-load kernel on cs (PDL dependent of the norm; its weight TMA + in-CTA quant run before + // its griddepcontrol.wait), kv_b: fp8 gq on ss (stream-ordered after the kv_b-only wquant + ev_norm) on the + // remaining SMs. + set_gq_npw((MODE & 16) ? 8 : 16); + rc3 = launch_gq_gemm(P8(o_kvq), P8(o_wkbq), PF(o_kvs), PF(o_wkbs), kv.data_ptr(), Mp, NKV, KR, ss, sy.nsm - en.fq, + (MODE >> 1) & 1, (MODE >> 2) & 1); + set_gq_npw(16); + cudaEventRecord(sy.ev_kv, ss); + rc2 = launch_fq_gemm(wqb.data_ptr(), P8(o_qaq), PF(o_qas), q.data_ptr(), Mp, NQ, QR, en.fq, cs, 1); + cudaStreamWaitEvent(cs, sy.ev_kv, 0); + return; + } + if (qcta >= 1 && qcta <= 4) { + const int epi = qcta == 1 ? 2 : qcta == 2 ? 0 : qcta == 3 ? 1 : -1; + set_pdl(fused_quant && ((en.wq & (256 | 2048)) || wdep_on)); + if (wdep_on) set_gq_wdep(wcnt, wcnt + 1, wper); if (seg0_on) set_gq_wdep0(wcnt + 2, (unsigned long long)(NQ / 128) * (QR / 128)); // wq bit18: in-kernel wait on the B wquant counter // bit11 (2048): same PDL edge on the M=256 row // wq bit8 (small M): combined gq launch as PDL dependent of the norm + set_gq_npw((MODE & 8) ? 8 : 16); // mode bit3: combined launch with 8 promotion warps (BN = 256) + set_gq_dyn(wdep_on && (en.wq & kDYN)); + rc2 = launch_gq_pair(P8(o_qaq), P8(o_wqbq), PF(o_qas), PF(o_wqbs), q.data_ptr(), NQ, QR, + P8(o_kvq), P8(o_wkbq), PF(o_kvs), PF(o_wkbs), kv.data_ptr(), NKV, KR, Mp, epi, + qcta == 1 ? 128 : 256, cs); + set_pdl(0); + set_gq_npw(16); + set_gq_wdep(nullptr, nullptr, 0); + set_gq_wdep0(nullptr, 0); + set_gq_dyn(0); + rc3 = 0; + cudaEventRecord(sy.ev_kv, ss); // join the side stream (no work on it here) + cudaStreamWaitEvent(cs, sy.ev_kv, 0); + return; + } + const int capq = qcta > 0 ? qcta : 0; + int capkv = qcta > 0 ? sy.nsm - qcta : 0; + if (qcta > 4 && (MODE & 3) == 3) { + const int mcl = gq_max_clusters(); + const int kvcl = mcl - qcta / 2; + if (kvcl >= 1 && 2 * kvcl < capkv) capkv = 2 * kvcl; + } + // rv bit2: gq m traversal starts on the rows the norm wrote last (norm high->low under bit1 -> gq low->high) + // (g1m_on: the norm runs low -> high rows, so the gq traversal is reversed to start on its last-written rows) + set_gq_mrev(!fused_quant && (en.rv & 4) && (!(en.rv & 2) || g1m_on)); + if (!fused_quant && qcta == 0 && (en.wq & kPAIR) && (MODE & 27) == 27 && Mp % 256 == 0) { + // wq bit26: q_b + kv_b as one persistent 2-SM launch on cs (PDL dependent of the norm like q_b under bit7/bit12; + // bit18: in-kernel wait on the B wquant counter). Same tiles / math as the separate launches: bit-identical. + if (wdep_on) set_gq_wdep(wcnt, wcnt + 1, wper); + set_pdl(((en.wq & 128) || (en.wq & 4096) || (en.wq & 65536) || wdep_on) ? 1 : 0); + set_gq_lpol(((MODE >> 11) & 1) | (((MODE >> 13) & 1) << 1)); + if (en.pgr >= 0) set_gq_raster(en.pgr); // pair-launch raster override (grouped L2 swizzle) + rc2 = launch_gq_two_pair(P8(o_qaq), P8(o_wqbq), PF(o_qas), PF(o_wqbs), q.data_ptr(), NQ, QR, + P8(o_kvq), P8(o_wkbq), PF(o_kvs), PF(o_wkbs), kv.data_ptr(), NKV, KR, Mp, (MODE >> 2) & 1, cs); + rc3 = 0; + set_gq_raster(en.gqr); + set_pdl(0); + set_gq_wdep(nullptr, nullptr, 0); + set_gq_lpol(0); + set_gq_mrev(0); + cudaEventRecord(sy.ev_kv, ss); + cudaStreamWaitEvent(cs, sy.ev_kv, 0); + return; + } + if (!fused_quant && qcta == 0 && (en.wq & 512)) { + // wq bit9 (large M, full grids): q_b then kv_b on ONE stream, kv_b as a PDL dependent of q_b. Every q_b CTA + // triggers launch_dependents once it has claimed its last tile, so kv_b CTAs take the SMs as q_b CTAs retire + // (fills q_b's wave tail); kv_b skips griddepcontrol.wait (it does not read q_b's output; its inputs - norm + // and B-weight quant - are complete before q_b can trigger). Same kernels / math: bit-identical outputs. + // bit23 (kKVF) here: kv_b first (norm's PDL dependent), q_b chained behind it (fills kv_b's tail) + const bool kvf9 = (en.wq & kKVF) != 0; + if (wdep_on) set_gq_wdep(wcnt, wcnt + 1, wper); // wq bit18: both gq wait in-kernel on the B wquant counter + for (int k = 0; k < 2; ++k) { + set_pdl(k ? 1 : ((en.wq & 128) || (en.wq & 4096))); + set_gq_pdlchain(k ? 1 : 0, k ? 0 : ((en.wq & kQET) ? 2 : 1)); + if ((k == 0) != kvf9) { + set_gq_npw((MODE & 8) ? 8 : 16); set_gq_mc(MODE & 32); set_gq_lpol(((MODE >> 11) & 1) | (((MODE >> 13) & 1) << 1)); + set_gq_pp(PPQ); rc2 = launch_gq_gemm(P8(o_qaq), P8(o_wqbq), PF(o_qas), PF(o_wqbs), q.data_ptr(), Mp, NQ, QR, cs, 0, MODE & 1, (MODE >> 2) & 1); set_gq_pp(0); + } else { + set_gq_npw((MODE & 16) ? 8 : 16); set_gq_mc(MODE & 64); set_gq_lpol(((MODE >> 12) & 1) | (((MODE >> 13) & 1) << 1)); + rc3 = launch_gq_gemm(P8(o_kvq), P8(o_wkbq), PF(o_kvs), PF(o_wkbs), kv.data_ptr(), Mp, NKV, KR, cs, 0, (MODE >> 1) & 1, (MODE >> 2) & 1); + } + } + set_gq_pdlchain(0, 0); + set_pdl(0); + set_gq_wdep(nullptr, nullptr, 0); + set_gq_npw(16); set_gq_mc(0); set_gq_lpol(0); + set_gq_mrev(0); + cudaEventRecord(sy.ev_kv, ss); // join the side stream (forked at ev_norm; no work on it here) + cudaStreamWaitEvent(cs, sy.ev_kv, 0); + return; + } + if (wdep_on && (en.wq & kKVCH) && fused_quant && (Mp == 256 || Mp == 512) && qcta > 4) { + set_gq_wdep(wcnt, wcnt + 1, wper); + cudaEventRecord(sy.ev_q0, cs); // fork point: last captured node of cs = the norm + cudaStreamWaitEvent(sy.qs, sy.ev_q0, 0); + set_pdl(1); + set_gq_pdlchain(0, 0); + set_gq_npw((MODE & 16) ? 8 : 16); set_gq_mc(MODE & 64); set_gq_lpol(((MODE >> 12) & 1) | (((MODE >> 13) & 1) << 1)); + if (seg0kv_on) set_gq_wdep0(wcnt + 2, (unsigned long long)(NKV / 128) * (KR / 128)); + rc3 = launch_gq_gemm(P8(o_kvq), P8(o_wkbq), PF(o_kvs), PF(o_wkbs), kv.data_ptr(), Mp, NKV, KR, cs, capkv, (MODE >> 1) & 1, (MODE >> 2) & 1); + set_gq_wdep0(nullptr, 0); + set_gq_npw((MODE & 8) ? 8 : 16); set_gq_mc(MODE & 32); set_gq_lpol(((MODE >> 11) & 1) | (((MODE >> 13) & 1) << 1)); + set_gq_pp(PPQ); rc2 = launch_gq_gemm(P8(o_qaq), P8(o_wqbq), PF(o_qas), PF(o_wqbs), q.data_ptr(), Mp, NQ, QR, sy.qs, capq, MODE & 1, (MODE >> 2) & 1); set_gq_pp(0); + cudaEventRecord(sy.ev_nd, sy.qs); + set_pdl(0); + set_gq_wdep(nullptr, nullptr, 0); + set_gq_npw(16); set_gq_mc(0); set_gq_lpol(0); + set_gq_mrev(0); + cudaEventRecord(sy.ev_kv, ss); // join the side stream (B wquant) and q_b's stream into the origin + cudaStreamWaitEvent(cs, sy.ev_kv, 0); + cudaStreamWaitEvent(cs, sy.ev_nd, 0); + return; + } + if (wdep_on && (en.wq & kKVCH)) { + // wq bit21 (with bit18, SM-partitioned co-run): no graph edges between the norm and q_b / kv_b at all. q_b is a + // PDL dependent of the norm (scheduled while the norm drains), waits for it with griddepcontrol.wait and then + // immediately triggers its own dependents; kv_b follows q_b on the SAME stream as its PDL dependent and skips + // griddepcontrol.wait (norm complete is implied: every q_b CTA passed its wait before triggering). Both acquire-wait + // in-kernel for the side-stream B-weight wquant counter (wcnt >= epoch * wper) before their first TMA. + // Same kernels / tiles / caps as the 2-stream co-run: bit-identical outputs. + set_gq_wdep(wcnt, wcnt + 1, wper); + set_pdl(1); + // bit23: kv_b first (the norm's direct dependent), q_b chained behind it + const bool kvf = (en.wq & kKVF) != 0; + for (int k = 0; k < 2; ++k) { + set_gq_pdlchain(k ? 1 : 0, k ? 0 : 2); + if ((k == 0) != kvf) { + set_gq_npw((MODE & 8) ? 8 : 16); set_gq_mc(MODE & 32); set_gq_lpol(((MODE >> 11) & 1) | (((MODE >> 13) & 1) << 1)); + set_gq_pp(PPQ); rc2 = launch_gq_gemm(P8(o_qaq), P8(o_wqbq), PF(o_qas), PF(o_wqbs), q.data_ptr(), Mp, NQ, QR, cs, capq, MODE & 1, (MODE >> 2) & 1); set_gq_pp(0); + } else { + set_gq_npw((MODE & 16) ? 8 : 16); set_gq_mc(MODE & 64); set_gq_lpol(((MODE >> 12) & 1) | (((MODE >> 13) & 1) << 1)); + if (seg0kv_on) set_gq_wdep0(wcnt + 2, (unsigned long long)(NKV / 128) * (KR / 128)); + rc3 = launch_gq_gemm(P8(o_kvq), P8(o_wkbq), PF(o_kvs), PF(o_wkbs), kv.data_ptr(), Mp, NKV, KR, cs, capkv, (MODE >> 1) & 1, (MODE >> 2) & 1); + set_gq_wdep0(nullptr, 0); + } + } + set_gq_pdlchain(0, 0); + set_pdl(0); + set_gq_wdep(nullptr, nullptr, 0); + set_gq_npw(16); set_gq_mc(0); set_gq_lpol(0); + set_gq_mrev(0); + cudaEventRecord(sy.ev_kv, ss); // join the side stream (B wquant) back into the capture origin + cudaStreamWaitEvent(cs, sy.ev_kv, 0); + return; + } + if (en.prio == 3 && qcta == 0 && !wdep_on && !(en.wq & (128 | 65536))) { + // prio 3 (large M, full grids): closes the norm -> q_b full graph edge. q_b is launched on cs as a PDL dependent of + // norm_fast (its grid is scheduled while the norm drains: launch latency + prologue overlap the norm tail; gq does + // griddepcontrol.wait before touching qq/qs; the B-wquant edge (cs waited ev_wb) stays a full edge). kv_b runs on + // the normal-priority side stream sy.ss after the norm + B wquant (joined through ev_q0) and fills q_b's tail. + // Same launches / grids / tiles as the prio-2 co-run: bit-identical outputs. + cudaEventRecord(sy.ev_q0, ss); // ss (= ss_hi): B wquant + wait(ev_norm) + cudaStreamWaitEvent(sy.ss, sy.ev_q0, 0); + set_gq_npw((MODE & 8) ? 8 : 16); set_gq_mc(MODE & 32); set_gq_lpol(((MODE >> 11) & 1) | (((MODE >> 13) & 1) << 1)); + set_pdl(1); + set_gq_pp(PPQ); rc2 = launch_gq_gemm(P8(o_qaq), P8(o_wqbq), PF(o_qas), PF(o_wqbs), q.data_ptr(), Mp, NQ, QR, cs, 0, MODE & 1, ((MODE >> 2) & 1) && !((MODE >> 22) & 1)); set_gq_pp(0); + set_pdl(0); + set_gq_npw((MODE & 16) ? 8 : 16); set_gq_mc(MODE & 64); set_gq_lpol(((MODE >> 12) & 1) | (((MODE >> 13) & 1) << 1)); + rc3 = launch_gq_gemm(P8(o_kvq), P8(o_wkbq), PF(o_kvs), PF(o_wkbs), kv.data_ptr(), Mp, NKV, KR, sy.ss, 0, (MODE >> 1) & 1, (MODE >> 2) & 1); + cudaEventRecord(sy.ev_kv, sy.ss); + set_gq_npw(16); set_gq_mc(0); set_gq_lpol(0); + set_gq_mrev(0); + cudaStreamWaitEvent(cs, sy.ev_kv, 0); + cudaStreamWaitEvent(cs, sy.ev_q0, 0); + return; + } + if (en.prio == 2 && qcta == 0 && !wdep_on && !(en.wq & (128 | 65536))) { + // prio 2 (large M, full grids): q_b on the HIGH-priority side stream (scheduled first, its 12-k-block tiles take + // the SMs), kv_b (4 k-blocks per tile) on the main stream fills q_b's last-wave tail. Same launches / grids as the + // default co-run, streams swapped: bit-identical outputs. + set_gq_npw((MODE & 8) ? 8 : 16); set_gq_mc(MODE & 32); set_gq_lpol(((MODE >> 11) & 1) | (((MODE >> 13) & 1) << 1)); + set_gq_pp(PPQ); rc2 = launch_gq_gemm(P8(o_qaq), P8(o_wqbq), PF(o_qas), PF(o_wqbs), q.data_ptr(), Mp, NQ, QR, ss, 0, MODE & 1, (MODE >> 2) & 1); set_gq_pp(0); + cudaEventRecord(sy.ev_kv, ss); + set_gq_npw((MODE & 16) ? 8 : 16); set_gq_mc(MODE & 64); set_gq_lpol(((MODE >> 12) & 1) | (((MODE >> 13) & 1) << 1)); + rc3 = launch_gq_gemm(P8(o_kvq), P8(o_wkbq), PF(o_kvs), PF(o_wkbs), kv.data_ptr(), Mp, NKV, KR, cs, 0, (MODE >> 1) & 1, (MODE >> 2) & 1); + set_gq_npw(16); set_gq_mc(0); set_gq_lpol(0); + set_gq_mrev(0); + cudaStreamWaitEvent(cs, sy.ev_kv, 0); + return; + } + set_gq_npw((MODE & 16) ? 8 : 16); set_gq_mc(MODE & 64); set_gq_lpol(((MODE >> 12) & 1) | (((MODE >> 13) & 1) << 1)); // mode bit4: kv_b with 8 promotion warps (BN = 256 / 2-SM gq launches) + rc3 = launch_gq_gemm(P8(o_kvq), P8(o_wkbq), PF(o_kvs), PF(o_wkbs), kv.data_ptr(), Mp, NKV, KR, ss, capkv, (MODE >> 1) & 1, (MODE >> 2) & 1); + TLR(ss, "kv_b"); + cudaEventRecord(sy.ev_kv, ss); + set_gq_npw((MODE & 8) ? 8 : 16); set_gq_mc(MODE & 32); set_gq_lpol(((MODE >> 11) & 1) | (((MODE >> 13) & 1) << 1)); // mode bit3: q_b with 8 promotion warps + set_pdl((!fused_quant && (en.wq & 128)) || (en.wq & 65536) || wdep_on); + if (wdep_on) set_gq_wdep(wcnt, wcnt + 1, wper); // q_b only (kv_b is stream-ordered after the wquant on ss) // bit16: q_b behind the norm (mid M) // wq bit7: q_b follows the norm on cs as a programmatic dependent launch + set_gq_pp(PPQ); rc2 = launch_gq_gemm(P8(o_qaq), P8(o_wqbq), PF(o_qas), PF(o_wqbs), q.data_ptr(), Mp, NQ, QR, cs, capq, MODE & 1, (MODE >> 2) & 1); set_gq_pp(0); + set_pdl(0); + set_gq_wdep(nullptr, nullptr, 0); + TLR(cs, "q_b"); + set_gq_npw(16); set_gq_mc(0); set_gq_lpol(0); + set_gq_mrev(0); + cudaStreamWaitEvent(cs, sy.ev_kv, 0); + }; + // GEMM1 launch for a variant (split-K small-M path is fixed). + auto gemm1 = [&](int g1) -> int { + if (F16 > 0) + return launch_f16_gemm(P8(o_xh), P8(o_wah), y1.data_ptr(), Mp, NY, (int)H, F16, cs, 0, PF(o_amax) + 2); + if (S > 1) + return launch_fp8_gemm_splitk(P8(o_xq), P8(o_waq), PF(o_xs), PF(o_was), PF(o_part), Mp, NY, (int)H, S, cs, 0); + if (g1 >= 8) // custom 2-SM gq GEMM1 (bf16 y1, same layout), weight scales at pitch kG1Ld; 9: n-fastest raster + return launch_gq_g1(P8(o_xq), P8(o_waq), PF(o_xs), PF(o_was), y1.data_ptr(), Mp, NY, NY, (int)H, kG1Ld, cs, g1cap, /* brows = NY: B rows >= 2112 (kv_a pad) TMA zero-filled, never read */ + (g1 == 9 || g1m_on) ? 0 : en.g1ra); // g1m_on: n-fastest so m-blocks complete in order + if (g1 >= 2) // stream-K scheduler: (g1-2)&1 = 2-SM, splits = 0 (pure stream-K) or ((g1-2)>>1)+1 (fixed split) + return launch_fp8_gemm_sk(P8(o_xq), P8(o_waq), PF(o_xs), PF(o_was), y1.data_ptr(), Mp, NY, (int)H, (g1 - 2) & 1, + (g1 - 2) >> 1 ? ((g1 - 2) >> 1) + 1 : 0, cs, 0); + if (g1 == 1) + return launch_fp8_gemm_2sm(P8(o_xq), P8(o_waq), PF(o_xs), PF(o_was), y1.data_ptr(), Mp, NY, (int)H, + g1 == 1 ? 128 : 256, cs, 0); + return launch_fp8_gemm(P8(o_xq), P8(o_waq), PF(o_xs), PF(o_was), y1.data_ptr(), Mp, NY, (int)H, cs, 0); + }; + auto capture = [&](int qcta, int g1, int qsp) { + // ---- (re)capture the full 2-stream sequence on the private capture stream + auto mk = [&](WSeg& sg, int& acc, const at::Tensor& src, void* dst, float* sf, int row_off, int ld_sf) { + sg.src = src.data_ptr(); sg.dst = dst; sg.sf = sf; + sg.N = (int)src.size(0); sg.K = (int)src.size(1); + sg.row_off = row_off; sg.ld_sf = ld_sf; sg.nblk_start = acc; + acc += (sg.N / 128) * (sg.K / 128); + }; + set_gq_ar(!fused_quant && Mp >= 16384 ? 4 : !fused_quant && Mp >= 8192 ? 3 : !fused_quant && Mp >= 1024 ? 1 : 0); // M >= 8192: GV_AR4 (A reused over 4 n-tiles) // only K = 512 single-problem 2-SM launches (kv_b); M >= 8192 too (kv_b there is plain npw8 2-SM; GV_PP is q_b only) + set_gq_raster(en.gqr); + set_g1_ss(en.g1ss >= 0 ? en.g1ss : (!fused_quant && Mp <= 4096 ? 1 : 0)); + set_g1_lpol(en.g1lp); + set_wq_ver((en.wq & kOWQ) ? 0 : 3); // wquant kernel: 3 = wquant_kernel<6> (decoupled store warp, single amax tree) + set_fg_whint(en.fgh); + set_gemm1_sched(en.g1r); + // wq bit10 (small M): late PDL triggers (aquant / fg2 / split-K norm / pquant after their final stores) + set_late_trig(fused_quant && (en.wq & 1024)); + set_pq_ptrig((en.wq & 16384) ? 1 : 0); // wq bit14 (mid M): quant producers trigger after their last claim + set_nf_etrig((en.wq & 65536) ? 1 : 0); // wq bit16 (mid M): norm_fast early trigger + // wq bit11 (small M, non-fused GEMM1 path): PDL chain pquant -> CUTLASS split-K GEMM1 (GDC) -> norm -> gq + const bool PCH = fused_quant && !en.fg && !en.fb && (en.wq & 2048); + { cudaError_t bce = cudaStreamBeginCapture(cs, cudaStreamCaptureModeRelaxed); TORCH_CHECK(bce == cudaSuccess, "begin capture failed M=", M, ": ", cudaGetErrorString(bce)); } + TLR(cs, "t0"); + // Small M (Mp <= 512): ONE persistent TMA-ring quant launch over all 4 weights + activation (the whole + // call is weight-bandwidth bound; GEMM1 is tiny). Larger M: B-weight quant on the side stream overlaps + // the A path / GEMM1 (original 2-launch schedule). + const bool FB = fused_quant && en.fb; + // wq bit18: small-M SM-partitioned path with the wquant B quant -> in-kernel dependency instead of the ev_wb join + // Large-M chunk pipeline (S == 1, fp8 GEMM1): tokens split into C chunks of Mc rows (multiple of 256). + const bool CH = !fused_quant && en.chunks > 1 && S == 1 && F16 == 0 && Mp % (256 * en.chunks) == 0 && en.chunks <= 8; + const int Cn = CH ? en.chunks : 1, Mc = Mp / Cn; + // B-weight quant on en.bqs SMs (TMA ring kernel) after the A quant, concurrently with GEMM1 on the other SMs + const bool BQ = !fused_quant && !CH && en.bqs > 0 && en.bqs < sy.nsm; + // wq bit18: the gq launches wait in-kernel for the side-stream B wquant (completion counter vs per-replay epoch + // bumped by the norm) instead of the ev_wb graph edge. Small M: SM-partitioned wquant (qsp SMs); mid M: the + // SM-capped wquant co-running with GEMM1 (BQ, bqs SMs). + fq_on = fused_quant && !FB && qsp > 0 && en.fq > 0; + wdep_on = !fq_on && (en.wq & 262144) && ((fused_quant && !FB && qsp > 0 && (en.wq & 1)) || (BQ && F16 == 0)); + // wq bit3 (with bit1, non-chunked): the activation quant runs on stream qs CONCURRENTLY with the A-weight wquant + // (both are short, latency/tail-bound launches; aquant's small CTAs co-reside with wquant's 1 CTA/SM); GEMM1 + // waits for it. The B-weight fork (BQ) then follows the A-weight quant alone. + // wq bit20 (mid M, Mp in [640, 2048]): GEMM1 = fused A-weight quant + split-K GEMM (fg1_kernel, section 9 of + // kernel.cu): the bf16 q_a|kv_a weights are TMA-loaded and quantized in-CTA (same 128x128 scheme), so the separate + // A-weight quant pass disappears; only the activation is quantized up front; the split-K norm reduces partials. + const bool FGM = !fused_quant && !CH && mid_split && F16 == 0 && (en.wq & kFGM); + const bool AQC = !fused_quant && !CH && !FGM && (en.wq & 2) && (en.wq & 8) && F16 == 0; + // wq bit19 (large M): norm_fast waits per 128-row block on GEMM1 tile-completion counters instead of the whole + // GEMM1 grid (overlaps the norm with GEMM1's last-wave tail). Needs: quant_kernel (resets the counters), gq GEMM1, + // norm_fast as its PDL dependent. + g1m_on = !fused_quant && !CH && !(en.wq & 2) && F16 == 0 && S == 1 && g1 >= 8 && en.nq && (en.wq & 2048) && + (en.wq & 524288); + qe_on = g1m_on && (en.wq & kQE) && (en.wq & 1024); + // Tiled fp8 activation (Mp >= 4096): ONLY when the producer is aqt_kernel and the consumer is the BN=192 gq GEMM1 + // (the only reader of xq on this path). Same bytes per tile in smem: bit-identical. + const bool ATL = !fused_quant && !CH && !FGM && !(en.wq & 2) && get_aqt() && !qe_on && F16 == 0 && S == 1 && + g1 >= 8 && ((MODE >> 21) & 1) && Mp % 256 == 0 && Mp >= 4096 && (H % 128) == 0; + set_act_tiled(ATL ? 1 : 0); + unsigned* const qe_cnt = (unsigned*)P8(o_g1c); // + nrb: row-block counters, + 2 nrb: weight counter + const int nrb = Mp / 128; + auto fork_bq = [&]() { + cudaEventRecord(sy.ev_start, cs); + cudaStreamWaitEvent(ss, sy.ev_start, 0); + WSeg segB[2]; int accB = 0; + mk(segB[0], accB, wqb, P8(o_wqbq), PF(o_wqbs), 0, NQ / 128); + mk(segB[1], accB, wkvb, P8(o_wkbq), PF(o_wkbs), 0, NKV / 128); + // M=1024/2048 rows (640 <= Mp < 3072): SM-capped B wquant co-running with GEMM1 (DRAM-bound phase) walks per-CTA + // runs of 4 ADJACENT k-block jobs (128 rows x 512 cols bf16 = 1 KB contiguous per row, kv_b: one contiguous + // 128 KB block) instead of round-robin 128x128 jobs: better DRAM row-buffer locality. Same per-job math and stores, + // same job count per CTA (max 44 / 56 jobs either way): bit-identical. (jc 4 previously tried only at 128 / 4096.) + set_wq_jc(Mp >= 640 && Mp < 1536 ? 4 : 1); + launch_wquant(segB, 2, accB, en.bqs, ss, 0, wdep_on ? wcnt : nullptr); + set_wq_jc(1); + TLR(ss, "Bquant"); + cudaEventRecord(sy.ev_wb, ss); + }; + if (FB) { + // Small M, fused B path: only the activation is quantized up front (A weights inside fused GEMM1, + // B weights inside the fused q_b/kv_b kernel after the norm). + if (en.pf) { + // side stream: prefetch the first pf MB of the bf16 B weights into L2 (in fb_kernel unit order) while + // the A path (act quant -> fused GEMM1 -> norm) runs; joined back at the end of the graph. + cudaEventRecord(sy.ev_start, cs); + cudaStreamWaitEvent(ss, sy.ev_start, 0); + launch_l2_prefetch(wqb.data_ptr(), (size_t)NQ * QR * 2, wkvb.data_ptr(), (size_t)NKV * KR * 2, + (size_t)(en.pf & 0xffff) << 20, en.pf >> 16, ss); + cudaEventRecord(sy.ev_wb, ss); + } + ActJob aj{x.data_ptr(), P8(o_xq), PF(o_xs), M, Mp, (int)H}; + launch_pquant(nullptr, 0, 0, &aj, cs); + } else if (fused_quant && qsp > 0) { + // Small M, SM-partitioned: side stream quantizes the B weights (q_b, kv_b) on qsp SMs (1 CTA/SM) while + // the main stream quantizes the A weights + activation on the remaining SMs and then immediately runs + // the split-K GEMM1 + norm there; q_b/kv_b GEMMs start once both sides are done. + cudaEventRecord(sy.ev_start, cs); + cudaStreamWaitEvent(ss, sy.ev_start, 0); + WSeg segB[2]; int accB = 0; + if (fq_on) { + mk(segB[0], accB, wkvb, P8(o_wkbq), PF(o_wkbs), 0, NKV / 128); // q_b weights quantized inside fq_kernel + } else if (Mp <= 128) { + mk(segB[0], accB, wqb, P8(o_wqbq), PF(o_wqbs), 0, NQ / 128); + mk(segB[1], accB, wkvb, P8(o_wkbq), PF(o_wkbs), 0, NKV / 128); + } else { + mk(segB[0], accB, wkvb, P8(o_wkbq), PF(o_wkbs), 0, NKV / 128); + mk(segB[1], accB, wqb, P8(o_wqbq), PF(o_wqbs), 0, NQ / 128); + } + // seg0_on: q_b is segment 0 of the B wquant (Mp <= 256 write order) and the combined gq launch consumes it + seg0_on = wdep_on && !fq_on && Mp <= 256 && qcta >= 1 && qcta <= 4 && (en.wq & 1) && !(en.wq & kOWQ); + // Mp > 256 (kv_b = segment 0) in the bit21 PDL chain: kv_b gq waits only for the kv_b part of the B wquant + seg0kv_on = wdep_on && !fq_on && Mp > 128 && qcta > 4 && (en.wq & 1) && !(en.wq & kOWQ) && (en.wq & kKVCH); + // Mp <= 256 (q_b written first): ~40 MB L2-resident prefix = 2560 x 16 KB jobs (all q_b + first kv_b) evict_last + set_wq_lastj(Mp <= 128 && !fq_on ? 2560 : 0); // Mp = 256: kv_b-first order -> all fp8 B evict_last (as 512) + set_wq_jc(1); + set_wq_rev0(Mp <= 128 && !fq_on && seg0_on ? 1 : 0); + if (en.wq & 1) launch_wquant(segB, fq_on ? 1 : 2, accB, qsp, ss, 0, wdep_on ? wcnt : nullptr, (seg0_on || seg0kv_on) ? wcnt + 2 : nullptr); // TMA ring quant on qsp SMs + else launch_pquant(segB, fq_on ? 1 : 2, accB, nullptr, ss, qsp); + set_wq_lastj(0); + set_wq_jc(1); + set_wq_rev0(0); + cudaEventRecord(sy.ev_wb, ss); + ActJob aj{x.data_ptr(), P8(o_xq), PF(o_xs), M, Mp, (int)H}; + if (en.fg) { + set_aq_early(1); + launch_pquant(nullptr, 0, 0, &aj, cs, sy.nsm - qsp); + set_aq_early(0); + } else { + WSeg segA[2]; int accA = 0; + const int ldS = (g1 >= 8 && S == 1) ? kG1Ld : NA / 128; // gq GEMM1 (g1 8/9): padded weight-scale pitch + mk(segA[0], accA, wqa, P8(o_waq), PF(o_was), 0, ldS); + mk(segA[1], accA, wkva, P8(o_waq), PF(o_was), QR, ldS); segA[1].vrows = KR + 64; // kv_a pad rows 576..639: amax only, no fp8 codes + launch_pquant(segA, 2, accA, &aj, cs, sy.nsm - qsp); + } + } else if (fused_quant) { + WSeg seg[4]; int acc = 0; + if (!en.fg) { + const int ldS = (g1 >= 8 && S == 1) ? kG1Ld : NA / 128; // gq GEMM1 (g1 8/9): padded weight-scale pitch + mk(seg[0], acc, wqa, P8(o_waq), PF(o_was), 0, ldS); + mk(seg[1], acc, wkva, P8(o_waq), PF(o_was), QR, ldS); seg[1].vrows = KR + 64; // kv_a pad rows 576..639: amax only, no fp8 codes + } + const int nb0 = en.fg ? 0 : 2; + mk(seg[nb0], acc, wqb, P8(o_wqbq), PF(o_wqbs), 0, NQ / 128); + mk(seg[nb0 + 1], acc, wkvb, P8(o_wkbq), PF(o_wkbs), 0, NKV / 128); + ActJob aj{x.data_ptr(), P8(o_xq), PF(o_xs), M, Mp, (int)H}; + launch_pquant(seg, nb0 + 2, acc, &aj, cs); // (A weights unless fused GEMM1) + B weights + activation + cudaEventRecord(sy.ev_wb, cs); + } else { + // fork: side stream quantizes q_b / kv_b weights while main does the A path + if (!BQ) { + cudaEventRecord(sy.ev_start, cs); + cudaStreamWaitEvent(ss, sy.ev_start, 0); + WSeg segB[2]; int accB = 0; + mk(segB[0], accB, wqb, P8(o_wqbq), PF(o_wqbs), 0, NQ / 128); + mk(segB[1], accB, wkvb, P8(o_wkbq), PF(o_wkbs), 0, NKV / 128); + if (en.wq & 4) launch_wquant(segB, 2, accB, sy.nsm, ss); // TMA ring quant, 1 CTA/SM + else launch_quant(segB, 2, accB, nullptr, ss); + TLR(ss, "Bquant"); + cudaEventRecord(sy.ev_wb, ss); + } + if (FGM) { + // B-weight quant first (bqs SMs, side stream), then only the activation quant on cs + if (BQ) fork_bq(); + ActJob aj{x.data_ptr(), P8(o_xq), PF(o_xs), M, Mp, (int)H}; + launch_pquant(nullptr, 0, 0, &aj, cs); + TLR(cs, "actquant"); + } else + // main: A weights (q_a | kv_a concatenated) -> fp8 128x128, fused with 1x128 act quant + { + WSeg segA[2]; int accA = 0; + // F16: same exact quantization, but the outputs are the dequantized fp16 values for the fp16 GEMM1 + const int ldA = (g1 >= 8 && !CH && S == 1 && F16 == 0) ? kG1Ld : NA / 128; // gq GEMM1: padded scale pitch + mk(segA[0], accA, wqa, F16 ? P8(o_wah) : P8(o_waq), PF(o_was), 0, ldA); + mk(segA[1], accA, wkva, F16 ? P8(o_wah) : P8(o_waq), PF(o_was), QR, ldA); segA[1].vrows = KR + 64; // kv_a pad rows 576..639: amax only, no fp8 codes + segA[0].f16 = segA[1].f16 = F16 ? 1 : 0; + ActJob aj{x.data_ptr(), F16 ? P8(o_xh) : P8(o_xq), PF(o_xs), M, Mp, (int)H}; + aj.f16 = F16 ? 1 : 0; + aj.rev = (en.rv & 1) ? 1 : 0; // rv bit0: act quant high rows first + if (CH) { aj.M = std::min(M, Mc); aj.Mp = Mc; } // chunk pipeline: only chunk 0 here (chunk-local scales) + if (F16) { + // per-tensor power-of-two prescales (|max| -> < 2^14): global |max| of x and [q_a|kv_a] first; the quant + // kernel emits code*scale*2^s and the exact factor 2^-(sA+sW) for the GEMM1 epilogue (alpha_ptr). + unsigned* am = (unsigned*)P8(o_amax); + launch_amax(x.data_ptr(), (size_t)M * H, wqa.data_ptr(), (size_t)QR * H, wkva.data_ptr(), (size_t)640 * H, am, cs); + segA[0].amax = segA[1].amax = am + 1; + aj.amax = am; + } + if ((en.wq & 2) && !F16) { + // A weights through the TMA-in/TMA-store quant (all SMs), then the activation (chunk 0 if chunked) + if (AQC) { // fork: act quant on qs alongside the A-weight quant + cudaEventRecord(sy.ev_q0, cs); + cudaStreamWaitEvent(sy.qs, sy.ev_q0, 0); + launch_pquant(nullptr, 0, 0, &aj, sy.qs); + TLR(sy.qs, "actquant"); + cudaEventRecord(sy.ev_nd, sy.qs); + } + launch_wquant(segA, 2, accA, sy.nsm, cs); + TLR(cs, "Aquant"); + if (!AQC) { + set_aq_pdl((en.wq & 131072) ? 1 : 0); // wq bit17: aquant PDL dependent of the A wquant (same stream) + launch_pquant(nullptr, 0, 0, &aj, cs); + set_aq_pdl(0); + TLR(cs, "actquant"); + } + } else { + if (g1m_on) set_quant_g1cnt((unsigned*)P8(o_g1c), Mp / 128 + (NPERS ? 1 : 0)); // + persistent-norm claim counter (zeroed per replay) + if (qe_on) { set_quant_early(qe_cnt + nrb, qe_cnt + 2 * nrb); aj.rev = 0; } // rows low -> high = GEMM1 order + // Mp >= 2048 (no early-start counters, fp8, unchunked): A weights + act through the TMA-ring aqt_kernel + // (wquant<7> structure, 1 CTA/SM); same codes / scales / counter reset / PDL trigger as quant_kernel. + set_aqt_dyn((unsigned*)P8(o_dyn)); + set_aqt_apol(Mp >= 16384 ? 1 : 0); // 117 MB fp8 act > L2: do not pin it evict_last + if (get_aqt() && !qe_on && !F16 && !CH && Mp >= 2048) launch_quant_tma(segA, 2, accA, &aj, sy.nsm, cs); + else launch_quant(segA, 2, accA, &aj, cs, F16 ? PF(o_amax) + 2 : nullptr); + set_aqt_apol(0); + set_quant_g1cnt(nullptr, 0); + set_quant_early(nullptr, nullptr); + TLR(cs, "A+actquant"); + } + } + // A quant done on all SMs -> side stream: B-weight quant on bqs SMs while GEMM1 runs capped on the rest + if (BQ && !FGM) fork_bq(); + if (AQC) cudaStreamWaitEvent(cs, sy.ev_nd, 0); // join: GEMM1 needs the quantized activation + } + // GEMM1: y1[Mp,2112] = [q_a | kv_a] (split-K -> fp32 partials, reduced in norm kernel) + int rc1, rc2, rc3; + int nsplit = S > 1 ? S : 0; + if (fused_quant && en.fg) { + // small M: fused A-weight quant + split-K GEMM1 on the SMs not used by the B-weight quant + const int Sf = en.sk > 0 ? std::min(en.sk, Smax) : fused_g1_splits(Mp, qsp > 0 ? sy.nsm - qsp : sy.nsm, (int)H); + // PDL: fused GEMM1 launches while the act quant runs (its weight TMA + in-CTA weight quant overlap it), and the + // split-K norm launches while GEMM1 runs (both griddepcontrol.wait before reading their inputs). Reset after norm. + set_fg_pdl(1); + set_fg_early(1); // small M: norm pre-launched behind fg2 (entry trigger) + rc1 = launch_fused_g1(wqa.data_ptr(), wkva.data_ptr(), P8(o_xq), PF(o_xs), PF(o_part), Mp, (int)H, Sf, cs); + set_fg_early(0); + nsplit = Sf; // always the partial-sum norm path (Sf >= 1) + } else if (FGM) { + // mid M: fused A-weight quant + split-K GEMM1 on the SMs not used by the co-running B-weight quant + const int Sf = std::max(1, std::min(Smax, fused_g1_splits(Mp, BQ ? sy.nsm - en.bqs : sy.nsm, (int)H))); + set_fg_pdl(1); // split-K norm as PDL dependent (griddepcontrol.wait before reading the partials) + rc1 = launch_fused_g1(wqa.data_ptr(), wkva.data_ptr(), P8(o_xq), PF(o_xs), PF(o_part), Mp, (int)H, Sf, cs); + nsplit = Sf; + } else if (CH) { + // ---- chunk pipeline. Act quant of chunk c writes chunk-local fp8 rows xq[c*Mc..] and chunk-local MN-major + // scales xs + c*(H/128)*Mc ([kb][Mc]), so GEMM1(c) is a plain M = Mc problem. Norm(c) writes the global + // y1 / qq / kq rows and scales with stride Mp (consumed by the unchanged full-M q_b / kv_b GEMMs). + // cs : [quant Wa + act(0)] GEMM1(0) GEMM1(1) ... GEMM1(C-1) (GEMM1(c) waits act(c); capped at nsm-qa + // SMs except the last chunk) ... wait all norms + // qs : act(1) | norm(0) act(2) | norm(1) act(3) | ... | norm(C-1) (norm(c) waits GEMM1(c)) + // so act(c+1) and norm(c-1) run on the free SM partition while GEMM1(c) runs. + const int nkbH = (int)(H / 128); + auto act_chunk = [&](int c) { + ActJob a{(const uint16_t*)x.data_ptr() + (size_t)c * Mc * H, (uint8_t*)P8(o_xq) + (size_t)c * Mc * H, + PF(o_xs) + (size_t)c * nkbH * Mc, std::max(0, std::min(Mc, M - c * Mc)), Mc, (int)H}; + launch_act_capped(&a, 4 * en.qa, sy.qs); + cudaEventRecord(sy.ev_a[c], sy.qs); + }; + auto norm_chunk = [&](int c) { + launch_norm_quant((uint16_t*)y1.data_ptr() + (size_t)c * Mc * NY, NY, nullptr, 0, lnq.data_ptr(), lnkv.data_ptr(), + (uint8_t*)P8(o_qaq) + (size_t)c * Mc * QR, PF(o_qas) + (size_t)c * Mc, + (uint8_t*)P8(o_kvq) + (size_t)c * Mc * KR, PF(o_kvs) + (size_t)c * Mc, epsf, Mp, sy.qs, Mc); + }; + cudaEventRecord(sy.ev_q0, cs); + cudaStreamWaitEvent(sy.qs, sy.ev_q0, 0); + act_chunk(1); + rc1 = 0; + for (int c = 0; c < Cn; ++c) { + if (c > 0) cudaStreamWaitEvent(cs, sy.ev_a[c], 0); + set_gemm1_sm_cap(c + 1 < Cn ? sy.nsm - en.qa : 0); + const void* A = (const uint8_t*)P8(o_xq) + (size_t)c * Mc * H; + const float* SFA = PF(o_xs) + (size_t)c * nkbH * Mc; + void* D = (uint16_t*)y1.data_ptr() + (size_t)c * Mc * NY; + const int r = g1 == 1 ? launch_fp8_gemm_2sm(A, P8(o_waq), SFA, PF(o_was), D, Mc, NY, (int)H, 128, cs, 0) + : launch_fp8_gemm(A, P8(o_waq), SFA, PF(o_was), D, Mc, NY, (int)H, cs, 0); + set_gemm1_sm_cap(0); + if (r) rc1 = r; + cudaEventRecord(sy.ev_g[c], cs); + cudaStreamWaitEvent(sy.qs, sy.ev_g[c], 0); + norm_chunk(c); + if (c + 2 < Cn) act_chunk(c + 2); + } + cudaEventRecord(sy.ev_nd, sy.qs); + cudaStreamWaitEvent(cs, sy.ev_nd, 0); // all norms done (joins qs back into the capture origin) + } else { + if (BQ) set_gemm1_sm_cap(sy.nsm - en.bqs); + else if (fused_quant && qsp > 0 && g1 > 0) set_gemm1_sm_cap(sy.nsm - qsp); // CUTLASS persistent / stream-K grid off the B-quant SMs + // small M with the SM-partitioned B quant (qsp SMs, side stream): the persistent GEMM1 grid stays on the rest + g1cap = BQ ? sy.nsm - en.bqs : (fused_quant && qsp > 0 && g1 > 0 ? sy.nsm - qsp : 0); + // wq bit10: gq GEMM1 (g1 8/9) launched as PDL dependent of the A+act quant (quant_kernel late-triggers; gq does + // griddepcontrol.wait before its first TMA). wq bit11: GEMM1 producers trigger after their last tile claim and + // the norm_fast that follows is launched as its PDL dependent (norm waits before reading y1). + const bool g1pdl = !fused_quant && g1 >= 8 && S == 1 && F16 == 0; + if (g1pdl && (en.wq & 1024)) set_pdl(1); + if (g1pdl && (en.wq & 2048)) set_gq_pdlchain(0, (g1m_on && (en.wq & kG1ET)) ? 2 : 1); + // wq bit14 (mid M): CUTLASS GEMM1 (g1 0/1, not gq / f16) as PDL dependent of the quant before it on cs; + // wq bit15: the non-split norm after it as GEMM1's PDL dependent (CUTLASS triggers after its last tile's MMAs). + const bool cpdl = g1 < 2 && F16 == 0; + set_g1_pdl((PCH || (cpdl && (en.wq & 16384))) ? 1 : 0); + if (g1m_on) set_g1_mcnt((unsigned*)P8(o_g1c)); + if (qe_on) set_g1_early(qe_cnt + nrb, (unsigned)(H / 128), qe_cnt + 2 * nrb, (unsigned)((NA / 128) * (H / 128))); + set_g1_bn192(g1 >= 8 && S == 1 && F16 == 0 && ((MODE >> 21) & 1) && Mp % 256 == 0); + set_g1_mc(!fused_quant && Mp >= 8192 && Mp < 16384 ? 1 : 0); + set_g1_sl(!fused_quant && Mp >= 16384 ? 1 : 0); + rc1 = gemm1(g1); + set_g1_sl(0); + set_g1_mc(0); + set_g1_bn192(0); + set_act_tiled(0); + set_g1_early(nullptr, 0, nullptr, 0); + set_g1_mcnt(nullptr); + set_g1_pdl(0); + if (cpdl && (en.wq & 32768) && nsplit == 0) set_fg_pdl(1); + set_pdl(0); + set_gq_pdlchain(0, 0); + if (g1pdl && (en.wq & 2048) && en.nq) set_fg_pdl(1); + if (PCH) set_fg_pdl(1); // small M bit11: split-K norm as PDL dependent of GEMM1 (reset after the norm launch) + g1cap = 0; + set_gemm1_sm_cap(0); + TLR(cs, "gemm1"); + } + // RMSNorm + requant (both halves), then fork kv_b GEMM to side stream + if (!CH && wdep_on) { set_norm_epoch(wcnt + 1); set_norm_early((en.wq & kNQE) ? 1 : 0); } // one epoch increment per replay + late PDL trigger + if (g1m_on && NPERS) set_nf_pers((unsigned*)P8(o_g1c) + Mp / 128, NPERS); + if (g1m_on) set_norm_mcnt((const unsigned*)P8(o_g1c), (unsigned)(((MODE >> 21) & 1) && Mp % 256 == 0 ? NY / 192 : (NY + 255) / 256)); // n-tiles per row block // 9 n-tiles per row block + set_nf_rows(en.nq == 2 ? 2 : en.nq == 8 ? 8 : 4); // nq 2 / 8: norm_fast 2 / 8 rows per CTA + set_nf_mb(en.nfb > 0 ? en.nfb : 1); + if (!CH) + launch_norm_quant(y1.data_ptr(), NY, nsplit > 0 ? PF(o_part) : nullptr, nsplit, + lnq.data_ptr(), lnkv.data_ptr(), P8(o_qaq), PF(o_qas), + P8(o_kvq), PF(o_kvs), epsf, Mp, cs, 0, (!fused_quant && (en.rv & 2) && !g1m_on) ? 1 : 0, + (nsplit == 0 && en.nq) ? 1 : 0); // nq: norm_fast_kernel<4> + set_fg_pdl(0); + set_norm_mcnt(nullptr, 0); + set_nf_pers(nullptr, 0); + set_norm_epoch(nullptr); + set_norm_early(0); + set_late_trig(0); + set_nf_etrig(0); + TLR(cs, "norm"); + if (FB) { + // fused B-weight quant + q_b / kv_b GEMMs (one persistent launch, reads the bf16 weights once) + rc2 = launch_fused_b(wqb.data_ptr(), wkvb.data_ptr(), P8(o_qaq), PF(o_qas), P8(o_kvq), PF(o_kvs), + q.data_ptr(), kv.data_ptr(), NQ, QR, NKV, KR, Mp, cs); + rc3 = 0; + if (en.pf) cudaStreamWaitEvent(cs, sy.ev_wb, 0); // join the prefetch side stream + } else { + cudaEventRecord(sy.ev_norm, cs); + cudaStreamWaitEvent(ss, sy.ev_norm, 0); + // main needs the q_b weights from the side stream; then kv_b (side) + q_b (main) co-run, joined into main + if (!wdep_on && !fq_on) cudaStreamWaitEvent(cs, sy.ev_wb, 0); // fq_on: kv_b on ss is stream-ordered after the wquant // wdep_on: gq waits on the wquant counter in-kernel + if (qe_on) set_gq_rst(qe_cnt, 2 * nrb + 1); // first q_b/kv_b launch (after the norm) zeroes all counters + gemm_b(qcta, rc2, rc3); + set_gq_rst(nullptr, 0); + wdep_on = false; + seg0_on = false; + seg0kv_on = false; + } + g1m_on = false; + qe_on = false; + TLR(cs, "end"); + cudaGraph_t graph = nullptr; + cudaError_t ce = cudaStreamEndCapture(cs, &graph); + set_gq_ar(0); + set_pq_ptrig(0); + TORCH_CHECK(ce == cudaSuccess && graph, "end capture failed: ", cudaGetErrorString(ce)); + TORCH_CHECK(rc1 == 0 && rc2 == 0 && rc3 == 0, "gemm launch failed ", rc1, " ", rc2, " ", rc3); + + bool updated = false; + // A different GEMM1 variant changes the kernel's cluster launch config (2x1 vs none), which + // cudaGraphExecUpdate may not carry over -> always re-instantiate when the variant changes. + if (en.exec && (en.cap_fg != en.fg || en.cap_g1 != g1 || en.cap_qsp != qsp || en.cap_S != S || en.cap_f16 != F16 || en.cap_mode != MODE || en.cap_fb != en.fb || en.cap_pf != en.pf || en.cap_chunks != en.chunks || en.cap_qa != en.qa || en.cap_bqs != en.bqs || en.cap_wq != en.wq || en.cap_gqr != en.gqr || en.cap_g1r != en.g1r || en.cap_sk != en.sk || en.cap_rv != en.rv || en.cap_nq != en.nq || en.cap_prio != en.prio || en.cap_fq != en.fq || en.cap_g1lp != en.g1lp || en.cap_g1ss != en.g1ss || en.cap_g1ra != en.g1ra || en.cap_nfb != en.nfb || en.cap_pgr != en.pgr)) { + cudaDeviceSynchronize(); + cudaGraphExecDestroy(en.exec); + en.exec = nullptr; + } + if (en.exec) { + cudaGraphExecUpdateResultInfo info; + updated = cudaGraphExecUpdate(en.exec, graph, &info) == cudaSuccess; + if (!updated) { cudaGetLastError(); cudaGraphExecDestroy(en.exec); en.exec = nullptr; } + } + if (!updated) { + ce = cudaGraphInstantiate(&en.exec, graph, en.prio ? cudaGraphInstantiateFlagUseNodePriority : 0); + TORCH_CHECK(ce == cudaSuccess, "graph instantiate failed: ", cudaGetErrorString(ce)); + } + cudaGraphDestroy(graph); + en.key = key; + en.cap_g1 = g1; + en.cap_S = S; + en.cap_f16 = F16; + en.cap_qsp = qsp; + en.cap_fg = en.fg; + en.cap_mode = MODE; + en.cap_fb = en.fb; + en.cap_pf = en.pf; + en.cap_chunks = en.chunks; + en.cap_qa = en.qa; + en.cap_bqs = en.bqs; + en.cap_wq = en.wq; + en.cap_gqr = en.gqr; en.cap_g1r = en.g1r; en.cap_sk = en.sk; en.cap_rv = en.rv; en.cap_nq = en.nq; en.cap_prio = en.prio; en.cap_fq = en.fq; en.cap_g1lp = en.g1lp; en.cap_g1ss = en.g1ss; en.cap_g1ra = en.g1ra; en.cap_nfb = en.nfb; en.cap_pgr = en.pgr; + }; + + bool need_cap = !en.exec || en.key != key; + if (need_cap && en.qcta >= 0) { + // tuned config: look the pointer set up in the per-M exec LRU before (re)capturing + auto findk = [&](const Key& k) -> int { + for (size_t i = 0; i < en.slots.size(); ++i) if (en.slots[i].key == k) return (int)i; + return -1; + }; + if (en.exec && findk(en.key) < 0) en.slots.push_back({en.key, en.exec, ++en.tick}); // register current exec + const int hit = findk(key); + if (hit >= 0) { + en.exec = en.slots[hit].exec; en.key = key; en.slots[hit].t = ++en.tick; + need_cap = false; + } else { + if (en.slots.size() >= kMaxSlots) { // evict LRU: its exec is updated in place by capture() + size_t j = 0; + for (size_t i = 1; i < en.slots.size(); ++i) if (en.slots[i].t < en.slots[j].t) j = i; + en.exec = en.slots[j].exec; + en.slots.erase(en.slots.begin() + j); + } else { + en.exec = nullptr; // fresh instantiation (other slots keep their execs) + } + } + } + if (need_cap) { + capture(en.qcta > 0 ? en.qcta : 0, en.g1, en.qsp); + en.slots.push_back({en.key, en.exec, ++en.tick}); + } + // replay on the torch current stream: all outputs are ready in-order on it + cudaError_t le = cudaGraphLaunch(en.exec, ms); + TORCH_CHECK(le == cudaSuccess, "graph launch failed: ", cudaGetErrorString(le)); + + // Output views straight into the single buffer (element offsets: y1 at 0, q at Mp*NY, kv at Mp*(NY+NQ)). + const int64_t oq = (int64_t)Mp * NY, okv = (int64_t)Mp * (NY + NQ); + if (!g_fv) + return {obuf.as_strided({B, L, 128, 128}, {L * NQ, NQ, 192, 1}, oq), + obuf.as_strided({B, L, 128, 64}, {L * NQ, NQ, 192, 1}, oq + 128), + obuf.as_strided({B, L, 128, 128}, {L * NKV, NKV, 256, 1}, okv), + obuf.as_strided({B, L, 1, 64}, {L * NY, NY, 64, 1}, QR + KR), + obuf.as_strided({B, L, 128, 128}, {L * NKV, NKV, 256, 1}, okv + 128)}; + // Host-latency diet (default): the same five strided views built directly as TensorImpls sharing obuf's storage + // (sizes / strides / storage offsets identical to the as_strided calls above, no dispatcher round trip per output). + return {mkview(obuf, {B, L, 128, 128}, {L * NQ, NQ, 192, 1}, oq), + mkview(obuf, {B, L, 128, 64}, {L * NQ, NQ, 192, 1}, oq + 128), + mkview(obuf, {B, L, 128, 128}, {L * NKV, NKV, 256, 1}, okv), + mkview(obuf, {B, L, 1, 64}, {L * NY, NY, 64, 1}, QR + KR), + mkview(obuf, {B, L, 128, 128}, {L * NKV, NKV, 256, 1}, okv + 128)}; +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("run", &run, "FP8 MLA QKV projection"); } diff --git a/kernels/Quant/017_fp8_shared_expert_mlp/README.md b/kernels/Quant/017_fp8_shared_expert_mlp/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1d7682f29831466641e4fc67c6eeacb6133bec78 --- /dev/null +++ b/kernels/Quant/017_fp8_shared_expert_mlp/README.md @@ -0,0 +1,10 @@ +# FP8 shared expert MLP (Quant 017) + +DeepSeek-style shared-expert SwiGLU MLP in FP8: the input is quantized per block and the bf16 weights with the given block scales, then a gate/up GEMM, SwiGLU and a down GEMM give a bf16 output. + +- Language: CUDA C++. Entry point: `main.cpp::run`. Files: 5 (7,310 lines). +- Idea: Quant kernels feed blockwise-scaled FP8 tcgen05 GEMMs (CUTLASS and custom); gate+up as one GEMM, SwiGLU + FP8 requant fused at larger M; small M streams weights; PDL. +- Result: SOL score 0.945; speedup 9.40x over the benchmark's baseline (geometric mean). Public SOL-ExecBench results as of 2026-11-11. +- Origin: search agent (Claude). +- Comments edited; the code that runs is identical to the scored submission. +- Generated by Claude via Amazon Bedrock. Verified on the SOL-ExecBench site; not production-ready. diff --git a/kernels/Quant/017_fp8_shared_expert_mlp/kernel.json b/kernels/Quant/017_fp8_shared_expert_mlp/kernel.json new file mode 100644 index 0000000000000000000000000000000000000000..6377f6d80dde4ff088c7bc92b42cf531084a34c9 --- /dev/null +++ b/kernels/Quant/017_fp8_shared_expert_mlp/kernel.json @@ -0,0 +1,76 @@ +{ + "board": "Quant", + "id": "017_fp8_shared_expert_mlp", + "name": "FP8 shared expert MLP", + "language": "CUDA C++", + "files": [ + { + "path": "src/bw2wg.h", + "lines": 4160, + "bytes": 275669 + }, + { + "path": "src/kernel.cu", + "lines": 1766, + "bytes": 101236 + }, + { + "path": "src/kernel.h", + "lines": 21, + "bytes": 1559 + }, + { + "path": "src/main.cpp", + "lines": 55, + "bytes": 2794 + }, + { + "path": "src/smallm.cu", + "lines": 1308, + "bytes": 70433 + } + ], + "origin": "search agent (Claude)", + "result": { + "public": true, + "sol_score": 0.945265, + "speedup": 9.3988, + "board_row": true, + "note": "the row the public SOL-ExecBench board shows for this problem, as of 2026-11-11" + }, + "idea": "Quant kernels feed blockwise-scaled FP8 tcgen05 GEMMs (CUTLASS and custom); gate+up as one GEMM, SwiGLU + FP8 requant fused at larger M; small M streams weights; PDL.", + "spec": { + "languages": [ + "cuda_cpp" + ], + "target_hardware": [ + "B200", + "LOCAL" + ], + "entry_point": "main.cpp::run", + "binding": "torch", + "destination_passing_style": false, + "dependencies": [], + "compile_options": { + "cuda_cflags": [ + "-std=c++17", + "-gencode=arch=compute_100a,code=sm_100a", + "--expt-relaxed-constexpr", + "--expt-extended-lambda", + "-O3", + "-DNDEBUG" + ], + "ld_flags": [ + "-lcuda" + ], + "cflags": [] + }, + "sources": [ + "kernel.h", + "bw2wg.h", + "kernel.cu", + "smallm.cu", + "main.cpp" + ] + } +} diff --git a/kernels/Quant/017_fp8_shared_expert_mlp/src/bw2wg.h b/kernels/Quant/017_fp8_shared_expert_mlp/src/bw2wg.h new file mode 100644 index 0000000000000000000000000000000000000000..48c3024cd1be1f738c4a077ce5569a97be63da04 --- /dev/null +++ b/kernels/Quant/017_fp8_shared_expert_mlp/src/bw2wg.h @@ -0,0 +1,4160 @@ +#pragma once +// all quant reciprocals 1.0f/sc -> __frcp_rn(sc) (IEEE RN reciprocal: bit-identical, MUFU.RCP + fixup, no div slow path) +// --------------------------------------------------------------------------------------------------------- +// Blockwise-scaled FP8 GEMM kernel for SM100 with FOUR promotion warpgroups (local, modified vendor copy of +// CUTLASS 4.4.1 kernel/sm100_gemm_tma_warpspecialized_mma_transform.hpp). Two configurations: +// * 1SM 128x128x128 (v7): each of 4 warpgroups promotes 32 columns. +// * 2SM 256x256x128, cluster 2x1 (v8): tcgen05.mma cta_group::2 issued by the even (leader) CTA; each CTA +// holds 128 rows x 256 cols in TMEM (2 accumulator stages x 256 cols = all 512 columns), A per CTA, B tile +// split across the pair. Each of 4 warpgroups promotes 64 columns into 64 fp32 regs/thread (4 x 16-column +// TMEM chunks per K block). 2SM extras as in CUTLASS: Allocator2Sm, leader-only MMA + accumulator +// producer_tail, peer TMEM-dealloc cluster barrier, accumulator consumers counted for both CTAs. +// +// Unchanged from CUTLASS (reused through the CollectiveMainloop built by the CollectiveBuilder for +// KernelTmaWarpSpecializedBlockwise1SmSm100): TMA A/B producer warp, scale-factor (cp.async) producer warp, +// tcgen05 MMA warp writing each 128-K block's partial product into one of 4 TMEM accumulator stages +// (PipelineUmmaAsync, so MMA of k-block kb+1.. overlaps promotion of kb), CLC persistent tile scheduler. +// +// Changed: +// * warp roles: 0 MMA, 1 CLC sched, 2 TMA A/B load, 3 scale-factor load (was the unused C-load warp), +// 4-19 = FOUR promotion/epilogue warpgroups (CUTLASS uses one warpgroup = 128 threads). +// * promotion (accumulator transform): warpgroup g owns columns [g*N/4, +N/4) of the CTA tile; warp +// (w%4) owns TMEM lanes / tile rows [32(w%4), +32), one row per thread. Per k-block a thread issues two +// tcgen05.ld.32x32b.x32 (64 fp32 columns), one wait::ld, releases the TMEM stage back to the MMA warp, +// then does acc += partial * (sa[row]*sb) with 32 packed fma.rn.f32x2. 64 accumulator regs / thread. +// Stage TMEM address = base + index*stride in registers (no stack array -> no LDL in the K loop). +// * epilogue: no CUTLASS collective epilogue (D = acc, source-less, alpha=1): each thread converts its 64 +// fp32 to bf16 (RN, same as the CUTLASS LinearCombination epilogue) and writes 8 x 16B straight to D, +// predicated on row < M and col < N. No epilogue smem -> more A/B stages. +// --------------------------------------------------------------------------------------------------------- +#include "cutlass/cutlass.h" +#include "cutlass/gemm/kernel/gemm_universal.hpp" +#include "cutlass/pipeline/pipeline.hpp" +#include "cute/tensor.hpp" +#include +#include +#include + + +namespace se2wg { +using namespace cute; +// kPair split-K DSMEM exchange in SE_PAIR_NCH chunks (1, 2 or 4), each with its own receive mbarrier +#ifndef SE_PAIR_NCH +#define SE_PAIR_NCH 4 +#endif +constexpr int pair_nch = SE_PAIR_NCH; +// kPair split cluster barrier: the setup cluster barrier (peer mbarriers initialized before any remote access) is +// split into arrive.release right after barrier init and wait.acquire right before the first DSMEM access (promotion +// threads: the split-K exchange; every other thread: the exit cluster barrier), so the producer warps reach +// griddepcontrol.wait / the first TMA without waiting for the peer CTA's setup. +#ifndef SE_PAIR_SPLITBAR +#define SE_PAIR_SPLITBAR 1 +#endif +constexpr bool pair_split = SE_PAIR_SPLITBAR != 0; +static_assert(SE_PAIR_NCH == 1 || SE_PAIR_NCH == 2 || SE_PAIR_NCH == 4, "chunk count (receive barriers pair_bar[4], [6..8])"); +// receive barrier of chunk j given chunk 0's (pair_bar[4]) address: chunk j > 0 -> pair_bar[5 + j] +__device__ __forceinline__ uint32_t pair_cbar(uint32_t b0, int j) { return b0 + (j == 0 ? 0u : (uint32_t)(j + 1) * 8u); } + +// tcgen05.ld 32 lanes x 32 bit, 32 consecutive columns -> 32 regs per thread (thread i = lane base + i) +__device__ __forceinline__ void tmem_ld32(uint32_t taddr, float* v) { + uint32_t* r = reinterpret_cast(v); + 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)); +} +// tcgen05.ld 32 lanes x 32 bit, 16 consecutive columns -> 16 regs per thread +__device__ __forceinline__ void tmem_ld16(uint32_t taddr, float* v) { + uint32_t* r = reinterpret_cast(v); + 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"(taddr)); +} +// tcgen05.ld 32 lanes x 32 bit, 8 consecutive columns -> 8 regs per thread +__device__ __forceinline__ void tmem_ld8(uint32_t taddr, float* v) { + uint32_t* r = reinterpret_cast(v); + 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"(taddr)); +} +// two fp32 -> packed bf16x2 (RN), low 16 bits = lo (== __floats2bfloat162_rn(lo, hi)) +__device__ __forceinline__ uint32_t pk_bf16x2(float lo, float hi) { + uint32_t r; + asm("cvt.rn.bf16x2.f32 %0, %1, %2;" : "=r"(r) : "f"(hi), "f"(lo)); + return r; +} +__device__ __forceinline__ void tmem_ld_wait() { asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); } +__device__ __forceinline__ void tc_fence_before() { asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory"); } + +// packed RN ops on float2 (one instruction for two lanes, results identical to the scalar RN ops) +__device__ __forceinline__ float2 mul2_rn(float2 x, float s) { + float2 r; + asm("{\n\t.reg .b64 rx, rs;\n\tmov.b64 rx, {%2, %3};\n\tmov.b64 rs, {%4, %4};\n\t" + "mul.rn.f32x2 rx, rx, rs;\n\tmov.b64 {%0, %1}, rx;\n\t}" + : "=f"(r.x), "=f"(r.y) : "f"(x.x), "f"(x.y), "f"(s)); + return r; +} +__device__ __forceinline__ float2 fma2_rn(float2 a, float2 b, float2 c) { // a * b + c + float2 r; + asm("{\n\t.reg .b64 ra, rb, rc;\n\tmov.b64 ra, {%2, %3};\n\tmov.b64 rb, {%4, %5};\n\tmov.b64 rc, {%6, %7};\n\t" + "fma.rn.f32x2 ra, ra, rb, rc;\n\tmov.b64 {%0, %1}, ra;\n\t}" + : "=f"(r.x), "=f"(r.y) : "f"(a.x), "f"(a.y), "f"(b.x), "f"(b.y), "f"(c.x), "f"(c.y)); + return r; +} +// packed (a0,a1) += (p0,p1) * (s,s) via fma.rn.f32x2 (one instruction for two accumulators) +__device__ __forceinline__ void fma2(float& a0, float& a1, float p0, float p1, float s) { + asm("{\n\t.reg .b64 ra, rp, rs;\n\t" + "mov.b64 ra, {%0, %1};\n\t" + "mov.b64 rp, {%2, %3};\n\t" + "mov.b64 rs, {%4, %4};\n\t" + "fma.rn.f32x2 ra, rp, rs, ra;\n\t" + "mov.b64 {%0, %1}, ra;\n\t}" + : "+f"(a0), "+f"(a1) + : "f"(p0), "f"(p1), "f"(s)); +} + +// packed-scale variant: (a0,a1) += (p0,p1) * s2, s2 = {s, s} packed ONCE per 32-col chunk (one 64-bit register +// pair reused by all 16 fma.rn.f32x2 of the chunk: no per-FMA scale pair materialization); same RN fma -> bit-identical +__device__ __forceinline__ uint64_t pack_s2(float s) { + uint64_t r; + asm("mov.b64 %0, {%1, %1};" : "=l"(r) : "f"(s)); + return r; +} +__device__ __forceinline__ void fma2s(float& a0, float& a1, float p0, float p1, uint64_t s2) { + asm("{\n\t.reg .b64 ra, rp;\n\t" + "mov.b64 ra, {%0, %1};\n\t" + "mov.b64 rp, {%2, %3};\n\t" + "fma.rn.f32x2 ra, rp, %4, ra;\n\t" + "mov.b64 {%0, %1}, ra;\n\t}" + : "+f"(a0), "+f"(a1) + : "f"(p0), "f"(p1), "l"(s2)); +} +__device__ __forceinline__ float silu_fma(float g) { + const float t = fminf(fmaxf(g * -1.4426950408889634f, -64.f), 64.f); + const float r = __fsub_rn(__fadd_rn(t, 12582912.0f), 12582912.0f); // round to nearest integer + const float f = __fsub_rn(t, r); + float p = fmaf(0.05508868f, f, 0.24260405f); + p = fmaf(p, f, 0.69327624f); + p = fmaf(p, f, 0.99992894f); + const float e = __int_as_float(__float_as_int(p) + ((int)r << 23)); + const float d = 1.0f + e; + float y = __int_as_float(0x7EF311C7 - __float_as_int(d)); + y = y * fmaf(-d, y, 2.0f); + y = y * fmaf(-d, y, 2.0f); + return g * y; +} +// fused-epilogue column pairs (bit p = pair p of 16) whose silu runs on the FMA pipe (0 = all MUFU.TANH) +#ifndef SE_SILU_MASK +#define SE_SILU_MASK 0u +#endif +__device__ __forceinline__ float silu_tanh(float g) { + const float hg = 0.5f * g; + float t; + asm("tanh.approx.f32 %0, %1;" : "=f"(t) : "f"(hg)); + return fmaf(hg, t, hg); +} + +// named barrier helpers for the split-K epilogue (ids 12/13 are above CUTLASS's reserved barriers) +__device__ __forceinline__ void named_bar_sync(int id, int n) { + asm volatile("bar.sync %0, %1;" ::"r"(id), "r"(n) : "memory"); +} +// barrier among n threads that also ORs a predicate across them (barrier.cta.red.or) +__device__ __forceinline__ int named_bar_red_or(int id, int n, int pred) { + int r; + asm volatile("{\n\t.reg .pred p, q;\n\tsetp.ne.s32 p, %1, 0;\n\t" + "barrier.cta.red.or.pred q, %2, %3, p;\n\tselp.s32 %0, 1, 0, q;\n\t}" + : "=r"(r) : "r"(pred), "r"(id), "r"(n) : "memory"); + return r; +} + +// ---- TMA-store epilogue helpers (kTmaStore) ---- +__device__ __forceinline__ void fence_proxy_async_smem() { asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); } +// 2-D TMA store smem -> global (box from the tensor map), tracked by the bulk async-group of this thread +__device__ __forceinline__ void tma_store_2d(const void* tmap, uint32_t smem, int c0, int c1) { + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group [%0, {%2, %3}], [%1];" + ::"l"(tmap), "r"(smem), "r"(c0), "r"(c1) : "memory"); + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); +} +// same store with an L2 cache-hint policy (createpolicy result) +__device__ __forceinline__ void tma_store_2d_hint(const void* tmap, uint32_t smem, int c0, int c1, uint64_t pol) { + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%2, %3}], [%1], %4;" + ::"l"(tmap), "r"(smem), "r"(c0), "r"(c1), "l"(pol) : "memory"); + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); +} +__device__ __forceinline__ uint64_t l2_pol_evict_first() { + uint64_t p; asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(p)); return p; +} +__device__ __forceinline__ uint64_t l2_pol_evict_last() { + uint64_t p; asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(p)); return p; +} +// wait until all of this thread's bulk stores have finished READING smem (buffer reusable) +__device__ __forceinline__ void bulk_wait_read0() { asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); } +// wait until all of this thread's bulk stores are complete (globally visible) +__device__ __forceinline__ void bulk_wait_all0() { asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); } + + +// ---- kCq: in-kernel quantization of x and the down weights (MO kJit, separate instantiation) ------------------- +// The pre-kernel quant pass only quantizes the gate/up weights. x (1x128 row scales) and the down weights (given +// 128x128 scales) are converted INSIDE the merged kernel by one extra CONVERTER warpgroup (warps 20-23) per CTA. +// Work = global ordered ticket list of CHUNKS (16 rows x one 128-wide k block = 4 KB bf16): +// [x chunk rows [0, r1) in groups of rg rows, kb-major inside a group] [down: slab-major (256 rows), kb, 16 chunks] +// [x chunk rows [r1, nr) in groups of rg rows, kb-major inside a group] +// Each converter WARP independently claims chunks one at a time (atomicAdd on a ticket zeroed by the quant kernel, +// one claim ahead), TMA-loads them into its own 2-slot smem ring (double buffer), converts (same math as fused_quant_kernel; satfinite e4m3, +// 16 B stores) and publishes one arrival per chunk: +// x: ready[tile128 * KB1 + kb] target = 16-row chunks of the tile (8 for a full tile) +// down: ready[NXC + slab256 * KB2 + kb] target 16 +// with fence.proxy.async.global + red.release.gpu. Consumers acquire-poll before use: the A/B producer before each GU +// A TMA (its CTA's 128-row tile) and DN B TMA (the unit's 256-row slab), the scale warp before each GU sx load. +// Converters never wait on anything but their own copies -> every claimed chunk completes (no deadlock). +struct CqArgs { + alignas(64) CUtensorMap tm_x; // x bf16 [Mr, Hd], box 128 k x 32 rows, no swizzle (rows >= Mr zero-filled) + alignas(64) CUtensorMap tm_d; // down weight bf16 [Hd, I], box 128 k x 32 rows + const float* ds; // down scales [I/128][Hd/128] + uint8_t* qx; float* sx; uint8_t* qwd; + int* ready; // x tile counters [ceil(M/128)][KB1], then down slab counters [Hd/256][KB2] (zeroed per call) + int* ticket; // chunk ticket (zeroed per call) + int M, Hd, I; + int rg; // x chunk rows (32-row units) per group + int r1; // x chunk rows before the down region (multiple of rg or nr) + int on; // bit 0: convert (0 = probe only: bypassed, counters prefilled); bit 1: evict_first source loads; + // bit 2: evict_last fp8 stores + int ds0; // down slabs [0, ds0) (256 rows each) quantized by the front quant pass (counters preset ready); + // the converters handle slabs [ds0, Hd/256) + int nxr; // x chunk rows in the list: ceil(M / 16), or 0 = x quantized by the quant kernel (down weights only) + int cb; // tickets per claim (consecutive tickets share a readiness counter -> one release per claim) + int xr0; // first in-kernel x chunk row (16-row units, 128-row tile aligned); x rows [0, 16 xr0) come from + // the front quant pass (their tiles are never polled), chunk rows [xr0, xr0 + nxr) are converted here + const void* xp; const void* dwp; int Mr; // host only (params cache key) +}; +constexpr int kCqRows = 16; // chunk = 16 rows x 128 k (4 KB bf16), converted by ONE warp +constexpr int kCqNR = 8; // converter ring: 2 slots of 4 KB per converter warp (double buffer) +__device__ __forceinline__ int cq_nr(const CqArgs& a) { return a.nxr; } +__device__ __forceinline__ int cq_nxc(const CqArgs& a) { return ((a.M + 127) >> 7) * (a.Hd >> 7); } +__device__ __forceinline__ int cq_nd(const CqArgs& a) { return (a.Hd / kCqRows - a.ds0 * (256 / kCqRows)) * (a.I >> 7); } +__device__ __forceinline__ int cq_total(const CqArgs& a) { return cq_nr(a) * (a.Hd >> 7) + cq_nd(a); } +// x readiness target of 128-row tile t (one arrival per 16-row chunk); 0 = tile entirely beyond M +__device__ __forceinline__ int cq_xtarget(const CqArgs& a, int t) { + const int rows = a.M - 128 * t; + if (rows <= 0 || a.nxr == 0) return 0; // nxr == 0: x converted by the quant kernel (no in-kernel x chunks) + if (128 * (t + 1) <= a.xr0 * kCqRows) return 0; // tile quantized by the front pass + const int ch = (rows + kCqRows - 1) / kCqRows; + return ch < 128 / kCqRows ? ch : 128 / kCqRows; +} +__device__ __forceinline__ uint32_t cq_bmax(uint32_t m, uint32_t u) { return __vmaxu2(m, u & 0x7fff7fffu); } +__device__ __forceinline__ uint32_t cq_q4(uint32_t a, uint32_t b, float inv) { + const float a0 = __uint_as_float(a << 16), a1 = __uint_as_float(a & 0xffff0000u); + const float b0 = __uint_as_float(b << 16), b1 = __uint_as_float(b & 0xffff0000u); + const uint32_t lo = (uint16_t)__nv_cvt_float2_to_fp8x2(make_float2(a0 * inv, a1 * inv), __NV_SATFINITE, __NV_E4M3); + const uint32_t hi = (uint16_t)__nv_cvt_float2_to_fp8x2(make_float2(b0 * inv, b1 * inv), __NV_SATFINITE, __NV_E4M3); + return lo | (hi << 16); +} +// 4 bf16 (words a = {e0, e1}, b = {e2, e3}) * inv -> 4 e4m3 bytes (byte i = element i), == cq_q4: bf16 unpack, packed +// mul.rn.f32x2 (same RN products), cvt.rn.satfinite.e4m3x2 (upper byte from the first operand), one asm block +__device__ __forceinline__ uint32_t cq_q4p(uint32_t a, uint32_t b, float inv) { + uint32_t r; + asm("{\n\t.reg .f32 x0, x1, y0, y1;\n\t.reg .b64 px, py, ps;\n\t.reg .b16 l, h;\n\t" + "shl.b32 x0, %1, 16;\n\tand.b32 x1, %1, 0xffff0000;\n\t" + "shl.b32 y0, %2, 16;\n\tand.b32 y1, %2, 0xffff0000;\n\t" + "mov.b64 ps, {%3, %3};\n\t" + "mov.b64 px, {x0, x1};\n\tmul.rn.f32x2 px, px, ps;\n\tmov.b64 {x0, x1}, px;\n\t" + "mov.b64 py, {y0, y1};\n\tmul.rn.f32x2 py, py, ps;\n\tmov.b64 {y0, y1}, py;\n\t" + "cvt.rn.satfinite.e4m3x2.f32 l, x1, x0;\n\t" + "cvt.rn.satfinite.e4m3x2.f32 h, y1, y0;\n\t" + "mov.b32 %0, {l, h};\n\t}" + : "=r"(r) : "r"(a), "r"(b), "f"(inv)); + return r; +} +// whole warp: lane j acquire-polls p[j] (j < n); spins until p[0] is ready, returns the number of consecutive ready +// counters from p[0] (>= 1, <= n), then orders them before this warp's later async-proxy (TMA) / cp.async reads +__device__ __forceinline__ int cq_wait_prefix(const int* p, int n, int target) { + const int lane = (int)(threadIdx.x & 31); + if (n > 32) n = 32; + int spins = 0; + while (true) { + int v = target; + if (lane < n) asm volatile("ld.acquire.gpu.global.s32 %0, [%1];" : "=r"(v) : "l"(p + lane) : "memory"); + const unsigned nr = __ballot_sync(0xffffffffu, v < target); + int k = nr ? __ffs(nr) - 1 : 32; + if (k > n) k = n; + if (k >= 1) { + __syncwarp(); + asm volatile("fence.proxy.async.global;" ::: "memory"); + return k; + } + // tight acquire re-poll (no nanosleep): readiness waits gate DN / GU-tail unit starts (critical path) + // energy backoff: after 256 failed polls (a long wait: data far from ready) back off with a short nanosleep so + // the spinning warp stops occupying issue slots / L2 request bandwidth; short waits stay tight + if (++spins > 256) __nanosleep(64); + } +} + +// kStatic (2SM fused 256x256 gate_up, or 1SM plain 128x128 down; below "pair tile" = cluster tile, s <= 4): +// static host-computed work list instead of the CLC scheduler. Work units: +// [0, st_dp) : full-K data-parallel pair tiles (tile = unit) +// [st_dp, st_units) : split-K units of the tail tiles: unit -> (tail tile tt, split j), k-blocks +// [j*KT/s, (j+1)*KT/s). Every split unit stores its fp32 partial (per CTA +// 128x256) to split_ws and bumps split_cnt[tt*2+rank]; the last arriving unit +// sums all s partials in fixed order j=0..s-1 (deterministic) and stores bf16. +// Cluster c (of G resident pair-clusters) processes units c, c+G, c+2G, ...: the DP waves come first, the +// split-K tail units form the final (partial) wave, so the tail wave is filled ~s times more evenly. +#ifndef SE_GU_B_HINT +#define SE_GU_B_HINT 1 +#endif +#ifndef SE_DN_A_HINT +#define SE_DN_A_HINT 1 +#endif +#ifndef SE_DN_B_HINT +#define SE_DN_B_HINT 1 +#endif +// access to the collective's (protected) TMA atom pointers via pointer-to-member of a derived helper +template +struct TmaAccessOf : CM { + using CM::observed_tma_load_a_; + using CM::observed_tma_load_b_; +}; +template +class Blockwise2WGKernel { + public: + using ProblemShape = ProblemShape_; + using CollectiveMainloop = CollectiveMainloop_; + using TileShape = typename CollectiveMainloop::TileShape; + using TiledMma = typename CollectiveMainloop::TiledMma; + using ArchTag = typename CollectiveMainloop::ArchTag; + using ElementA = typename CollectiveMainloop::ElementA; + using StrideA = typename CollectiveMainloop::StrideA; + using ElementB = typename CollectiveMainloop::ElementB; + using StrideB = typename CollectiveMainloop::StrideB; + using DispatchPolicy = typename CollectiveMainloop::DispatchPolicy; + using ElementAccumulator = typename CollectiveMainloop::ElementAccumulator; + using ClusterShape = typename DispatchPolicy::ClusterShape; + using MainloopArguments = typename CollectiveMainloop::Arguments; + using MainloopParams = typename CollectiveMainloop::Params; + using MainloopTmaAccess = TmaAccessOf; + + // Epilogue types are only kept for the Arguments layout / device adapter typedefs. + using CollectiveEpilogue = CollectiveEpilogue_; + using EpilogueTile = typename CollectiveEpilogue::EpilogueTile; + using ElementC = typename CollectiveEpilogue::ElementC; + using StrideC = typename CollectiveEpilogue::StrideC; + using ElementD = typename CollectiveEpilogue::ElementD; + using StrideD = typename CollectiveEpilogue::StrideD; + using EpilogueArguments = typename CollectiveEpilogue::Arguments; + static_assert(cute::is_void_v, "source-less epilogue only"); + static_assert(cute::is_same_v, "bf16 output only"); + + static constexpr uint32_t SchedulerPipelineStageCount = DispatchPolicy::Schedule::SchedulerPipelineStageCount; + static constexpr uint32_t AccumulatorPipelineStageCount = DispatchPolicy::Schedule::AccumulatorPipelineStageCount; + + using AtomThrShapeMNK = typename CollectiveMainloop::AtomThrShapeMNK; + using CtaShape_MNK = typename CollectiveMainloop::CtaShape_MNK; + using TileSchedulerTag = TileSchedulerTag_; + static_assert(cute::is_void_v || + cute::is_same_v, + "data-parallel scheduler only (no split-K fixup in this kernel)"); + using TileScheduler = typename cutlass::gemm::kernel::detail::TileSchedulerSelector< + TileSchedulerTag, ArchTag, CtaShape_MNK, ClusterShape, SchedulerPipelineStageCount>::Scheduler; + using TileSchedulerArguments = typename TileScheduler::Arguments; + using TileSchedulerParams = typename TileScheduler::Params; + static constexpr bool IsSchedDynamicPersistent = TileScheduler::IsDynamicPersistent; + + // Supported: 1SM MMA with a 128x128 CTA tile, or 2SM (cta_group::2) MMA 256x256 -> 128x256 per CTA. + static constexpr bool kTwoSm = size(AtomThrShapeMNK{}) == 2; + static constexpr int kCtaN = size<1>(CtaShape_MNK{}); // 128 (1SM) or 256 (2SM) + // Ping-pong (v9 1SM 128x128 / 2SM 256x128 = 128x128 per CTA, B tile split across the CTA pair): WG0-1 = + // team 0, WG2-3 = team 1; teams alternate persistent tiles (both CTAs of a pair see the same tile sequence, so + // the same team consumes a given TMEM stage in both CTAs), each WG promotes 64 of the 128 columns. Otherwise all 4 WGs share every tile (kCtaN/4 columns each). + static constexpr bool kPingPong = kPingPong_; + // kN224 (2SM 256x224 TMA-store down GEMM, 7168 = 32 x 224): per CTA 128 x 224; WG0-2 promote 64 cols each, WG3 + // the last 32 (cols 192..223). B scales come at 32-col granularity (the 224 tile straddles 128-col weight blocks at + // a multiple of 32): one scale per 32-col TMEM chunk (scale for chunk 0, scale_hi for chunk 1). + // kN160 (1SM 128x160 TMA-store down tile, M384 bucket: 3 x 45 = 135 CTAs in one wave instead of 2 x 32 2SM + // pairs with a half-padded M block): same layout family as kN224 ("kN224" below = odd 32-col tail family): WG0/WG1 + // promote 64 cols, WG2 the last 32 (cols 128..159), WG3 idle (waits / releases only). Last N tile is partial + // (7168 = 44 x 160 + 128): TMA zero-fills / clips, the 32-col direct store is predicated on col < N. + static constexpr bool kN224 = kCtaN == 224 || kCtaN == 160; // also 1SM 128x224 (same per-CTA 128 x 224 layout) + static constexpr int kHalfWg = (kCtaN - 32) / 64; // kN224 family: WG owning the 32-col tail (224: 3, 160: 2) + // kHalfStg (1SM 128x224 TMA-store down tile built with the trimmed carve-out, Gemm1SM224TmaC -> 4 A/B stages + // instead of 3): each staging WG (0-2) writes its 128 x 64 bf16 slice as two 32-col halves (64 B rows, SWIZZLE_64B) + // through ONE 8 KB buffer (2nd half waits until the 1st half's TMA store has read it), 24 KB staging instead of 48 KB. + // Selected by the stage count (the default-carve-out build has 3 stages and keeps the 16 KB-per-WG staging). + static constexpr bool kHalfStg = kTmaStore_ && !kMerged_ && !kTwoSm && kCtaN == 224 && (int)DispatchPolicy::Stages >= 4; + // kBal40: promotion columns now 40/40/40/40 (x32 + x8 per WG, see the kBal160 promotion / epilogue code); + // the description below is the previous 48/48/32/32 layout. + // kBal160 (1SM 128x160 TMA-store down tile, / M384): promotion columns rebalanced 64/64/32/0 -> 48/48/32/32. + // WG0 / WG1 promote cols [0,48) / [64,112) of their 64-col slice, WG2 [128,160), the formerly idle WG3 promotes the + // other two 16-col chunks [48,64) and [112,128) and, in the epilogue, writes them as bf16 straight into WG0's / WG1's + // 128B-swizzled staging tiles (chunks 6,7) before their TMA stores (256-thread named barriers 8 / 9 = WG0|WG1 + WG3). + // Per-kb promotion critical path 64 -> 48 columns per thread; same per-element FMA / scale -> bit-identical. +#ifndef SE_BAL160 +#define SE_BAL160 1 +#endif + static constexpr bool kBal160 = SE_BAL160 && kCtaN == 160 && kTmaStore_ && !kMerged_ && size(AtomThrShapeMNK{}) == 1; + // kBal224 (1SM 128x224 kHalfStg TMA-store down tile, / M512 bucket): promotion columns rebalanced + // 64/64/64/32 -> 56/56/56/56. WG g < 3 promotes cols [64g, 64g+56) of its slice (x16, x16 | x16, x8: two TMEM round + // trips per kb instead of three), WG3 its own [192,224) plus the three 8-col pieces [64b+56, +8) (b = 0..2, B-scale + // groups 1/3/5) and, in the epilogue, writes those bf16 pieces into chunk 3 of WG b's second-half SWIZZLE_64B staging + // tile (256-thread named barriers 12+b = WG b + WG3 around the second half). Same per-element FMA / scale -> + // bit-identical. +#ifndef SE_BAL224 +#define SE_BAL224 0 +#endif + static constexpr bool kBal224 = SE_BAL224 && kHalfStg; + // kLateNM (kHalfStg 1SM 128x224 TMA-store down GEMM, M512 chain bucket): the MMA warp fetches the next CLC work + // tile AFTER issuing the unit's MMAs (was before the first MMA: a CLC try_cancel round trip right after the PDL wait, + // on the per-CTA first-MMA path) and relays it then; the promotion warps read the relayed tile after their k loop + // (it is only used by the epilogue: last-tile ring staging decision + loop continuation). Same MMAs -> bit-identical. +#ifndef SE_LATE_NM +#define SE_LATE_NM 1 +#endif + static constexpr bool kLateNM = SE_LATE_NM && kHalfStg; + static constexpr int kWgCols = kN224 ? 64 : (kPingPong ? kCtaN / 2 : kCtaN / 4); // columns promoted per warpgroup + static constexpr bool kFuse = kFuse_; + static_assert(!kFuse || (!kPingPong && kCtaN == 256), "fused SwiGLU epilogue: 2SM 256x256 or 1SM 128x256 only"); + static constexpr bool kTmaStore = kTmaStore_; + // kMerged: ONE persistent kernel running the fused gate_up GEMM (units [0, gu_units)) AND the down GEMM + // (units [gu_units, st_units)). Both are 2SM 256x256 blockwise FP8 with identical smem / TMEM layouts; only the + // TMA descriptors / scale pointers (mainloop vs mainloop_dn params) and the epilogue differ: + // gate_up unit u: mb = u / gu_tn, nt = u % gu_tn -> fused SwiGLU + fp8 requant epilogue (writes qh, sh); then + // each CTA bumps mb_cnt[mb]; the last of the 2*gu_tn CTA arrivals resets it and publishes + // mb_flag[mb] = epoch (st.release.gpu). + // down unit: mb = d / dn_tn, nt = d % dn_tn -> TMA A/B and SF producer warps spin (ld.acquire.gpu) until + // mb_flag[mb] == epoch, fence.proxy.async.global, then load qh/sh; TMA-store bf16 epilogue (as ). + // Units are handed out in increasing order by CLC, and every gate_up unit precedes every down unit, so all gate_up + // tiles a waiting down unit depends on are already owned by running clusters (which never wait) -> no deadlock. + static constexpr bool kMerged = kMerged_; + static_assert(!kMerged || (kFuse_ && kStatic_ && !kTmaStore_), "merged: built on the fused static 2SM kernel"); + static constexpr bool kEpiStage = kTmaStore || kMerged; + static_assert(!kTmaStore || (!kFuse_ && !kStatic_ && !kPingPong_ && ((kTwoSm && kCtaN == 256) || kCtaN == 224 || (!kTwoSm && kCtaN == 160))), + "TMA-store epilogue: plain 2SM 256x256 only (64 cols = 128 B per warpgroup row)"); + static_assert(!kStatic_ || (kTwoSm && kFuse_) || (!kTwoSm && !kFuse_ && !kPingPong_) || + (!kTwoSm && kFuse_ && kCtaN == 256), + "static split-K schedule: fused 2SM 256x256, fused 1SM 128x256 (v17) or plain 1SM 128x128 (4WG) only"); + static_assert(size<0>(CtaShape_MNK{}) == 128, "128-row CTA tile only"); + static_assert((!kTwoSm && (kCtaN == 128 || (kCtaN == 256 && kFuse_) || ((kCtaN == 224 || kCtaN == 160) && kTmaStore_))) || (kTwoSm && (kCtaN == 256 || (kCtaN == 224 && kTmaStore_) || (kCtaN == 128 && kPingPong_))), + "1SM 128x128, 2SM 256x256, or 2SM 256x128 ping-pong (v13) only"); + static_assert(CollectiveMainloop::ScaleKsPerTile == 1, "one scale block per K tile"); + static_assert(!kPingPong || (kCtaN == 128 && AccumulatorPipelineStageCount >= 2), + "ping-pong: 128-col CTA tile (1SM 128x128 or 2SM 256x128), >=2 TMEM stages"); + static_assert(kN224 ? (CollectiveMainloop::ScaleGranularityN == 32) : (CollectiveMainloop::ScaleGranularityN % kWgCols == 0), "one B scale per warpgroup column slice"); + + // Warp roles + static constexpr uint32_t NumSchedThreads = 32; + static constexpr uint32_t NumMMAThreads = 32; + static constexpr uint32_t NumMainloopABLoadThreads = 32; + static constexpr uint32_t NumMainloopSFLoadThreads = 32; + static constexpr uint32_t NumPromoWarpGroups = 4; + static constexpr uint32_t NumEpilogueThreads = 128 * NumPromoWarpGroups; // promotion + store threads + // threads that consume (wait + release) each SF / TMEM accumulator stage: one team in ping-pong mode + static constexpr uint32_t NumStageConsumers = kPingPong ? NumEpilogueThreads / 2 : NumEpilogueThreads; + // kMerged: one extra STAGING-EPILOGUE warpgroup (warps 20-23) that runs the fused SwiGLU/requant of gate_up + // units from the smem staging buffer while the 4 promotion WGs already promote the next unit. + static constexpr bool kStg = kMerged_ && kStgWG_; + // kCq: one extra CONVERTER warpgroup (warps 20-23), see the converter role + static constexpr bool kCq = kCq_; + static constexpr uint32_t NumStgThreads = (kStg || kCq_) ? 128 : 0; + static constexpr uint32_t MaxThreadsPerBlock = 128 + NumEpilogueThreads + NumStgThreads; // 640 (768 merged) + static constexpr uint32_t MinBlocksPerMultiprocessor = 1; + static constexpr uint32_t NumEpilogueSubTiles = CollectiveEpilogue::get_load_pipe_increment(CtaShape_MNK{}); + static constexpr uint32_t NumFixupBarriers = 1; + static constexpr uint32_t CLCResponseSize = sizeof(typename TileScheduler::CLCResponse); + + using MainloopABPipeline = typename CollectiveMainloop::MainloopABPipeline; + using MainloopABPipelineState = typename CollectiveMainloop::MainloopABPipelineState; + // kHalves (merged kernels): each 128-K block's 256x256 2SM MMA is issued as two 256x128 N-halves into a + // 4-slot x 128-column TMEM ring (own PipelineUmmaAsync<4>), see the MMA warp / promotion code. +#ifndef SE_HALVES +#define SE_HALVES 1 +#endif + static constexpr bool kHalves = kMerged_ && SE_HALVES && kHalvesK_; + using AccumulatorPipeline = cute::conditional_t, + typename CollectiveMainloop::AccumulatorPipeline>; + using AccumulatorPipelineState = typename AccumulatorPipeline::PipelineState; + using MainloopSFPipeline = typename CollectiveMainloop::MainloopSFPipeline; + using MainloopSFPipelineState = typename MainloopSFPipeline::PipelineState; + using CLCPipeline = cutlass::PipelineCLCFetchAsync; + using CLCPipelineState = typename CLCPipeline::PipelineState; + using CLCThrottlePipeline = cutlass::PipelineAsync; + using CLCThrottlePipelineState = typename CLCThrottlePipeline::PipelineState; + using TmemAllocator = cute::conditional_t; + + // kStatic: 56 for the producer/MMA/sched warps (work-unit decode); 128*56 + 512*104 = 60416 <= 61440 pool. + // 640 threads at 1 CTA/SM -> launch allocation 96 regs/thread (pool 640*96 = 61440). 128*48 + 512*R must fit + // -> R <= 108 -> 104 (2SM: 64 fp32 accumulators + 32 partials per thread). + // kStg (768 threads -> launch allocation 80 regs, pool 61440): promotion WGs get 104 too (2 x x32 TMEM loads + // without spills), producer/MMA/sched warps and the staging WG share the rest: + // 128*SE_STG_GEN + 512*104 + 128*SE_STG_REGS <= 61440 -> GEN + STG <= 64. Default 24 + 40 (= exactly the pool): + // cudaFuncGetAttributes local bytes of the MS kernel: 32/32 -> 32 B, 40/24 -> 32 B (staging WG spills), 24/40 -> 0. +#ifndef SE_STG_GEN +#define SE_STG_GEN 24 +#endif +#ifndef SE_STG_REGS +#define SE_STG_REGS 40 +#endif + static_assert(SE_STG_GEN + SE_STG_REGS <= 64, "kStg register pool overflow (setmaxnreg would hang)"); + // kCq (768 threads, pool 61440): 128*SE_CQ_GEN + 512*104 + 128*(64 - SE_CQ_GEN) = 61440 +#ifndef SE_CQ_GEN +#define SE_CQ_GEN 32 +#endif +#ifndef SE_CQ_GEN_ALT +#define SE_CQ_GEN_ALT 32 // probe-only alternate (kRegs_=false kCq instantiation, not dispatched) +#endif +#ifndef SE_BASE_GEN +#define SE_BASE_GEN 56 // kJit non-kJitRegs (JitBase) producer registers +#endif + // register rebalance of the MO kJit instantiations (plain + kRedSplit, not kCq): 640 threads, pool 61440 -> + // promotion WGs SE_JIT_PROMO regs (default 112), producer / MMA / scheduler warps SE_JIT_GEN (default 32): + // 128*32 + 512*112 = 61440. Was 56 / 104. +#ifndef SE_JIT_PROMO +#define SE_JIT_PROMO 112 +#endif +#ifndef SE_JIT_GEN +#define SE_JIT_GEN 32 +#endif + static constexpr bool kJitRegs = kJit_ && !kCq_ && !kStg && kRegs_; +#ifndef SE_PROMO_UNROLL +#define SE_PROMO_UNROLL 2 +#endif + // promotion k-loop unroll factor (MO kJit 112-register kernels only) + static_assert(!kJitRegs || 128 * SE_JIT_GEN + 512 * SE_JIT_PROMO <= 61440, "kJit register pool overflow"); +#ifndef SE_NM_REGS +#define SE_NM_REGS 1 +#endif +#ifndef SE_PAIR_REGS +#define SE_PAIR_REGS 1 +#endif +#ifndef SE_PAIR_UNROLL +#define SE_PAIR_UNROLL 1 +#endif + static constexpr bool kNmRegs = SE_NM_REGS && !kMerged_ && (!kStatic_ || (kPair_ && SE_PAIR_REGS)) && !kPingPong_ && + (!kPair_ || SE_PAIR_REGS) && kRegs_ && (kFuse_ || kTmaStore_); +#ifndef SE_CQ_UNROLL +#define SE_CQ_UNROLL 0 +#endif +#ifndef SE_CQ_UNROLL_ALT +#define SE_CQ_UNROLL_ALT 1 +#endif + static constexpr bool kCqUnroll = kCq_ && (kRegs_ ? SE_CQ_UNROLL : SE_CQ_UNROLL_ALT); + static constexpr int kPromoUnroll = + (kJitRegs || (kNmRegs && kFuse_ && (kTwoSm || (kPair_ && SE_PAIR_UNROLL))) || kCqUnroll) ? SE_PROMO_UNROLL : 1; + static constexpr uint32_t GenericRegisterRequirement = + kStg ? SE_STG_GEN : (kCq_ ? (kRegs_ ? SE_CQ_GEN : SE_CQ_GEN_ALT) + : ((kJitRegs || kNmRegs) ? SE_JIT_GEN : (kStatic_ ? (kJit_ ? SE_BASE_GEN : 56) : 48))); + static constexpr uint32_t CqRegisterRequirement = 64 - (kRegs_ ? SE_CQ_GEN : SE_CQ_GEN_ALT); + static constexpr uint32_t AccumRegisterRequirement = (kJitRegs || kNmRegs) ? SE_JIT_PROMO : 104; + // promotion TMEM loads as 2 x 32x32b.x32 (32 partial regs) instead of 4 x x16 (16 regs), every kernel. + static constexpr bool kLd32 = true; +#ifndef SE_WARP_REL +#define SE_WARP_REL 1 +#endif + static constexpr bool kWarpRel = SE_WARP_REL && !kMerged_ && !kPingPong_ && kWgCols == 64; + static constexpr uint32_t StgRegisterRequirement = SE_STG_REGS; + // Producer: cp.async raw A scales (16 B / lane = 4 rows) into the lane's own stage region + 8 B B scales, kGsfLook + // k blocks ahead (commit groups, wait_group kGsfLook), then multiplies in place and arrives on the stage barrier. + // NOT in the staging-WG merged kernel (kStg): any ring consumer code in its 104-reg promotion warps spills 32 B + // (probe: producer-only ring 0 B, consumer-only ring 32 B, also with ring position from the TMEM pipeline count, + // all-thread empty arrivals or 32-bit LDS addressing); that kernel keeps the CUTLASS SF pipeline. + // also in kStg (SE_STG_GSF=1), made spill-free by deferring the promotion warps' CLC fetch (kLateFetch below). +#ifndef SE_STG_GSF +#define SE_STG_GSF 1 +#endif + static constexpr bool kGsf = kCtaN == 256 && !kPingPong && kLd32 && (!kStg || SE_STG_GSF) && + (kFuse_ || kTmaStore_); + // kLateFetch (kStg only): the promotion warps fetch the NEXT work tile (CLC response) after the k loop instead + // of before it, so next_work_tile_info is not live across the 104-register k loop (it otherwise forces spills once + // the scale-ring consumer state is added). The CLC response is still consumed exactly once per tile per thread. +#ifndef SE_LATE_FETCH +#define SE_LATE_FETCH 1 +#endif + static constexpr bool kLateFetch = kStg && SE_LATE_FETCH; +#ifndef SE_GSF_ST +#define SE_GSF_ST 16 +#endif +#ifndef SE_GSF_LOOK +#define SE_GSF_LOOK 8 +#endif +#ifndef SE_GSF_LOOK_MO +#define SE_GSF_LOOK_MO 2 +#endif + static constexpr int kGsfStages = kGsf ? SE_GSF_ST : 1; +#ifndef SE_LATE_SCALE +#define SE_LATE_SCALE 0 +#endif + static constexpr bool kLateScale = kGsf && kHalves && kLd32 && SE_LATE_SCALE; + static constexpr int kGsfLog = SE_GSF_ST == 4 ? 2 : SE_GSF_ST == 8 ? 3 : SE_GSF_ST == 16 ? 4 : 5; + + struct SharedStorage { + struct PipelineStorage : cute::aligned_struct<16, _1> { + using MainloopPipelineStorage = typename CollectiveMainloop::PipelineStorage; + using CLCPipelineStorage = typename CLCPipeline::SharedStorage; + using CLCThrottlePipelineStorage = typename CLCThrottlePipeline::SharedStorage; + alignas(16) MainloopPipelineStorage mainloop; + alignas(16) CLCPipelineStorage clc; + alignas(16) CLCThrottlePipelineStorage clc_throttle; + alignas(16) cutlass::arch::ClusterBarrier epilogue_throttle; + alignas(16) cutlass::arch::ClusterBarrier tmem_dealloc; // 2SM: peer MMA warps sync before TMEM free + } pipelines; + alignas(16) typename TileScheduler::CLCResponse clc_response[SchedulerPipelineStageCount]; + uint32_t tmem_base_ptr; + // kN224 family (160 / 224-col TMA-store down tiles): A/B stages explicitly 1024 B aligned (SWIZZLE_128B TMA + // destination / UMMA descriptor base offset 0); the offset of `tensors` depends on the stage-count dependent pipeline + // barrier storage before it (the other kernels keep their original layout) + struct alignas((kN224 && !kMerged_) ? 1024 : 128) TensorStorage : cute::aligned_struct<128, _1> { + typename CollectiveMainloop::TensorStorage mainloop; + } tensors; + // fused epilogue: per-row partial amax of each WG, double-buffered by tile parity (one barrier per tile) + alignas(16) float amax_red[kFuse ? 2 : 1][4][128]; + // kTmaStore: 4 warpgroups x (128 rows x 128 B) bf16 staging, SWIZZLE_128B layout (needs 1024 B alignment) + // kCq: 16 KB (WG0: qh tile + two 32-col DN halves) + 3 x 8 KB (WG1-3: one 32-col DN half at a time); the freed + // 24 KB hold the converter ring + alignas(1024) uint8_t epi_stage[kEpiStage ? (kCq_ ? 16384 + 3 * 8192 : ((kN224 && !kMerged_) ? kHalfWg * (kHalfStg ? 8192 : 128 * 128) : 4 * 128 * 128)) : 16]; // kN224 family stages WG < kHalfWg only + // kMerged staging handshake: full (512 promotion arrivals) / empty (128 staging-WG arrivals) + unit info + alignas(16) cutlass::arch::ClusterBarrier stg_full; + alignas(16) cutlass::arch::ClusterBarrier stg_empty; + int stg_info[4]; // {cta m tile, nt, M block, terminate} + // kGsf combined-scale ring: stage s = 128 x float2 (row r at floats [2r, 2r+1]); lane l's raw A scales (rows 4l..4l+3) + // are staged by cp.async at floats [8l+4, 8l+8) and converted in place + alignas(16) float gsf_c[kGsfStages][256]; + alignas(16) float gsf_b[kGsfStages][4]; // raw B scales (2 used) + alignas(16) cutlass::arch::ClusterBarrier gsf_full[kGsfStages]; // 32 scale-warp lane arrivals + alignas(16) cutlass::arch::ClusterBarrier gsf_empty[kGsfStages]; // 512 promotion-thread arrivals + // kHalves: 4-stage TMEM accumulator pipeline barriers (replaces the collective's 2-stage pipeline_accum) + alignas(16) typename AccumulatorPipeline::SharedStorage acc4; + // kPair: [0,2) TMEM full (MMA commit), [2,4) TMEM empty (512 promotion arrivals), [4] DSMEM receive (expect_tx), + // [5] peer's receive buffer is free (1 remote arrival) + // + [6..8] receive barriers of DSMEM chunks 1..3 (chunk 0 = [4]) + alignas(16) cutlass::arch::ClusterBarrier pair_bar[kPair_ ? 9 : 1]; + // kPub (MO merged kernel): delegated M-block publish ring (2 slots). full: 512 promotion-thread arrivals after the + // unit's qh / sh stores (release.cta); empty: 1 publisher arrival; info: M block (-1 = terminate) + alignas(16) cutlass::arch::ClusterBarrier pub_full[2]; + alignas(16) cutlass::arch::ClusterBarrier pub_empty[2]; + int pub_info[2]; + int pub_n; // gate_up units this CTA has handed to the publisher (written / read by promotion threads only) + int pub_rc[2][2]; // kTmaQh: {row, col} of the slot's qh tile (TMA store coordinates) + int stg_waited; // kTmaQh: stg_free completions consumed by thread 128 + alignas(16) cutlass::arch::ClusterBarrier stg_free; // kTmaQh: publisher's qh TMA store finished reading staging + // kCq converter ring: kCqNR slots x (32 rows x 256 B bf16), full barriers (tx), empty (4 warp arrivals) + // 1024-aligned: after every converter warp has finished (cq_done == 4) the idle ring holds WG1-3's second + // 32-col DN staging half (SWIZZLE_64B pattern needs a 512 B aligned base) + alignas(1024) uint8_t cq_ring[kCq_ ? kCqNR * kCqRows * 256 : 16]; + int cq_rok[4]; // per-WG "second DN half in the ring" decision of the current unit + int cq_done; // converter warps finished (release.cta arrivals, 4 = ring free) + alignas(16) cutlass::arch::ClusterBarrier cq_bar[kCq_ ? kCqNR : 1]; + int cq_id[kCq_ ? kCqNR : 1]; // slot -> chunk descriptor (r0 | kb << 23 | kind << 30, -1: none) + int cq_cl[kCq_ ? 4 : 1][4]; // per converter warp claim window {c_cur, c_end, c_nb} (lane 0) + // kInfoRelay: next-work-tile ring written by the MMA warp, read by the promotion threads + alignas(16) typename TileScheduler::WorkTileInfo nxt_info[2]; + alignas(16) cutlass::arch::ClusterBarrier nxt_full[2]; + alignas(16) cutlass::arch::ClusterBarrier nxt_empty[2]; // kInfoRelayNM: 16 promotion-warp arrivals + // kSfRelay2: next-work-tile ring written by the scale warp (sole CTA-side CLC consumer), read by A/B + MMA + alignas(16) typename TileScheduler::WorkTileInfo sfi_info[2]; + int sfi_inc[2]; + alignas(16) cutlass::arch::ClusterBarrier sfi_full[2]; // 1 scale-warp arrival + alignas(16) cutlass::arch::ClusterBarrier sfi_empty[2]; // 2 reader arrivals (A/B lane, MMA lane) + }; + static constexpr int SharedStorageSize = sizeof(SharedStorage); + + // kHalfT side parameters (global memory): odd-CTA A maps shifted by 192 rows (gate_up: qx, down: qh) + struct HalfExt { + MainloopParams mainloop_t; + MainloopParams mainloop_dn_t; + }; + + struct Arguments { + cutlass::gemm::GemmUniversalMode mode{}; + ProblemShape problem_shape{}; + MainloopArguments mainloop{}; + EpilogueArguments epilogue{}; + cutlass::KernelHardwareInfo hw_info{}; + TileSchedulerArguments scheduler{}; + float* fused_scale{nullptr}; // kFuse: h scales [N/256][M] (ptr_D is then the fp8 h matrix [M, N/2]) + float* split_ws{nullptr}; // kStatic: fp32 partial workspace (>= P split units x cluster tile fp32), may be null -> no split + int* split_cnt{nullptr}; // kStatic: per (tail tile, CTA rank) arrival counters, zero-initialized, self-reset + int st_force_s{0}; // probe/debug: force the split count (0 = auto) + // kMerged: down GEMM operands (A = qh [M, dn_k] fp8, B = qWd [dn_n, dn_k], SFA = sh, SFB = down scales), output + MainloopArguments mainloop_dn{}; + cutlass::bfloat16_t* out{nullptr}; + int dn_n{0}, dn_k{0}; + int* mb_cnt{nullptr}; // per 256-row M block arrival counters (zeroed once, self-reset) + int* mb_flag{nullptr}; // per M block ready flag = epoch of the call that completed it + int epoch{0}; + HalfExt* half_host{nullptr}; // host struct filled when half_fill (copied to half_dev by the launcher) + const HalfExt* half_dev{nullptr}; // device copy read by the kernel + bool half_fill{true}; + int mg_split{1}; // kTailSplit: K-split count of the gate_up tail tiles (1 = none) + int mg_split_t0{0}; // kTailSplit: first split gate_up tile + int mg_half{0}; // MO (kPub): enable the half last M block path (wide M=128 units), see kHalfT + CqArgs cq{}; // kCq + float* split_alt{nullptr}; // kRedSplit: the other parity's reduction workspace (zeroed by first arrivers) + int mg_lag{1 << 20}; // kMerged: IGNORED since (decode fixed to L = all); was work-list lag L (down units of M block b-L follow gate_up units of block b) + }; + + struct Params { + cutlass::gemm::GemmUniversalMode mode{}; + ProblemShape problem_shape{}; + MainloopParams mainloop{}; + ElementD* ptr_D{nullptr}; + int64_t ldd{0}; + TileSchedulerParams scheduler{}; + cutlass::KernelHardwareInfo hw_info{}; + float* fused_scale{nullptr}; + // static schedule (kStatic) + float* split_ws{nullptr}; + int* split_cnt{nullptr}; + int st_units{0}, st_dp{0}, st_tiles_m{1}, st_split{1}, st_kt{1}, st_clusters{1}; + alignas(64) CUtensorMap tmap_d{}; // kTmaStore: D [M, N] bf16, box 64 cols x 128 rows, 128B swizzle + // kMerged + MainloopParams mainloop_dn{}; + int dn_n{0}, dn_k{0}, gu_units{0}, gu_tn{1}, dn_tn{1}, epoch{0}, mg_lag{1}; + int* mb_cnt{nullptr}; + int* mb_flag{nullptr}; + // kGsf: raw MN-major scale tables: SFA [K/128][M] (row stride M), SFB [K/128][N/128] + const float* gsf_a{nullptr}; + const float* gsf_b{nullptr}; + const float* gsf_a_dn{nullptr}; + const float* gsf_b_dn{nullptr}; + const HalfExt* hx{nullptr}; + int mg_half{0}; + cutlass::bfloat16_t* out_d{nullptr}; // kMerged: bf16 output [M, dn_n] (wide-unit direct stores) + int mg_split_t0{0}; // kTailSplit: first K-split gate_up tile (st_split = split count); last member: the + // offsets of every earlier field (and so the default MO SASS) are unchanged + int gu_all{0}; // kTailSplit: total gate_up work units (gu_units + split extra units) + alignas(64) CUtensorMap tmap_qh{}; // kTmaQh: qh [M, N/2] fp8, box 128 x 128, 128B swizzle (appended last) + CqArgs cq{}; // kCq (last member) + alignas(64) CUtensorMap tmap_d32{}; // kCq: out [M, dn_n] bf16, box 32 cols x 128 rows, 64B swizzle + float* split_alt{nullptr}; // kRedSplit: workspace of the other call parity (appended last) + }; + + static constexpr bool kStatic = kStatic_; + // kPub (merged kernel without staging WG = MO): the gate_up unit's M-block publish (fence + red.release.gpu) is + // delegated to warp 1 (CTA rank 0: the CLC scheduler warp, between its CLC queries; rank 1: otherwise idle). The + // promotion threads only arrive (release.cta) on pub_full[slot] after their qh / sh stores and go straight on to + // the next unit; the publisher waits (acquire.cta), then fence.proxy.async.global + fence.acq_rel.gpu + + // red.release.gpu.add (cumulativity: the 512 threads' stores observed through the CTA-scope barrier are released). + static constexpr bool kPub = kMerged_ && !kStgWG_; + static constexpr bool kHalfT = kPub && kHalves && kHalfTK_; + static constexpr bool kTailSplit = kTailSplit_; + // kJit (separate MO instantiation): JUST-IN-TIME unit hand-out. Default CUTLASS flow: the A/B warp releases the + // CLC throttle at the START of unit i, so the response for unit i+1 is fetched ~one whole unit early (MMA / promotion + // warps fetch it at the top of unit i). Gantt probe @M1920: when the first GU wave ends, the clusters starting their + // 2nd (GU) unit already reserve READY down units of blocks 0-3 as their 3rd unit, while the + // few clusters doing down units run through and get down units of blocks 4-7 that are not ready yet (40 units, 190 + // cluster-us of h-flag waits). kJit: the A/B warp releases the throttle AFTER issuing all loads of unit i (the CLC + // query for unit i+1 then overlaps the last ~ring-depth k blocks), the MMA and promotion warps fetch after their k + // loops, and the publisher publishes the CURRENT gate_up unit right after that fetch. Units are therefore bound to + // a cluster only shortly before it can start them (CLC still hands them out in increasing order). + static constexpr bool kJit = kJit_; +#ifndef SE_JIT_D +#define SE_JIT_D 8 // CLC query for the next unit 8 k blocks before the A/B loads end +#endif + static constexpr int kJitD = SE_JIT_D; + // kInfoRelay (kJit kernels): the promotion warps no longer consume the CLC pipeline. The MMA warp (which already + // fetches the next work tile right after issuing a unit's MMAs, ~2 k blocks before the promotion k loop ends) copies + // the WorkTileInfo into a 2-slot smem ring (slot = unit ordinal & 1) and arrives on nxt_full[slot] (count 1, release.cta); + // each promotion thread waits on it (acquire) and reads the struct after its k loop. Removes the CLC consumer wait + + // response read + 512 remote (rank-0) consumer arrivals per unit from the promotion's unit boundary, which is an MMA + // bubble (TMEM ring = 2 k blocks of lead). Overwrite safety: slot s is rewritten for ordinal u + 2 only after the MMA + // issued unit u + 2's k loop, which needed TMEM slots released by the promotion of unit u + 2 (after its read of u). +#ifndef SE_INFO_RELAY +#define SE_INFO_RELAY 1 +#endif + static constexpr bool kInfoRelay = kJit && SE_INFO_RELAY; + // kSfInfo (kJit kernels): the scale-factor warp is the ONLY per-CTA consumer of the CLC response (besides the + // rank-0 scheduler warp itself). It runs ahead of the A/B producer (which waits on the scale ring before every TMA) and + // hence of the MMA warp, so it reaches each unit's end first; after its fetch it copies {WorkTileInfo, increment_pipe} + // into a 2-slot smem ring (sfi_full, 1 arrival) read by the A/B warp and the MMA warp (sfi_empty, 2 arrivals, guards + // the slot rewrite two units later). The MMA warp still relays to the promotion warps (kInfoRelay). Removes 2 x 64 + // remote consumer arrivals + CLC waits per unit. +#ifndef SE_SF_INFO +#define SE_SF_INFO 1 +#endif + static constexpr bool kSfInfo = kInfoRelay && kGsf && SE_SF_INFO; + // kTmaQh (default MO kJit instantiation only): the gate_up unit's qh tile (128 rows x 128 B fp8 per CTA, staged + // 128B-swizzled in WG0's epi_stage region) is written by ONE TMA 2-D store issued by the CTA's delegated publisher + // warp (pub_one) instead of a 512-thread named barrier + smem -> global copy in the promotion warps. Probe (MO kJit, + // thread 128, per GU unit, cycles) M2432 / M3712: epilogue 2638 / 2589 = silu 1163 / 1150 + amax barrier 712 / 696 + // + fp8 convert + staging 396 / 388 + bar 13 + copy 368 / 356; the MMA can only run 2 k blocks (~1.05k cyc) ahead, + // so the epilogue tail is an MMA bubble at every GU unit boundary. Promotion threads now: st.shared staging + + // fence.proxy.async, sh store, pub_full arrive -> next unit. Publisher: pub_full wait -> TMA store (rows >= M clipped + // by the tensor map) -> wait_group 0 -> stg_free arrive (staging reusable) -> the usual fence + red.release publish. + // Thread 128 (WG0 staging owner) waits for every stg_free completion before the next write of that region. +#ifndef SE_TMA_QH +#define SE_TMA_QH 1 +#endif + static constexpr bool kTmaQh = kPub && kJit && !kTailSplit && !kHalfTK_ && SE_TMA_QH; + // kTileRdy (kCq kJit merged kernels): GU->DN readiness at h-TILE granularity. mb_cnt[mb * gu_tn + nt] counts the + // 2 CTA publishes of gate_up tile (mb, nt) (h cols [128 nt, +128) of the block's rows = DN k block nt). A DN unit's + // scale warp acquire-polls tile kb before loading sh[kb] (per k block, prefix polls), so its first k blocks start as + // soon as THOSE gate_up tiles are published instead of waiting for all 16 tiles of the block (blocks straddling a GU + // wave boundary). The A/B producer gets readiness transitively via gsf_full + one proxy fence per DN k block. +#ifndef SE_TILE_RDY +#define SE_TILE_RDY 1 +#endif + static constexpr bool kTileRdy = kPub && kJit_ && kCq_ && SE_TILE_RDY; + // verification that per-tile readiness covers EVERY dispatched kCq merged kernel, including the kRedSplit + kCq + // instantiation (M1216-1344): its last split arriver publishes the tile index once per CTA (target 2), non-last splits + // publish -2 (nothing), so the per-tile counters need no split adjustment. + static_assert(!SE_TILE_RDY || !(kCq_ && kJit_ && kMerged_) || kTileRdy, "kTileRdy must be active in all kCq kJit merged kernels"); + static_assert(!kJit || (kPub && kHalves && !kLateFetch), "kJit: MO merged kernel only"); +#ifndef SE_PAIR_SCALE +#define SE_PAIR_SCALE 0 +#endif + static constexpr bool kPairScale = kJit && !kTailSplit && kHalves && kGsf && !kLateFetch && SE_PAIR_SCALE; +#ifndef SE_PAIR_WAIT +#ifndef SE_SF_RELAY +#define SE_SF_RELAY 1 +#endif +#define SE_PAIR_WAIT 0 +#endif + static constexpr bool kPairWait = kJit && !kTailSplit && !kHalfT && kHalves && kGsf && !kLateFetch && !kPairScale && + SE_PAIR_WAIT && !SE_SF_RELAY; + static_assert(!kPairWait || kGsfStages % 2 == 0, "kPairWait: even ring depth"); + // kSfRelay (MO kJit default instantiation, replaces kPairWait): the promotion threads do NO scale-ring handshake. + // * full: the A/B producer waits on gsf_full[kb] before issuing k block kb's TMA (it has slack). TMEM-full(kb) then + // implies the scales of kb are in smem (MMA waited on A/B-full(kb), which needs both CTAs' kb loads), so the + // promotion's LDS.64 of kb is issued right after its TMEM-full wait, with no ring wait. + // * empty: the A/B producer relays it (1 arrival per kb, lane 0): once its producer_acquire of k block kb' returned, + // A/B stage of kb' - Stages was released by the MMA commit, issued after the MMA acquired the TMEM slots of + // kb' - Stages, which needed every promotion thread (both CTAs) to release the slots of kb' - Stages - 2; their LDS + // of that kb precede that release -> scale slot (kb' - Stages - 2) is free. A plain single-producer ring (no + // phase aliasing), observed in order by the scale warp. Deadlock-free iff Stages + 2 + kGsfLook + 1 <= ring depth. +#ifndef SE_SF_RELAY +#define SE_SF_RELAY 1 +#endif + static constexpr bool kSfRelay = kGsf && (kJit || !kMerged_) && !kHalfT && !kLateFetch && !kPairScale && + !kPairWait && !kLateScale && SE_SF_RELAY; +#ifndef SE_EARLY_TMA +#define SE_EARLY_TMA 8 // 6 -> 8 (merged kJit: first 8 k blocks of the CTA issue A/B TMA without waiting for the scale warp; promotion waits on gsf_full itself) // 4 -> 6 +#endif + // k blocks (per CTA, from the kernel start) whose A/B TMA is issued before their scales landed (MO kJit only) +#ifndef SE_EARLY_SPLIT +#define SE_EARLY_SPLIT 1 // k loop versioned on the early-TMA k blocks (kCq kJit merged kernels) +#endif +#ifndef SE_EARLY_TMA_NM +#define SE_EARLY_TMA_NM 1 +#endif +#ifndef SE_EARLY_TMA_PAIR +#define SE_EARLY_TMA_PAIR 15 +#endif + static constexpr int kEarlyCap = kPair_ ? SE_EARLY_TMA_PAIR : (int)DispatchPolicy::Stages; + static constexpr int kEarlyNM = (kSfRelay && !kJit && SE_EARLY_TMA_NM) + ? (kEarlyCap < kGsfStages - 1 ? kEarlyCap : kGsfStages - 1) + : 0; + static constexpr int kEarlyTma = (kSfRelay && kJit) ? SE_EARLY_TMA : kEarlyNM; + static_assert(kEarlyTma < kGsfStages, "early-TMA k blocks must lie in the first scale-ring pass"); + static constexpr int kRelayLag = (int)DispatchPolicy::Stages + (kHalves ? 2 : (int)AccumulatorPipelineStageCount); + static constexpr int kGsfLookRaw = kHalves ? SE_GSF_LOOK_MO : SE_GSF_LOOK; + static constexpr int kGsfLook = (kSfRelay && kGsfLookRaw > kGsfStages - kRelayLag - 1) ? kGsfStages - kRelayLag - 1 + : kGsfLookRaw; + static_assert(kGsfLook >= 1, "scale lookahead >= 1"); +#ifndef SE_SF_SLIM +#define SE_SF_SLIM 1 +#endif +#ifndef SE_FAST_SF +#define SE_FAST_SF 1 +#endif + static constexpr bool kFastSF = kGsf && !kHalfT && !kPairScale && !kStg && SE_FAST_SF; + // kHalveGate (fused SwiGLU kernels with the fast scale producer): the scale warp stores the GATE combined scale + // pre-multiplied by 0.5 (exact power of 2), so the gate accumulator holds 0.5 g exactly and bf16(0.5 g) = 0.5 bf16(g): + // the epilogue uses it directly as hg of silu = hg + hg tanh(hg) (one mul.rn.f32x2 per column pair less). Bit-identical. +#ifndef SE_HALVE_GATE +#define SE_HALVE_GATE 1 +#endif + static constexpr bool kHalveGate = kFuse && kFastSF && SE_HALVE_GATE; + static_assert(!kSfRelay || kRelayLag + kGsfLook + 1 <= kGsfStages, "kSfRelay: scale ring too shallow"); + static_assert(!kTailSplit || (kPub && !kHalfT), "kTailSplit: MO merged kernel (no half-block units) only"); + static constexpr bool kRedSplit = kTailSplit && kJit_; + static constexpr int kMaxSplitMg = kRedSplit ? 8 : 4; +#ifndef SE_HT_MASK +#define SE_HT_MASK 15 +#endif + // probe bisection only (shipped: all set): per-role half-path code + static constexpr bool kHT_AB = kHalfT && (SE_HT_MASK & 1), kHT_SF = kHalfT && (SE_HT_MASK & 2), + kHT_MMA = kHalfT && (SE_HT_MASK & 4), kHT_PR = kHalfT && (SE_HT_MASK & 8); + // kPair (1SM fused 128x256 static split-K, s == 2, all tiles split, launched as HARDWARE 2-CTA clusters): the two + // K splits of a tile are the two CTAs of one cluster (unit = blockIdx.x, split = cluster rank). CUTLASS still sees a + // 1x1 cluster (no multicast), so everything whose CUTLASS masks would be derived from the hardware cluster rank is + // replaced: own tcgen05.mma issue loop (local commits to the A/B empty and own TMEM-full barriers), own TMEM-empty + // barriers, no CLC (one unit per CTA). Split-K fixup through DSMEM: split j owns rows [64j, +64); after its k loop + // each CTA arms its receive barrier (expect_tx 64 KB, buffer = its now idle smem_B stage memory) and tells the peer; + // the non-owner threads st.async their fp32 partial straight into the owner's smem (mbarrier complete_tx); the owner + // threads add it to their register partial (own + other == fixed-order sum, fp add is commutative) and run the fused + // SwiGLU / requant epilogue for their rows. No global workspace, counters or polling. + static constexpr bool kPair = kPair_; + // kInfoRelayNM (NON-merged persistent CLC kernels: / / / / /...): the promotion warps do + // not consume the CLC pipeline either. The MMA warp fetches the next work tile at the top of every unit (as before) + // and immediately copies it into the 2-slot nxt_info ring (nxt_full, 1 arrival); each promotion thread reads it at the + // top of its unit (same unit ordinal = tile_iter). Slot reuse is guarded by nxt_empty (one arrival per promotion warp + // after its read), so no assumption on the k-block count / pipeline depth. CLC consumer count drops by 512 per CTA. +#ifndef SE_INFO_RELAY_NM +#define SE_INFO_RELAY_NM 1 +#endif + static constexpr bool kInfoRelayNM = SE_INFO_RELAY_NM && !kMerged_ && !kPingPong_ && !kPair_ && !kLateFetch && + IsSchedDynamicPersistent; + // lean hand-written MMA issue loop for the non-merged 2SM 256x256 kernels +#ifndef SE_LEAN_NM +#define SE_LEAN_NM 1 +#endif + static constexpr bool kLeanNM = SE_LEAN_NM && kTwoSm && kCtaN == 256 && !kMerged_ && !kPingPong_ && !kPair_; +#ifndef SE_LEAN_224 +#define SE_LEAN_224 1 +#endif + static constexpr bool kLean224 = SE_LEAN_224 && (kCtaN == 224 || kCtaN == 160) && kTmaStore_ && !kMerged_ && !kPingPong_ && !kPair_; + static_assert(!kPair || (kStatic_ && kFuse_ && !kTwoSm && kCtaN == 256 && !kMerged_), "kPair: 1SM fused static only"); + // static schedule geometry: cluster tile (256x256 for the 2SM pair, 128x128 for 1SM), CTAs per cluster, + // max split count + static constexpr int kClTileM = kTwoSm ? 256 : 128; + static constexpr int kClTileN = kTwoSm ? 256 : kCtaN; // 1SM fused 128x256 + static constexpr int kClCtas = kTwoSm ? 2 : 1; + static constexpr int kMaxSplit = 4; + // kStatic: 1-D scheduler problem with one cluster tile per work unit + static auto fake_problem(Params const& p) { + return make_shape(p.st_units * kClTileM, kClTileN, get<2>(p.problem_shape), 1); + } + + // Host: hybrid DP + split-K tail schedule. T pair tiles, P = SMs/2 pair slots. full = T/P full waves stay + // data-parallel; the tail = T - full*P tiles are split along K into s = min(4, P/tail, KT) units each. + static void make_schedule(Params& p, int M, int N, int K, int sm_count, bool have_ws, int force_s = 0) { + const int tm = (M + kClTileM - 1) / kClTileM, tn = (N + kClTileN - 1) / kClTileN, T = tm * tn; + const int P = sm_count / kClCtas > 0 ? sm_count / kClCtas : 1; + const int KT = (K + 127) / 128; + const int full = T / P, tail = T - full * P; + int s = 1; + if (tail > 0 && have_ws) { + s = P / tail; + if (s > kMaxSplit) s = kMaxSplit; + if (s > KT) s = KT; + if (s < 1) s = 1; + if (force_s > 0) s = force_s > kMaxSplit ? kMaxSplit : force_s; + if (tail * s > P) s = P / tail; // workspace holds at most P split units + if (s < 1) s = 1; + } + p.st_tiles_m = tm; + p.st_kt = KT; + p.st_split = s; + if (s == 1) { p.st_dp = T; p.st_units = T; } + else { p.st_dp = full * P; p.st_units = full * P + tail * s; } + p.st_clusters = p.st_units < P ? p.st_units : P; + if (p.st_clusters < 1) p.st_clusters = 1; + } + + static Params to_underlying_arguments_base(Arguments const& args, void* workspace) { + auto problem_shape_MNKL = append<4>(args.problem_shape, 1); + uint8_t* workspace_ptr = reinterpret_cast(workspace); + void* scheduler_workspace = workspace_ptr; + return {args.mode, + args.problem_shape, + CollectiveMainloop::to_underlying_arguments(args.problem_shape, args.mainloop, nullptr, args.hw_info), + args.epilogue.ptr_D, + (int64_t)get<0>(args.epilogue.dD), + TileScheduler::to_underlying_arguments(problem_shape_MNKL, TileShape{}, AtomThrShapeMNK{}, + ClusterShape{}, args.hw_info, args.scheduler, + scheduler_workspace), + args.hw_info, + args.fused_scale}; + } + static Params to_underlying_arguments(Arguments const& args, void* workspace) { + Params p = to_underlying_arguments_base(args, workspace); + p.gsf_a = args.mainloop.ptr_SFA; + p.gsf_b = args.mainloop.ptr_SFB; + p.gsf_a_dn = args.mainloop_dn.ptr_SFA; + p.gsf_b_dn = args.mainloop_dn.ptr_SFB; + if constexpr (kStatic) { + p.split_ws = args.split_ws; + p.split_cnt = args.split_cnt; + p.split_alt = args.split_alt; + auto ps = append<4>(args.problem_shape, 1); + if constexpr (kMerged) { + const int M = get<0>(ps); + p.dn_n = args.dn_n; p.dn_k = args.dn_k; p.epoch = args.epoch; + p.mb_cnt = args.mb_cnt; p.mb_flag = args.mb_flag; + p.out_d = args.out; + p.cq = args.cq; + p.mainloop_dn = CollectiveMainloop::to_underlying_arguments(ProblemShape{M, args.dn_n, args.dn_k, 1}, + args.mainloop_dn, nullptr, args.hw_info); + const int tm = (M + kClTileM - 1) / kClTileM; + p.gu_tn = get<1>(ps) / kClTileN; + p.dn_tn = (args.dn_n + kClTileN - 1) / kClTileN; + p.gu_units = tm * p.gu_tn; + p.mg_lag = args.mg_lag < 1 ? 1 : (args.mg_lag > tm ? tm : args.mg_lag); // clamp to [1, tm] + p.st_tiles_m = tm; p.st_split = 1; p.st_kt = (get<2>(ps) + 127) / 128; + p.st_units = p.st_dp = tm * (p.gu_tn + p.dn_tn); + p.st_clusters = p.st_units; + // TMA store map for the bf16 output [M, dn_n] + const cuuint64_t gdim[2] = {(cuuint64_t)args.dn_n, (cuuint64_t)M}; + const cuuint64_t gstride[1] = {(cuuint64_t)args.dn_n * sizeof(cutlass::bfloat16_t)}; + const cuuint32_t box[2] = {64, 128}; + const cuuint32_t estr[2] = {1, 1}; + CUresult rr = cuTensorMapEncodeTiled(&p.tmap_d, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, (void*)args.out, gdim, + gstride, box, estr, 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 (rr != CUDA_SUCCESS) p.ptr_D = nullptr; + if constexpr (kCq) { + const cuuint32_t box32[2] = {32, 128}; + CUresult r3 = cuTensorMapEncodeTiled(&p.tmap_d32, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, (void*)args.out, gdim, + gstride, box32, estr, 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 (r3 != CUDA_SUCCESS) p.ptr_D = nullptr; + } + if constexpr (kTmaQh) { + const cuuint64_t qdim[2] = {(cuuint64_t)(get<1>(ps) / 2), (cuuint64_t)M}; + const cuuint64_t qstr[1] = {(cuuint64_t)(get<1>(ps) / 2)}; + const cuuint32_t qbox[2] = {128, 128}; + CUresult rq = cuTensorMapEncodeTiled(&p.tmap_qh, CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, (void*)args.epilogue.ptr_D, + qdim, qstr, qbox, estr, 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 (rq != CUDA_SUCCESS) p.ptr_D = nullptr; + } + if constexpr (kHalfT) { + // kHalfT: the last 256-row M block holds <= 128 valid rows -> its units are WIDE M=128 units (128 rows x + // 2 adjacent 256-col tiles), half as many units for that block + const int K1 = get<2>(ps), N1 = get<1>(ps); + const int last_rows = M - kClTileM * (tm - 1); + if (args.mg_half && args.half_dev && args.half_host && tm >= 2 && last_rows <= 128 && (p.gu_tn % 2) == 0 && (p.dn_tn % 2) == 0 && + (N1 % 512) == 0 && (args.dn_n % 512) == 0) { + if (args.half_fill) { + auto mt = args.mainloop; + mt.ptr_A = args.mainloop.ptr_A + (size_t)192 * K1; + args.half_host->mainloop_t = CollectiveMainloop::to_underlying_arguments(ProblemShape{M - 192, N1, K1, 1}, + mt, nullptr, args.hw_info); + auto md = args.mainloop_dn; + md.ptr_A = args.mainloop_dn.ptr_A + (size_t)192 * args.dn_k; + args.half_host->mainloop_dn_t = CollectiveMainloop::to_underlying_arguments( + ProblemShape{M - 192, args.dn_n, args.dn_k, 1}, md, nullptr, args.hw_info); + } + p.hx = args.half_dev; + p.mg_half = 1; + p.gu_units = (tm - 1) * p.gu_tn + p.gu_tn / 2; + p.st_units = p.st_dp = p.gu_units + (tm - 1) * p.dn_tn + p.dn_tn / 2; + p.st_clusters = p.st_units; + } + } + if constexpr (kTailSplit) { + p.gu_all = p.gu_units; + // host guarantees (gu_units - t0) * s <= resident pair clusters and <= the split workspace + if (args.mg_split > 1 && args.split_ws != nullptr && args.split_cnt != nullptr && args.mg_split_t0 >= 0 && + args.mg_split_t0 < p.gu_units && args.mg_split <= kMaxSplitMg) { + p.st_split = args.mg_split; + p.mg_split_t0 = args.mg_split_t0; + p.st_units += (p.gu_units - p.mg_split_t0) * (p.st_split - 1); + p.st_dp = p.st_units; + p.st_clusters = p.st_units; + p.gu_all = p.gu_units + (p.gu_units - p.mg_split_t0) * (p.st_split - 1); + } + } + } else + make_schedule(p, get<0>(ps), get<1>(ps), get<2>(ps), args.hw_info.sm_count, + args.split_ws != nullptr && args.split_cnt != nullptr, args.st_force_s); + auto sched_args = args.scheduler; + sched_args.raster_order = decltype(sched_args.raster_order)::AlongM; + sched_args.max_swizzle_size = 1; + p.scheduler = TileScheduler::to_underlying_arguments(fake_problem(p), TileShape{}, AtomThrShapeMNK{}, + ClusterShape{}, args.hw_info, sched_args, workspace); + } + if constexpr (kTmaStore) { + auto ps = append<4>(args.problem_shape, 1); + const cuuint64_t gdim[2] = {(cuuint64_t)get<1>(ps), (cuuint64_t)get<0>(ps)}; + const cuuint64_t gstride[1] = {(cuuint64_t)p.ldd * sizeof(cutlass::bfloat16_t)}; + const cuuint32_t box[2] = {64, 128}; + const cuuint32_t estr[2] = {1, 1}; + CUresult rr = cuTensorMapEncodeTiled(&p.tmap_d, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, (void*)p.ptr_D, gdim, + gstride, box, estr, 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 (rr != CUDA_SUCCESS) p.ptr_D = nullptr; // flagged; launcher checks + if constexpr (kHalfStg) { // 32-col halves, SWIZZLE_64B + const cuuint32_t box32[2] = {32, 128}; + CUresult r3 = cuTensorMapEncodeTiled(&p.tmap_d32, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, (void*)p.ptr_D, gdim, + gstride, box32, estr, 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 (r3 != CUDA_SUCCESS) p.ptr_D = nullptr; + } + } + return p; + } + + static bool can_implement(Arguments const& args) { + auto p = append<4>(args.problem_shape, 1); + bool ok = args.mode == cutlass::gemm::GemmUniversalMode::kGemm; + ok &= get<3>(p) == 1; + ok &= (get<1>(p) % 8) == 0; + ok &= CollectiveMainloop::can_implement(args.problem_shape, args.mainloop); + ok &= TileScheduler::can_implement(args.scheduler); + ok &= args.epilogue.ptr_D != nullptr; + if constexpr (kFuse) ok &= (get<1>(p) % 256) == 0 && args.fused_scale != nullptr; + if constexpr (kPairScale || kPairWait) // every unit's k-block count even (scale-ring pairs) + ok &= ((get<2>(p) + 127) / 128) % 2 == 0 && ((args.dn_k + 127) / 128) % 2 == 0; + if constexpr (kMerged) + ok &= args.out != nullptr && args.mb_cnt != nullptr && (args.dn_n % 8) == 0 && + CollectiveMainloop::can_implement(ProblemShape{get<0>(p), args.dn_n, args.dn_k, 1}, args.mainloop_dn); + return ok; + } + + static size_t get_workspace_size(Arguments const& args) { + size_t ws = TileScheduler::template get_workspace_size( + args.scheduler, args.problem_shape, args.hw_info, NumFixupBarriers, NumEpilogueSubTiles, 1); + return cutlass::round_nearest(ws, cutlass::MinWorkspaceAlignment); + } + + static cutlass::Status initialize_workspace(Arguments const& args, void* workspace = nullptr, + cudaStream_t stream = nullptr, + cutlass::CudaHostAdapter* cuda_adapter = nullptr) { + return TileScheduler::template initialize_workspace( + args.scheduler, workspace, stream, args.problem_shape, args.hw_info, NumFixupBarriers, + NumEpilogueSubTiles, 1, cuda_adapter); + } + + static dim3 get_grid_shape(Params const& params) { + if constexpr (kStatic) { // one pair-cluster per work unit; CLC hands them out dynamically + auto cs = cutlass::detail::select_cluster_shape(ClusterShape{}, params.hw_info.cluster_shape); + return TileScheduler::get_grid_shape(params.scheduler, fake_problem(params), TileShape{}, AtomThrShapeMNK{}, cs, + params.hw_info); + } + auto cluster_shape = cutlass::detail::select_cluster_shape(ClusterShape{}, params.hw_info.cluster_shape); + auto problem_shape_MNKL = append<4>(params.problem_shape, Int<1>{}); + return TileScheduler::get_grid_shape(params.scheduler, problem_shape_MNKL, TileShape{}, AtomThrShapeMNK{}, + cluster_shape, params.hw_info); + } + + static dim3 get_block_shape() { return dim3(MaxThreadsPerBlock, 1, 1); } + + CUTLASS_DEVICE + void operator()(Params const& params, char* smem_buf) { + static_assert(SharedStorageSize <= cutlass::arch::sm100_smem_capacity_bytes, "SMEM usage exceeded capacity."); + auto problem_shape_MNKL = append<4>(params.problem_shape, Int<1>{}); + const int M = get<0>(problem_shape_MNKL); + const int N = get<1>(problem_shape_MNKL); + + const int warp_idx = cutlass::canonical_warp_idx_sync(); + // 0 MMA, 1 sched, 2 A/B TMA load, 3 scale-factor load, 4..19 promotion/epilogue (4 warpgroups) + const bool is_mma = warp_idx == 0, is_sched_warp = warp_idx == 1, is_ab = warp_idx == 2, + is_sf = warp_idx == 3, is_epi = warp_idx >= 4 && warp_idx < 20; + [[maybe_unused]] const bool is_stg = (kStg || kCq_) && warp_idx >= 20; // kCq: converter WG + + uint32_t lane_predicate = cute::elect_one_sync(); + auto cluster_shape = cutlass::detail::select_cluster_shape(ClusterShape{}); + int cluster_size = size(cluster_shape); + uint32_t cta_rank_in_cluster = cute::block_rank_in_cluster(); + bool is_first_cta_in_cluster = cta_rank_in_cluster == 0; + const bool is_sched = is_sched_warp && is_first_cta_in_cluster; + // 2SM: the even CTA of the pair is the MMA leader (issues tcgen05.mma cta_group::2 for both CTAs) + const bool is_mma_leader_cta = (cta_rank_in_cluster % size<0>(typename TiledMma::AtomThrID{})) == 0; + [[maybe_unused]] const uint32_t mma_peer_cta_rank = kTwoSm ? (cta_rank_in_cluster ^ 1) : cta_rank_in_cluster; + + SharedStorage& shared_storage = *reinterpret_cast(smem_buf); + CollectiveMainloop collective_mainloop(params.mainloop, cluster_shape, kPair ? 0u : cta_rank_in_cluster); + // kMerged: second collective bound to the down GEMM's TMA descriptors / scale tensors (same smem layout) + CollectiveMainloop collective_dn(kMerged ? params.mainloop_dn : params.mainloop, cluster_shape, kPair ? 0u : cta_rank_in_cluster); + [[maybe_unused]] auto problem_shape_dn = make_shape(get<0>(params.problem_shape), params.dn_n, params.dn_k, 1); + + if (is_sched_warp && lane_predicate) { + collective_mainloop.prefetch_tma_descriptors(); + if constexpr (kMerged) collective_dn.prefetch_tma_descriptors(); + if constexpr (kTmaStore && !kMerged) asm volatile("prefetch.tensormap [%0];" ::"l"(¶ms.tmap_d) : "memory"); + if constexpr (kHalfStg) asm volatile("prefetch.tensormap [%0];" ::"l"(¶ms.tmap_d32) : "memory"); + // the merged kernel's own (non-collective) TMA descriptors are prefetched here too, in the prologue that + // runs before griddepcontrol.wait (descriptors live in the kernel params: no dependency on the front quant pass), + // so the first qh / output TMA store and the converter's first chunk loads do not pay a descriptor miss + if constexpr (kMerged) { + asm volatile("prefetch.tensormap [%0];" ::"l"(¶ms.tmap_d) : "memory"); + if constexpr (kTmaQh) asm volatile("prefetch.tensormap [%0];" ::"l"(¶ms.tmap_qh) : "memory"); + if constexpr (kCq) { + asm volatile("prefetch.tensormap [%0];" ::"l"(¶ms.tmap_d32) : "memory"); + if (params.cq.on) { + asm volatile("prefetch.tensormap [%0];" ::"l"(¶ms.cq.tm_d) : "memory"); + if (params.cq.nxr) asm volatile("prefetch.tensormap [%0];" ::"l"(¶ms.cq.tm_x) : "memory"); + } + } + } + } + + // A/B smem pipeline (TMA producer -> MMA consumer) + typename MainloopABPipeline::Params ab_params; + if (is_ab) ab_params.role = MainloopABPipeline::ThreadCategory::Producer; + if (is_mma) ab_params.role = MainloopABPipeline::ThreadCategory::Consumer; + ab_params.is_leader = lane_predicate && is_ab && is_mma_leader_cta; // leader CTA expects the tx bytes + ab_params.transaction_bytes = CollectiveMainloop::TmaTransactionBytes; + ab_params.initializing_warp = 0; + MainloopABPipeline mainloop_ab_pipeline(shared_storage.pipelines.mainloop.pipeline_ab, ab_params, cluster_shape, + cute::true_type{}, cute::false_type{}); + + // scale-factor smem pipeline (cp.async producer warp 3 -> 256 promotion threads) + typename MainloopSFPipeline::Params sf_params; + if (is_sf) sf_params.role = MainloopSFPipeline::ThreadCategory::Producer; + if (is_epi) sf_params.role = MainloopSFPipeline::ThreadCategory::Consumer; + sf_params.initializing_warp = 3; + sf_params.producer_arv_count = CollectiveMainloop::NumMainloopSFProducerThreadEvents; + sf_params.consumer_arv_count = (kWarpRel && !kGsf) ? NumStageConsumers / 32 : NumStageConsumers; + MainloopSFPipeline mainloop_sf_pipeline(shared_storage.pipelines.mainloop.pipeline_sf, sf_params); + + // CLC pipeline + typename CLCPipeline::Params clc_params; + clc_params.role = is_sched_warp ? CLCPipeline::ThreadCategory::ProducerConsumer + : CLCPipeline::ThreadCategory::Consumer; + clc_params.producer_blockid = 0; + clc_params.producer_arv_count = 1; + clc_params.consumer_arv_count = + NumSchedThreads + + cluster_size * ((kSfInfo ? 0u : NumMainloopABLoadThreads + NumMMAThreads) + ((kInfoRelay || kInfoRelayNM) ? 0u : NumEpilogueThreads) + NumMainloopSFLoadThreads); + clc_params.transaction_bytes = CLCResponseSize; + clc_params.initializing_warp = 1; + CLCPipeline clc_pipeline(shared_storage.pipelines.clc, clc_params, cluster_shape); + + // TMEM accumulator pipeline (MMA producer -> 512 promotion threads), 4 stages of 128 columns + typename AccumulatorPipeline::Params acc_params; + if (is_mma) acc_params.role = AccumulatorPipeline::ThreadCategory::Producer; + if (is_epi) acc_params.role = AccumulatorPipeline::ThreadCategory::Consumer; + acc_params.producer_arv_count = 1; + // kHalves: each 128-col slot is consumed by the 2 warpgroups owning that N half (in both CTAs) + acc_params.consumer_arv_count = + size(AtomThrShapeMNK{}) * (kHalves ? NumStageConsumers / 2 : (kWarpRel ? NumStageConsumers / 32 : NumStageConsumers)); + acc_params.initializing_warp = 2; + auto& acc_pipe_storage = [&]() -> auto& { + if constexpr (kHalves) return shared_storage.acc4; + else return shared_storage.pipelines.mainloop.pipeline_accum; + }(); + AccumulatorPipeline accumulator_pipeline(acc_pipe_storage, acc_params, + cluster_shape); + + // CLC throttle + typename CLCThrottlePipeline::Params thr_params; + if (is_ab) thr_params.role = CLCThrottlePipeline::ThreadCategory::Producer; + if (is_sched_warp) thr_params.role = CLCThrottlePipeline::ThreadCategory::Consumer; + thr_params.producer_arv_count = NumMainloopABLoadThreads; + thr_params.consumer_arv_count = NumSchedThreads; + thr_params.dst_blockid = 0; + thr_params.initializing_warp = 4; + CLCThrottlePipeline clc_throttle_pipeline(shared_storage.pipelines.clc_throttle, thr_params); + CLCThrottlePipelineState clc_pipe_throttle_consumer_state; + CLCThrottlePipelineState clc_pipe_throttle_producer_state = + cutlass::make_producer_start_state(); + + TmemAllocator tmem_allocator{}; + cutlass::arch::NamedBarrier tmem_allocation_result_barrier( + NumMMAThreads + NumEpilogueThreads, cutlass::arch::ReservedNamedBarriers::TmemAllocBarrier); + + cutlass::arch::ClusterBarrier& epilogue_throttle_barrier = shared_storage.pipelines.epilogue_throttle; + cutlass::arch::ClusterBarrier& tmem_dealloc_barrier = shared_storage.pipelines.tmem_dealloc; + if (kTwoSm && is_mma && lane_predicate) tmem_dealloc_barrier.init(NumMMAThreads); + if (kGsf && is_mma && lane_predicate) { + for (int i = 0; i < kGsfStages; ++i) { + shared_storage.gsf_full[i].init(32); + shared_storage.gsf_empty[i].init(kSfRelay ? 1 : NumStageConsumers); + } + cutlass::arch::fence_barrier_init(); + } + static_assert(!kPub || IsSchedDynamicPersistent, "kPub: rank-0 publisher is the CLC scheduler warp"); + if (kPub && is_mma && lane_predicate) { + for (int i = 0; i < 2; ++i) { + shared_storage.pub_full[i].init(NumEpilogueThreads); + shared_storage.pub_empty[i].init(1); + } + shared_storage.pub_n = 0; + shared_storage.stg_waited = 0; + shared_storage.stg_free.init(1); + cutlass::arch::fence_barrier_init(); + } + if (kInfoRelay && is_mma && lane_predicate) { + for (int i = 0; i < 2; ++i) shared_storage.nxt_full[i].init(1); + if constexpr (kSfInfo) + for (int i = 0; i < 2; ++i) { shared_storage.sfi_full[i].init(1); shared_storage.sfi_empty[i].init(2); } + cutlass::arch::fence_barrier_init(); + } + if (kInfoRelayNM && is_mma && lane_predicate) { + for (int i = 0; i < 2; ++i) { shared_storage.nxt_full[i].init(1); shared_storage.nxt_empty[i].init(NumEpilogueThreads / 32); } + cutlass::arch::fence_barrier_init(); + } + if (kCq && is_mma && lane_predicate) { + for (int i = 0; i < kCqNR; ++i) shared_storage.cq_bar[i].init(1); + shared_storage.cq_done = 0; + cutlass::arch::fence_barrier_init(); + } + if (kStg && is_mma && lane_predicate) { + shared_storage.stg_full.init(NumEpilogueThreads); + shared_storage.stg_empty.init(NumStgThreads); + cutlass::arch::fence_barrier_init(); + } + if (kPair && is_mma && lane_predicate) { + shared_storage.pair_bar[0].init(1); + shared_storage.pair_bar[1].init(1); + shared_storage.pair_bar[2].init(kWarpRel ? NumStageConsumers / 32 : NumStageConsumers); + shared_storage.pair_bar[3].init(kWarpRel ? NumStageConsumers / 32 : NumStageConsumers); + shared_storage.pair_bar[4].init(1); + shared_storage.pair_bar[5].init(1); + for (int i = 6; i < 9; ++i) shared_storage.pair_bar[i].init(1); + cutlass::arch::fence_barrier_init(); // release.cluster: visible to the peer after the cluster barrier below + } + if (is_mma && lane_predicate) { + epilogue_throttle_barrier.init(NumMMAThreads + (is_first_cta_in_cluster ? NumSchedThreads : 0) + + NumMainloopABLoadThreads); + } + + cutlass::pipeline_init_arrive_relaxed(cluster_size); + + auto load_inputs0 = collective_mainloop.load_ab_init(problem_shape_MNKL, params.mainloop, + shared_storage.tensors.mainloop); + auto load_inputs_dn = collective_dn.load_ab_init(problem_shape_dn, params.mainloop_dn, + shared_storage.tensors.mainloop); + + MainloopABPipelineState mainloop_ab_pipe_consumer_state; + MainloopABPipelineState mainloop_ab_pipe_producer_state = + cutlass::make_producer_start_state(); + CLCPipelineState clc_pipe_consumer_state; + CLCPipelineState clc_pipe_producer_state = cutlass::make_producer_start_state(); + AccumulatorPipelineState accumulator_pipe_consumer_state; + AccumulatorPipelineState accumulator_pipe_producer_state = + cutlass::make_producer_start_state(); + MainloopSFPipelineState mainloop_sf_pipe_consumer_state; + MainloopSFPipelineState mainloop_sf_pipe_producer_state = + cutlass::make_producer_start_state(); + + // kPair: CUTLASS objects see CTA (0,0,0) of a 1x1 cluster (their masks are unused in that mode) + dim3 block_id_in_cluster = kPair ? dim3(0, 0, 0) : cute::block_id_in_cluster(); + mainloop_ab_pipeline.init_masks(cluster_shape, block_id_in_cluster); + accumulator_pipeline.init_masks(cluster_shape, block_id_in_cluster); + + TileScheduler scheduler(&shared_storage.clc_response[0], params.scheduler, block_id_in_cluster); + typename TileScheduler::WorkTileInfo work_tile_info = scheduler.initial_work_tile_info(cluster_shape); + auto cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + + auto tmem_storage = collective_mainloop.template init_tmem_tensors(EpilogueTile{}); + // kLean224 spill audit (224-col TMA-store down kernels): the initial work tile (CLC scheduler raster decode, + // runtime divisions) was computed once here and kept live across the role split; in the 32-register producer warps + // it was spilled (8 B local). These kernels recompute it at the top of every role, after setmaxnreg (pure function + // of the block index), so the setup copy is dead and each role holds only its own short-lived copy. + auto reinit_work = [&]() { + work_tile_info = scheduler.initial_work_tile_info(cluster_shape); + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + }; + + cutlass::pipeline_init_wait(cluster_size); + // kPair: hardware cluster barrier (all threads of both CTAs) -> the peer's barriers are initialized before any + // remote arrive / st.async targets them + if constexpr (kPair) { + if (pair_split) asm volatile("barrier.cluster.arrive.release;" ::: "memory"); // wait deferred + else asm volatile("barrier.cluster.arrive.release;\n\tbarrier.cluster.wait.acquire;" ::: "memory"); + } + + // kStatic: the CLC scheduler runs over a fake [units*kClTileM, kClTileN] problem (one cluster tile per work unit, + // AlongM raster): work unit = M_idx / kClCtas. Decode it into the real per-CTA tile coord and k-block range. + // unit -> (per-CTA coord, first k block, k block count, tail tile index, split index or -1 for full-K) + // decode reads the schedule straight from the kernel params (constant bank; nothing kept live in registers) + // work unit of a scheduler tile (kPair: no CLC, the CTA's unit is its block index) + auto st_unit = [&](auto const& w) -> int { + if constexpr (kPair) return (int)blockIdx.x; + else return (int)(w.M_idx / kClCtas); + }; + auto st_decode = [&](int u, int& kb0, int& kcnt, int& tt, int& sj) { + int tile; + if (u < params.st_dp) { tile = u; kb0 = 0; kcnt = params.st_kt; tt = 0; sj = -1; } + else { + const int v = u - params.st_dp; + tt = v / params.st_split; sj = v - tt * params.st_split; tile = params.st_dp + tt; + kb0 = sj * params.st_kt / params.st_split; + kcnt = (sj + 1) * params.st_kt / params.st_split - kb0; + } + const int pm = tile % params.st_tiles_m, pn = tile / params.st_tiles_m; + return make_coord(kClCtas * pm + (kTwoSm ? (int)(cta_rank_in_cluster & 1) : 0), pn, _, 0); + }; + + auto mg_decode7 = [&](int u, int& kcnt, bool& dn, int& mb, int& kb0, int& tt, int& sj) { + kb0 = 0; tt = 0; sj = -1; + if constexpr (kTailSplit) { + if (params.st_split > 1) { + const int s = params.st_split, t0 = params.mg_split_t0, ns = (params.gu_units - t0) * s; + if (u >= t0 && u < t0 + ns) { + const int v = u - t0; + tt = v / s; sj = v - tt * s; + const int tile = t0 + tt; + dn = false; mb = tile / params.gu_tn; + const int nt = tile - mb * params.gu_tn; + kb0 = sj * params.st_kt / s; + kcnt = (sj + 1) * params.st_kt / s - kb0; + return make_coord(kClCtas * mb + (kTwoSm ? (int)(cta_rank_in_cluster & 1) : 0), nt, _, 0); + } + if (u >= t0 + ns) u -= ns - (params.gu_units - t0); + } + } + // lag fixed to L = tm (all gate_up units, then all down units; the shipped MG_LAG). The general lagged + // decode needed several runtime divisions whose temporaries spilled 32 B in the 24-register producer warps. + // kHalfT: gu_units = (tm-1)*gu_tn + gu_tn/2 when the last block is half; its units w in [(tm-1)tn, +tn/2) + // decode to mb = tm-1, wide-unit index nt -> first 256-col tile 2*nt + const int A = kHalfT ? params.gu_units : params.st_tiles_m * params.gu_tn; + dn = u >= A; + const int w = dn ? u - A : u, tn = dn ? params.dn_tn : params.gu_tn; + mb = w / tn; + int nt = w - mb * tn; + if (kHalfT && params.mg_half && mb == params.st_tiles_m - 1) nt *= 2; + // kTailGrpCT (compile-time, own instantiation dispatched only at the M1408 bucket): the GU tiles of the LAST + // two 256-row M blocks are handed out N-major (tile a0 + 2 nt + j -> block tm - 2 + j). The partial last GU wave + // (22 of 96 tiles on 74 clusters at M1408) then holds the high-nt tiles of BOTH blocks, so with per-tile readiness + // both blocks' DN units run their low k blocks during the tail. Pure bijection (bit-identical). Compile-time so the + // default merged kernels carry no extra decode branch. + if constexpr (kTg_) { + const int tm2 = params.st_tiles_m - 2; + if (!dn && tm2 >= 0 && mb >= tm2) { + const int v = w - tm2 * tn; + nt = v >> 1; + mb = tm2 + (v & 1); + } + } + kcnt = dn ? (params.dn_k + 127) / 128 : params.st_kt; + return make_coord(kClCtas * mb + (kTwoSm ? (int)(cta_rank_in_cluster & 1) : 0), nt, _, 0); + }; + auto mg_decode = [&](int u, int& kcnt, bool& dn, int& mb) { + int a, b, c; + return mg_decode7(u, kcnt, dn, mb, a, b, c); + }; + // kHalfT: unit of the half last M block (wide M=128 unit) + // kSfInfo reader (A/B / MMA warp, whole warp): next work tile of this CTA's unit ordinal u + auto sfi_read = [&](uint32_t u, typename TileScheduler::WorkTileInfo& nw, bool& inc) { + const uint32_t sl = u & 1u; + shared_storage.sfi_full[sl].wait((u >> 1) & 1u); + nw = shared_storage.sfi_info[sl]; + inc = shared_storage.sfi_inc[sl] != 0; + __syncwarp(); + if (cute::elect_one_sync()) shared_storage.sfi_empty[sl].arrive(); + __syncwarp(); + }; + auto mg_tail = [&](int mb) { return kHalfT && params.mg_half != 0 && mb == params.st_tiles_m - 1; }; + // kMerged: producer-side wait until every gate_up tile of M block mb has published qh / sh (all lanes spin on the + // same word), then order the generic-proxy writes before this thread's async-proxy (TMA) reads. + auto mg_wait_block = [&](int mb) { + if constexpr (kTileRdy) { // all gu_tn tile counters of the block (2 publishes each) + const int* tf = params.mb_cnt + mb * params.gu_tn; + int ok = 0; + while (ok < params.gu_tn) ok += cq_wait_prefix(tf + ok, params.gu_tn - ok, 2); + return; + } + // mb_cnt[mb] counts gate_up CTA arrivals of this call (zeroed by this call's quant kernel, which fully + // completes before our griddepcontrol.wait returns); the block is ready once all 2 * gu_tn CTAs arrived. + const int* f = params.mb_cnt + mb; + int target = 2 * params.gu_tn; + if constexpr (kTailSplit && !kRedSplit) { + if (params.st_split > 1) { // every split unit's CTAs publish too + const int lo = mb * params.gu_tn > params.mg_split_t0 ? mb * params.gu_tn : params.mg_split_t0; + const int nsp = (mb + 1) * params.gu_tn - lo; + if (nsp > 0) target += 2 * (params.st_split - 1) * nsp; + } + } + int seen, spins = 0; + while (true) { + asm volatile("ld.acquire.gpu.global.s32 %0, [%1];" : "=r"(seen) : "l"(f) : "memory"); + if (seen >= target) break; // tight acquire re-poll + if (++spins > 256) __nanosleep(64); // energy backoff on long waits only + } + asm volatile("fence.proxy.async.global;" ::: "memory"); + }; + // kPub publisher (whole warp): wait for GU publish slot it (acquire.cta), lane 0 releases the M-block arrival at gpu + // scope, then frees the slot. Returns false on the terminate entry. + auto pub_one = [&](uint32_t& it) -> bool { + if constexpr (kTmaQh) { + // publisher trim (MO kJit kTmaQh): 32-bit smem barrier addresses, raw try_wait.parity on pub_full, ONE + // elected lane (chosen once per call, warp converged) does TMA store + wait + stg_free arrive + publish fences + // + red.release + pub_empty arrive in program order (was: two elect_one_sync + 2 __syncwarp). Same sequence. + const uint32_t sl = it & 1u; + const uint32_t fb = (uint32_t)__cvta_generic_to_shared(&shared_storage.pub_full[0]) + sl * 8u; + // idle publisher warp: suspend-time hint (wakes on phase completion) -> fewer re-poll issues (power) + asm volatile("{\n\t.reg .pred p;\n\tPW_%=:\n\t" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, 1000000;\n\t" + "@!p bra PW_%=;\n\t}" ::"r"(fb), "r"((it >> 1) & 1u) : "memory"); + const int mb = shared_storage.pub_info[sl]; + if (cute::elect_one_sync()) { + if (mb >= 0) { + tma_store_2d_hint(¶ms.tmap_qh, (uint32_t)__cvta_generic_to_shared(shared_storage.epi_stage), + shared_storage.pub_rc[sl][1], shared_storage.pub_rc[sl][0], l2_pol_evict_last()); + // staging reusable as soon as the TMA store has READ smem (stg_free), then wait for global completion + // of the qh tile before the M-block / tile release below (same publish ordering, earlier staging handoff) + bulk_wait_read0(); + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"((uint32_t)__cvta_generic_to_shared(&shared_storage.stg_free)) : "memory"); + bulk_wait_all0(); + asm volatile("fence.proxy.async.global;" ::: "memory"); + // no fence.acq_rel.gpu: red.release.gpu already orders (cumulatively) the prior writes + asm volatile("red.release.gpu.global.add.s32 [%0], %1;" ::"l"(params.mb_cnt + mb), "r"(1) : "memory"); + } + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"((uint32_t)__cvta_generic_to_shared(&shared_storage.pub_empty[0]) + sl * 8u) : "memory"); + } + __syncwarp(); + ++it; + return mb != -1; + } + const int sl = (int)(it & 1u); + shared_storage.pub_full[sl].wait((it >> 1) & 1u); + const int mb = shared_storage.pub_info[sl]; + if (mb >= 0 && cute::elect_one_sync()) { + if constexpr (kTmaQh) { + // qh tile of this unit: staged by the 512 promotion threads (fence.proxy.async + pub_full arrive each) + // qh is re-read by the down units of this M block -> keep it L2 resident (evict_last) + tma_store_2d_hint(¶ms.tmap_qh, (uint32_t)__cvta_generic_to_shared(shared_storage.epi_stage), + shared_storage.pub_rc[sl][1], shared_storage.pub_rc[sl][0], l2_pol_evict_last()); + bulk_wait_all0(); // stores complete (and staging read) + shared_storage.stg_free.arrive(); // WG0 staging region reusable + } + asm volatile("fence.proxy.async.global;" ::: "memory"); + // fence.acq_rel.gpu dropped (redundant before red.release.gpu) + // a wide half-block unit covers 2 tiles -> 2 arrivals per CTA (block target stays 2 * gu_tn) + const int na = mg_tail(mb) ? 2 : 1; + asm volatile("red.release.gpu.global.add.s32 [%0], %1;" ::"l"(params.mb_cnt + mb), "r"(na) : "memory"); + } + __syncwarp(); + if (cute::elect_one_sync()) shared_storage.pub_empty[sl].arrive(); + __syncwarp(); + ++it; + return mb != -1; // -2: split unit with nothing to publish (kRedSplit) + }; + + if (is_ab) { + // ---------------- TMA A/B producer (unchanged CUTLASS logic) ---------------- + cutlass::arch::warpgroup_reg_dealloc(); + if constexpr (kLean224) reinit_work(); // initial tile computed per role (see reinit_work) + // kLean224 spill audit: the A/B TMA load tensors are built HERE (after the 32-register dealloc), not in the + // shared setup, so their shape / stride values are not live across the role split (8 B local before) + auto load_inputs = [&]() { + if constexpr (kLean224) + return collective_mainloop.load_ab_init(problem_shape_MNKL, params.mainloop, shared_storage.tensors.mainloop); + else return load_inputs0; + }(); + // pre-PDL-wait audit: every operand of this kernel (qx / qwgu / qwd / qh and ALL scale tables, including + // the weight scales sgu / sd*) is written by the preceding quant kernel(s), so only state that needs no global + // input may precede griddepcontrol.wait. Moved before it: the dependent trigger (dependents still wait for our + // FULL completion before reading our outputs; the chain successor (down-weight quant) reads none of them) and + // the epilogue-throttle arrival (lets the promotion warps reach their first TMEM-full wait during the wait). + cutlass::arch::launch_dependent_grids(); + epilogue_throttle_barrier.arrive(); + // before griddepcontrol.wait, L2-prefetch hints (cp.async.bulk.prefetch.tensor, + // no smem write, no completion) of the B (fp8 down weight) tiles of this CTA's first 3 k blocks. qwd is produced + // by the preceding PDL dq kernel, so the smem TMA loads themselves stay after the wait (L2 is the coherence point: + // a hint fetched early can never return stale data to the post-wait TMA loads). + if constexpr (kHalfStg) { + if (cute::elect_one_sync()) { + auto const& [p_kt, p_gA, p_gB, p_sA, p_sB, p_mA, p_mB] = load_inputs; + (void)p_kt; (void)p_gA; (void)p_sA; (void)p_sB; (void)p_mA; (void)p_mB; + Tensor tBgB = p_gB(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + const int nk = (int)size<1>(tBgB) < 3 ? (int)size<1>(tBgB) : 3; + auto const* tb = collective_mainloop.*(&MainloopTmaAccess::observed_tma_load_b_); + for (int k = 0; k < nk; ++k) cute::prefetch(*tb, tBgB(_, k)); + } + __syncwarp(); + } + cutlass::arch::wait_on_dependent_grids(); + bool requires_clc_query = true; + [[maybe_unused]] uint32_t ab_u = 0; // kSfInfo: this CTA's unit ordinal + [[maybe_unused]] uint32_t ab_sf_it = 0; // kSfRelay: this CTA's k-block ordinal (= scale-ring position) + do { + auto k_tile_iter = scheduler.get_k_tile_iterator(work_tile_info, problem_shape_MNKL, CtaShape_MNK{}, + load_inputs.k_tiles); + auto k_tile_count = TileScheduler::get_work_k_tile_count(work_tile_info, problem_shape_MNKL, CtaShape_MNK{}); + [[maybe_unused]] bool mg_dn = false; + [[maybe_unused]] int mg_mb = 0; + if constexpr (kMerged && kTailSplit) { + int kb0, tt, sj; + cta_coord_mnkl = mg_decode7(work_tile_info.M_idx / kClCtas, k_tile_count, mg_dn, mg_mb, kb0, tt, sj); + for (int i = 0; i < kb0; ++i) ++k_tile_iter; // split unit: start at its first k block + } else if constexpr (kMerged) { + cta_coord_mnkl = mg_decode(work_tile_info.M_idx / kClCtas, k_tile_count, mg_dn, mg_mb); + } else if constexpr (kStatic) { + int kb0, tt, sj; + cta_coord_mnkl = st_decode(st_unit(work_tile_info), kb0, k_tile_count, tt, sj); + for (int i = 0; i < kb0; ++i) ++k_tile_iter; // start at this unit's first k block + } + if constexpr (IsSchedDynamicPersistent && !kJit) { + if (!kPair && is_first_cta_in_cluster && requires_clc_query) { + clc_throttle_pipeline.producer_acquire(clc_pipe_throttle_producer_state); + clc_throttle_pipeline.producer_commit(clc_pipe_throttle_producer_state); + ++clc_pipe_throttle_producer_state; + } + } + if (kHT_AB && mg_tail(mg_mb)) { + // ---- wide half-block unit: per k block two A/B stages, stage j = (A slice, B half of tile nt0 + j). + // Odd CTA: A through the 192-row shifted map at per-CTA tile 2(mb-1)+1 -> rows [256mb+64, +128) (the M=128 + // MMA reads its first 64). Same boxes / tx bytes as a full stage; the coordinate tensors of load_inputs are + // reused (coordinates only, bounds come from the descriptor). + const bool odd = (cta_rank_in_cluster & 1) != 0; + const int cm = odd ? 2 * (mg_mb - 1) + 1 : 2 * mg_mb; + const int cn = get<1>(cta_coord_mnkl); + if (mg_dn) mg_wait_block(mg_mb); + CollectiveMainloop ch(mg_dn ? (odd ? params.hx->mainloop_dn_t : params.mainloop_dn) + : (odd ? params.hx->mainloop_t : params.mainloop), + cluster_shape, cta_rank_in_cluster); + CUTLASS_PRAGMA_NO_UNROLL + for (int kt = 0; kt < (int)k_tile_count; ++kt) { + CUTLASS_PRAGMA_UNROLL + for (int j = 0; j < 2; ++j) { + if (mg_dn) { + auto [st_next, it_next] = ch.load_ab(mainloop_ab_pipeline, mainloop_ab_pipe_producer_state, + load_inputs_dn, make_coord(cm, cn + j, _, 0), k_tile_iter, 1); + mainloop_ab_pipe_producer_state = st_next; + } else { + auto [st_next, it_next] = ch.load_ab(mainloop_ab_pipeline, mainloop_ab_pipe_producer_state, + load_inputs, make_coord(cm, cn + j, _, 0), k_tile_iter, 1); + mainloop_ab_pipe_producer_state = st_next; + } + } + ++k_tile_iter; + } + } else + if (kJit) { + // kJit: release the CLC throttle when kJitD k blocks of this unit remain to be loaded (the next unit is then + // queried / bound only ~kJitD k blocks before this cluster needs it; the query latency stays hidden) + // kCq DN unit past the early-TMA k blocks -> readiness acquired by the scale warp (see there) + [[maybe_unused]] const bool dn_rel = kCq && mg_dn && ab_sf_it >= (uint32_t)kEarlyTma; + if (mg_dn && !dn_rel) mg_wait_block(mg_mb); + const int kc = (int)k_tile_count; + const int n1 = kc > kJitD ? kc - kJitD : 0; + auto jit_commit = [&]() { + if (is_first_cta_in_cluster && requires_clc_query) { + clc_throttle_pipeline.producer_acquire(clc_pipe_throttle_producer_state); + clc_throttle_pipeline.producer_commit(clc_pipe_throttle_producer_state); + ++clc_pipe_throttle_producer_state; + } + }; + if constexpr (kSfRelay) { + // per k block: scales of kb in smem -> TMA kb -> relay the scale-slot release of kb - kRelayLag + // kCq: before the TMA of k block kt, poll the in-kernel conversion of its operand (GU: x of this CTA's + // 128-row tile; DN: the down-weight slab of the unit); counters seen ready are cached in cq_hi + [[maybe_unused]] const int* cq_p = nullptr; + [[maybe_unused]] int cq_tg = 0, cq_hi = 0; + if constexpr (kCq) { + if (mg_dn) { cq_p = params.cq.ready + cq_nxc(params.cq) + get<1>(cta_coord_mnkl) * (params.cq.I >> 7); cq_tg = 256 / kCqRows; } + else { cq_p = params.cq.ready + get<0>(cta_coord_mnkl) * (params.cq.Hd >> 7); cq_tg = cq_xtarget(params.cq, get<0>(cta_coord_mnkl)); } + if (cq_tg == 0) cq_hi = kc; + if (dn_rel) cq_hi = kc + 1; // marker: no polls, one proxy fence after the kb-0 ring wait + } +#if SE_DN_B_HINT && SE_GU_B_HINT + // A/B loop trim: the unit-constant work is hoisted out of the per-kb loop: GU / DN loop selected once per + // unit (no per-kb mg_dn branch), the A / B coordinate-tensor slices of the unit, the collective's TMA atom + // pointers and the issuing lane (warp converged) are computed once. Same TMA sequence / hints / barriers. + auto ab_loop = [&](auto& coll, auto const& li) { + auto const& [x_kt, x_gA, x_gB, x_sA, x_sB, x_mA, x_mB] = li; + (void)x_kt; + Tensor tAgA = x_gA(_, get<0>(cta_coord_mnkl) / size(typename TiledMma::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgB = x_gB(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + auto const* ta = coll.*(&MainloopTmaAccess::observed_tma_load_a_); + auto const* tb = coll.*(&MainloopTmaAccess::observed_tma_load_b_); + const bool lead = cute::elect_one_sync(); + CUTLASS_PRAGMA_NO_UNROLL + for (int kt = 0; kt < kc; ++kt) { + if (kt == n1) jit_commit(); + const uint32_t sl = ab_sf_it; + if (sl >= (uint32_t)kEarlyTma) shared_storage.gsf_full[sl & (kGsfStages - 1)].wait((sl >> kGsfLog) & 1u); + if constexpr (kCq) if ((kTileRdy || kt == 0) && cq_hi > kc) asm volatile("fence.proxy.async.global;" ::: "memory"); + if constexpr (kCq) if (kt >= cq_hi) { + cq_hi = kt + cq_wait_prefix(cq_p + kt, kc - kt, cq_tg); + } + mainloop_ab_pipeline.producer_acquire(mainloop_ab_pipe_producer_state); + auto* tma_barrier = mainloop_ab_pipeline.producer_get_barrier(mainloop_ab_pipe_producer_state); + const int write_stage = mainloop_ab_pipe_producer_state.index(); + if (lead) { + // DN units' A operand (qh, stored evict_last, re-read by all dn_tn down units of the M block) + // is loaded with an L2 evict_last hint too (default policy loads demote it to evict_normal, so the + // streamed bf16 x / down-weight converter traffic and the output stores can evict it between the + // DN units of a block); GU A (qx) keeps the default policy + if constexpr (kTwoSm && kJit && SE_DN_A_HINT) { + if (mg_dn) copy(ta->with(*tma_barrier, x_mA, cute::TMA::CacheHintSm100::EVICT_LAST), tAgA(_, *k_tile_iter), + x_sA(_, write_stage)); + else copy(ta->with(*tma_barrier, x_mA), tAgA(_, *k_tile_iter), x_sA(_, write_stage)); + } else + copy(ta->with(*tma_barrier, x_mA), tAgA(_, *k_tile_iter), x_sA(_, write_stage)); + if constexpr (kTwoSm && kJit) // 2SM merged kernels: SM100_TMA_2SM_LOAD (CacheHintSm100) + copy(tb->with(*tma_barrier, x_mB, cute::TMA::CacheHintSm100::EVICT_LAST), tBgB(_, *k_tile_iter), + x_sB(_, write_stage)); + else + copy(tb->with(*tma_barrier, x_mB), tBgB(_, *k_tile_iter), x_sB(_, write_stage)); + } + ++mainloop_ab_pipe_producer_state; + ++k_tile_iter; + __syncwarp(); + if (sl >= (uint32_t)kRelayLag && (threadIdx.x & 31) == 0) + shared_storage.gsf_empty[(sl - (uint32_t)kRelayLag) & (kGsfStages - 1)].arrive(); + ++ab_sf_it; + } + }; + if (mg_dn) ab_loop(collective_dn, load_inputs_dn); + else ab_loop(collective_mainloop, load_inputs); +#else + CUTLASS_PRAGMA_NO_UNROLL + for (int kt = 0; kt < kc; ++kt) { + if (kt == n1) jit_commit(); + const uint32_t sl = ab_sf_it; + // kEarlyTma: the first kEarlyTma k blocks of this CTA are loaded WITHOUT waiting for their scales (the + // TMA of qx no longer serializes behind the scale warp's sx round trip after griddepcontrol.wait); the + // promotion threads wait on gsf_full themselves for exactly those k blocks (see fetch_scale) + if (sl >= (uint32_t)kEarlyTma) shared_storage.gsf_full[sl & (kGsfStages - 1)].wait((sl >> kGsfLog) & 1u); + if constexpr (kCq) if (kt >= cq_hi) { + cq_hi = kt + cq_wait_prefix(cq_p + kt, kc - kt, cq_tg); + } + if (mg_dn) { +#if SE_DN_B_HINT + // one k block of a down unit, same steps as CollectiveMainloop::load_ab (acquire stage, A + B TMA + // through the collective's own TMA atoms onto the stage's full barrier), but the B operand (qWd, re-read + // by the down units of every M block) carries an L2 evict_last cache hint; A (qh) keeps the default. + auto const& [ld_kt, ld_gA, ld_gB, ld_sA, ld_sB, ld_mA, ld_mB] = load_inputs_dn; + (void)ld_kt; + Tensor tAgA = ld_gA(_, get<0>(cta_coord_mnkl) / size(typename TiledMma::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgB = ld_gB(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + mainloop_ab_pipeline.producer_acquire(mainloop_ab_pipe_producer_state); + auto* tma_barrier = mainloop_ab_pipeline.producer_get_barrier(mainloop_ab_pipe_producer_state); + const int write_stage = mainloop_ab_pipe_producer_state.index(); + if (cute::elect_one_sync()) { + auto const* ta = collective_dn.*(&MainloopTmaAccess::observed_tma_load_a_); + auto const* tb = collective_dn.*(&MainloopTmaAccess::observed_tma_load_b_); + copy(ta->with(*tma_barrier, ld_mA), tAgA(_, *k_tile_iter), ld_sA(_, write_stage)); + if constexpr (kTwoSm && kJit) // 2SM merged kernels: SM100_TMA_2SM_LOAD (CacheHintSm100) + copy(tb->with(*tma_barrier, ld_mB, cute::TMA::CacheHintSm100::EVICT_LAST), tBgB(_, *k_tile_iter), + ld_sB(_, write_stage)); + else + copy(tb->with(*tma_barrier, ld_mB), tBgB(_, *k_tile_iter), ld_sB(_, write_stage)); + } + ++mainloop_ab_pipe_producer_state; +#else + auto [s1, it1] = collective_dn.load_ab(mainloop_ab_pipeline, mainloop_ab_pipe_producer_state, + load_inputs_dn, cta_coord_mnkl, k_tile_iter, 1); + mainloop_ab_pipe_producer_state = s1; +#endif + } else { +#if SE_GU_B_HINT + // GU k block, same steps as CollectiveMainloop::load_ab; B (fp8 gate/up weights, re-read by the GU + // units of every M block) carries an L2 evict_last cache hint; A (qx) keeps the default. + auto const& [lg_kt, lg_gA, lg_gB, lg_sA, lg_sB, lg_mA, lg_mB] = load_inputs; + (void)lg_kt; + Tensor tAgA = lg_gA(_, get<0>(cta_coord_mnkl) / size(typename TiledMma::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgB = lg_gB(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + mainloop_ab_pipeline.producer_acquire(mainloop_ab_pipe_producer_state); + auto* tma_barrier = mainloop_ab_pipeline.producer_get_barrier(mainloop_ab_pipe_producer_state); + const int write_stage = mainloop_ab_pipe_producer_state.index(); + if (cute::elect_one_sync()) { + auto const* ta = collective_mainloop.*(&MainloopTmaAccess::observed_tma_load_a_); + auto const* tb = collective_mainloop.*(&MainloopTmaAccess::observed_tma_load_b_); + copy(ta->with(*tma_barrier, lg_mA), tAgA(_, *k_tile_iter), lg_sA(_, write_stage)); + if constexpr (kTwoSm && kJit) + copy(tb->with(*tma_barrier, lg_mB, cute::TMA::CacheHintSm100::EVICT_LAST), tBgB(_, *k_tile_iter), + lg_sB(_, write_stage)); + else + copy(tb->with(*tma_barrier, lg_mB), tBgB(_, *k_tile_iter), lg_sB(_, write_stage)); + } + ++mainloop_ab_pipe_producer_state; +#else + auto [s1, it1] = collective_mainloop.load_ab(mainloop_ab_pipeline, mainloop_ab_pipe_producer_state, + load_inputs, cta_coord_mnkl, k_tile_iter, 1); + mainloop_ab_pipe_producer_state = s1; +#endif + } + ++k_tile_iter; + __syncwarp(); + if (sl >= (uint32_t)kRelayLag && (threadIdx.x & 31) == 0) + shared_storage.gsf_empty[(sl - (uint32_t)kRelayLag) & (kGsfStages - 1)].arrive(); + ++ab_sf_it; + } +#endif + } else + if (mg_dn) { + auto [s1, it1] = collective_dn.load_ab(mainloop_ab_pipeline, mainloop_ab_pipe_producer_state, load_inputs_dn, + cta_coord_mnkl, k_tile_iter, n1); + jit_commit(); + auto [s2, it2] = collective_dn.load_ab(mainloop_ab_pipeline, s1, load_inputs_dn, cta_coord_mnkl, it1, kc - n1); + mainloop_ab_pipe_producer_state = s2; + } else { + auto [s1, it1] = collective_mainloop.load_ab(mainloop_ab_pipeline, mainloop_ab_pipe_producer_state, load_inputs, + cta_coord_mnkl, k_tile_iter, n1); + jit_commit(); + auto [s2, it2] = collective_mainloop.load_ab(mainloop_ab_pipeline, s1, load_inputs, cta_coord_mnkl, it1, kc - n1); + mainloop_ab_pipe_producer_state = s2; + } + } else + if (kMerged && mg_dn) { + // down unit: wait for this M block's qh / sh (written by gate_up epilogues), then TMA from the dn maps + mg_wait_block(mg_mb); + auto [st_next, it_next] = collective_dn.load_ab(mainloop_ab_pipeline, mainloop_ab_pipe_producer_state, + load_inputs_dn, cta_coord_mnkl, k_tile_iter, k_tile_count); + mainloop_ab_pipe_producer_state = st_next; + } else if constexpr (kSfRelay) { + // non-merged kSfRelay: per k block wait for its scales, TMA it, relay the scale-slot release of kb - lag + CUTLASS_PRAGMA_NO_UNROLL + for (int kt = 0; kt < (int)k_tile_count; ++kt) { + const uint32_t sl = ab_sf_it; + // kEarlyNM: the CTA's first kEarlyTma k blocks do not wait for their scales (promotion waits instead) + if (sl >= (uint32_t)kEarlyTma) shared_storage.gsf_full[sl & (kGsfStages - 1)].wait((sl >> kGsfLog) & 1u); + auto [s1, it1] = collective_mainloop.load_ab(mainloop_ab_pipeline, mainloop_ab_pipe_producer_state, + load_inputs, cta_coord_mnkl, k_tile_iter, 1); + mainloop_ab_pipe_producer_state = s1; + ++k_tile_iter; + __syncwarp(); + if (sl >= (uint32_t)kRelayLag && (threadIdx.x & 31) == 0) + shared_storage.gsf_empty[(sl - (uint32_t)kRelayLag) & (kGsfStages - 1)].arrive(); + ++ab_sf_it; + } + } else { + auto [st_next, it_next] = collective_mainloop.load_ab(mainloop_ab_pipeline, mainloop_ab_pipe_producer_state, + load_inputs, cta_coord_mnkl, k_tile_iter, k_tile_count); + mainloop_ab_pipe_producer_state = st_next; + } + __syncwarp(); + if constexpr (kPair) break; // one unit per CTA + typename TileScheduler::WorkTileInfo next_work_tile_info; + bool increment_pipe; + if constexpr (kSfInfo) { sfi_read(ab_u, next_work_tile_info, increment_pipe); ++ab_u; } + else { + auto [nw_, inc_] = scheduler.fetch_next_work(work_tile_info, clc_pipeline, clc_pipe_consumer_state); + next_work_tile_info = nw_; increment_pipe = inc_; + } + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + requires_clc_query = increment_pipe; + if (!kSfInfo && increment_pipe) ++clc_pipe_consumer_state; + } while (work_tile_info.is_valid()); + collective_mainloop.load_ab_tail(mainloop_ab_pipeline, mainloop_ab_pipe_producer_state); + } else if (is_sf) { + // ---------------- scale-factor producer (unchanged CUTLASS logic, now on warp 3) ---------------- + auto sf_inputs = collective_mainloop.load_sf_init(problem_shape_MNKL, params.mainloop, + shared_storage.tensors.mainloop); + auto sf_inputs_dn = collective_dn.load_sf_init(problem_shape_dn, params.mainloop_dn, + shared_storage.tensors.mainloop); + cutlass::arch::warpgroup_reg_dealloc(); + if constexpr (kLean224) reinit_work(); // initial tile computed per role (see reinit_work) + [[maybe_unused]] uint32_t sf_u = 0; // kSfInfo: this CTA's unit ordinal + [[maybe_unused]] uint32_t gsf_it = 0; // kGsf ring counter: slot = it % 16, parity = (it / 16) & 1 + cutlass::arch::wait_on_dependent_grids(); + do { + auto k_tile_iter = scheduler.get_k_tile_iterator(work_tile_info, problem_shape_MNKL, CtaShape_MNK{}, + sf_inputs.k_tiles); + auto k_tile_count = TileScheduler::get_work_k_tile_count(work_tile_info, problem_shape_MNKL, CtaShape_MNK{}); + [[maybe_unused]] bool mg_dn = false; + [[maybe_unused]] int mg_mb = 0; + [[maybe_unused]] int mg_kb0 = 0; + if constexpr (kMerged && kTailSplit) { + int tt, sj; + cta_coord_mnkl = mg_decode7(work_tile_info.M_idx / kClCtas, k_tile_count, mg_dn, mg_mb, mg_kb0, tt, sj); + for (int i = 0; i < mg_kb0; ++i) ++k_tile_iter; + } else if constexpr (kMerged) { + cta_coord_mnkl = mg_decode(work_tile_info.M_idx / kClCtas, k_tile_count, mg_dn, mg_mb); + } else if constexpr (kStatic) { + int kb0, tt, sj; + cta_coord_mnkl = st_decode(st_unit(work_tile_info), kb0, k_tile_count, tt, sj); + for (int i = 0; i < kb0; ++i) ++k_tile_iter; + } + if constexpr (kGsf) { + int kb0 = 0; + if constexpr (!kMerged && kStatic) { + int kc2, tt2, sj2; + st_decode(st_unit(work_tile_info), kb0, kc2, tt2, sj2); + } + if constexpr (kMerged && kTailSplit) kb0 = mg_kb0; + const bool dnu = kMerged && mg_dn; + if (dnu && !kTileRdy) mg_wait_block(mg_mb); // sh of this M block is produced by the gate_up epilogues + if constexpr (kCq && kJit) { + if (dnu && gsf_it >= (uint32_t)kEarlyTma) { + const int* sp = params.cq.ready + cq_nxc(params.cq) + get<1>(cta_coord_mnkl) * (params.cq.I >> 7); + const int kcd = (int)k_tile_count; + int dn_ok = 0; + while (dn_ok < kcd) dn_ok += cq_wait_prefix(sp + dn_ok, kcd - dn_ok, 256 / kCqRows); + } + } + const int lane = (int)(threadIdx.x & 31); + // wide half-block unit: ring entry of TMEM lane L = 32q + l (row L & 63 of the CTA's rows [256mb + 64r, + // +64), tile col half k = L >> 6) is the float2 {sa*sb[2nt0 + k], sa*sb[2nt0 + 2 + k]} (tile nt0 / nt0+1): the + // promotion thread reads the same address as in a full unit and picks .x / .y by g>>1. Lane l: 4 rows from + // (4l) & 63, half k = l >> 4; 4 B scales loaded (16 B). + const bool hu = kHT_SF && mg_tail(mg_mb); + const int row0 = hu ? kClTileM * mg_mb + 64 * (int)(cta_rank_in_cluster & 1) + ((lane * 4) & 63) + : get<0>(cta_coord_mnkl) * 128 + lane * 4; + const bool row_ok = row0 < M; // M % 4 == 0: a 4-row group is entirely valid or entirely padding + // 32-bit element offsets (bases / strides re-read from the param constant bank: 24-register warp) + uint32_t oa = (uint32_t)kb0 * (uint32_t)M + (uint32_t)(row_ok ? row0 : 0); + uint32_t ob = (uint32_t)kb0 * (uint32_t)((dnu ? params.dn_n : N) >> 7) + 2u * (uint32_t)get<1>(cta_coord_mnkl); + // packed per-unit B-scale pick: byte 0 / byte 1 = gsf_b index of b.x / b.y, bit 16 = wide unit + const int bsel = hu ? ((lane >> 4) | (((lane >> 4) + 2) << 8) | 0x10000) : (1 << 8); + const int cnt = (int)k_tile_count; + static_assert(kGsfStages == (1 << kGsfLog) && kGsfLook < kGsfStages, "slot math assumes a power-of-2 ring"); + if constexpr (kFastSF) { + const char* ga = reinterpret_cast((dnu ? params.gsf_a_dn : params.gsf_a) + oa); + const char* gbp = reinterpret_cast((dnu ? params.gsf_b_dn : params.gsf_b) + ob); + const uint32_t sa_stride = (uint32_t)M * 4u; + const uint32_t sb_stride = (uint32_t)((dnu ? params.dn_n : N) >> 7) * 4u; + const uint32_t a_sz = row_ok ? 16u : 0u; + const uint32_t is_l0 = lane == 0 ? 1u : 0u; + constexpr uint32_t kCS = (uint32_t)sizeof(shared_storage.gsf_c[0]); // 1024 B per stage + constexpr uint32_t kBS = (uint32_t)sizeof(shared_storage.gsf_b[0]); // 16 B per stage + const uint32_t c_base = (uint32_t)__cvta_generic_to_shared(&shared_storage.gsf_c[0][0]) + (uint32_t)lane * 32u; + const uint32_t b_base = (uint32_t)__cvta_generic_to_shared(&shared_storage.gsf_b[0][0]); + // raw A scales staged CONTIGUOUSLY in the slot's upper half (lane l: bytes [512 + 16 l, +16)), so the + // cp.async smem writes and the convert's LDS.128 are 4-wavefront (conflict-free); the global side was already + // one 512 B contiguous request per warp (32 lanes x 16 B of consecutive MN-major row scales) + const uint32_t r_base = (uint32_t)__cvta_generic_to_shared(&shared_storage.gsf_c[0][0]) + 512u + (uint32_t)lane * 16u; + const uint32_t f_base = (uint32_t)__cvta_generic_to_shared(&shared_storage.gsf_full[0]); + const uint32_t e_base = (uint32_t)__cvta_generic_to_shared(&shared_storage.gsf_empty[0]); + // issue position (slot, parity of the ring pass) and convert position, both start at gsf_it + uint32_t i_slot = gsf_it & (uint32_t)(kGsfStages - 1), i_par = (gsf_it >> kGsfLog) & 1u; + uint32_t c_off = i_slot; // convert slot index +#if SE_SF_SLIM + // slim scale producer (112/32 register split): only the ring positions (i_slot / i_par, c_off) stay live; + // the 6 per-position smem addresses are recomputed at each use (base + slot * stride, one IMAD each) +#define SF_IC (c_base + i_slot * kCS) +#define SF_IB (b_base + i_slot * kBS) +#define SF_IE (e_base + i_slot * 8u) +#define SF_CC (c_base + c_off * kCS) +#define SF_CB (b_base + c_off * kBS) +#define SF_CF (f_base + c_off * 8u) +#else + uint32_t i_c = c_base + i_slot * kCS, i_b = b_base + i_slot * kBS, i_e = e_base + i_slot * 8u; + uint32_t c_c = i_c, c_b = i_b, c_f = f_base + i_slot * 8u; +#define SF_IC i_c +#define SF_IB i_b +#define SF_IE i_e +#define SF_CC c_c +#define SF_CB c_b +#define SF_CF c_f +#endif + // kCq: GU units poll the in-kernel conversion of this CTA tile's x (sx) per k block before loading it + [[maybe_unused]] const int* cq_p = nullptr; + [[maybe_unused]] int cq_tg = 0, cq_kb = 0, cq_hi = 0; + if constexpr (kCq) { + cq_p = params.cq.ready + get<0>(cta_coord_mnkl) * (params.cq.Hd >> 7); + cq_tg = dnu ? 0 : cq_xtarget(params.cq, get<0>(cta_coord_mnkl)); + if (kTileRdy && dnu) { cq_p = params.mb_cnt + mg_mb * params.gu_tn; cq_tg = 2; } // per h tile + if (cq_tg == 0) cq_hi = 1 << 20; + } + auto issue = [&]() { + if constexpr (kCq) { + if (cq_kb >= cq_hi) { + cq_hi = cq_kb + cq_wait_prefix(cq_p + cq_kb, cnt - cq_kb, cq_tg); + } + ++cq_kb; + } + // wait until this slot was released (previous ring pass; kSfRelay: the A/B warp's relay) + asm volatile("{\n\t.reg .pred p;\n\tSFW_%=:\n\t" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n\t" + "@!p bra SFW_%=;\n\t}" ::"r"(SF_IE), "r"(i_par ^ 1u) : "memory"); + asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;" ::"r"(r_base + i_slot * kCS), "l"(ga), "r"(a_sz) + : "memory"); + asm volatile("{\n\t.reg .pred q;\n\tsetp.ne.u32 q, %2, 0;\n\t" + "@q cp.async.ca.shared.global [%0], [%1], 8;\n\t}" ::"r"(SF_IB), "l"(gbp), "r"(is_l0) + : "memory"); + ga += sa_stride; + gbp += sb_stride; +#if SE_SF_SLIM + if (++i_slot == (uint32_t)kGsfStages) { i_slot = 0; i_par ^= 1u; } +#else + ++i_slot; i_c += kCS; i_b += kBS; i_e += 8u; + if (i_slot == (uint32_t)kGsfStages) { i_slot = 0; i_c = c_base; i_b = b_base; i_e = e_base; i_par ^= 1u; } +#endif + }; + auto commit = []() { asm volatile("cp.async.commit_group;" ::: "memory"); }; + auto convert = [&]() { + asm volatile("cp.async.wait_group %0;" ::"n"(kGsfLook) : "memory"); // k block t - L landed + __syncwarp(); // lane 0's B-scale cp.async is visible to the whole warp + float bx, by, a0, a1, a2, a3; + asm volatile("ld.shared.v2.f32 {%0, %1}, [%2];" : "=f"(bx), "=f"(by) : "r"(SF_CB) : "memory"); + if constexpr (kHalveGate) if (!dnu) bx *= 0.5f; // gate block scale x 0.5 (see kHalveGate) + asm volatile("ld.shared.v4.f32 {%0, %1, %2, %3}, [%4];" : "=f"(a0), "=f"(a1), "=f"(a2), "=f"(a3) + : "r"(r_base + c_off * kCS) : "memory"); + __syncwarp(); // every lane's raw read precedes the combined stores (lanes 16-31 overwrite raw rows) + // own lane region only: raw rows 0-3 at floats [4,8) -> combined {sa*sb0, sa*sb1} pairs at [0,8) + asm volatile("st.shared.v4.f32 [%0], {%1, %2, %3, %4};" ::"r"(SF_CC), "f"(a0 * bx), "f"(a0 * by), + "f"(a1 * bx), "f"(a1 * by) : "memory"); + asm volatile("st.shared.v4.f32 [%0], {%1, %2, %3, %4};" ::"r"(SF_CC + 16u), "f"(a2 * bx), "f"(a2 * by), + "f"(a3 * bx), "f"(a3 * by) : "memory"); + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(SF_CF) : "memory"); // release +#if SE_SF_SLIM + if (++c_off == (uint32_t)kGsfStages) c_off = 0; +#else + ++c_off; c_c += kCS; c_b += kBS; c_f += 8u; + if (c_off == (uint32_t)kGsfStages) { c_off = 0; c_c = c_base; c_b = b_base; c_f = f_base; } +#endif + }; + // prologue: steps t < L (issue only, if t < cnt) + CUTLASS_PRAGMA_UNROLL + for (int t = 0; t < kGsfLook; ++t) { + if (t < cnt) issue(); + commit(); + } + // steady state: steps L <= t < cnt, two k blocks per iteration + int t = kGsfLook; + CUTLASS_PRAGMA_NO_UNROLL + for (; t + 1 < cnt; t += 2) { + issue(); commit(); convert(); + issue(); commit(); convert(); + } + if (t < cnt) { issue(); commit(); convert(); ++t; } + // epilogue: remaining converts (empty commit groups keep the wait_group L accounting) + const int t_end = cnt + kGsfLook; + for (t = t < kGsfLook ? kGsfLook : t; t < t_end; ++t) { commit(); convert(); } + gsf_it += (uint32_t)cnt; +#undef SF_IC +#undef SF_IB +#undef SF_IE +#undef SF_CC +#undef SF_CB +#undef SF_CF + } else { + // ONE software-pipelined loop (few live registers: this warp runs with 24): step t issues the raw loads of + // k block t (t < cnt) into ring slot gsf_it + t, commits one cp.async group per step (empty at the tail), + // and converts k block t - kGsfLook once its group has landed (wait_group kGsfLook). + CUTLASS_PRAGMA_NO_UNROLL + for (int t = 0; t < cnt + kGsfLook; ++t) { + if (t < cnt) { + const uint32_t sl = gsf_it + (uint32_t)(t < kGsfLook ? t : kGsfLook); + const int is = (int)(sl & (kGsfStages - 1)); + shared_storage.gsf_empty[kPairScale ? (is | 1) : is].wait(((sl >> kGsfLog) & 1u) ^ 1u); + const uint32_t da = (uint32_t)__cvta_generic_to_shared(&shared_storage.gsf_c[is][lane * 8 + 4]); + asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;" ::"r"(da), + "l"((dnu ? params.gsf_a_dn : params.gsf_a) + oa), "r"(row_ok ? 16 : 0) : "memory"); + if (lane == 0) { + const uint32_t db = (uint32_t)__cvta_generic_to_shared(&shared_storage.gsf_b[is][0]); + const float* gb = (dnu ? params.gsf_b_dn : params.gsf_b) + ob; + asm volatile("cp.async.ca.shared.global [%0], [%1], 8;" ::"r"(db), "l"(gb) : "memory"); + if (kHT_SF && (bsel & 0x10000)) + asm volatile("cp.async.ca.shared.global [%0], [%1], 8;" ::"r"(db + 8u), "l"(gb + 2) : "memory"); + } + oa += (uint32_t)M; + ob += (uint32_t)((dnu ? params.dn_n : N) >> 7); + } + asm volatile("cp.async.commit_group;" ::: "memory"); + if (t >= kGsfLook) { + asm volatile("cp.async.wait_group %0;" ::"n"(kGsfLook) : "memory"); // k block t - kGsfLook landed + __syncwarp(); // lane 0's B-scale cp.async is visible to the whole warp + const int gsf_slot = (int)(gsf_it & (kGsfStages - 1)); + // this lane's region = floats [8 lane, +8): raw A scales of its 4 rows sit in the upper half; converting + // rows 0,1 writes the lower half, then rows 2,3 overwrite the (already read) upper half -> no cross-lane + // hazard + float* st = shared_storage.gsf_c[gsf_slot] + lane * 8; + // full unit: b = {sb[2nt], sb[2nt+1]}; wide half-block unit: b = {sb[2nt0 + k], sb[2nt0 + 2 + k]} + const float2 b = make_float2(shared_storage.gsf_b[gsf_slot][bsel & 0xff], + shared_storage.gsf_b[gsf_slot][(bsel >> 8) & 0xff]); + const float2 a01 = *reinterpret_cast(st + 4); + *reinterpret_cast(st) = make_float4(a01.x * b.x, a01.x * b.y, a01.y * b.x, a01.y * b.y); + const float2 a23 = *reinterpret_cast(st + 6); + *reinterpret_cast(st + 4) = make_float4(a23.x * b.x, a23.x * b.y, a23.y * b.x, a23.y * b.y); + shared_storage.gsf_full[gsf_slot].arrive(); // release: this lane's combined rows + ++gsf_it; + } + } + } // !kFastSF + } else if (kMerged && mg_dn) { + mg_wait_block(mg_mb); // sh of this M block is produced by the gate_up epilogues + auto [st_next, it_next] = collective_dn.load_sf(mainloop_sf_pipeline, mainloop_sf_pipe_producer_state, + sf_inputs_dn, cta_coord_mnkl, k_tile_iter, k_tile_count); + mainloop_sf_pipe_producer_state = st_next; + } else { + auto [st_next, it_next] = collective_mainloop.load_sf(mainloop_sf_pipeline, mainloop_sf_pipe_producer_state, + sf_inputs, cta_coord_mnkl, k_tile_iter, k_tile_count); + mainloop_sf_pipe_producer_state = st_next; + } + __syncwarp(); + if constexpr (kPair) break; // one unit per CTA + auto [next_work_tile_info, increment_pipe] = + scheduler.fetch_next_work(work_tile_info, clc_pipeline, clc_pipe_consumer_state); + if constexpr (kSfInfo) { // relay to the A/B + MMA warps (see kSfInfo) + const uint32_t sl = sf_u & 1u; + shared_storage.sfi_empty[sl].wait(((sf_u >> 1) & 1u) ^ 1u); + if (cute::elect_one_sync()) { + shared_storage.sfi_info[sl] = next_work_tile_info; + shared_storage.sfi_inc[sl] = increment_pipe ? 1 : 0; + shared_storage.sfi_full[sl].arrive(); + } + __syncwarp(); + ++sf_u; + } + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + if (increment_pipe) ++clc_pipe_consumer_state; + } while (work_tile_info.is_valid()); + if constexpr (kGsf) asm volatile("cp.async.wait_all;" ::: "memory"); // no cp.async in flight at exit + else collective_mainloop.load_sf_tail(mainloop_sf_pipeline, mainloop_sf_pipe_producer_state); + } else if (is_sched) { + // ---------------- CLC scheduler (unchanged) ---------------- + cutlass::arch::warpgroup_reg_dealloc(); + if constexpr (kLean224) reinit_work(); // initial tile computed per role (see reinit_work) + epilogue_throttle_barrier.arrive(); + if constexpr (IsSchedDynamicPersistent && !kPair) { + bool requires_clc_query = true; + [[maybe_unused]] uint32_t pub_it = 0; + [[maybe_unused]] bool prev_gu = false; // kPub: previous unit was a gate_up unit (publish still pending) + cutlass::arch::wait_on_dependent_grids(); + do { + if (requires_clc_query) { + clc_throttle_pipeline.consumer_wait(clc_pipe_throttle_consumer_state); + clc_throttle_pipeline.consumer_release(clc_pipe_throttle_consumer_state); + ++clc_pipe_throttle_consumer_state; + clc_pipe_producer_state = scheduler.advance_to_next_work(clc_pipeline, clc_pipe_producer_state); + } + auto [next_work_tile_info, increment_pipe] = + scheduler.fetch_next_work(work_tile_info, clc_pipeline, clc_pipe_consumer_state); + requires_clc_query = increment_pipe; + if (increment_pipe) ++clc_pipe_consumer_state; + if constexpr (kPub) { + // unit i is current, unit i+1 already fetched: publish unit i-1 (its epilogue ends about now; nothing it + // depends on waits for this warp any more), then remember whether unit i is a gate_up unit + if constexpr (kJit) { + // kJit: unit i+1 is fetched when unit i's loads are all issued: publish unit i itself (its epilogue ends + // a few us later; the next throttle release is at least one unit's loads away) + if ((int)(work_tile_info.M_idx / kClCtas) < (kTailSplit ? params.gu_all : params.gu_units)) pub_one(pub_it); + } else { + if (prev_gu) pub_one(pub_it); + prev_gu = (int)(work_tile_info.M_idx / kClCtas) < (kTailSplit ? params.gu_all : params.gu_units); + } + } + work_tile_info = next_work_tile_info; + } while (work_tile_info.is_valid()); + if constexpr (kPub) if (prev_gu) pub_one(pub_it); + clc_pipeline.producer_tail(clc_pipe_producer_state); + } + } else if (is_mma) { + // ---------------- tcgen05 MMA issuer (unchanged CUTLASS collective mma) ---------------- + cutlass::arch::warpgroup_reg_dealloc(); + if constexpr (kLean224) reinit_work(); // initial tile computed per role (see reinit_work) + tmem_allocator.allocate(TmemAllocator::Sm100TmemCapacityColumns, &shared_storage.tmem_base_ptr); + __syncwarp(); + tmem_allocation_result_barrier.arrive(); + uint32_t tmem_base_ptr = shared_storage.tmem_base_ptr; + collective_mainloop.set_tmem_offsets(tmem_storage, tmem_base_ptr); + auto mma_inputs = collective_mainloop.mma_init(tmem_storage, shared_storage.tensors.mainloop); + epilogue_throttle_barrier.arrive(); + if constexpr (kPair) { + // ---- kPair MMA: one 128x256x128 k block per TMEM stage (4 x K=32 cta_group::1 f8f6f4), local commits ---- + int kb0, tt, sj, kcnt; + st_decode(st_unit(work_tile_info), kb0, kcnt, tt, sj); + static_assert(sizeof(shared_storage.tensors.mainloop.smem_A) == 16384 * DispatchPolicy::Stages && + sizeof(shared_storage.tensors.mainloop.smem_B) == 32768 * DispatchPolicy::Stages, + "kPair MMA assumes 128 x 128 B (A) / 256 x 128 B (B) SW128 K-major stages"); + static_assert(AccumulatorPipelineStageCount == 2, "kPair: 2 TMEM accumulator stages"); + const uint32_t sa0 = (uint32_t)__cvta_generic_to_shared(shared_storage.tensors.mainloop.smem_A.begin()); + const uint32_t sb0 = (uint32_t)__cvta_generic_to_shared(shared_storage.tensors.mainloop.smem_B.begin()); + const uint32_t dacc0 = get<0>(CollectiveMainloop::slice_accumulator(tmem_storage, 0)).data().get(); + const uint32_t dstride = get<0>(CollectiveMainloop::slice_accumulator(tmem_storage, 1)).data().get() - dacc0; + // idesc kind::f8f6f4: D f32 (bit 4), A/B e4m3 K-major, N>>3 @17, M>>4 @24 + constexpr uint32_t idesc = (1u << 4) | ((256u >> 3) << 17) | ((128u >> 4) << 24); + auto sw128 = [](uint32_t a) -> uint64_t { // SW128 K-major smem descriptor, SBO 1024 B, sm100 version + return (uint64_t)((a >> 4) & 0x3FFF) | ((uint64_t)1 << 16) | ((uint64_t)(1024 >> 4) << 32) | + ((uint64_t)1 << 46) | ((uint64_t)2 << 61); + }; + constexpr uint32_t kDescHi = (uint32_t)(1024 >> 4) | (1u << 14) | (2u << 29); + const uint32_t loA0 = ((sa0 >> 4) & 0x3FFFu) | (1u << 16); + const uint32_t loB0 = ((sb0 >> 4) & 0x3FFFu) | (1u << 16); + (void)sw128; + const bool mlane = cute::elect_one_sync(); // issuing lane, chosen once (warp converged) + CUTLASS_PRAGMA_NO_UNROLL + for (int kt = 0; kt < kcnt; ++kt) { + mainloop_ab_pipeline.consumer_wait(mainloop_ab_pipe_consumer_state); + const int ai = accumulator_pipe_producer_state.index(); + shared_storage.pair_bar[2 + ai].wait(accumulator_pipe_producer_state.phase()); // stage drained + asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); + const uint32_t rs = (uint32_t)mainloop_ab_pipe_consumer_state.index(); + if (mlane) { + const uint32_t d = dacc0 + (uint32_t)ai * dstride; + // lean issue: lo words from the stage index (A stage 16 KB -> +1024, B stage 32 KB -> +2048), constant + // hi word, 4 K=32 sub-descriptors via immediate adds (+32 B -> +2) and 4 tcgen05.mma in one asm block + const uint32_t loA = loA0 + rs * 1024u, loB = loB0 + rs * 2048u; + asm volatile( + "{\n\t.reg .b64 a0, a1, a2, a3, b0, b1, b2, b3;\n\t.reg .b32 la, lb;\n\t.reg .pred p0, p1;\n\t" + "setp.ne.b32 p0, %5, 0;\n\tsetp.eq.b32 p1, %5, 0;\n\t" + "mov.b64 a0, {%1, %3};\n\tmov.b64 b0, {%2, %3};\n\t" + "add.u32 la, %1, 2;\n\tadd.u32 lb, %2, 2;\n\tmov.b64 a1, {la, %3};\n\tmov.b64 b1, {lb, %3};\n\t" + "add.u32 la, %1, 4;\n\tadd.u32 lb, %2, 4;\n\tmov.b64 a2, {la, %3};\n\tmov.b64 b2, {lb, %3};\n\t" + "add.u32 la, %1, 6;\n\tadd.u32 lb, %2, 6;\n\tmov.b64 a3, {la, %3};\n\tmov.b64 b3, {lb, %3};\n\t" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], a0, b0, %4, p0;\n\t" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], a1, b1, %4, p1;\n\t" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], a2, b2, %4, p1;\n\t" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], a3, b3, %4, p1;\n\t}" + ::"r"(d), "r"(loA), "r"(loB), "r"(kDescHi), "r"(idesc), "r"(0u) + : "memory"); + // A/B stage free once these MMAs completed; TMEM stage ai holds the k block's partial + const uint32_t eb = (uint32_t)__cvta_generic_to_shared( + &shared_storage.pipelines.mainloop.pipeline_ab.empty_barrier_[rs]); + const uint32_t fb = (uint32_t)__cvta_generic_to_shared(&shared_storage.pair_bar[ai]); + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(eb) : "memory"); + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(fb) : "memory"); + } + __syncwarp(); + ++mainloop_ab_pipe_consumer_state; + ++accumulator_pipe_producer_state; + } + // tail: both TMEM stages drained by the promotion warps before the TMEM is freed + for (int i = 0; i < 2; ++i) { + shared_storage.pair_bar[2 + accumulator_pipe_producer_state.index()].wait(accumulator_pipe_producer_state.phase()); + ++accumulator_pipe_producer_state; + } + } else { + [[maybe_unused]] uint32_t mma_u = 0; // kInfoRelay: this CTA's unit ordinal + do { + auto k_tile_count = TileScheduler::get_work_k_tile_count(work_tile_info, problem_shape_MNKL, CtaShape_MNK{}); + typename TileScheduler::WorkTileInfo next_work_tile_info; + auto mma_fetch = [&]() { + if constexpr (kSfInfo) { bool inc_; sfi_read(mma_u, next_work_tile_info, inc_); } + else { + auto [nw, inc] = scheduler.fetch_next_work(work_tile_info, clc_pipeline, clc_pipe_consumer_state); + if (inc) ++clc_pipe_consumer_state; + next_work_tile_info = nw; + } + }; + auto relay_nm = [&]() { + if constexpr (kInfoRelayNM) { // relay to the promotion warps (they wait at their unit top / kLateNM: end) + const uint32_t sl = mma_u & 1u; + shared_storage.nxt_empty[sl].wait(((mma_u >> 1) & 1u) ^ 1u); + if (cute::elect_one_sync()) { + shared_storage.nxt_info[sl] = next_work_tile_info; + shared_storage.nxt_full[sl].arrive(); + } + __syncwarp(); + ++mma_u; + } + }; + if constexpr (!kJit && !kLateNM) { mma_fetch(); relay_nm(); } + [[maybe_unused]] int st_tt = 0, st_sj = -1; + [[maybe_unused]] bool mma_half = false; + if constexpr (kMerged) { + bool dn; int mb; + cta_coord_mnkl = mg_decode(work_tile_info.M_idx / kClCtas, k_tile_count, dn, mb); + mma_half = mg_tail(mb); + } else if constexpr (kStatic) { + int kb0; + cta_coord_mnkl = st_decode(st_unit(work_tile_info), kb0, k_tile_count, st_tt, st_sj); + } + if constexpr (kHalves) { + // ---- split-N MMA: per 128-K block, two 256x128x128 cta_group::2 MMAs (4 x K=32 each) into + // consecutive 128-col TMEM slots. Local B rows [0,64) (+ peer's) = half 0, rows [64,128) = half 1; + // fused layout: half h = gate h-cols [64h,+64) (slot cols 0..63) + up h-cols [64h,+64) (slot cols 64..127). + // Each half is committed separately so promotion of half 0 overlaps the MMA of half 1. + if (is_mma_leader_cta) { + static_assert(sizeof(shared_storage.tensors.mainloop.smem_A) == 16384 * DispatchPolicy::Stages && + sizeof(shared_storage.tensors.mainloop.smem_B) == 16384 * DispatchPolicy::Stages, + "split-N MMA assumes 128 x 128 B SW128 K-major A/B stages per CTA"); + const uint32_t sa0 = (uint32_t)__cvta_generic_to_shared(shared_storage.tensors.mainloop.smem_A.begin()); + const uint32_t sb0 = (uint32_t)__cvta_generic_to_shared(shared_storage.tensors.mainloop.smem_B.begin()); + const uint32_t dacc = get<0>(CollectiveMainloop::slice_accumulator(tmem_storage, 0)).data().get(); + // idesc kind::f8f6f4: D f32 (bit 4), A/B e4m3 K-major, N>>3 @17, M>>4 @24 + constexpr uint32_t idesc = (1u << 4) | ((128u >> 3) << 17) | ((256u >> 4) << 24); + auto sw128 = [](uint32_t a) -> uint64_t { // SW128 K-major smem descriptor, SBO 1024 B, sm100 version + return (uint64_t)((a >> 4) & 0x3FFF) | ((uint64_t)1 << 16) | ((uint64_t)(1024 >> 4) << 32) | + ((uint64_t)1 << 46) | ((uint64_t)2 << 61); + }; + const bool wide = kHT_MMA && mma_half; + constexpr uint32_t idesc_w = (1u << 4) | ((256u >> 3) << 17) | ((128u >> 4) << 24); + const uint32_t idesc_r = wide ? idesc_w : idesc; + const uint32_t bstep = wide ? 0u : 8192u; + const int n_stage = wide ? 2 * (int)k_tile_count : (int)k_tile_count; + if constexpr (!kHT_MMA) { + // ---- lean MMA issue loop (no wide units in this instantiation) ---- + // Descriptor = {lo, hi}: lo = start-address field (addr >> 4, 14 bits) | LBO 1 << 16, hi = SBO (1024 >> 4) + // | version bit 46 | SW128 layout type 2 << 61 (constant). A stage = 16 KB -> lo + 1024 per stage, B N-half + // 1 = +8 KB -> lo + 512, K=32 step = +32 B -> lo + 2 (no carry out of the 14-bit field: smem < 256 KB). + // The per-stage lo words come from the pipeline index with ONE multiply-add; the 4 sub-descriptors of a + // half are formed inside one asm block (immediate adds) and the 4 tcgen05.mma issue back-to-back. + constexpr uint32_t kDescHi = (uint32_t)(1024 >> 4) | (1u << 14) | (2u << 29); + const uint32_t loA0 = ((sa0 >> 4) & 0x3FFFu) | (1u << 16); + const uint32_t loB0 = ((sb0 >> 4) & 0x3FFFu) | (1u << 16); + const bool mlane = cute::elect_one_sync(); // issuing lane (same lane every half, warp converged) + // MMA loop trim: barrier addresses hoisted (32-bit smem bases of the A/B full / empty rings and the + // 4-slot TMEM full / empty rings, + 8 B per stage), raw try_wait.parity waits with the pipeline-state + // phases (== ClusterBarrier::wait), and the 3 per-kb commits (2 TMEM-full, 1 A/B-empty) issued by the + // MMA lane itself as tcgen05.commit.cta_group::2 multicast to both CTAs of the pair (mask 0b11 == the + // CUTLASS 2x1 umma_arrive_multicast_2x1SM masks, which elect the same single lane). Same MMA sequence. + const uint32_t ab_full0 = (uint32_t)__cvta_generic_to_shared(&shared_storage.pipelines.mainloop.pipeline_ab.full_barrier_[0]); + const uint32_t ab_empty0 = (uint32_t)__cvta_generic_to_shared(&shared_storage.pipelines.mainloop.pipeline_ab.empty_barrier_[0]); + const uint32_t ac_full0 = (uint32_t)__cvta_generic_to_shared(&acc_pipe_storage.full_barrier_[0]); + const uint32_t ac_empty0 = (uint32_t)__cvta_generic_to_shared(&acc_pipe_storage.empty_barrier_[0]); + auto bwait = [](uint32_t a, uint32_t ph) { + asm volatile("{\n\t.reg .pred p;\n\tMW_%=:\n\t" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n\t" + "@!p bra MW_%=;\n\t}" ::"r"(a), "r"(ph) : "memory"); + }; + auto mcommit = [](uint32_t a) { + asm volatile("tcgen05.commit.cta_group::2.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%0], %1;" + ::"r"(a), "h"((uint16_t)3) : "memory"); + }; + // MMA-loop register trim: the A/B consumer and TMEM producer pipeline positions are kept as plain + // loop-carried registers (stage index, phase; TMEM: even slot ai0 in {0, 2} + phase) with branch-free + // wraps instead of PipelineState objects (index / phase / count update per ++), written back after the + // loop. Same barrier / MMA / commit sequence -> bit-identical. + constexpr uint32_t kABSt = (uint32_t)DispatchPolicy::Stages; + uint32_t rs = (uint32_t)mainloop_ab_pipe_consumer_state.index(); + uint32_t abph = (uint32_t)mainloop_ab_pipe_consumer_state.phase(); + uint32_t ai0 = (uint32_t)accumulator_pipe_producer_state.index(); + uint32_t aph = (uint32_t)accumulator_pipe_producer_state.phase(); + const uint32_t ab_cnt0 = (uint32_t)mainloop_ab_pipe_consumer_state.count(); + const uint32_t ac_cnt0 = (uint32_t)accumulator_pipe_producer_state.count(); + CUTLASS_PRAGMA_NO_UNROLL + for (int kt = 0; kt < n_stage; ++kt) { + bwait(ab_full0 + rs * 8u, abph); + asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); + const uint32_t loA = loA0 + rs * 1024u, loB = loB0 + rs * 1024u; + // the k block's two TMEM slots are ai0 (even), ai0 + 1 of the same ring pass (4-slot ring, 2 slots + // per kb) + CUTLASS_PRAGMA_UNROLL + for (int h = 0; h < 2; ++h) { + const uint32_t ai = ai0 + (uint32_t)h; + bwait(ac_empty0 + ai * 8u, aph); + asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); + if (mlane) { + asm volatile( + "{\n\t.reg .b64 a0, a1, a2, a3, b0, b1, b2, b3;\n\t.reg .b32 la, lb;\n\t.reg .pred p0, p1;\n\t" + "setp.ne.b32 p0, %5, 0;\n\tsetp.eq.b32 p1, %5, 0;\n\t" + "mov.b64 a0, {%1, %3};\n\tmov.b64 b0, {%2, %3};\n\t" + "add.u32 la, %1, 2;\n\tadd.u32 lb, %2, 2;\n\tmov.b64 a1, {la, %3};\n\tmov.b64 b1, {lb, %3};\n\t" + "add.u32 la, %1, 4;\n\tadd.u32 lb, %2, 4;\n\tmov.b64 a2, {la, %3};\n\tmov.b64 b2, {lb, %3};\n\t" + "add.u32 la, %1, 6;\n\tadd.u32 lb, %2, 6;\n\tmov.b64 a3, {la, %3};\n\tmov.b64 b3, {lb, %3};\n\t" + "tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], a0, b0, %4, p0;\n\t" + "tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], a1, b1, %4, p1;\n\t" + "tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], a2, b2, %4, p1;\n\t" + "tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], a3, b3, %4, p1;\n\t}" + ::"r"(dacc + ai * 128u), "r"(loA), "r"(loB + (uint32_t)h * 512u), "r"(kDescHi), "r"(idesc), "r"(0u) + : "memory"); + mcommit(ac_full0 + ai * 8u); // TMEM slot ai holds this half's partial (both CTAs) + if (h == 1) mcommit(ab_empty0 + rs * 8u); // A/B stage free once these MMAs completed + } + __syncwarp(); + } + // TMEM ring: 4 slots, 2 per kb -> ai0 alternates 0 / 2, phase flips after slot 3 + ai0 ^= 2u; + if (ai0 == 0u) aph ^= 1u; + if (++rs == kABSt) { rs = 0u; abph ^= 1u; } + } + mainloop_ab_pipe_consumer_state = MainloopABPipelineState((int)rs, abph, ab_cnt0 + (uint32_t)n_stage); + accumulator_pipe_producer_state = AccumulatorPipelineState((int)ai0, aph, ac_cnt0 + 2u * (uint32_t)n_stage); + } else + { + CUTLASS_PRAGMA_NO_UNROLL + for (int kt = 0; kt < n_stage; ++kt) { + mainloop_ab_pipeline.consumer_wait(mainloop_ab_pipe_consumer_state); + asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); + const uint32_t rs = (uint32_t)mainloop_ab_pipe_consumer_state.index(); + CUTLASS_PRAGMA_UNROLL + for (int h = 0; h < 2; ++h) { + if (h == 1 && wide) break; // wide unit: one slot per A/B stage + accumulator_pipeline.producer_acquire(accumulator_pipe_producer_state); + asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); + const uint32_t d = dacc + (uint32_t)accumulator_pipe_producer_state.index() * 128u; + if (cute::elect_one_sync()) { + CUTLASS_PRAGMA_UNROLL + for (int k = 0; k < 4; ++k) { + const uint64_t ad = sw128(sa0 + rs * 16384u + k * 32); + const uint64_t bd = sw128(sb0 + rs * 16384u + h * bstep + k * 32); + asm volatile("{\n\t.reg .pred p;\n\tsetp.ne.b32 p, %3, 0;\n\t" + "tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], %1, %2, %4, p;\n\t}" ::"r"(d), "l"(ad), + "l"(bd), "r"((uint32_t)k), "r"(idesc_r) : "memory"); + } + } + __syncwarp(); + accumulator_pipeline.producer_commit(accumulator_pipe_producer_state); + ++accumulator_pipe_producer_state; + } + mainloop_ab_pipeline.consumer_release(mainloop_ab_pipe_consumer_state); + ++mainloop_ab_pipe_consumer_state; + } + } // generic loop + } + } else + if constexpr (kLeanNM) { + // ---- lean MMA issue loop for the NON-merged 2SM 256x256 kernels: replaces the + // CUTLASS collective mma with the same pipeline order (A/B full wait -> TMEM stage acquire -> 4 x K=32 + // tcgen05.mma.cta_group::2 M=256 N=256 into stage idx -> commit stage (multicast to both CTAs) -> release + // A/B stage). Descriptor = {lo, hi}: lo = (addr >> 4) | LBO 1 << 16 (A / B stage 16 KB per CTA -> +1024), + // K=32 step +32 B -> +2 (no carry: smem < 256 KB), hi = SBO 1024 B | version | SW128 (constant). + if (is_mma_leader_cta) { + static_assert(sizeof(shared_storage.tensors.mainloop.smem_A) == 16384 * DispatchPolicy::Stages && + sizeof(shared_storage.tensors.mainloop.smem_B) == 16384 * DispatchPolicy::Stages, + "lean 2SM MMA assumes 128 x 128 B SW128 K-major A/B stages per CTA"); + static_assert(AccumulatorPipelineStageCount >= 2, "lean 2SM MMA: >= 2 TMEM accumulator stages"); + const uint32_t sa0 = (uint32_t)__cvta_generic_to_shared(shared_storage.tensors.mainloop.smem_A.begin()); + const uint32_t sb0 = (uint32_t)__cvta_generic_to_shared(shared_storage.tensors.mainloop.smem_B.begin()); + const uint32_t dacc0 = get<0>(CollectiveMainloop::slice_accumulator(tmem_storage, 0)).data().get(); + const uint32_t dstride = get<0>(CollectiveMainloop::slice_accumulator(tmem_storage, 1)).data().get() - dacc0; + constexpr uint32_t idesc = (1u << 4) | ((256u >> 3) << 17) | ((256u >> 4) << 24); + constexpr uint32_t kDescHi = (uint32_t)(1024 >> 4) | (1u << 14) | (2u << 29); + const uint32_t loA0 = ((sa0 >> 4) & 0x3FFFu) | (1u << 16); + const uint32_t loB0 = ((sb0 >> 4) & 0x3FFFu) | (1u << 16); + const bool mlane = cute::elect_one_sync(); + // MMA loop trim (port of the MO trim): 32-bit A/B full / empty + TMEM full / empty barrier bases + // (+8 B per stage), raw try_wait.parity with the pipeline-state phases (== ClusterBarrier::wait), commits + // issued by the MMA lane itself (2SM: cta_group::2 multicast mask 0b11 == the CUTLASS 2x1 umma_arrive masks; + // 1SM: cta_group::1 local arrive == umma_arrive). Same MMA sequence. + const uint32_t ab_full0 = (uint32_t)__cvta_generic_to_shared(&shared_storage.pipelines.mainloop.pipeline_ab.full_barrier_[0]); + const uint32_t ab_empty0 = (uint32_t)__cvta_generic_to_shared(&shared_storage.pipelines.mainloop.pipeline_ab.empty_barrier_[0]); + const uint32_t ac_full0 = (uint32_t)__cvta_generic_to_shared(&acc_pipe_storage.full_barrier_[0]); + const uint32_t ac_empty0 = (uint32_t)__cvta_generic_to_shared(&acc_pipe_storage.empty_barrier_[0]); + auto bwait = [](uint32_t a, uint32_t ph) { + asm volatile("{\n\t.reg .pred p;\n\tLW_%=:\n\t" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n\t" + "@!p bra LW_%=;\n\t}" ::"r"(a), "r"(ph) : "memory"); + }; + auto mcommit = [](uint32_t a) { + if constexpr (kTwoSm) + asm volatile("tcgen05.commit.cta_group::2.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%0], %1;" + ::"r"(a), "h"((uint16_t)3) : "memory"); + else + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(a) : "memory"); + }; + CUTLASS_PRAGMA_NO_UNROLL + for (int kt = 0; kt < (int)k_tile_count; ++kt) { + bwait(ab_full0 + (uint32_t)mainloop_ab_pipe_consumer_state.index() * 8u, mainloop_ab_pipe_consumer_state.phase()); + bwait(ac_empty0 + (uint32_t)accumulator_pipe_producer_state.index() * 8u, accumulator_pipe_producer_state.phase()); + asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); + const uint32_t rs = (uint32_t)mainloop_ab_pipe_consumer_state.index(); + const uint32_t loA = loA0 + rs * 1024u, loB = loB0 + rs * 1024u; + const uint32_t d = dacc0 + (uint32_t)accumulator_pipe_producer_state.index() * dstride; + if (mlane) { + asm volatile( + "{\n\t.reg .b64 a0, a1, a2, a3, b0, b1, b2, b3;\n\t.reg .b32 la, lb;\n\t.reg .pred p0, p1;\n\t" + "setp.ne.b32 p0, %5, 0;\n\tsetp.eq.b32 p1, %5, 0;\n\t" + "mov.b64 a0, {%1, %3};\n\tmov.b64 b0, {%2, %3};\n\t" + "add.u32 la, %1, 2;\n\tadd.u32 lb, %2, 2;\n\tmov.b64 a1, {la, %3};\n\tmov.b64 b1, {lb, %3};\n\t" + "add.u32 la, %1, 4;\n\tadd.u32 lb, %2, 4;\n\tmov.b64 a2, {la, %3};\n\tmov.b64 b2, {lb, %3};\n\t" + "add.u32 la, %1, 6;\n\tadd.u32 lb, %2, 6;\n\tmov.b64 a3, {la, %3};\n\tmov.b64 b3, {lb, %3};\n\t" + "tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], a0, b0, %4, p0;\n\t" + "tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], a1, b1, %4, p1;\n\t" + "tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], a2, b2, %4, p1;\n\t" + "tcgen05.mma.cta_group::2.kind::f8f6f4 [%0], a3, b3, %4, p1;\n\t}" + ::"r"(d), "r"(loA), "r"(loB), "r"(kDescHi), "r"(idesc), "r"(0u) + : "memory"); + mcommit(ac_full0 + (uint32_t)accumulator_pipe_producer_state.index() * 8u); // TMEM stage full (both CTAs) + mcommit(ab_empty0 + rs * 8u); // A/B stage free once these MMAs completed + } + __syncwarp(); + ++accumulator_pipe_producer_state; + ++mainloop_ab_pipe_consumer_state; + } + } + } else + if constexpr (kLean224) { + if (is_mma_leader_cta) { + constexpr uint32_t kAStage = (uint32_t)(sizeof(shared_storage.tensors.mainloop.smem_A) / DispatchPolicy::Stages); + constexpr uint32_t kBStage = (uint32_t)(sizeof(shared_storage.tensors.mainloop.smem_B) / DispatchPolicy::Stages); + static_assert(kAStage == 16384 && kBStage == (kTwoSm ? (uint32_t)kCtaN / 2u : (uint32_t)kCtaN) * 128u && + sizeof(shared_storage.tensors.mainloop.smem_B) == kBStage * DispatchPolicy::Stages, + "lean N224 MMA assumes SW128 K-major 128 B rows, stage-contiguous A/B"); + static_assert(AccumulatorPipelineStageCount >= 2, "lean N224 MMA: >= 2 TMEM accumulator stages"); + const uint32_t sa0 = (uint32_t)__cvta_generic_to_shared(shared_storage.tensors.mainloop.smem_A.begin()); + const uint32_t sb0 = (uint32_t)__cvta_generic_to_shared(shared_storage.tensors.mainloop.smem_B.begin()); + const uint32_t dacc0 = get<0>(CollectiveMainloop::slice_accumulator(tmem_storage, 0)).data().get(); + const uint32_t dstride = get<0>(CollectiveMainloop::slice_accumulator(tmem_storage, 1)).data().get() - dacc0; + constexpr uint32_t idesc = (1u << 4) | (((uint32_t)kCtaN >> 3) << 17) | (((kTwoSm ? 256u : 128u) >> 4) << 24); + constexpr uint32_t kDescHi = (uint32_t)(1024 >> 4) | (1u << 14) | (2u << 29); + const uint32_t loA0 = ((sa0 >> 4) & 0x3FFFu) | (1u << 16); + const uint32_t loB0 = ((sb0 >> 4) & 0x3FFFu) | (1u << 16); + const bool mlane = cute::elect_one_sync(); + // MMA loop trim (port of the MO trim): 32-bit A/B full / empty + TMEM full / empty barrier bases + // (+8 B per stage), raw try_wait.parity with the pipeline-state phases (== ClusterBarrier::wait), commits + // issued by the MMA lane itself (2SM: cta_group::2 multicast mask 0b11 == the CUTLASS 2x1 umma_arrive masks; + // 1SM: cta_group::1 local arrive == umma_arrive). Same MMA sequence. + const uint32_t ab_full0 = (uint32_t)__cvta_generic_to_shared(&shared_storage.pipelines.mainloop.pipeline_ab.full_barrier_[0]); + const uint32_t ab_empty0 = (uint32_t)__cvta_generic_to_shared(&shared_storage.pipelines.mainloop.pipeline_ab.empty_barrier_[0]); + const uint32_t ac_full0 = (uint32_t)__cvta_generic_to_shared(&acc_pipe_storage.full_barrier_[0]); + const uint32_t ac_empty0 = (uint32_t)__cvta_generic_to_shared(&acc_pipe_storage.empty_barrier_[0]); + auto bwait = [](uint32_t a, uint32_t ph) { + asm volatile("{\n\t.reg .pred p;\n\tLW_%=:\n\t" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n\t" + "@!p bra LW_%=;\n\t}" ::"r"(a), "r"(ph) : "memory"); + }; + auto mcommit = [](uint32_t a) { + if constexpr (kTwoSm) + asm volatile("tcgen05.commit.cta_group::2.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%0], %1;" + ::"r"(a), "h"((uint16_t)3) : "memory"); + else + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(a) : "memory"); + }; + CUTLASS_PRAGMA_NO_UNROLL + for (int kt = 0; kt < (int)k_tile_count; ++kt) { + bwait(ab_full0 + (uint32_t)mainloop_ab_pipe_consumer_state.index() * 8u, mainloop_ab_pipe_consumer_state.phase()); + bwait(ac_empty0 + (uint32_t)accumulator_pipe_producer_state.index() * 8u, accumulator_pipe_producer_state.phase()); + asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); + const uint32_t rs = (uint32_t)mainloop_ab_pipe_consumer_state.index(); + const uint32_t loA = loA0 + rs * (kAStage >> 4), loB = loB0 + rs * (kBStage >> 4); + const uint32_t d = dacc0 + (uint32_t)accumulator_pipe_producer_state.index() * dstride; + if (mlane) { +#define SE_L224_MMA(CG) \ + asm volatile( \ + "{\n\t.reg .b64 a0, a1, a2, a3, b0, b1, b2, b3;\n\t.reg .b32 la, lb;\n\t.reg .pred p0, p1;\n\t" \ + "setp.ne.b32 p0, %5, 0;\n\tsetp.eq.b32 p1, %5, 0;\n\t" \ + "mov.b64 a0, {%1, %3};\n\tmov.b64 b0, {%2, %3};\n\t" \ + "add.u32 la, %1, 2;\n\tadd.u32 lb, %2, 2;\n\tmov.b64 a1, {la, %3};\n\tmov.b64 b1, {lb, %3};\n\t" \ + "add.u32 la, %1, 4;\n\tadd.u32 lb, %2, 4;\n\tmov.b64 a2, {la, %3};\n\tmov.b64 b2, {lb, %3};\n\t" \ + "add.u32 la, %1, 6;\n\tadd.u32 lb, %2, 6;\n\tmov.b64 a3, {la, %3};\n\tmov.b64 b3, {lb, %3};\n\t" \ + "tcgen05.mma.cta_group::" CG ".kind::f8f6f4 [%0], a0, b0, %4, p0;\n\t" \ + "tcgen05.mma.cta_group::" CG ".kind::f8f6f4 [%0], a1, b1, %4, p1;\n\t" \ + "tcgen05.mma.cta_group::" CG ".kind::f8f6f4 [%0], a2, b2, %4, p1;\n\t" \ + "tcgen05.mma.cta_group::" CG ".kind::f8f6f4 [%0], a3, b3, %4, p1;\n\t}" \ + ::"r"(d), "r"(loA), "r"(loB), "r"(kDescHi), "r"(idesc), "r"(0u) \ + : "memory") + if constexpr (kTwoSm) SE_L224_MMA("2"); + else SE_L224_MMA("1"); +#undef SE_L224_MMA + mcommit(ac_full0 + (uint32_t)accumulator_pipe_producer_state.index() * 8u); // TMEM stage full (both CTAs) + mcommit(ab_empty0 + rs * 8u); // A/B stage free once these MMAs completed + } + __syncwarp(); + ++accumulator_pipe_producer_state; + ++mainloop_ab_pipe_consumer_state; + } + } + } else + if (is_mma_leader_cta) { + auto [ab_st, acc_st] = collective_mainloop.mma( + cute::make_tuple(mainloop_ab_pipeline, accumulator_pipeline), + cute::make_tuple(mainloop_ab_pipe_consumer_state, accumulator_pipe_producer_state), tmem_storage, + mma_inputs, cta_coord_mnkl, k_tile_count); + mainloop_ab_pipe_consumer_state = ab_st; + accumulator_pipe_producer_state = acc_st; + } + if constexpr (kJit) mma_fetch(); // kJit: after this unit's MMAs were issued + if constexpr (kLateNM) { mma_fetch(); relay_nm(); } // kLateNM: CLC round trip off the first-MMA path + if constexpr (kInfoRelay) { // hand the next work tile to the promotion warps (see kInfoRelay) + if (cute::elect_one_sync()) { + shared_storage.nxt_info[mma_u & 1u] = next_work_tile_info; + shared_storage.nxt_full[mma_u & 1u].arrive(); + } + __syncwarp(); + ++mma_u; + } + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + } while (work_tile_info.is_valid()); + } // !kPair + cutlass::arch::launch_dependent_grids(); + tmem_allocator.release_allocation_lock(); + if (!kPair && is_mma_leader_cta) accumulator_pipeline.producer_tail(accumulator_pipe_producer_state); + if constexpr (kTwoSm) { + // leader: wait for peer then signal; follower: signal then wait (same handshake as CUTLASS) + tmem_dealloc_barrier.arrive(mma_peer_cta_rank, !is_mma_leader_cta); + tmem_dealloc_barrier.wait(0); + tmem_dealloc_barrier.arrive(mma_peer_cta_rank, is_mma_leader_cta); + } + tmem_allocator.free(tmem_base_ptr, TmemAllocator::Sm100TmemCapacityColumns); + } else if (is_epi) { + // ---------------- 4 promotion warpgroups + direct bf16 epilogue ---------------- + cutlass::arch::warpgroup_reg_alloc(); + if constexpr (kLean224) reinit_work(); // initial tile computed per role (see reinit_work) + epilogue_throttle_barrier.wait(0); + tmem_allocation_result_barrier.arrive_and_wait(); + uint32_t tmem_base_ptr = shared_storage.tmem_base_ptr; + collective_mainloop.set_tmem_offsets(tmem_storage, tmem_base_ptr); + auto accum_inputs = collective_mainloop.accum_init(problem_shape_MNKL, shared_storage.tensors.mainloop); + Tensor sSFA = accum_inputs.sSFA; // (ScaleMsPerTile..., ScaleKsPerTile..., SF_PIPE) + Tensor sSFB = accum_inputs.sSFB; // (ScaleNsPerTile..., ScaleKsPerTile..., SF_PIPE) + + int wg = (warp_idx - 4) >> 2; // warpgroup 0..3 + // ping-pong: team = wg>>1 owns every other tile, wg&1 picks the 64-col half; else column quarter wg + const int team = kPingPong ? (wg >> 1) : 0; + int g = kPingPong ? (wg & 1) : wg; // column slice [kWgCols*g, +kWgCols) + int q = warp_idx & 3; // TMEM lane quarter accessible by this warp + int row_local = q * 32 + (int)(threadIdx.x & 31); + uint32_t lane_off = (uint32_t)(q * 32) << 16; + // TMEM base address (lane 0, col 0) of accumulator stage s = stage0 + s * stage_stride. Kept as two + // scalars (not a runtime-indexed array, which ptxas places on the stack -> an LDL per K block). + uint32_t stage0 = get<0>(CollectiveMainloop::slice_accumulator(tmem_storage, 0)).data().get(); + [[maybe_unused]] const uint32_t stage0_off = stage0 - tmem_base_ptr; // compile-time layout offset + // kLateFetch (staging-WG kernel, 104 regs): re-derive the per-thread constants at each tile start / after the k + // loop from a VOLATILE %tid.x (and the smem TMEM base) instead of keeping them live across the k loop, where + // ptxas spilled 8 of them (32 B local). Volatile asm cannot be hoisted, so these stay short-lived. + auto rederive = [&](bool with_tmem) { + uint32_t tid; + asm volatile("mov.u32 %0, %%tid.x;" : "=r"(tid)); + const int w = (int)(tid >> 5); + wg = (w - 4) >> 2; + g = kPingPong ? (wg & 1) : wg; + q = w & 3; + row_local = q * 32 + (int)(tid & 31); + lane_off = (uint32_t)(q * 32) << 16; + if (with_tmem) { + uint32_t b; + asm volatile("ld.shared.u32 %0, [%1];" : "=r"(b) + : "r"((uint32_t)__cvta_generic_to_shared(&shared_storage.tmem_base_ptr)) : "memory"); + stage0 = b + stage0_off; + } + }; + // kTmaQh (thread 128 only): consume every stg_free completion of the qh tiles handed to the publisher so far + [[maybe_unused]] auto stg_sync = [&]() { + int w = shared_storage.stg_waited; + const int n = shared_storage.pub_n; + while (w < n) { shared_storage.stg_free.wait((uint32_t)(w & 1)); ++w; } + shared_storage.stg_waited = w; + }; + uint32_t stage_stride = 0; + if constexpr (AccumulatorPipelineStageCount > 1) + stage_stride = kHalves ? 128u : get<0>(CollectiveMainloop::slice_accumulator(tmem_storage, 1)).data().get() - stage0; + + int tile_iter = 0; // persistent tile counter of this CTA (ping-pong team selection) + [[maybe_unused]] uint32_t stg_empty_phase = 1; // kMerged: parity to wait for "staging released" + [[maybe_unused]] int gsf_slot = 0; // kGsf scale ring position (same sequence as the producer) + [[maybe_unused]] uint32_t gsf_phase = 0; + [[maybe_unused]] uint32_t gsf_it = 0; // kLateFetch kernels: ring position as ONE counter (slot, parity) + do { + auto k_tile_count = TileScheduler::get_work_k_tile_count(work_tile_info, problem_shape_MNKL, CtaShape_MNK{}); + typename TileScheduler::WorkTileInfo next_work_tile_info; + auto fetch_next = [&]() { + if constexpr (kInfoRelayNM) { + // unit ordinal = tile_iter (fetched at the unit top, before the increment below) + const uint32_t u = (uint32_t)(kLateNM ? tile_iter - 1 : tile_iter); // kLateNM: read after ++tile_iter + shared_storage.nxt_full[u & 1u].wait((u >> 1) & 1u); + next_work_tile_info = shared_storage.nxt_info[u & 1u]; + __syncwarp(); + if ((threadIdx.x & 31) == 0) shared_storage.nxt_empty[u & 1u].arrive(); + } else + if constexpr (kInfoRelay) { + // unit ordinal of this CTA = tile_iter - 1 (incremented at every unit start below, same sequence as the MMA) + const uint32_t u = (uint32_t)(tile_iter - 1); + shared_storage.nxt_full[u & 1u].wait((u >> 1) & 1u); + next_work_tile_info = shared_storage.nxt_info[u & 1u]; + } else { + auto [nw, inc] = scheduler.fetch_next_work(work_tile_info, clc_pipeline, clc_pipe_consumer_state); + if (inc) ++clc_pipe_consumer_state; + next_work_tile_info = nw; + } + }; + if constexpr (!kLateFetch && !kPair && !kJit && !kLateNM) fetch_next(); + if constexpr (kLateFetch) rederive(true); + [[maybe_unused]] int st_tt = 0, st_sj = -1; + [[maybe_unused]] bool mg_dn = false; + [[maybe_unused]] int mg_mb = 0; + if constexpr (kMerged && kTailSplit) { + int kb0; + cta_coord_mnkl = mg_decode7(work_tile_info.M_idx / kClCtas, k_tile_count, mg_dn, mg_mb, kb0, st_tt, st_sj); + } else if constexpr (kMerged) { + cta_coord_mnkl = mg_decode(work_tile_info.M_idx / kClCtas, k_tile_count, mg_dn, mg_mb); + } else if constexpr (kStatic) { + int kb0; + cta_coord_mnkl = st_decode(st_unit(work_tile_info), kb0, k_tile_count, st_tt, st_sj); + } + + // fz: this unit runs the fused SwiGLU epilogue (gate/up column layout). kMerged down units use the plain + // layout: WG g owns contiguous cols [64g, +64) (one B scale block) and the TMA-store epilogue. + bool fz = kFuse && !(kMerged && mg_dn); + int col_local = fz ? g * 32 : g * kWgCols; // fused: gate cols [32g,+32), up cols +128 + if constexpr (kBal160) if (g == 3) col_local = 32; // kBal40: WG3 x32 piece at cols [32,64) + // kHalves: WG g reads N half g>>1 (slot = 2*kb + (g>>1)); fused: gate at slot col (g&1)*32, up at +64; + // plain: 64 contiguous slot cols (g&1)*64 = global cols (g&1)*128 + (g>>1)*64 of the 256-col tile + // wide half-block unit (hu): every WG reads 64 contiguous slot cols (g&1)*64 of slot 2kb + (g>>1) (= tile + // nt0 + (g>>1)); TMEM lane 32q + l = row (q&1)*32 + l of the CTA's 64 rows, tile col half q>>1 (fused: gate / + // up). Scale = ring float2 of this TMEM lane, .x / .y by g>>1 (see the scale warp). + [[maybe_unused]] const bool hu = kHT_PR && mg_tail(mg_mb); + const bool fzk = kHT_PR ? (fz && !hu) : fz; // fused TMEM column layout in the k loop + [[maybe_unused]] const bool selx = fzk || !(hu ? (g >> 1) : (g & 1)); + const uint32_t tbase = stage0 + lane_off + (uint32_t)(kHalves ? (fzk ? (g & 1) * 32 : (g & 1) * 64) : col_local); + + if (kPingPong && (tile_iter & 1) != team) { + // the other team's tile: skip its SF / TMEM stages (no wait, no release) so our ring states stay in + // step with the producers. Its stages are released by the other team; the producers can never lap + // a stage we still need because they must first see OUR release of it. + for (int kt = 0; kt < k_tile_count; ++kt) { + ++mainloop_sf_pipe_consumer_state; + ++accumulator_pipe_consumer_state; + } + ++tile_iter; + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + continue; + } + ++tile_iter; + // ping-pong team handoff (named barriers 14/15 alternating by tile parity, 256 arrive + 256 sync): before + // waiting on tile t's SF/TMEM stages, the owner of tile t waits until the owner of tile t-1 has passed its + // LAST stage wait. Without it a team that merely skipped the other team's stages can see a stale phase of + // the same parity on a stage (parity aliasing) and read/release the wrong k block. + if constexpr (kPingPong) { + if (tile_iter > 1) named_bar_sync(14 + ((tile_iter - 2) & 1), NumEpilogueThreads); + } + + // 32-bit shared addresses of this + // thread's A / B scale entries, hoisted per tile (stage = +stride); per kb: 3 LDS.32 + index MAD, same values + [[maybe_unused]] uint32_t sf_a0 = 0, sf_ast = 0, sf_b0 = 0, sf_bh = 0, sf_bst = 0, sf_bd = 0; + if constexpr (!kGsf) { + const int cb_hi = kBal160 ? 96 : (kBal224 && g == 3) ? 56 : kN224 ? (col_local + 32 < kCtaN ? col_local + 32 : kCtaN - 1) : (fz ? col_local + 128 : col_local); + const int cb_lo = kN224 ? (col_local < kCtaN ? col_local : kCtaN - 1) : col_local; // kN160 idle WG3: in-tile + sf_a0 = (uint32_t)__cvta_generic_to_shared((const void*)&sSFA(row_local, 0, 0)); + sf_ast = (uint32_t)__cvta_generic_to_shared((const void*)&sSFA(row_local, 0, 1)) - sf_a0; + sf_b0 = (uint32_t)__cvta_generic_to_shared((const void*)&sSFB(cb_lo, 0, 0)); + sf_bh = (uint32_t)__cvta_generic_to_shared((const void*)&sSFB(cb_hi, 0, 0)); + sf_bst = (uint32_t)__cvta_generic_to_shared((const void*)&sSFB(cb_lo, 0, 1)) - sf_b0; + // kBal224 WG3: B-scale groups 1, 3, 5 at sf_bh, sf_bh + sf_bd, sf_bh + 2 sf_bd (cols 56, 120, 184) + if constexpr (kBal224) + sf_bd = (uint32_t)__cvta_generic_to_shared((const void*)&sSFB(120, 0, 0)) - sf_bh; + } + float acc[kWgCols]; + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < kWgCols; ++i) acc[i] = 0.f; + + // MO kJit (112-reg promotion) k loop unrolled x2 (same per-kb ops, bit-identical); others not unrolled + // kEarlySplit (kCq kJit merged kernels): the k loop is versioned into phase 0 = this CTA's first kEarlyTma k + // blocks (k-block ordinal gsf_it < kEarlyTma: only the CTA's first unit; promotion waits on gsf_full itself, see + // kEarlyTma) and phase 1 = all other k blocks (no per-kb ordinal compare / branch in the steady-state loop). Same + // per-kb operation sequence -> bit-identical. + constexpr bool kEarlySplit = kSfRelay && kJit && kCq_ && SE_EARLY_SPLIT; + const int kpre = kEarlySplit ? (gsf_it < (uint32_t)kEarlyTma + ? ((int)(kEarlyTma - gsf_it) < (int)k_tile_count ? (int)(kEarlyTma - gsf_it) + : (int)k_tile_count) + : 0) + : 0; + // per-thread scale-ring addresses of {scale, scale_hi} (ring slot 0; + slot * 1 KB per k block): + // scale = .x iff (fz || !(g & 1)) (fused: gate block / plain: the WG's 128-col block), scale_hi = .y iff fused + [[maybe_unused]] uint32_t sc_lo = 0, sc_hi = 0; + if constexpr (kEarlySplit) { + const uint32_t rb = (uint32_t)__cvta_generic_to_shared(&shared_storage.gsf_c[0][0]) + (uint32_t)row_local * 8u; + const uint32_t olo = (fz || !(g & 1)) ? 0u : 4u; + sc_lo = rb + olo; + sc_hi = rb + (fzk ? 4u : olo); + } + CUTLASS_PRAGMA_UNROLL + for (int ph = kEarlySplit ? 0 : 1; ph < 2; ++ph) { +#pragma unroll (kPromoUnroll) + for (int kt = 0; kt < (ph ? (int)k_tile_count - kpre : kpre); ++kt) { // per-phase trip count (counter merges with gsf_it) + // per-(row, K block) combined scale sa[row] * sb[col block] + float scale, scale_hi; + [[maybe_unused]] float scale_x1 = 0.f, scale_x2 = 0.f; // kBal224 WG3: groups 3 / 5 + auto fetch_scale = [&]() { + if constexpr (kGsf) { + // pre-multiplied ring: one LDS.64 = {sa*sb[blk 2nt], sa*sb[blk 2nt+1]} for this row. fused: gate / up + // block; plain: the WG's 64 columns lie in block 2nt + (g >> 1). + if constexpr (kLateFetch) { gsf_slot = (int)(gsf_it & (kGsfStages - 1)); gsf_phase = (gsf_it >> kGsfLog) & 1u; } + constexpr bool kPW = kPairScale || kPairWait; // one ring wait per slot pair + if (!kSfRelay && (!kPW || !(gsf_slot & 1))) shared_storage.gsf_full[kPW ? (gsf_slot | 1) : gsf_slot].wait(gsf_phase); + // kEarlyTma: the A/B warp did not wait on the scale ring for the CTA's first kEarlyTma k blocks + // (ring pass 0, slot = ordinal) -> wait here for those only + if constexpr (kSfRelay && kJit) { + if (kEarlySplit ? ph == 0 : gsf_it < (uint32_t)kEarlyTma) shared_storage.gsf_full[gsf_it].wait(0u); + } + // kEarlyNM (non-merged: ring position = gsf_slot / gsf_phase): wait for the scales in pass-0 parity slots + // < kEarlyTma (exact for the CTA's first kEarlyTma k blocks; at later ordinals with the same slot / parity it is + // the slot's correct-phase wait, already complete since TMEM-full implies the A/B warp waited) + if constexpr (kSfRelay && !kJit && kEarlyNM > 0) + if (gsf_phase == 0u && gsf_slot < kEarlyNM) shared_storage.gsf_full[gsf_slot].wait(0u); + // kSfRelay + kHalves: ring slot derived from the k-block ordinal gsf_it (no separate slot / phase + // counters with wrap logic in the promotion k loop; gsf_phase is unused there) + constexpr bool kSlotIt = kSfRelay && kHalves && !kLateFetch; + const uint32_t sl_rd = kSlotIt ? (gsf_it & (uint32_t)(kGsfStages - 1)) : (uint32_t)gsf_slot; + if constexpr (kEarlySplit) { + // the per-unit pick of the scale pair is folded into two per-thread LDS.32 addresses (sc_lo / sc_hi, + // set at the unit top): same values as LDS.64 + the 2 FSEL selects below + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(scale) : "r"(sc_lo + sl_rd * (uint32_t)sizeof(shared_storage.gsf_c[0])) : "memory"); + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(scale_hi) : "r"(sc_hi + sl_rd * (uint32_t)sizeof(shared_storage.gsf_c[0])) : "memory"); + } else { + float2 c2; // 32-bit shared address (a generic 64-bit pointer costs registers here) + asm volatile("ld.shared.v2.f32 {%0, %1}, [%2];" : "=f"(c2.x), "=f"(c2.y) + : "r"((uint32_t)__cvta_generic_to_shared(&shared_storage.gsf_c[0][0]) + + sl_rd * (uint32_t)sizeof(shared_storage.gsf_c[0]) + + (uint32_t)row_local * 8u) + : "memory"); + scale = (kHT_PR ? selx : (fz || (kHalves ? !(g & 1) : g < 2))) ? c2.x : c2.y; + scale_hi = fzk ? c2.y : scale; + } + if (!kSfRelay && (!kPairScale || (gsf_slot & 1))) + shared_storage.gsf_empty[gsf_slot].arrive(); // every promotion thread arrives (as the CUTLASS SF pipe) + if constexpr (kLateFetch || kHalves) ++gsf_it; // kHalves: also the TMEM slot sequence (below) + if constexpr (!kLateFetch && !kSlotIt) if (++gsf_slot == kGsfStages) { gsf_slot = 0; gsf_phase ^= 1; } + } else { + mainloop_sf_pipeline.consumer_wait(mainloop_sf_pipe_consumer_state); + const int sidx = mainloop_sf_pipe_consumer_state.index(); + float sa, sbl, sbh; + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(sa) : "r"(sf_a0 + (uint32_t)sidx * sf_ast) : "memory"); + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(sbl) : "r"(sf_b0 + (uint32_t)sidx * sf_bst) : "memory"); + scale = sa * sbl; + // fused: chunks 2,3 are the up block (cols 128+) with its own B scale; kN224: next 32-col scale group + if (kN224 || fz) { + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(sbh) : "r"(sf_bh + (uint32_t)sidx * sf_bst) : "memory"); + scale_hi = sa * sbh; + if constexpr (kBal224) if (g == 3) { + float sb3, sb5; + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(sb3) : "r"(sf_bh + sf_bd + (uint32_t)sidx * sf_bst) : "memory"); + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(sb5) : "r"(sf_bh + 2u * sf_bd + (uint32_t)sidx * sf_bst) : "memory"); + scale_x1 = sa * sb3; + scale_x2 = sa * sb5; + } + } else scale_hi = scale; + if constexpr (kWarpRel) { // one arrival per warp (scale LDS of all lanes ordered by __syncwarp) + __syncwarp(); + if ((threadIdx.x & 31) == 0) mainloop_sf_pipeline.consumer_release(mainloop_sf_pipe_consumer_state); + } else + mainloop_sf_pipeline.consumer_release(mainloop_sf_pipe_consumer_state); + ++mainloop_sf_pipe_consumer_state; + } + }; + if constexpr (!kLateScale && !kSfRelay) fetch_scale(); + + // TMEM partial of this K block: two x32 loads, one wait, then release the stage to the MMA warp + // kHalves: k block ordinal it (= gsf_it - 1, same per-CTA sequence as the MMA warp) uses slots 2it, 2it+1 + // of the 4-slot ring; this WG's slot = 2it + (g >> 1) -> index ((it & 1) << 1) | (g >> 1), phase (it >> 1) & 1. + // Derived from the scale-ring counter: no extra pipeline state live across the 104-register k loop. + [[maybe_unused]] AccumulatorPipelineState acc_st = accumulator_pipe_consumer_state; + if constexpr (kHalves) { + const uint32_t it = (kLateScale || kSfRelay) ? gsf_it : gsf_it - 1u; + acc_st = AccumulatorPipelineState((int)(((it & 1u) << 1) | (uint32_t)(g >> 1)), (it >> 1) & 1u, 0u); + } + if constexpr (kPair) { + // raw try_wait.parity with a suspend-time hint (== ClusterBarrier::wait; fewer re-poll issues) + const uint32_t fa = (uint32_t)__cvta_generic_to_shared(&shared_storage.pair_bar[0]) + + (uint32_t)accumulator_pipe_consumer_state.index() * 8u; + asm volatile("{\n\t.reg .pred p;\n\tPP_%=:\n\t" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, 1000000;\n\t" + "@!p bra PP_%=;\n\t}" ::"r"(fa), "r"((uint32_t)accumulator_pipe_consumer_state.phase()) : "memory"); + asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); + } else + if constexpr (kHalves) { + // promotion barrier trim (MO split-N kernels): raw 32-bit try_wait.parity on this CTA's TMEM-full slot + // (== PipelineUmmaAsync::consumer_wait / ClusterBarrier::wait), then the tcgen05 after-sync fence + const uint32_t fa = (uint32_t)__cvta_generic_to_shared(&acc_pipe_storage.full_barrier_[0]) + (uint32_t)acc_st.index() * 8u; + asm volatile("{\n\t.reg .pred p;\n\tPF_%=:\n\t" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, 1000000;\n\t" + "@!p bra PF_%=;\n\t}" ::"r"(fa), "r"((uint32_t)acc_st.phase()) : "memory"); + asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); + } else + if constexpr (!kPingPong) { + // promotion barrier trim (non-merged kernels): raw 32-bit try_wait.parity on the TMEM-full stage + // (== PipelineUmmaAsync::consumer_wait), then the tcgen05 after-sync fence + const uint32_t fa = (uint32_t)__cvta_generic_to_shared(&acc_pipe_storage.full_barrier_[0]) + + (uint32_t)accumulator_pipe_consumer_state.index() * 8u; + asm volatile("{\n\t.reg .pred p;\n\tPN_%=:\n\t" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, 1000000;\n\t" + "@!p bra PN_%=;\n\t}" ::"r"(fa), "r"((uint32_t)accumulator_pipe_consumer_state.phase()) : "memory"); + asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); + } else + accumulator_pipeline.consumer_wait(accumulator_pipe_consumer_state); + if constexpr (kSfRelay) fetch_scale(); // TMEM-full(kb) implies the scales of kb landed (see kSfRelay) + const uint32_t taddr = tbase + (uint32_t)(kHalves ? acc_st.index() : accumulator_pipe_consumer_state.index()) * stage_stride; + if constexpr (kWgCols == 32) { + // 1SM: 32 columns per warpgroup -> one x32 load, wait, release the stage, 16 packed FMAs + float part[32]; + tmem_ld32(taddr, part); + tmem_ld_wait(); + tc_fence_before(); + accumulator_pipeline.consumer_release(accumulator_pipe_consumer_state); + ++accumulator_pipe_consumer_state; + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 32; i += 2) fma2(acc[i], acc[i + 1], part[i], part[i + 1], scale); + } else { + // 2SM / ping-pong: 64 columns per warpgroup in 4 chunks of 16 through ONE 16-reg partial buffer (register + // budget is 104/thread: 64 acc + 16 partial). Latency is hidden by the 4 promotion warps per + // scheduler rather than intra-warp ping-pong. Stage released right after the last load lands. +#ifndef SE_PAIR_DB16 +#define SE_PAIR_DB16 1 +#endif + if constexpr (kPair && SE_PAIR_DB16) { + // software-pipelined promotion. 4 x16 TMEM chunks (gate cols + // [32g,+16), [32g+16,+16), up cols 128 + same) through TWO 16-reg buffers: the load of chunk c+1 is in + // flight while chunk c is FMA'd (was: 2 x32 load -> wait -> FMA round trips serialized per warp). Same 32 + // partial registers, same per-element fma (bit-identical); stage released once the last load landed. + // the first TWO chunks are issued before the first wait (one TMEM round trip covers chunks 0 and 1; + // was ld c0 -> wait -> ld c1), then chunk c+2's load overlaps chunk c+1's FMAs. 3 waits per k block + // instead of 4, same registers / FMA order -> bit-identical. + float pa[16], pb[16]; + tmem_ld16(taddr, pa); + tmem_ld16(taddr + 16u, pb); + tmem_ld_wait(); + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 16; i += 2) fma2(acc[i], acc[i + 1], pa[i], pa[i + 1], scale); + tmem_ld16(taddr + 128u, pa); + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 16; i += 2) fma2(acc[16 + i], acc[16 + i + 1], pb[i], pb[i + 1], scale); + tmem_ld_wait(); + tmem_ld16(taddr + 144u, pb); + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 16; i += 2) fma2(acc[32 + i], acc[32 + i + 1], pa[i], pa[i + 1], scale_hi); + tmem_ld_wait(); + tc_fence_before(); + if constexpr (kWarpRel) __syncwarp(); + if (!kWarpRel || (threadIdx.x & 31) == 0) + shared_storage.pair_bar[2 + accumulator_pipe_consumer_state.index()].arrive(); + ++accumulator_pipe_consumer_state; + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 16; i += 2) fma2(acc[48 + i], acc[48 + i + 1], pb[i], pb[i + 1], scale_hi); + } else +#ifndef SE_DN_DB16 +#define SE_DN_DB16 1 +#endif + if constexpr (kBal224) { + // kBal224 promotion (see kBal224): WG g < 3: +0,+16 (scale), +32 (x16), +48 (x8) (scale_hi); + // WG3: own +0,+16 (scale); pieces at slice-relative -136 / -72 / -8 (cols 56 / 120 / 184) -> acc[32..55] + const bool w3 = g == 3; + float pa[16], pb[16]; + tmem_ld16(taddr, pa); + tmem_ld16(taddr + 16u, pb); + tmem_ld_wait(); + const uint64_t s0 = pack_s2(scale); + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 16; i += 2) fma2s(acc[i], acc[i + 1], pa[i], pa[i + 1], s0); + if (w3) { tmem_ld8(taddr - 136u, pa); tmem_ld8(taddr - 72u, pa + 8); } + else tmem_ld16(taddr + 32u, pa); + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 16; i += 2) fma2s(acc[16 + i], acc[16 + i + 1], pb[i], pb[i + 1], s0); + tmem_ld8(w3 ? taddr - 8u : taddr + 48u, pb); + tmem_ld_wait(); + tc_fence_before(); + __syncwarp(); + if ((threadIdx.x & 31) == 0) { + const uint32_t ea = (uint32_t)__cvta_generic_to_shared(&acc_pipe_storage.empty_barrier_[0]) + + (uint32_t)accumulator_pipe_consumer_state.index() * 8u; + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(ea) : "memory"); + } + ++accumulator_pipe_consumer_state; + const uint64_t s1 = pack_s2(scale_hi); + const uint64_t sA = s1, sB = w3 ? pack_s2(scale_x1) : s1, sC = w3 ? pack_s2(scale_x2) : s1; + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 8; i += 2) fma2s(acc[32 + i], acc[32 + i + 1], pa[i], pa[i + 1], sA); + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 8; i += 2) fma2s(acc[40 + i], acc[40 + i + 1], pa[8 + i], pa[8 + i + 1], sB); + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 8; i += 2) fma2s(acc[48 + i], acc[48 + i + 1], pb[i], pb[i + 1], sC); + } else + if constexpr (kBal160) { + // kBal40 promotion (128x160 down tile): every WG owns 40 cols = one aligned x32 piece (scale: 32-col + // B-scale group of col_local) + one aligned x8 piece in cols [96,128) (scale_hi: group 3): + // WG0 [0,32)+[104,112) WG1 [64,96)+[112,120) WG2 [128,160)+[120,128) WG3 [32,64)+[96,104) + // both TMEM loads issued before ONE wait; same per-element scale / fma.rn.f32x2 -> bit-identical + const uint32_t off8 = g == 0 ? 104u : g == 1 ? 48u : g == 2 ? (uint32_t)-8 : 64u; // x8 col - col_local + float pa[32], pb[8]; + tmem_ld32(taddr, pa); + tmem_ld8(taddr + off8, pb); + tmem_ld_wait(); + tc_fence_before(); + __syncwarp(); + if ((threadIdx.x & 31) == 0) { + const uint32_t ea = (uint32_t)__cvta_generic_to_shared(&acc_pipe_storage.empty_barrier_[0]) + + (uint32_t)accumulator_pipe_consumer_state.index() * 8u; + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(ea) : "memory"); + } + ++accumulator_pipe_consumer_state; + const uint64_t s0 = pack_s2(scale); + const uint64_t s1 = pack_s2(scale_hi); + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 32; i += 2) fma2s(acc[i], acc[i + 1], pa[i], pa[i + 1], s0); + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 8; i += 2) fma2s(acc[32 + i], acc[32 + i + 1], pb[i], pb[i + 1], s1); + } else + if constexpr (kN224 && !kMerged && !kPingPong && SE_DN_DB16) { + // kDnDB16 (chain-path TMA-store down GEMMs / /, 224 / 160-col tiles): the WG's 64 columns + // as 4 x16 TMEM chunks (cols +0, +16 scale; +32, +48 scale_hi) through TWO 16-reg buffers, the first two + // chunks issued before the first wait, then chunk c+2's load overlaps chunk c+1's FMAs (3 waits per k + // block instead of 2 serialized x32 round trips). WG kHalfWg owns only the first 32 cols, WGs above it + // are idle (warp-uniform). Same per-element fma.rn.f32x2 with the same scales -> bit-identical. + const bool h0 = g <= kHalfWg, h1 = g < kHalfWg; + float pa[16], pb[16]; + if (h0) { tmem_ld16(taddr, pa); tmem_ld16(taddr + 16u, pb); } + tmem_ld_wait(); + const uint64_t s0 = pack_s2(scale); + if (h0) { + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 16; i += 2) fma2s(acc[i], acc[i + 1], pa[i], pa[i + 1], s0); + } + if (h1) tmem_ld16(taddr + 32u, pa); + if (h0) { + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 16; i += 2) fma2s(acc[16 + i], acc[16 + i + 1], pb[i], pb[i + 1], s0); + } + tmem_ld_wait(); + if (h1) tmem_ld16(taddr + 48u, pb); + const uint64_t s1 = pack_s2(scale_hi); + if (h1) { + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 16; i += 2) fma2s(acc[32 + i], acc[32 + i + 1], pa[i], pa[i + 1], s1); + } + tmem_ld_wait(); + tc_fence_before(); + if constexpr (kWarpRel) __syncwarp(); + if (!kWarpRel || (threadIdx.x & 31) == 0) { + // raw TMEM-stage release (== PipelineUmmaAsync::consumer_release): 2SM -> leader CTA (rank 0) via mapa + const uint32_t ea = (uint32_t)__cvta_generic_to_shared(&acc_pipe_storage.empty_barrier_[0]) + + (uint32_t)accumulator_pipe_consumer_state.index() * 8u; + if constexpr (kTwoSm) { + asm volatile("{\n\t.reg .b32 ra;\n\tmapa.shared::cluster.u32 ra, %0, 0;\n\t" + "mbarrier.arrive.shared::cluster.b64 _, [ra];\n\t}" ::"r"(ea) : "memory"); + } else { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(ea) : "memory"); + } + } + ++accumulator_pipe_consumer_state; + if (h1) { + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 16; i += 2) fma2s(acc[48 + i], acc[48 + i + 1], pb[i], pb[i + 1], s1); + } + } else + if constexpr (kLd32) { + // 2 x tcgen05.ld.32x32b.x32 (32 cols each) instead of 4 x.x16. Promotion microbench (probe-only + // SE_PROBE_PM, 148 SMs, 128x256 fp32 per CTA per kb, packed FMAs): 4 x x16 370 cyc/kb, 2 x x32 293 + // (2 x16 in flight before one wait: 369 -> the cost is per ld instruction, not per wait). fused: chunk 0 + // = gate cols [32g,+32), chunk 1 = up cols 128 + [32g,+32) (own B scale). + float part[32]; + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < 2; ++c) { + // kN224: WG3 owns only 32 columns (warp-uniform skip of its second chunk) + const bool skip_c = kN224 && ((c == 1 && g == kHalfWg) || g > kHalfWg); // kN160: WG3 idle + if (!skip_c) tmem_ld32(taddr + (fzk ? c * (kHalves ? 64 : 128) : c * 32), part); + if constexpr (kLateScale) if (c == 0) fetch_scale(); // overlaps the TMEM load latency + tmem_ld_wait(); + if (c == 1) { + tc_fence_before(); + if constexpr (kHalves) { + // TMEM slot release straight to the MMA leader CTA's empty barrier (2x1 cluster: rank 0), every + // promotion thread arrives (== PipelineUmmaAsync::consumer_release: mapa + mbarrier.arrive.shared::cluster) + static_assert(cute::size(ClusterShape{}) == 2, "kHalves: 2x1 cluster, MMA leader = rank 0"); + // the rank-0 cluster address of empty_barrier_[0] is loop invariant: mapa in a NON-volatile asm + // (pure function of the CTA-local base, hoistable out of the k loop), then + slot * 8 (the shared::cluster + // window maps each CTA's smem contiguously -> == mapa(base + slot * 8)); same arrive, bit-identical + uint32_t ea0; + asm("mapa.shared::cluster.u32 %0, %1, 0;" : "=r"(ea0) + : "r"((uint32_t)__cvta_generic_to_shared(&acc_pipe_storage.empty_barrier_[0]))); + asm volatile("mbarrier.arrive.shared::cluster.b64 _, [%0];" ::"r"(ea0 + (uint32_t)acc_st.index() * 8u) : "memory"); + } // early release + else { + if constexpr (kWarpRel) __syncwarp(); // all lanes' TMEM loads done -> one arrival per warp + const bool rel_lane = !kWarpRel || (threadIdx.x & 31) == 0; + if constexpr (kPair) { if (rel_lane) shared_storage.pair_bar[2 + accumulator_pipe_consumer_state.index()].arrive(); } + else if constexpr (!kPingPong) { if (rel_lane) { + // raw TMEM-stage release (== PipelineUmmaAsync::consumer_release, every thread arrives): + // 2SM -> MMA leader CTA (rank 0 of the 2x1 cluster) via mapa; 1SM -> own CTA + const uint32_t ea = (uint32_t)__cvta_generic_to_shared(&acc_pipe_storage.empty_barrier_[0]) + + (uint32_t)accumulator_pipe_consumer_state.index() * 8u; + if constexpr (kTwoSm) { + static_assert(cute::size(ClusterShape{}) == 2, "2SM: 2x1 cluster, MMA leader = rank 0"); + asm volatile("{\n\t.reg .b32 ra;\n\tmapa.shared::cluster.u32 ra, %0, 0;\n\t" + "mbarrier.arrive.shared::cluster.b64 _, [ra];\n\t}" ::"r"(ea) : "memory"); + } else { + static_assert(cute::size(ClusterShape{}) == 1, "1SM: no cluster"); + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(ea) : "memory"); + } + } } + else accumulator_pipeline.consumer_release(accumulator_pipe_consumer_state); // early release + ++accumulator_pipe_consumer_state; + } + } + const float sc_c = c ? scale_hi : scale; + if (skip_c) continue; + CUTLASS_PRAGMA_UNROLL + const uint64_t sc2 = pack_s2(sc_c); // packed scale pair once per chunk + for (int i = 0; i < 32; i += 2) fma2s(acc[c * 32 + i], acc[c * 32 + i + 1], part[i], part[i + 1], sc2); + } + } else { + float part[16]; + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < 4; ++c) { + tmem_ld16(taddr + (fz ? (c >> 1) * 128 + (c & 1) * 16 : c * 16), part); + tmem_ld_wait(); + if (c == 3) { + tc_fence_before(); + accumulator_pipeline.consumer_release(accumulator_pipe_consumer_state); // early release + ++accumulator_pipe_consumer_state; + } + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 16; i += 2) + fma2(acc[c * 16 + i], acc[c * 16 + i + 1], part[i], part[i + 1], c >= 2 ? scale_hi : scale); + } + } + } + } + } + + if constexpr (kLateNM) fetch_next(); // kLateNM: relayed next tile read after the k loop + if constexpr (kJit) fetch_next(); // kJit: after the k loop (unit i+1 is queried at the end of unit i's loads) + if constexpr (kLateFetch) { + fetch_next(); // after the k loop (see kLateFetch) + rederive(false); + // re-decode the unit from M_idx (laundered through asm so the compiler cannot keep the pre-loop decode + // results live across the k loop instead): only one register of tile state crosses the loop + int u = (int)work_tile_info.M_idx; + asm volatile("mov.b32 %0, %0;" : "+r"(u)); + int kc_unused; + cta_coord_mnkl = mg_decode(u / kClCtas, kc_unused, mg_dn, mg_mb); + fz = kFuse && !(kMerged && mg_dn); + col_local = fz ? g * 32 : g * kWgCols; + } + if constexpr (kPingPong) { // hand off to the next tile's team (only if there is a next tile) + if (next_work_tile_info.is_valid()) + asm volatile("bar.arrive %0, %1;" ::"r"(14 + ((tile_iter - 1) & 1)), "n"(NumEpilogueThreads) : "memory"); + } + // epilogue: bf16 RN convert, kWgCols/8 x 16B stores of this thread's contiguous columns + const int row = get<0>(cta_coord_mnkl) * 128 + row_local; + // ---- kStatic split-K unit: distributed fixup partitioned by ROWS (the fused 1x128 requant needs whole rows) + // 3. split j owns rows [128j/s, 128(j+1)/s): the threads of those rows (all 4 WGs -> all kCtaN cols) sum + // the s partials in fixed order j'=0..s-1 (deterministic, independent of arrival order) into acc and run + // the epilogue below; other threads only join the named barriers; 4. bump done = cnt[1]; the last split + // resets both counters (self-cleaning for the next launch). + bool st_active = true; + [[maybe_unused]] int* st_cnt = nullptr; + // kPair chunked DSMEM exchange helpers: chunk of float4 c (0-7 gate, 8-15 up), barrier address of chunk j + // (rebased from chunk 0's address b0 in either CTA's window), and pair_add(j): owner waits for chunk j of the + // peer's partial and adds it (same per-element fp32 add as before -> bit-identical) + [[maybe_unused]] auto pair_chunk = [&](int c) -> int { return (c & 7) / (8 / pair_nch); }; + [[maybe_unused]] auto pair_corder = [&](int jc) -> int { // jc-th float4 sent: chunk-major order + const int per = 8 / pair_nch, j = jc / (2 * per), w = jc - j * 2 * per; + return (w < per ? 0 : 8) + j * per + (w % per); + }; + [[maybe_unused]] auto pair_add = [&](int j) { + if constexpr (kPair) { + const uint32_t b0 = (uint32_t)__cvta_generic_to_shared(&shared_storage.pair_bar[4]); + asm volatile("{\n\t.reg .pred p;\n\tPAW_%=:\n\t" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], 0, 1000000;\n\t" + "@!p bra PAW_%=;\n\t}" ::"r"(pair_cbar(b0, j)) : "memory"); + const uint32_t rbuf = (uint32_t)__cvta_generic_to_shared(shared_storage.tensors.mainloop.smem_B.begin()); + const int r = row_local & 63; // owner row within the 64 owned rows + const int per = 8 / pair_nch; + CUTLASS_PRAGMA_UNROLL + for (int h = 0; h < 2; ++h) { + CUTLASS_PRAGMA_UNROLL + for (int w = 0; w < per; ++w) { + const int c = h * 8 + j * per + w; + float4 v; + asm volatile("ld.shared.v4.f32 {%0, %1, %2, %3}, [%4];" : "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w) + : "r"(rbuf + (uint32_t)(((c * 4 + g) * 64 + r) * 16)) : "memory"); + acc[4 * c] += v.x; acc[4 * c + 1] += v.y; acc[4 * c + 2] += v.z; acc[4 * c + 3] += v.w; + } + } + } + }; + if constexpr (kPair) { + // ---- kPair DSMEM fixup (see kPair): split st_sj (= cluster rank) owns rows [64 st_sj, +64) ---- + // deferred half of the setup cluster barrier (peer's barriers initialized) before the first remote access + if (pair_split) asm volatile("barrier.cluster.wait.acquire;" ::: "memory"); + const int own0 = st_sj * 64; + st_active = row_local >= own0 && row_local < own0 + 64; + const uint32_t peer = cta_rank_in_cluster ^ 1u; + // receive buffer: 64 rows x 256 fp32 = 64 KB at the start of smem_B (idle: every MMA completed (we waited on + // the last TMEM-full commit) and no TMA load is outstanding (one unit per CTA)). float4 slot of (row r, + // WG g, chunk c) = (c * 4 + g) * 64 + r: a warp's 32 rows are 512 contiguous bytes. + static_assert(sizeof(shared_storage.tensors.mainloop.smem_B) >= 65536, "kPair receive buffer"); + const uint32_t rbuf = (uint32_t)__cvta_generic_to_shared(shared_storage.tensors.mainloop.smem_B.begin()); + const uint32_t rbar = (uint32_t)__cvta_generic_to_shared(&shared_storage.pair_bar[4]); + if ((int)threadIdx.x == 128) { + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // async-proxy (TMA/MMA) use -> generic + // one receive barrier per DSMEM chunk (chunk 0: pair_bar[4], chunk j > 0: pair_bar[5 + j]) + for (int j = 0; j < pair_nch; ++j) + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(pair_cbar(rbar, j)), + "r"(65536 / pair_nch) : "memory"); + shared_storage.pair_bar[5].arrive(peer, 1u); // remote: "my receive buffer is free and armed" + } + if (!st_active) { + // non-owned row: push the partial into the owner's (peer's) buffer + const int r = row_local - (64 - own0); + shared_storage.pair_bar[5].wait(0); + uint32_t rb, rm; + asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(rb) : "r"(rbuf), "r"(peer)); + asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(rm) : "r"(rbar), "r"(peer)); + // issued chunk by chunk (chunk j: gate float4s c = 2j, 2j+1 and up c = 8+2j, 9+2j for 4 chunks), + // each completing its own receive barrier, so the owner starts the SwiGLU of chunk 0 while 1..3 arrive + CUTLASS_PRAGMA_UNROLL + for (int jc = 0; jc < kWgCols / 4; ++jc) { + const int c = pair_corder(jc); + const uint32_t a = rb + (uint32_t)(((c * 4 + g) * 64 + r) * 16); + asm volatile("st.async.shared::cluster.mbarrier::complete_tx::bytes.v4.f32 [%0], {%1, %2, %3, %4}, [%5];" + ::"r"(a), "f"(acc[4 * c]), "f"(acc[4 * c + 1]), "f"(acc[4 * c + 2]), "f"(acc[4 * c + 3]), + "r"(pair_cbar(rm, pair_chunk(c))) : "memory"); + } + } else { + const int r = row_local - own0; + pair_add(0); // chunk 0 of the peer's partial (chunks 1.. are added in the SwiGLU loop) + (void)r; + } + } else + if constexpr (kStatic) { + if constexpr (kRedSplit) { + if (st_sj >= 0) { + const int etid = (int)threadIdx.x - 128; // 0..511 + uint32_t crank; + asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(crank)); + const int slot = st_tt * 2 + (int)(crank & 1u); + float4* base = reinterpret_cast(params.split_ws) + (size_t)slot * (16 * 512) + etid; + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < 16; ++c) + asm volatile("red.relaxed.gpu.global.add.v4.f32 [%0], {%1, %2, %3, %4};" ::"l"(base + c * 512), + "f"(acc[4 * c]), "f"(acc[4 * c + 1]), "f"(acc[4 * c + 2]), "f"(acc[4 * c + 3]) : "memory"); + named_bar_sync(12, NumEpilogueThreads); + if ((int)threadIdx.x == 128) { + int* cp = params.split_cnt + slot; + int old; + asm volatile("fence.acq_rel.gpu;" ::: "memory"); + asm volatile("atom.acq_rel.gpu.global.add.s32 %0, [%1], 1;" : "=r"(old) : "l"(cp) : "memory"); + const int last = old == params.st_split - 1; + if (last) { *cp = 0; __threadfence(); } + shared_storage.stg_info[0] = last; + shared_storage.stg_info[1] = old == 0; // first arriver (never last: st_split > 1) + } + named_bar_sync(13, NumEpilogueThreads); + if (shared_storage.stg_info[0]) { + // last arriver: whole reduced tile (own partial included). NO re-zeroing here (critical path); + // this call's FIRST arriver zeroes the same slot of the other-parity workspace (split_alt), which the + // next split call uses. Each warp instruction: 32 lanes x 16 B = 512 contiguous bytes. + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < 16; ++c) { + const float4 q4 = __ldcg(base + c * 512); + acc[4 * c] = q4.x; acc[4 * c + 1] = q4.y; acc[4 * c + 2] = q4.z; acc[4 * c + 3] = q4.w; + } + st_sj = -1; // epilogue below = full tile, normal publish + } else { + // not last: hand the publisher a "nothing" entry (keeps the ring sequence) and go on + if (shared_storage.stg_info[1]) { + // first arriver: zero this slot of the other-parity workspace (off the critical path; that buffer + // is not touched by this call, its previous reader (last call of that parity) completed) + float4* alt = reinterpret_cast(params.split_alt) + (size_t)slot * (16 * 512) + etid; + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < 16; ++c) __stcg(alt + c * 512, make_float4(0.f, 0.f, 0.f, 0.f)); + } + const uint32_t pi = (uint32_t)(tile_iter - 1); + const int sl = (int)(pi & 1u); + if ((int)threadIdx.x == 128) { + shared_storage.pub_empty[sl].wait(((pi >> 1) & 1u) ^ 1u); + shared_storage.pub_info[sl] = -2; + shared_storage.pub_n = (int)pi + 1; + } + shared_storage.pub_full[sl].arrive(); + __syncwarp(); + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + continue; + } + } + } else + if (st_sj >= 0) { + const int s = params.st_split; + const int etid = (int)threadIdx.x - 128; // 0..511 epilogue thread + const int rank = kTwoSm ? (int)(cta_rank_in_cluster & 1) : 0; + constexpr int kF4 = kWgCols / 4; // float4 per thread (16 for 2SM 256-col, 8 for 1SM) + constexpr int kSlot = kF4 * 512; // float4s per CTA partial (128 x kCtaN fp32) + constexpr int kSlotStride = kClCtas * kSlot; // float4s between split j and j+1 of the same (tt, rank) + st_cnt = params.split_cnt + (st_tt * kClCtas + rank) * 2; + float4* base = reinterpret_cast(params.split_ws) + + (size_t)(st_tt * s * kClCtas + rank) * kSlot + etid; + // for s == 2 the owner keeps its own rows' partial in registers; only NON-owned rows are + // published and the owner reads only the partner's partial (half the fixup L2 traffic, bit-identical). + st_active = row_local >= st_sj * 128 / s && row_local < (st_sj + 1) * 128 / s; + if (s != 2 || !st_active) { + float4* mine = base + st_sj * kSlotStride; + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < kF4; ++c) + __stcg(mine + c * 512, make_float4(acc[4 * c], acc[4 * c + 1], acc[4 * c + 2], acc[4 * c + 3])); + } + __threadfence(); + named_bar_sync(12, NumEpilogueThreads); + if (etid == 0) { + atomicAdd(st_cnt, 1); + int seen; + while (true) { + asm volatile("ld.acquire.gpu.global.s32 %0, [%1];" : "=r"(seen) : "l"(st_cnt) : "memory"); + if (seen >= s) break; + __nanosleep(32); + } + __threadfence(); + } + named_bar_sync(13, NumEpilogueThreads); + if (st_active && s == 2) { + const float4* other = base + (1 - st_sj) * kSlotStride; + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < kF4; ++c) { + const float4 q4 = __ldcg(other + c * 512); + acc[4 * c] += q4.x; acc[4 * c + 1] += q4.y; acc[4 * c + 2] += q4.z; acc[4 * c + 3] += q4.w; + } + } else if (st_active) { + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < kF4; ++c) { + float4 t = __ldcg(base + c * 512); // fixed order j = 0, 1, ..., s-1 + CUTLASS_PRAGMA_UNROLL + for (int jj = 1; jj < kMaxSplit; ++jj) + if (jj < s) { + const float4 q4 = __ldcg(base + jj * kSlotStride + c * 512); + t.x += q4.x; t.y += q4.y; t.z += q4.z; t.w += q4.w; + } + acc[4 * c] = t.x; acc[4 * c + 1] = t.y; acc[4 * c + 2] = t.z; acc[4 * c + 3] = t.w; + } + } + } + } + // kStatic: after the epilogue, count this split done; the last one resets the tile's counters + auto st_finish = [&]() { + if constexpr (kStatic && !kPair) { + if (st_sj >= 0) { + named_bar_sync(12, NumEpilogueThreads); // all workspace reads of this CTA are done + if ((int)threadIdx.x == 128) { + if (atomicAdd(st_cnt + 1, 1) == params.st_split - 1) { // every split is past its wait and reads + st_cnt[0] = 0; st_cnt[1] = 0; + __threadfence(); + } + } + } + } + }; + if constexpr (kFuse) if (fz) { + if constexpr (kStg) { + uint8_t* buf = shared_storage.epi_stage + wg * (128 * 128); + const uint32_t sbuf = (uint32_t)__cvta_generic_to_shared(buf); + if ((threadIdx.x & 127) == 0) bulk_wait_read0(); // an earlier down TMA store finished reading region + named_bar_sync(8 + wg, 128); + shared_storage.stg_empty.wait(stg_empty_phase); // staging WG released the previous gate_up tile + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < 8; ++c) { + __nv_bfloat162 b0 = __floats2bfloat162_rn(acc[c * 8 + 0], acc[c * 8 + 1]); + __nv_bfloat162 b1 = __floats2bfloat162_rn(acc[c * 8 + 2], acc[c * 8 + 3]); + __nv_bfloat162 b2 = __floats2bfloat162_rn(acc[c * 8 + 4], acc[c * 8 + 5]); + __nv_bfloat162 b3 = __floats2bfloat162_rn(acc[c * 8 + 6], acc[c * 8 + 7]); + const uint32_t ad = sbuf + row_local * 128 + ((c ^ (row_local & 7)) << 4); + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(ad), + "r"(*reinterpret_cast(&b0)), "r"(*reinterpret_cast(&b1)), + "r"(*reinterpret_cast(&b2)), "r"(*reinterpret_cast(&b3)) + : "memory"); + } + if (threadIdx.x == 128) { + shared_storage.stg_info[0] = get<0>(cta_coord_mnkl); + shared_storage.stg_info[1] = get<1>(cta_coord_mnkl); + shared_storage.stg_info[2] = mg_mb; + shared_storage.stg_info[3] = 0; + } + shared_storage.stg_full.arrive(); // release: staging + info visible to the staging WG + stg_empty_phase ^= 1; + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + continue; + } + if (kHT_PR && hu) { + // ---- wide half-block gate_up epilogue: thread (WG g, warp q, lane l) holds 64 accumulators of row + // rr = (q&1)*32 + l of the CTA's 64 rows, h block hb = nt0 + (g>>1), h cols (g&1)*64 + [0,64): gate (q < 2) + // or up (q >= 2). Up threads hand bf16(up) to their gate partner (same WG, warp q-2, same lane) through the + // WG's epi_stage region (row rr at bytes [128 rr, +128), 16 B chunk c at c ^ (rr & 7)); the gate thread + // computes h = bf16(bf16(silu(bf16 g)) * bf16 u) (same roundings as the full path), 128-col row amax with + // the partner WG g^1 (amax_red, bar 12), 1x128 requant, 64 B of qh + the scale (g&1 == 0). + // Region reuse: the previous unit's readers of these bytes finished before this unit's k loop could + // complete (every TMEM slot / scale-ring stage needs all 512 threads' releases). + const bool upt = q >= 2; + const int rr = (q & 1) * 32 + (int)(threadIdx.x & 31); + const uint32_t xa = (uint32_t)__cvta_generic_to_shared(shared_storage.epi_stage) + (uint32_t)wg * 16384u + + (uint32_t)rr * 128u; + const uint32_t xsw = (uint32_t)(rr & 7); + if (upt) { + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < 8; ++c) { + __nv_bfloat162 b0 = __floats2bfloat162_rn(acc[c * 8 + 0], acc[c * 8 + 1]); + __nv_bfloat162 b1 = __floats2bfloat162_rn(acc[c * 8 + 2], acc[c * 8 + 3]); + __nv_bfloat162 b2 = __floats2bfloat162_rn(acc[c * 8 + 4], acc[c * 8 + 5]); + __nv_bfloat162 b3 = __floats2bfloat162_rn(acc[c * 8 + 6], acc[c * 8 + 7]); + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(xa + (((uint32_t)c ^ xsw) << 4)), + "r"(*reinterpret_cast(&b0)), "r"(*reinterpret_cast(&b1)), + "r"(*reinterpret_cast(&b2)), "r"(*reinterpret_cast(&b3)) + : "memory"); + } + } + named_bar_sync(8 + wg, 128); + float amax = 0.f; + if (!upt) { + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < 8; ++c) { + uint32_t uw[4]; + asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4];" : "=r"(uw[0]), "=r"(uw[1]), "=r"(uw[2]), "=r"(uw[3]) + : "r"(xa + (((uint32_t)c ^ xsw) << 4)) : "memory"); + CUTLASS_PRAGMA_UNROLL + for (int j = 0; j < 4; ++j) { + const int i = c * 8 + 2 * j; + const __nv_bfloat162 g2 = __floats2bfloat162_rn(acc[i], acc[i + 1]); + const __nv_bfloat162 u2 = *reinterpret_cast(&uw[j]); + const float2 gf = __bfloat1622float2(g2); + const float s0 = silu_tanh(gf.x); + const float s1 = silu_tanh(gf.y); + const __nv_bfloat162 h2 = __hmul2(__floats2bfloat162_rn(s0, s1), u2); + const float2 hf = __bfloat1622float2(h2); + acc[i] = hf.x; + acc[i + 1] = hf.y; + amax = fmaxf(amax, fmaxf(fabsf(hf.x), fabsf(hf.y))); + } + } + } + float (*red)[128] = shared_storage.amax_red[tile_iter & 1]; + if (!upt) red[g][rr] = amax; + asm volatile("bar.sync 12, %0;" ::"n"(NumEpilogueThreads) : "memory"); + if (!upt) { + amax = fmaxf(red[g][rr], red[g ^ 1][rr]); + const float sc = fmaxf(amax * (1.0f / 448.0f), 1e-12f); + const float inv = __frcp_rn(sc); + uint32_t crank; // re-read (volatile): the cluster rank is not kept live across the k loop + asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(crank)); + const int row = kClTileM * mg_mb + 64 * (int)(crank & 1u) + rr; + const int hb = get<1>(cta_coord_mnkl) + (g >> 1); + if (row < M) { + uint8_t* dst = reinterpret_cast(params.ptr_D) + (int64_t)row * (N >> 1) + hb * 128 + (g & 1) * 64; + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < 4; ++c) { + uint32_t w[4]; + CUTLASS_PRAGMA_UNROLL + for (int j = 0; j < 4; ++j) { + const int i = c * 16 + 4 * j; + const uint32_t lo = (uint32_t)__nv_cvt_float2_to_fp8x2(make_float2(acc[i] * inv, acc[i + 1] * inv), + __NV_SATFINITE, __NV_E4M3); + const uint32_t hi = (uint32_t)__nv_cvt_float2_to_fp8x2( + make_float2(acc[i + 2] * inv, acc[i + 3] * inv), __NV_SATFINITE, __NV_E4M3); + w[j] = lo | (hi << 16); + } + *reinterpret_cast(dst + c * 16) = make_uint4(w[0], w[1], w[2], w[3]); + } + if ((g & 1) == 0) params.fused_scale[(int64_t)hb * M + row] = sc; + } + } + } else { + float amax = 0.f; + uint32_t mbits = 0; + // kMerged keeps h as 16 packed bf16x2 words (hw) for the fp8 convert below (no unpack into acc here); + // gate bf16 -> fp32 unpack with explicit shift / mask (was PRMT + IMAD per element), bit-identical + uint32_t hw[16]; + constexpr unsigned smask = SE_SILU_MASK; + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 32; i += 2) { + // kPair owner rows: add the next DSMEM chunk of the peer's partial right before its first column pair + if constexpr (kPair) if (st_active && i > 0 && (i % (32 / pair_nch)) == 0) pair_add(i / (32 / pair_nch)); + const __nv_bfloat162 g2 = __floats2bfloat162_rn(acc[i], acc[i + 1]); + const __nv_bfloat162 u2 = __floats2bfloat162_rn(acc[32 + i], acc[32 + i + 1]); + const uint32_t gw2 = *reinterpret_cast(&g2); + const float2 gf = make_float2(__uint_as_float(gw2 << 16), __uint_as_float(gw2 & 0xffff0000u)); + float2 sl; + // silu offload: column pairs selected by smask (merged kernels) evaluate silu on the FMA pipe (silu_fma), + // the others via one MUFU.TANH per element (the epilogue is MUFU-bound) + if (kMerged && ((smask >> (i >> 1)) & 1u)) { + sl = kHalveGate ? make_float2(silu_fma(2.f * gf.x), silu_fma(2.f * gf.y)) : make_float2(silu_fma(gf.x), silu_fma(gf.y)); + } else { + const float2 hg = kHalveGate ? gf : mul2_rn(gf, 0.5f); // gate accumulator already holds 0.5 g + float2 t; + asm("tanh.approx.f32 %0, %1;" : "=f"(t.x) : "f"(hg.x)); + asm("tanh.approx.f32 %0, %1;" : "=f"(t.y) : "f"(hg.y)); + sl = fma2_rn(hg, t, hg); + } + const __nv_bfloat162 h2 = __hmul2(__floats2bfloat162_rn(sl.x, sl.y), u2); + const uint32_t hb = *reinterpret_cast(&h2); + // one max.xorsign.abs.bf16x2 per pair (|.| max per half, sign bits = xor, masked off below) instead of + // LOP (& 0x7fff7fff) + VIMNMX: same magnitude for non-NaN values -> bit-identical amax + asm("max.xorsign.abs.bf16x2 %0, %0, %1;" : "+r"(mbits) : "r"(hb)); + hw[i >> 1] = hb; // packed h kept for every fused kernel (merged + non-merged) + } + // half-merge of the packed |h| max with one more max.xorsign.abs.bf16x2 against the half-swapped word + // (PRMT), then the low half's magnitude bits (sign = xor, masked) -> fp32 bits: PRMT + HMNMX2 + LOP + SHL + // (was LOP, LOP, SHR, VIMNMX, SHL). Magnitude max is order independent -> bit-identical amax. + { + uint32_t sw2 = __byte_perm(mbits, 0u, 0x1032), mm; + asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(mm) : "r"(mbits), "r"(sw2)); + amax = __uint_as_float((mm & 0x7fffu) << 16); + } + // row amax over 128 h cols = max of the 4 WGs' partials (smem, double-buffered by tile parity; all 512 + // epilogue threads hit the named barrier every tile, including rows >= M). tile_iter was already + // incremented for this tile, so its parity alternates per tile. + // kMerged: the qh tile is staged in WG0's epi_stage region below; WG0's elect thread (128) owns the bulk group + // of any earlier DN TMA store from that region -> wait until it has read smem (ordered by bar 12 below) + if constexpr (kMerged) if (threadIdx.x == 128) bulk_wait_read0(); + // kQuarterBar (kTmaQh kernels): the row-amax exchange only couples the 4 warps that own the same TMEM lane + // quarter q (warps 4+q, 8+q, 12+q, 16+q: the 4 WGs' 32-col slices of the same 32 rows) -> one 128-thread named + // barrier per quarter (ids 2..5, unused CUTLASS-reserved ids in this kernel) instead of the 512-thread bar 12. + // The other job of bar 12 (ordering every thread's qh staging writes after the previous qh TMA store finished + // reading the staging tile, observed by thread 128's stg_sync) is done by each thread itself: parity wait on + // stg_free for this CTA's previous gate_up unit (completion index tile_iter - 2; GU units precede all DN units + // in a CTA's unit sequence, and the current unit's completion needs this thread's pub_full arrival -> at most + // one phase ahead, parity wait exact). Thread 128 keeps stg_sync (stg_waited bookkeeping for the DN path). + if constexpr (kTmaQh) { + if (threadIdx.x == 128) stg_sync(); // previous qh TMA store finished reading staging + else if (tile_iter >= 2) shared_storage.stg_free.wait((uint32_t)((tile_iter - 2) & 1)); + } + // row-major [128 rows][4 WGs] exchange: one STS.32 (slot g ^ ((row >> 3) & 3): the 32 rows of a warp hit 32 + // distinct banks) + ONE LDS.128 of the row's 4 partials (was 1 STS + 4 LDS.32). fmaxf over the same 4 values + // (all >= +0, order independent) -> bit-identical. + const uint32_t red32 = (uint32_t)__cvta_generic_to_shared(&shared_storage.amax_red[tile_iter & 1][0][0]) + + (uint32_t)row_local * 16u; + asm volatile("st.shared.f32 [%0], %1;" ::"r"(red32 + 4u * (uint32_t)(g ^ ((row_local >> 3) & 3))), "f"(amax) + : "memory"); + if constexpr (kTmaQh) named_bar_sync(2 + q, 128); + else asm volatile("bar.sync 12, %0;" ::"n"(NumEpilogueThreads) : "memory"); + { + float r0, r1, r2, r3; + asm volatile("ld.shared.v4.f32 {%0, %1, %2, %3}, [%4];" : "=f"(r0), "=f"(r1), "=f"(r2), "=f"(r3) : "r"(red32) + : "memory"); + amax = fmaxf(fmaxf(r0, r1), fmaxf(r2, r3)); + } + const float sc = fmaxf(amax * (1.0f / 448.0f), 1e-12f); + // rcp.rn.ftz (sc always normal -> == 1.0f / sc bit-for-bit) + float inv; + asm("rcp.rn.ftz.f32 %0, %1;" : "=f"(inv) : "f"(sc)); + const int nt = get<1>(cta_coord_mnkl); + const int Nh = N >> 1; // h width (= intermediate size) + if constexpr (kMerged) { + // ---- coalesced qh store (merged kernel) ---- + // Unit-boundary probe @M3712 (MO, clock64): the MMA warp idles ~3k cyc at kt 2 of every GU unit because the + // promotion boundary (epilogue ~3.5k + publish + restart) outlasts the 2-k-block TMEM ring. ~1k of the + // epilogue was the qh store: each thread wrote 32 B of its OWN row (2 x st.v4) -> every warp store touched + // 32 different 128 B lines (1024 L1 transactions per CTA tile). Now: phase 1 writes the thread's 32 fp8 + // bytes into a 128 x 128 B smem tile (WG0's epi_stage region, 128B-swizzled: 16 B chunk c of row r at + // c ^ (r & 7), conflict-free), CTA barrier, phase 2: thread t copies 16 B chunks j = t, t + 512 (row j/8, + // chunk j%8) -> one warp store = 4 full contiguous 128 B row segments (128 transactions per tile). + // 4 h (2 packed bf16x2 words) * inv with packed mul.rn.f32x2 + cvt.rn.satfinite.e4m3x2 (cq_q4p: same RN + // products / byte order as the former scalar acc[i] * inv path) + uint32_t w[8]; + CUTLASS_PRAGMA_UNROLL + for (int j = 0; j < 8; ++j) w[j] = cq_q4p(hw[2 * j], hw[2 * j + 1], inv); + const uint32_t qs = (uint32_t)__cvta_generic_to_shared(shared_storage.epi_stage); + const uint32_t ra = qs + (uint32_t)row_local * 128u; + const uint32_t sw = (uint32_t)(row_local & 7); + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(ra + (((2u * g) ^ sw) << 4)), "r"(w[0]), + "r"(w[1]), "r"(w[2]), "r"(w[3]) : "memory"); + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(ra + (((2u * g + 1u) ^ sw) << 4)), "r"(w[4]), + "r"(w[5]), "r"(w[6]), "r"(w[7]) : "memory"); + // kTmaQh: the sh store is issued AFTER the staging proxy fence (the fence then does not wait on it) + if (!kTmaQh && g == 0 && row < M && (!kTailSplit || st_active)) params.fused_scale[(int64_t)nt * M + row] = sc; + if constexpr (kTmaQh) { + // the publisher warp TMA-stores the staged tile after all 512 pub_full arrivals (see kTmaQh) + fence_proxy_async_smem(); // this thread's staging writes -> visible to the async proxy (TMA) + if (g == 0 && row < M) // write-once sh, no L1 allocation (ordered by the pub_full arrive) + asm volatile("st.global.L1::no_allocate.f32 [%0], %1;" ::"l"(params.fused_scale + (int64_t)nt * M + row), "f"(sc) : "memory"); + } else { + named_bar_sync(13, NumEpilogueThreads); + // kTailSplit split unit: this split owns tile rows [sj*128/s, (sj+1)*128/s) of the reduced tile + const int r_lo = (kTailSplit && st_sj >= 0) ? st_sj * 128 / params.st_split : 0; + const int r_hi = (kTailSplit && st_sj >= 0) ? (st_sj + 1) * 128 / params.st_split : 128; + const int etid = (int)threadIdx.x - 128; // 0..511 + const int mrow0 = get<0>(cta_coord_mnkl) * 128; + uint8_t* qbase = reinterpret_cast(params.ptr_D) + nt * 128; + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 2; ++i) { + const int j = etid + 512 * i, r = j >> 3, c = j & 7; + 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"(qs + (uint32_t)r * 128u + ((uint32_t)(c ^ (r & 7)) << 4)) : "memory"); + if (mrow0 + r < M && (!kTailSplit || (r >= r_lo && r < r_hi))) *reinterpret_cast(qbase + (int64_t)(mrow0 + r) * Nh + c * 16) = v; + } + } // !kTmaQh + // (the publish below re-syncs all 512 threads before anyone rewrites this smem tile or WG0 reuses it) + } else + if (row < M && st_active) { + uint8_t* dst = reinterpret_cast(params.ptr_D) + (int64_t)row * Nh + nt * 128 + g * 32; + // packed e4m3x2 quant of the packed bf16x2 h words (cq_q4p == former scalar acc[i] * inv path) + uint32_t w[8]; + CUTLASS_PRAGMA_UNROLL + for (int j = 0; j < 8; ++j) w[j] = cq_q4p(hw[2 * j], hw[2 * j + 1], inv); + // ONE 256-bit store (st.global.v8.b32, sm_100) of the thread's 32 B (32 B aligned: g*32 within the + // row's 128 B h block) -> every store instruction writes full 32 B sectors (was 2 x 16 B half sectors) + asm volatile("st.global.v8.b32 [%0], {%1, %2, %3, %4, %5, %6, %7, %8};" ::"l"(dst), "r"(w[0]), "r"(w[1]), + "r"(w[2]), "r"(w[3]), "r"(w[4]), "r"(w[5]), "r"(w[6]), "r"(w[7]) : "memory"); + if (g == 0) params.fused_scale[(int64_t)nt * M + row] = sc; + } + } // full (non-wide) gate_up epilogue + if constexpr (kPub) { + // delegated publish: thread 128 claims the ring slot (publisher released its previous use; in practice + // never waits: one slot use per 2 gate_up units) and stores the M block, then every thread arrives + // (release.cta orders its qh / sh stores) and starts the next unit at once. The publish barrier that was + // here also ordered the qh staging-tile reads / amax_red reads before their next writers: those writers + // (next GU unit: after bar 12 of all 512 threads; DN TMA-store staging: after a full k loop that needs + // every thread's TMEM / scale-ring releases) cannot run before every thread finished this epilogue. + // ring index = this CTA's gate_up unit ordinal = tile_iter - 1 (every gate_up unit precedes every down unit in + // the CTA's increasing unit sequence), so no extra counter is live across the 104-register k loop + const uint32_t pi = (uint32_t)(tile_iter - 1); + const int sl = (int)(pi & 1u); + if ((int)threadIdx.x == 128) { + shared_storage.pub_empty[sl].wait(((pi >> 1) & 1u) ^ 1u); + shared_storage.pub_info[sl] = kTileRdy ? mg_mb * params.gu_tn + get<1>(cta_coord_mnkl) : mg_mb; + if constexpr (kTmaQh) { + shared_storage.pub_rc[sl][0] = get<0>(cta_coord_mnkl) * 128; + shared_storage.pub_rc[sl][1] = get<1>(cta_coord_mnkl) * 128; + } + shared_storage.pub_n = (int)pi + 1; + } + shared_storage.pub_full[sl].arrive(); + __syncwarp(); // code-motion boundary only: without it ptxas spills 64 B in the k loop (local 64 -> 0) + } else + if constexpr (kMerged) { + // publish: all 512 threads' qh / sh stores -> CTA barrier -> one release-add on the per-M-block arrival + // counter (down producers wait for 2 * gu_tn arrivals). This barrier also orders this tile's amax_red reads before the next fused tile's + // writes (down tiles in between break the tile-parity double buffering). + asm volatile("fence.proxy.async.global;" ::: "memory"); + named_bar_sync(13, NumEpilogueThreads); + if ((int)threadIdx.x == 128) + asm volatile("red.release.gpu.global.add.s32 [%0], 1;" ::"l"(params.mb_cnt + mg_mb) : "memory"); + } + st_finish(); + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + continue; + } + // wide half-block down unit: WG g's cols 256 (nt0 + (g>>1)) + 64 (g&1) (+128 for TMEM lanes 64-127) + const int col0 = (kHT_PR && hu) ? get<1>(cta_coord_mnkl) * kCtaN + (g >> 1) * 256 + (g & 1) * 64 + : get<1>(cta_coord_mnkl) * kCtaN + (kHalves ? (g & 1) * 128 + (g >> 1) * 64 : col_local); + auto clk_record = [&]() {}; + if constexpr (kBal160) { + // kBal40 epilogue: WG0 / WG1 own the 128B-swizzled staging tiles of cols [0,64) / [64,128) (one TMA store + // each, rows >= M / cols >= N clipped by TMA); every WG writes its bf16 pieces (16 B chunk c of row r at + // c ^ (r & 7)): x32 pieces WG0 -> tile 0 chunks 0-3, WG3 -> tile 0 chunks 4-7, WG1 -> tile 1 chunks 0-3; x8 + // pieces -> tile 1 chunk 4 (WG3) / 5 (WG0) / 6 (WG1) / 7 (WG2); WG2's x32 cols [128,160) -> direct 16 B stores. + // 512-thread named barrier 8 before (staging free: elects waited for the previous store's smem read) / after. + const bool elect = (threadIdx.x & 127) == 0; + // kLastRing160: on the CTA's LAST tile (no next work tile: always at the M384 bucket, 135 CTAs <= SMs) the + // A/B smem_A ring is idle (every MMA of this tile completed: all 4 WGs waited on every TMEM-full commit; no more + // TMA loads) -> stage the two 16 KB SWIZZLE_128B tiles in smem_A (1024 B aligned) instead of epi_stage: no + // bulk_wait_read0 for the previous tile's stores + no pre-staging 512-thread barrier. Same bytes -> bit-identical. + static_assert(sizeof(shared_storage.tensors.mainloop.smem_A) >= 2 * 16384, "kLastRing160: 2 x 16 KB in smem_A"); + const bool last_ring = !next_work_tile_info.is_valid(); + const uint32_t stg_base = last_ring ? (uint32_t)__cvta_generic_to_shared(shared_storage.tensors.mainloop.smem_A.begin()) + : (uint32_t)__cvta_generic_to_shared(shared_storage.epi_stage); + if (last_ring) { + fence_proxy_async_smem(); // async-proxy (TMA write / MMA read) use of the ring -> generic writes + } else { + if (elect && g < 2) bulk_wait_read0(); + named_bar_sync(8, NumEpilogueThreads); + } + const uint32_t rbx = stg_base + (uint32_t)row_local * 128u + + ((uint32_t)(row_local & 7) << 4); + auto put = [&](uint32_t tile, uint32_t c, int i0) { + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"((rbx + tile * 16384u) ^ (c << 4)), + "r"(pk_bf16x2(acc[i0 + 0], acc[i0 + 1])), "r"(pk_bf16x2(acc[i0 + 2], acc[i0 + 3])), + "r"(pk_bf16x2(acc[i0 + 4], acc[i0 + 5])), "r"(pk_bf16x2(acc[i0 + 6], acc[i0 + 7])) + : "memory"); + }; + if (g != 2) { + const uint32_t t32 = g == 1 ? 1u : 0u, c32 = g == 3 ? 4u : 0u; + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < 4; ++c) put(t32, c32 + (uint32_t)c, c * 8); + } + put(1u, g == 0 ? 5u : g == 1 ? 6u : g == 2 ? 7u : 4u, 32); + fence_proxy_async_smem(); + if (g == 2 && row < M && col0 < N) { + __nv_bfloat16* dst = reinterpret_cast<__nv_bfloat16*>(params.ptr_D) + (int64_t)row * params.ldd + col0; + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < 4; ++c) + *reinterpret_cast(dst + c * 8) = + make_uint4(pk_bf16x2(acc[c * 8 + 0], acc[c * 8 + 1]), pk_bf16x2(acc[c * 8 + 2], acc[c * 8 + 3]), + pk_bf16x2(acc[c * 8 + 4], acc[c * 8 + 5]), pk_bf16x2(acc[c * 8 + 6], acc[c * 8 + 7])); + } + named_bar_sync(8, NumEpilogueThreads); + if (elect && g < 2) + tma_store_2d(¶ms.tmap_d, stg_base + (uint32_t)g * 16384u, + col0, get<0>(cta_coord_mnkl) * 128); + clk_record(); + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + continue; + } + if constexpr (kN224) if (g >= kHalfWg) { + if constexpr (kBal224) { + // kBal224 WG3: bf16 pieces [64b+56, +8) (acc[32+8b..]) -> chunk 3 of WG b's second-half SWIZZLE_64B + // staging tile; pre barrier = WG b's buffer free (its elect waited for the first half's smem read) + const uint32_t sbase = (uint32_t)__cvta_generic_to_shared(shared_storage.epi_stage) + (uint32_t)row_local * 64u + + ((uint32_t)(3 ^ ((row_local >> 1) & 3)) << 4); + CUTLASS_PRAGMA_UNROLL + for (int b = 0; b < 3; ++b) { + named_bar_sync(12 + b, 256); + const int i0 = 32 + 8 * b; + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(sbase + (uint32_t)b * 8192u), + "r"(pk_bf16x2(acc[i0 + 0], acc[i0 + 1])), "r"(pk_bf16x2(acc[i0 + 2], acc[i0 + 3])), + "r"(pk_bf16x2(acc[i0 + 4], acc[i0 + 5])), "r"(pk_bf16x2(acc[i0 + 6], acc[i0 + 7])) + : "memory"); + fence_proxy_async_smem(); + named_bar_sync(12 + b, 256); + } + } + // kN224 WG3: its 32 columns [192, 224) of the tile -> direct 16 B stores (64 contiguous bytes per row); the + // 64-col TMA box would spill into the neighbouring tile. kN160: WG2 cols [128, 160) (partial last N tile: + // predicated on col0 < N, N % 32 == 0), WG3 idle. + if (g == kHalfWg && row < M && col0 < N) { + __nv_bfloat16* dst = reinterpret_cast<__nv_bfloat16*>(params.ptr_D) + (int64_t)row * params.ldd + col0; + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < 4; ++c) { + __nv_bfloat162 b0 = __floats2bfloat162_rn(acc[c * 8 + 0], acc[c * 8 + 1]); + __nv_bfloat162 b1 = __floats2bfloat162_rn(acc[c * 8 + 2], acc[c * 8 + 3]); + __nv_bfloat162 b2 = __floats2bfloat162_rn(acc[c * 8 + 4], acc[c * 8 + 5]); + __nv_bfloat162 b3 = __floats2bfloat162_rn(acc[c * 8 + 6], acc[c * 8 + 7]); + *reinterpret_cast(dst + c * 8) = + make_uint4(*reinterpret_cast(&b0), *reinterpret_cast(&b1), + *reinterpret_cast(&b2), *reinterpret_cast(&b3)); + } + } + clk_record(); + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + continue; + } + if constexpr (kEpiStage) if (kTmaStore || mg_dn) { + // kMerged: the staging WG may still be reading the last gate_up tile from this region + if constexpr (kStg) shared_storage.stg_empty.wait(stg_empty_phase); + if constexpr (kCq) { + // ---- kCq: halved staging. The WG's 128 rows x 64 cols go out as two 32-col halves (64 B rows, + // SWIZZLE_64B: 16 B chunk c of row r at c ^ ((r >> 1) & 3), conflict-free per quarter warp), one TMA store + // each. WG0 stages both halves in its 16 KB region at once; WG1-3 reuse one 8 KB buffer (wait until the + // first store has read it). + const uint32_t sb0 = (uint32_t)__cvta_generic_to_shared(shared_storage.epi_stage) + + (wg == 0 ? 0u : 16384u + (uint32_t)(wg - 1) * 8192u); + const bool elect = (threadIdx.x & 127) == 0; + const int orow0 = get<0>(cta_coord_mnkl) * 128; + if (elect) bulk_wait_read0(); // all earlier stores of this WG (both halves) finished reading smem + if constexpr (kTmaQh) if (threadIdx.x == 128) stg_sync(); + // once all 4 converter warps are done (monotonic flag cq_done, acquired by the elect thread), WG1-3 stage + // their second half in the idle converter ring (8 KB each): no wait for the first half's TMA store to read smem + // between the two halves. The decision is published in cq_rok[wg] before the WG barrier (ordered by it; the + // previous unit's readers passed this WG's later barrier first) and re-read at the second half, so nothing + // extra stays live in the 104-register promotion warps. + if (elect) { + int dn_ = 0; + if (kRegs_ && wg != 0) // kRegs_=false: probe-only alternate keeps the path + asm volatile("ld.acquire.cta.shared::cta.s32 %0, [%1];" : "=r"(dn_) + : "r"((uint32_t)__cvta_generic_to_shared(&shared_storage.cq_done)) : "memory"); + shared_storage.cq_rok[wg] = dn_ >= 4; + } + named_bar_sync(8 + wg, 128); + CUTLASS_PRAGMA_UNROLL + for (int h = 0; h < 2; ++h) { + int ring_ok = 0; + if (h == 1 && wg != 0) { + asm volatile("ld.shared.s32 %0, [%1];" : "=r"(ring_ok) + : "r"((uint32_t)__cvta_generic_to_shared(&shared_storage.cq_rok[0]) + 4u * (uint32_t)wg) : "memory"); + if (!ring_ok) { if (elect) bulk_wait_read0(); named_bar_sync(8 + wg, 128); } + } + // second half: WG0 its own upper 8 KB, WG1-3 the converter ring (ring_ok) or the reused 8 KB buffer + const uint32_t sb = h == 0 ? sb0 + : (wg == 0 ? sb0 + 8192u + : (ring_ok ? (uint32_t)__cvta_generic_to_shared(shared_storage.cq_ring) + + (uint32_t)(wg - 1) * 8192u + : sb0)); + // kPadDn: padding rows (>= M, half-filled last M block) skip the bf16 convert + staging stores + // (their staging bytes are never stored: the TMA store clips rows >= M) + const bool live_row = orow0 + row_local < M; + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < 4; ++c) { + if (!live_row) break; + const int i0 = h * 32 + c * 8; + __nv_bfloat162 b0 = __floats2bfloat162_rn(acc[i0 + 0], acc[i0 + 1]); + __nv_bfloat162 b1 = __floats2bfloat162_rn(acc[i0 + 2], acc[i0 + 3]); + __nv_bfloat162 b2 = __floats2bfloat162_rn(acc[i0 + 4], acc[i0 + 5]); + __nv_bfloat162 b3 = __floats2bfloat162_rn(acc[i0 + 6], acc[i0 + 7]); + const uint32_t a = sb + (uint32_t)row_local * 64u + ((uint32_t)(c ^ ((row_local >> 1) & 3)) << 4); + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(a), + "r"(*reinterpret_cast(&b0)), "r"(*reinterpret_cast(&b1)), + "r"(*reinterpret_cast(&b2)), "r"(*reinterpret_cast(&b3)) + : "memory"); + } + fence_proxy_async_smem(); + named_bar_sync(8 + wg, 128); + if (elect) tma_store_2d_hint(¶ms.tmap_d32, sb, col0 + 32 * h, orow0, l2_pol_evict_first()); + } + clk_record(); + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + continue; + } + if constexpr (kHalfStg) { + // ---- kHalfStg: two 32-col halves through one 8 KB SWIZZLE_64B buffer per WG (16 B chunk c of row r at + // c ^ ((r >> 1) & 3), conflict-free per quarter warp), one TMA store per half (rows >= M clipped by TMA) + const uint32_t sb = (uint32_t)__cvta_generic_to_shared(shared_storage.epi_stage) + (uint32_t)wg * 8192u; + const bool elect = (threadIdx.x & 127) == 0; + const int orow0 = get<0>(cta_coord_mnkl) * 128; + // kLastRing: on the CTA's LAST tile (no next work tile: always at the M512 bucket, 128 tiles <= SMs) the + // A/B smem_A ring is idle (every MMA of this tile completed: this thread waited on all its TMEM-full commits; + // no further TMA loads) -> the second 32-col half goes to a fresh 8 KB slot of smem_A (WG wg at +8 KB wg) + // instead of reusing the WG buffer, so it no longer waits for the first half's TMA store to read smem + // (bulk_wait_read0 + WG barrier removed). Same bytes / stores -> bit-identical. + static_assert(sizeof(shared_storage.tensors.mainloop.smem_A) >= 3 * 8192, "kLastRing: 3 x 8 KB in smem_A"); + const bool last_ring = !kBal224 && !next_work_tile_info.is_valid(); + CUTLASS_PRAGMA_UNROLL + for (int h = 0; h < 2; ++h) { + const bool ring_h = h == 1 && last_ring; + const uint32_t sbh = ring_h ? (uint32_t)__cvta_generic_to_shared(shared_storage.tensors.mainloop.smem_A.begin()) + + (uint32_t)wg * 8192u + : sb; + // kBal224: second half joined by WG3 (writes chunk 3 = slice cols 56..63) on barrier 12 + wg + const int bid = (kBal224 && h == 1) ? 12 + wg : 8 + wg, bn = (kBal224 && h == 1) ? 256 : 128; + if (ring_h) { + fence_proxy_async_smem(); // async-proxy (TMA write / MMA read) use of the ring slot -> generic writes + } else { + if (elect) bulk_wait_read0(); // previous store from this buffer finished reading smem + named_bar_sync(bid, bn); + } + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < ((kBal224 && h == 1) ? 3 : 4); ++c) { + const int i0 = h * 32 + c * 8; + const uint32_t a = sbh + (uint32_t)row_local * 64u + ((uint32_t)(c ^ ((row_local >> 1) & 3)) << 4); + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(a), + "r"(pk_bf16x2(acc[i0 + 0], acc[i0 + 1])), "r"(pk_bf16x2(acc[i0 + 2], acc[i0 + 3])), + "r"(pk_bf16x2(acc[i0 + 4], acc[i0 + 5])), "r"(pk_bf16x2(acc[i0 + 6], acc[i0 + 7])) + : "memory"); + } + fence_proxy_async_smem(); + named_bar_sync(bid, bn); + // final bf16 output is never re-read on the GPU -> L2 evict_first (keeps qWd / qh resident) + if (elect) tma_store_2d_hint(¶ms.tmap_d32, sbh, col0 + 32 * h, orow0, l2_pol_evict_first()); + } + clk_record(); + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + continue; + } + // ---- TMA-store epilogue: this warpgroup's 128 rows x 64 cols -> smem (SWIZZLE_128B) -> one TMA store ---- + // Row r occupies bytes [128r, +128); its 16 B chunk c lives at chunk (c ^ (r & 7)) (TMA 128B swizzle, + // buffer 1024 B aligned). Each quarter-warp's 8 rows hit 8 distinct chunks -> conflict-free st.shared.v4. + uint8_t* buf = shared_storage.epi_stage + wg * (128 * 128); + const uint32_t sbuf = (uint32_t)__cvta_generic_to_shared(buf); + const bool elect = (threadIdx.x & 127) == 0; // first thread of the warpgroup owns its bulk group + if (elect) bulk_wait_read0(); // previous tile's store has finished reading the buffer + if constexpr (kTmaQh) if (threadIdx.x == 128) stg_sync(); // WG0 region: last qh TMA store read done + named_bar_sync(8 + wg, kBal160 ? 256 : 128); // kBal160: + WG3 (writes chunks 6,7) + // row base with the swizzle pre-applied: sbuf is 1024 B aligned and row_local * 128 has bits 4-6 clear, + // so rb ^ (c << 4) == sbuf + 128 row + ((c ^ (row & 7)) << 4) -> one immediate XOR per 16 B store; packing via + // one cvt.rn.bf16x2.f32 per column pair (== __floats2bfloat162_rn, low half = first value) + const uint32_t rbx = sbuf + (uint32_t)row_local * 128u + ((uint32_t)(row_local & 7) << 4); + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < (kBal160 ? 6 : 8); ++c) { + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(rbx ^ ((uint32_t)c << 4)), + "r"(pk_bf16x2(acc[c * 8 + 0], acc[c * 8 + 1])), "r"(pk_bf16x2(acc[c * 8 + 2], acc[c * 8 + 3])), + "r"(pk_bf16x2(acc[c * 8 + 4], acc[c * 8 + 5])), "r"(pk_bf16x2(acc[c * 8 + 6], acc[c * 8 + 7])) + : "memory"); + } + fence_proxy_async_smem(); // make generic-proxy smem writes visible to the TMA (async proxy) + named_bar_sync(8 + wg, kBal160 ? 256 : 128); + // TMA clips rows >= M (partial last M tile) + if (kHT_PR && hu) { + // wide unit: staging rows 0-63 = output rows x cols [col0, +64), rows 64-127 = same rows x cols col0 + 128 + // (TMEM lanes 64-127). copied out by the WG's 128 threads with coalesced 16 B stores (8 threads per + // 128 B row segment), rows >= M skipped (no 64-row TMA map in the kernel params). + uint32_t crank; + asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(crank)); + const int rb = kClTileM * mg_mb + 64 * (int)(crank & 1u); + const int t = (int)(threadIdx.x & 127); + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 8; ++i) { + const int j = t + 128 * i, r = j >> 3, c = j & 7; + const int orow = rb + (r & 63); + 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"(sbuf + (uint32_t)r * 128u + ((uint32_t)(c ^ (r & 7)) << 4)) : "memory"); + if (orow < M) + *reinterpret_cast(params.out_d + (int64_t)orow * params.dn_n + col0 + (r >> 6) * 128 + c * 8) = v; + } + } else + if (elect) { + // merged kernel: the final bf16 output is never re-read on the GPU -> evict_first (keeps the fp8 + // weights / qh resident in L2 for the remaining units) + if constexpr (kMerged) tma_store_2d_hint(¶ms.tmap_d, sbuf, col0, get<0>(cta_coord_mnkl) * 128, l2_pol_evict_first()); + else tma_store_2d(¶ms.tmap_d, sbuf, col0, get<0>(cta_coord_mnkl) * 128); + } + clk_record(); + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + continue; + } + if (row < M && st_active) { + __nv_bfloat16* dst = reinterpret_cast<__nv_bfloat16*>(params.ptr_D) + (int64_t)row * params.ldd + col0; + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < kWgCols / 8; ++c) { + if (col0 + c * 8 + 8 <= N) { + uint4 v; + __nv_bfloat162 b0 = __floats2bfloat162_rn(acc[c * 8 + 0], acc[c * 8 + 1]); + __nv_bfloat162 b1 = __floats2bfloat162_rn(acc[c * 8 + 2], acc[c * 8 + 3]); + __nv_bfloat162 b2 = __floats2bfloat162_rn(acc[c * 8 + 4], acc[c * 8 + 5]); + __nv_bfloat162 b3 = __floats2bfloat162_rn(acc[c * 8 + 6], acc[c * 8 + 7]); + v.x = *reinterpret_cast(&b0); + v.y = *reinterpret_cast(&b1); + v.z = *reinterpret_cast(&b2); + v.w = *reinterpret_cast(&b3); + *reinterpret_cast(dst + c * 8) = v; + } + } + } + st_finish(); + clk_record(); + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + } while (!kPair && work_tile_info.is_valid()); + if constexpr (kEpiStage) { + if ((threadIdx.x & 127) == 0) bulk_wait_all0(); // all output stores complete before exit + } + if constexpr (kPub) { // rank 1: terminate its publisher warp (rank 0's scheduler warp counts its own units) + uint32_t crank; // re-read (volatile): keeps the cluster rank from being live across the k loop + asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(crank)); + if (crank != 0) { + // pub_n (zeroed at init) was last written by thread 128 in this CTA's last gate_up epilogue: barrier, then all read + named_bar_sync(13, NumEpilogueThreads); + const uint32_t pi = (uint32_t)shared_storage.pub_n; + const int sl = (int)(pi & 1u); + if ((int)threadIdx.x == 128) { + shared_storage.pub_empty[sl].wait(((pi >> 1) & 1u) ^ 1u); + shared_storage.pub_info[sl] = -1; + } + shared_storage.pub_full[sl].arrive(); + } + } + if constexpr (kStg) { // terminate the staging WG (after it released the last real tile) + shared_storage.stg_empty.wait(stg_empty_phase); + if (threadIdx.x == 128) shared_storage.stg_info[3] = 1; + shared_storage.stg_full.arrive(); + } + } else if (is_stg) { + if constexpr (kStg) { + cutlass::arch::warpgroup_reg_dealloc(); + const int r = (int)threadIdx.x - (int)(128 + NumEpilogueThreads); // 0..127 + const uint32_t sb = (uint32_t)__cvta_generic_to_shared(shared_storage.epi_stage) + r * 128; + const int sw = r & 7; + const int Nh = N >> 1; + uint32_t full_phase = 0; + while (true) { + shared_storage.stg_full.wait(full_phase); + full_phase ^= 1; + const int mt = shared_storage.stg_info[0], nt = shared_storage.stg_info[1], mb = shared_storage.stg_info[2]; + if (shared_storage.stg_info[3]) break; + // 32-register budget -> strictly 8 columns (one 16 B gate chunk + its 16 B up chunk) in flight; h is + // computed in place of the gate words. The volatile smem asm keeps load/compute/store in program order, so + // ptxas cannot hoist later chunks' loads (which would need more live registers). + uint32_t mbits = 0; // packed |h| bit-max (h >= 0 ordering == unsigned bits & 0x7fff) + CUTLASS_PRAGMA_NO_UNROLL + for (int gg = 0; gg < 4; ++gg) { + const uint32_t rb = sb + gg * (128 * 128); + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < 4; ++c) { + uint32_t gw[4], uw[4]; + const uint32_t ag = rb + ((c ^ sw) << 4), au = rb + (((c + 4) ^ sw) << 4); + asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4];" + : "=r"(gw[0]), "=r"(gw[1]), "=r"(gw[2]), "=r"(gw[3]) : "r"(ag) : "memory"); + asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4];" + : "=r"(uw[0]), "=r"(uw[1]), "=r"(uw[2]), "=r"(uw[3]) : "r"(au) : "memory"); + CUTLASS_PRAGMA_UNROLL + for (int j = 0; j < 4; ++j) { // packed bf16x2: silu(g) rounded to bf16, times bf16 up (one RN) + const float g0 = __uint_as_float(gw[j] << 16), g1 = __uint_as_float(gw[j] & 0xffff0000u); + const __nv_bfloat162 sl = __floats2bfloat162_rn(silu_tanh(g0), silu_tanh(g1)); + const __nv_bfloat162 h2 = __hmul2(sl, *reinterpret_cast(&uw[j])); + gw[j] = *reinterpret_cast(&h2); + mbits = __vmaxu2(mbits, gw[j] & 0x7fff7fffu); + } + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(ag), "r"(gw[0]), "r"(gw[1]), "r"(gw[2]), + "r"(gw[3]) : "memory"); + } + } + const uint32_t mh = max(mbits & 0xffffu, mbits >> 16); + const float amax = __uint_as_float(mh << 16); + const float sc = fmaxf(amax * (1.0f / 448.0f), 1e-12f); + const float inv = __frcp_rn(sc); + const int row = mt * 128 + r; + uint8_t* dst = reinterpret_cast(params.ptr_D) + (int64_t)row * Nh + nt * 128; + // quantize: 16 h (two 16 B smem chunks) -> one 16 B fp8 store at a time (8 data registers live) + CUTLASS_PRAGMA_NO_UNROLL + for (int gg = 0; gg < 4; ++gg) { + const uint32_t rb = sb + gg * (128 * 128); + CUTLASS_PRAGMA_UNROLL + for (int cp = 0; cp < 2; ++cp) { + uint32_t o[4]; + CUTLASS_PRAGMA_UNROLL + for (int h = 0; h < 2; ++h) { + const int c = 2 * cp + h; + uint32_t hw[4]; + asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4];" + : "=r"(hw[0]), "=r"(hw[1]), "=r"(hw[2]), "=r"(hw[3]) : "r"(rb + ((c ^ sw) << 4)) : "memory"); + CUTLASS_PRAGMA_UNROLL + for (int j = 0; j < 2; ++j) { + const float a0 = __uint_as_float(hw[2 * j] << 16), a1 = __uint_as_float(hw[2 * j] & 0xffff0000u); + const float b0 = __uint_as_float(hw[2 * j + 1] << 16), b1 = __uint_as_float(hw[2 * j + 1] & 0xffff0000u); + const uint32_t lo = (uint32_t)__nv_cvt_float2_to_fp8x2(make_float2(a0 * inv, a1 * inv), __NV_SATFINITE, __NV_E4M3); + const uint32_t hi = (uint32_t)__nv_cvt_float2_to_fp8x2(make_float2(b0 * inv, b1 * inv), __NV_SATFINITE, __NV_E4M3); + o[2 * h + j] = lo | (hi << 16); + } + } + if (row < M) *reinterpret_cast(dst + gg * 32 + cp * 16) = make_uint4(o[0], o[1], o[2], o[3]); + } + } + if (row < M) params.fused_scale[(int64_t)nt * M + row] = sc; + shared_storage.stg_empty.arrive(); // staging reads done (stores are from registers) + // publish (as ): qh / sh stores of all 128 threads -> WG barrier -> one release reduction + asm volatile("fence.proxy.async.global;" ::: "memory"); + named_bar_sync(14, NumStgThreads); // id 14: only ping-pong kernels use it otherwise + if (r == 0) asm volatile("red.release.gpu.global.add.s32 [%0], 1;" ::"l"(params.mb_cnt + mb) : "memory"); + } + } else if constexpr (kCq_) { + // ---------------- converter warpgroup (kCq): in-kernel fp8 quantization of x and the down weights ---------- + // Every warp runs its own pipeline: claims chunks (16 rows x 128 k, see CqArgs) one ticket at a time in + // increasing order, double-buffers their bf16 TMA loads in its 2 ring slots, converts a chunk with the whole warp + // (lane: one row half; x: 1x128 row amax scale = max(amax/448, 1e-12); down: given 128x128 scale; reciprocal + // multiply, satfinite e4m3 == quant kernel) straight to qx / sx / qWd (16 B stores), then publishes it + // (fence.proxy.async + red.release, deferred while consecutive chunks hit the same counter). + cutlass::arch::warpgroup_reg_dealloc(); + cutlass::arch::wait_on_dependent_grids(); // ticket / counters zeroed by the quant kernel + if (params.cq.on) { + // register-lean converter (24 registers / thread): kept ~15 loop-carried values (lane / warp ids, ring + // addresses, claim window, list size, ...) live across the chunk loop and spilled 64 B (LDL / STL around every + // e4m3 convert). Now every per-thread constant is re-derived from a VOLATILE %tid.x read at its use (cannot be + // hoisted / kept live), the list size / claim size come from the param constant bank, and lane 0's claim window + // {c_cur, c_end, c_nb} lives in a per-warp smem slot (cq_cl). Loop-carried registers: it, pend_r, pend_n. + // Same claims, TMA loads, conversions, stores and publishes as (bit-identical). + constexpr uint32_t kCqT0 = 128 + NumEpilogueThreads; // first converter thread + auto vtid = []() -> uint32_t { uint32_t v; asm volatile("mov.u32 %0, %%tid.x;" : "=r"(v)); return v; }; + // chunk c -> descriptor r0 | kb << 23 | kind << 30 (kind 0 x, 1 down), -1 beyond the list + auto decode = [&](int c) -> int { + const CqArgs& a = params.cq; + if (c >= cq_total(a)) return -1; + const int KB1 = a.Hd >> 7, nA = KB1 * a.r1, nD = cq_nd(a); + if (c >= nA && c < nA + nD) { + constexpr int kPerKb = 256 / kCqRows; + const int per = kPerKb * (a.I >> 7), d = c - nA, sl = d / per, w = d - sl * per; + const int kb = w / kPerKb, r0 = (a.ds0 + sl) * 256 + (w % kPerKb) * kCqRows; + return r0 | (kb << 23) | (1 << 30); + } + int base = 0, R = a.r1; + if (c >= nA) { c -= nA + nD; base = a.r1; R = cq_nr(a) - a.r1; } + const int gsz = KB1 * a.rg, g = c / gsz, w = c - g * gsz; + int rows = R - g * a.rg; + if (rows > a.rg) rows = a.rg; + const int kb = w / rows; + return ((a.xr0 + base + g * a.rg + (w - kb * rows)) * kCqRows) | (kb << 23); + }; + // tickets are claimed cb at a time, one claim ahead (lane 0; the atomic's latency overlaps conversions) + // lane 0: cq_cl[cw] = {c_cur, c_end, c_nb}: current claim [c_cur, c_end), start of the claim after it + if ((vtid() & 31u) == 0) { + int* cl = shared_storage.cq_cl[(vtid() - kCqT0) >> 5]; + const int c0 = atomicAdd(params.cq.ticket, params.cq.cb); + cl[0] = c0; cl[1] = c0 + params.cq.cb; cl[2] = atomicAdd(params.cq.ticket, params.cq.cb); + } + // claim the next chunk into slot s (lane 0) and start its 4 KB TMA load (or complete the barrier: none left) + auto issue = [&](int s) { + const uint32_t tid = vtid(); + if ((tid & 31u) == 0) { + const int cw = (int)((tid - kCqT0) >> 5); + int* cl = shared_storage.cq_cl[cw]; + int c_cur = cl[0]; + if (c_cur == cl[1]) { + c_cur = cl[2]; + cl[1] = c_cur + params.cq.cb; + cl[2] = atomicAdd(params.cq.ticket, params.cq.cb); + } + cl[0] = c_cur + 1; + const int d = decode(c_cur); + const int sl = 2 * cw + s; + const uint32_t bar = (uint32_t)__cvta_generic_to_shared(&shared_storage.cq_bar[0]) + (uint32_t)sl * 8u; + shared_storage.cq_id[sl] = d; + if (d < 0) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(bar) : "memory"); + } else { + const uint32_t dsts = (uint32_t)__cvta_generic_to_shared(shared_storage.cq_ring) + (uint32_t)sl * (kCqRows * 256u); + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(bar), "r"((uint32_t)kCqRows * 256u) : "memory"); + // on & 2 -> the bf16 source (read exactly once) is loaded with an L2 evict_first hint + if (params.cq.on & 2) + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%3, %4}], [%2], %5;" + ::"r"(dsts), "l"((d >> 30) ? ¶ms.cq.tm_d : ¶ms.cq.tm_x), "r"(bar), + "r"(((d >> 23) & 127) * 128), "r"(d & 0x7fffff), "l"(l2_pol_evict_first()) : "memory"); + else + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1, {%3, %4}], [%2];" + ::"r"(dsts), "l"((d >> 30) ? ¶ms.cq.tm_d : ¶ms.cq.tm_x), "r"(bar), + "r"(((d >> 23) & 127) * 128), "r"(d & 0x7fffff) : "memory"); + } + } + __syncwarp(); + }; + issue(0); + issue(1); + constexpr int kCqPub = 8; + int pend_r = 0, pend_n = 0; + auto flush = [&]() { + if (pend_n > 0) { + asm volatile("fence.proxy.async.global;" ::: "memory"); // this lane's stores -> later TMA reads + __syncwarp(); + if ((vtid() & 31u) == 0) // release (cumulative over the warp's stores ordered by __syncwarp) + asm volatile("red.release.gpu.global.add.s32 [%0], %1;" ::"l"(params.cq.ready + pend_r), "r"(pend_n) + : "memory"); + __syncwarp(); + pend_n = 0; + } + }; + for (int it = 0;; ++it) { + const int s = it & 1; + const uint32_t tid = vtid(); + const uint32_t sl = ((tid - kCqT0) >> 5) * 2u + (uint32_t)s; // this warp's ring slot + asm volatile("{\n\t.reg .pred p;\n\tCQW_%=:\n\t" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n\t" + "@!p bra CQW_%=;\n\t}" ::"r"((uint32_t)__cvta_generic_to_shared(&shared_storage.cq_bar[0]) + sl * 8u), + "r"((uint32_t)((it >> 1) & 1)) : "memory"); + const int d = *reinterpret_cast(&shared_storage.cq_id[sl]); + if (d < 0) break; // tickets are increasing per warp: the other slot holds no chunk either + const int kind = d >> 30, kb = (d >> 23) & 127, r0 = d & 0x7fffff; + const CqArgs& a = params.cq; + const int lane = (int)(tid & 31u), row = lane >> 1, h = lane & 1; // lane: row of the chunk, 128 B half + float sc; + if (kind == 0) { + // 16 B piece pair m of this lane: pieces pa, pa + 1 (pa = 8h + ((2m + rot) & 7), rot = 2 (row & 3)) + const uint32_t rot = (uint32_t)(2 * (row & 3)); + const uint4* rbp = reinterpret_cast(shared_storage.cq_ring + (size_t)sl * (kCqRows * 256) + + (size_t)row * 256); + uint32_t mb = 0; + CUTLASS_PRAGMA_UNROLL + for (int m = 0; m < 4; ++m) { + const uint32_t pa = 8u * h + ((2u * m + rot) & 7u); + CUTLASS_PRAGMA_UNROLL + for (int e = 0; e < 2; ++e) { + const uint4 v = rbp[pa + (e ^ h)]; + mb = cq_bmax(mb, v.x); mb = cq_bmax(mb, v.y); mb = cq_bmax(mb, v.z); mb = cq_bmax(mb, v.w); + } + } + const uint32_t hm = max(mb & 0xffffu, mb >> 16); + float am = __uint_as_float(hm << 16); + am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, 1)); // the row's other 128 B half + sc = fmaxf(am * (1.0f / 448.0f), 1e-12f); + } else { + asm volatile("ld.global.nc.L1::no_allocate.f32 %0, [%1];" : "=f"(sc) : "l"(a.ds + kb * (a.Hd >> 7) + (r0 >> 7))); // read-once scale, no L1 allocation // chunk in one 128x128 block (small table: L1 hits) + } + // deferred publish of the previous chunks unless this chunk feeds the same counter + const int ridx = kind ? cq_nxc(a) + (r0 >> 8) * (a.I >> 7) + kb : (r0 >> 7) * (a.Hd >> 7) + kb; + if (pend_n > 0 && ridx != pend_r) flush(); + const int grow = r0 + row; + if (kind != 0 || grow < a.M) { // x rows >= Mr were zero-filled by the TMA (qx 0, scale 1e-12) + const float inv = __frcp_rn(sc); + uint8_t* dsth = (kind ? a.qwd + (size_t)grow * a.I : a.qx + (size_t)grow * a.Hd) + kb * 128 + 64u * (uint32_t)h; + const uint32_t lb = (uint32_t)__cvta_generic_to_shared(shared_storage.cq_ring) + sl * (kCqRows * 256u) + + (uint32_t)row * 256u + (uint32_t)h * 128u; + const uint32_t rq = (uint32_t)(row & 3); + // piece pair m at byte ((m + (row & 3)) & 3) * 32 of the lane's 128 B half; one 16 B store per pair + CUTLASS_PRAGMA_UNROLL + for (int m = 0; m < 4; ++m) { + const uint32_t po = (((uint32_t)m + rq) & 3u) * 32u; + uint4 v0, v1; + asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4];" : "=r"(v0.x), "=r"(v0.y), "=r"(v0.z), "=r"(v0.w) + : "r"(lb + po) : "memory"); + asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4+16];" : "=r"(v1.x), "=r"(v1.y), "=r"(v1.z), "=r"(v1.w) + : "r"(lb + po) : "memory"); + const uint4 qv = make_uint4(cq_q4p(v0.x, v0.y, inv), cq_q4p(v0.z, v0.w, inv), cq_q4p(v1.x, v1.y, inv), + cq_q4p(v1.z, v1.w, inv)); + if (a.on & 4) // fp8 output (qWd / qx), re-read by many units -> L2 evict_last store + asm volatile("st.global.L1::no_allocate.L2::cache_hint.v4.u32 [%0], {%1, %2, %3, %4}, %5;" ::"l"(dsth + (po >> 1)), + "r"(qv.x), "r"(qv.y), "r"(qv.z), "r"(qv.w), "l"(l2_pol_evict_last()) : "memory"); + else // no L1 allocation for the streamed fp8 converter output + asm volatile("st.global.L1::no_allocate.v4.u32 [%0], {%1, %2, %3, %4};" ::"l"(dsth + (po >> 1)), + "r"(qv.x), "r"(qv.y), "r"(qv.z), "r"(qv.w) : "memory"); + } + if (kind == 0 && h == 0) // write-once sx, no L1 allocation + asm volatile("st.global.L1::no_allocate.f32 [%0], %1;" ::"l"(a.sx + (size_t)kb * a.M + grow), "f"(sc) : "memory"); + } + // generic reads of the slot before its next async-proxy refill (same warp) + // no per-chunk WAR proxy fence: every slot read has been consumed into + // registers -> stores / shuffles before the __syncwarp below, and only then does lane 0 issue the slot's TMA + // refill (same consumer-read -> sync -> TMA-overwrite pattern as the CUTLASS TMA pipelines' consumer_release) + if (!(a.on & 8)) asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + pend_r = ridx; + if (++pend_n >= kCqPub) flush(); + issue(s); + } + flush(); + } // params.cq.on + // this warp no longer touches the ring (all its slots' TMA loads were consumed, generic reads ordered by + // the per-chunk fence + __syncwarp) -> one release arrival on cq_done + __syncwarp(); + if ((threadIdx.x & 31) == 0) + asm volatile("red.release.cta.shared::cta.add.s32 [%0], 1;" + ::"r"((uint32_t)__cvta_generic_to_shared(&shared_storage.cq_done)) : "memory"); + } + } else { + // warp 1 of a non-first cluster CTA (2SM: the odd CTA has no scheduler warp) + cutlass::arch::warpgroup_reg_dealloc(); + if constexpr (kPub) { + if (is_sched_warp) { // kPub: this CTA's M-block publisher until the terminate entry + uint32_t it = 0; + while (pub_one(it)) {} + } + } + } + // kPair: no CTA exits while its peer may still access its shared memory + if constexpr (kPair) { + // threads that did not take the deferred setup wait (all but the promotion warps) complete it here first + if (pair_split && !is_epi) asm volatile("barrier.cluster.wait.acquire;" ::: "memory"); + // kPairNoExit: no exit cluster barrier when the setup barrier is split. + // Every remote op INTO a CTA (peer's pair_bar[5] arrive, st.async partial chunks on pair_bar[4,6..8]) is consumed + // by that CTA's own mbarrier waits before it exits, and no CTA reads peer smem. + if (!pair_split) asm volatile("barrier.cluster.arrive.release;\n\tbarrier.cluster.wait.acquire;" ::: "memory"); + } + } +}; + +} // namespace se2wg diff --git a/kernels/Quant/017_fp8_shared_expert_mlp/src/kernel.cu b/kernels/Quant/017_fp8_shared_expert_mlp/src/kernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..7e7652db64b2351a5622fc7240ef0510e9459233 --- /dev/null +++ b/kernels/Quant/017_fp8_shared_expert_mlp/src/kernel.cu @@ -0,0 +1,1766 @@ +// FP8 shared-expert MLP (DeepSeek-V3) on B200 (sm_100a). +// +// Pipeline: main-stream launches chained with PDL (programmatic dependent launch); the down-weight quant is +// a PDL kernel between gate_up (/swiglu) and the down GEMM (no side stream). Historical notes below: +// was one side-stream launch +// (down_proj weight quant, forked after step 1 and joined before step 4, overlapping steps 2-3): +// 1. fused_quant_kernel : ONE launch quantizing x (1x128 per-row blocks, scale = max(amax/448,1e-12), +// sx MN-major [56][M]) AND gate/up bf16 weights with the given 128x128 block +// scales. 32 elements per thread (4x16B loads), packed bf16x2 unpack, +// packed bit-max amax, cvt e4m3x2 packing. gate and up are stacked into one +// [4096,7168] K-major matrix (scales into one [56][32] table) so gate_up is ONE GEMM. +// L2 policy: bf16 weights are read evict-first (__ldcs, streamed once) and all +// fp8 outputs (qx, qwgu, qwd) are stored with an L2::evict_last cache-hint policy +// so the following GEMMs read them from L2 (gate+up fp8 = 29MB, down 14MB << L2). +// Weight blocks are processed in REVERSE order so the rows quantized last +// (gate rows near n=0) are the ones the GEMM rasterization touches first. +// Launched normally (full serialization vs. the previous call), but it triggers +// launch_dependents early so the GEMM prologue can be scheduled during its tail. +// 3. swiglu_quant_kernel : PDL launch; griddepcontrol.wait, then h = bf16(bf16(silu(bf16 gate)) * bf16 up), +// re-quantized per 1x128 -> qh, sh. One warp per (row,128-block), one 16B load/lane. +#ifndef CUTLASS_ENABLE_GDC_FOR_SM100 +#define CUTLASS_ENABLE_GDC_FOR_SM100 1 +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cutlass/cutlass.h" +#include "cute/tensor.hpp" +#include "cutlass/numeric_types.h" +#include "cutlass/gemm/device/gemm_universal_adapter.h" +#include "cutlass/gemm/kernel/gemm_universal.hpp" +#include "cutlass/gemm/collective/collective_builder.hpp" +#include "cutlass/epilogue/collective/collective_builder.hpp" +#include "cutlass/detail/blockwise_scale_layout.hpp" +#include "cutlass/util/packed_stride.hpp" + +#include "kernel.h" +#include "bw2wg.h" + +using namespace cute; + +// PDL primitives (sm_90+): wait for the preceding grid's completion + memory flush / allow dependents to launch. +__device__ __forceinline__ void pdl_wait() { asm volatile("griddepcontrol.wait;" ::: "memory"); } +__device__ __forceinline__ void pdl_trigger() { asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); } + +// L2 evict_last access policy (fraction 1.0) + 16B store carrying that cache hint: keeps the fp8 GEMM +// operands resident in L2 for the consumer GEMM instead of being evicted by the streamed bf16 reads. +__device__ __forceinline__ uint64_t l2_evict_last_policy() { + uint64_t p; + asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(p)); + return p; +} +__device__ __forceinline__ void st_evict_last(void* ptr, uint4 v, uint64_t pol) { + asm volatile("st.global.L2::cache_hint.v4.u32 [%0], {%1, %2, %3, %4}, %5;" ::"l"(ptr), "r"(v.x), "r"(v.y), + "r"(v.z), "r"(v.w), "l"(pol) + : "memory"); +} + +__device__ __forceinline__ uint16_t f2_to_fp8x2(float a, float b) { + return (uint16_t)__nv_cvt_float2_to_fp8x2(make_float2(a, b), __NV_SATFINITE, __NV_E4M3); +} + +// Packed bf16x2 -> f32x2: bf16 is the top half of an fp32, so the conversion is one shift / one AND. +__device__ __forceinline__ float2 bf2_to_f2(uint32_t u) { + return make_float2(__uint_as_float(u << 16), __uint_as_float(u & 0xffff0000u)); +} + +// Packed |bf16x2| max on raw bits: for non-NaN values |v| ordering == unsigned ordering of (bits & 0x7fff), +// so __vmaxu2 reduces 2 elements per instruction. (NaN bits sort above Inf -> NaN scale, like torch amax.) +// one max.xorsign.abs.bf16x2 per word (|.| max per half; sign bits = xor, masked off in bits_amax_to_float) +// instead of LOP + VIMNMX: same magnitudes for non-NaN values -> bit-identical amax (== merged-kernel path) +__device__ __forceinline__ uint32_t absmax_bits(uint32_t m, uint32_t u) { + asm("max.xorsign.abs.bf16x2 %0, %0, %1;" : "+r"(m) : "r"(u)); + return m; +} +// half-merge via PRMT + max.xorsign.abs.bf16x2, then the low half's magnitude bits -> fp32 (sign masked) +__device__ __forceinline__ float bits_amax_to_float(uint32_t m) { + const uint32_t sw = __byte_perm(m, 0u, 0x1032); + uint32_t mm; + asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(mm) : "r"(m), "r"(sw)); + return __uint_as_float((mm & 0x7fffu) << 16); +} + +__device__ __forceinline__ uint32_t q4w(uint32_t a, uint32_t b, float inv) { return se2wg::cq_q4p(a, b, inv); } +// 8 bf16 (one uint4) -> 8 fp8 (one uint2) +__device__ __forceinline__ uint2 q8(uint4 r, float inv) { return make_uint2(q4w(r.x, r.y, inv), q4w(r.z, r.w, inv)); } + +// --------------------------------------------------------------------------------------------- +// ONE fused quantization launch covering x and all three weights. Every thread handles 32 consecutive +// elements (four 16B loads in flight, two 16B stores) to amortize index math and raise MLP. +// blocks [0, nbx) : x activations. 4 threads per (row, 128-wide K block) unit, 64 units +// per 256-thread block; amax via packed bit-max + 2 xor shuffles. +// blocks [nbx, nbx + k*nbw) : gate / up / down weights, 32 k per thread with the given 128x128 scale. +// Mapped in reverse (last launched block -> weight wbase, row 0). +// Gate/up are written stacked into one [2I, Hd] K-major matrix and their scales into sgu[56][2I/128]. +// --------------------------------------------------------------------------------------------- +struct QuantArgs { + const __nv_bfloat16* x; uint8_t* qx; float* sx; int M, Hd, I; + int Mr; // real x rows (<= M): rows [Mr, M) are the zero padding rows (M = Mr rounded up to a multiple of 4) + const __nv_bfloat16* gw; const float* gs; + const __nv_bfloat16* uw; const float* us; + const __nv_bfloat16* dw; const float* ds; + uint8_t* qgu; float* sgu; uint8_t* qd; + float* sgu64; float* sd64; // weight scales duplicated to 128(K)x64(N) granularity for the N=64 tile variant + float* sd32; // down weight scales at 128(K)x32(N) granularity (MN-major [K/128][N/32]) for the 256x224 down tile + int nbx, nbw; // block counts: x part, per-weight part + int wbase; // first weight handled by this launch (0 = gate [main stream], 2 = down [side stream]) + int* mb_cnt; int n_mb; // merged path: per-M-block arrival counters of THIS call, zeroed here (n_mb = 0: none) + int* z2; int nz2; int z2v; int z2a, z2b; // z2[z2a, z2b) preset to 16 (pre-quantized down slabs). kCq: conversion counters + ticket of THIS call, set to z2v (0; probe: prefill) + int dq_off; // first down-weight quant block handled by down_quant_pdl_kernel (blocks [0, dq_off) ran in the front pass) +}; + +// One weight quant unit: 32 consecutive k of row n of weight `which` (0 gate, 1 up, 2 down), thread-unit idx. +__device__ __forceinline__ void st_evict_last8(void* ptr, uint2 v, uint64_t pol) { + asm volatile("st.global.L2::cache_hint.v2.u32 [%0], {%1, %2}, %3;" ::"l"(ptr), "r"(v.x), "r"(v.y), "l"(pol) : "memory"); +} +// coalesced weight-quant mapping (kCoal): the WARP's element range is unchanged ([1024 w, +1024) of the flattened +// weight = 8 consecutive 128-k blocks of one row when K % 1024 == 0), only the lane -> element assignment is permuted: +// load i of lane l covers k0 + 256 i + 8 l (16 B), so every warp load instruction reads 512 contiguous bytes (4 full +// 128 B lines) and every 8 B store writes 256 contiguous bytes, instead of 32 lanes at a 64 B stride (each instruction +// touching 16 lines with half-used sectors, the same sectors re-requested by the next instruction). Each element is +// quantized with its own 128x128 block scale (lanes 0-15 / 16-31 of load i: k blocks 2i, 2i+1 of the warp) -> the +// output bytes are identical to the per-thread-contiguous mapping. Scale tables written by the same (k%128==0, +// n%128==0) elements as before. +__device__ __forceinline__ void quant_w_coal(const __nv_bfloat16* W, const float* S, uint8_t* Q, int N, int K, int which, + const QuantArgs& a, size_t idx, uint64_t pol) { + const int lane = (int)(idx & 31); + const size_t e0 = (idx - (size_t)lane) * 32; // first element of this warp's 1024 + const int n = (int)(e0 / (size_t)K); + const int k0 = (int)(e0 - (size_t)n * K); + const int nbN = N >> 7; + const __nv_bfloat16* src = W + (size_t)n * K + k0 + lane * 8; + uint4 r[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) r[i] = __ldcs(reinterpret_cast(src + i * 256)); // evict-first + const int qrow = which < 2 ? ((n >> 7) * 256 + which * 128 + (n & 127)) : n; + uint8_t* dst = Q + (size_t)qrow * K + k0 + lane * 8; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int k = k0 + i * 256 + lane * 8; + const float sc = __ldg(S + (k >> 7) * nbN + (n >> 7)); + const float inv = __frcp_rn(sc); + st_evict_last8(dst + i * 256, q8(r[i], inv), pol); // keep fp8 weights L2-resident for the GEMM + if ((k & 127) == 0 && (n & 127) == 0) { + if (which < 2) { + a.sgu[(k >> 7) * (2 * a.I / 128) + 2 * (n >> 7) + which] = sc; + float* p = a.sgu64 + (k >> 7) * (2 * a.I / 64) + 4 * (n >> 7) + 2 * which; + p[0] = sc; p[1] = sc; + } else { + float* p = a.sd64 + (k >> 7) * (a.Hd / 64) + 2 * (n >> 7); + p[0] = sc; p[1] = sc; + float* p32 = a.sd32 + (k >> 7) * (a.Hd / 32) + 4 * (n >> 7); + p32[0] = sc; p32[1] = sc; p32[2] = sc; p32[3] = sc; + } + } + } +} +// variant B: lane l -> 128-k block (l >> 2) of the warp's 8, piece p = l & 3; loads at 8p + 32i (one scale per thread, +// each warp load instruction = 8 blocks x 64 contiguous bytes), 4 x 8 B stores +__device__ __forceinline__ void quant_w_grp(const __nv_bfloat16* W, const float* S, uint8_t* Q, int N, int K, int which, + const QuantArgs& a, size_t idx, uint64_t pol) { + const int lane = (int)(idx & 31); + const size_t e0 = (idx - (size_t)lane) * 32; + const int n = (int)(e0 / (size_t)K); + const int k = (int)(e0 - (size_t)n * K) + (lane >> 2) * 128; // this thread's 128-k block + const int po = (lane & 3) * 8; + const __nv_bfloat16* src = W + (size_t)n * K + k + po; + uint4 r[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) r[i] = __ldcs(reinterpret_cast(src + i * 32)); + const int nbN = N >> 7; + const float sc = __ldg(S + (k >> 7) * nbN + (n >> 7)); + const float inv = __frcp_rn(sc); + const int qrow = which < 2 ? ((n >> 7) * 256 + which * 128 + (n & 127)) : n; + uint8_t* dst = Q + (size_t)qrow * K + k + po; +#pragma unroll + for (int i = 0; i < 4; ++i) st_evict_last8(dst + i * 32, q8(r[i], inv), pol); + if (po == 0 && (n & 127) == 0) { + if (which < 2) { + a.sgu[(k >> 7) * (2 * a.I / 128) + 2 * (n >> 7) + which] = sc; + float* p = a.sgu64 + (k >> 7) * (2 * a.I / 64) + 4 * (n >> 7) + 2 * which; + p[0] = sc; p[1] = sc; + } else { + float* p = a.sd64 + (k >> 7) * (a.Hd / 64) + 2 * (n >> 7); + p[0] = sc; p[1] = sc; + float* p32 = a.sd32 + (k >> 7) * (a.Hd / 32) + 4 * (n >> 7); + p32[0] = sc; p32[1] = sc; p32[2] = sc; p32[3] = sc; + } + } +} +// variant C: lane l -> 128-k blocks (l >> 3) and (l >> 3) + 4 of the warp's 8, 16-element piece j = l & 7 (32 B of +// bf16 per block, two adjacent 16 B loads), one 16 B fp8 store per block (each warp store instruction: 4 blocks x 128 +// contiguous bytes), 2 scales per thread +__device__ __forceinline__ void quant_w_c(const __nv_bfloat16* W, const float* S, uint8_t* Q, int N, int K, int which, + const QuantArgs& a, size_t idx, uint64_t pol) { + const int lane = (int)(idx & 31); + // index trim: warp ordinal / warps-per-row in 32-bit (K % 1024 == 0 on this path; N*K/1024 < 2^32), no 64-bit + // division: same (n, kw) as e0 = 1024 * w, n = e0 / K, kw = e0 - n K + const uint32_t w = (uint32_t)(idx >> 5), wpr = (uint32_t)K >> 10; + const int n = (int)(w / wpr); + const int kw = (int)((w - (uint32_t)n * wpr) << 10); + const int po = (lane & 7) * 16; + const int kA = kw + (lane >> 3) * 128, kB = kA + 512; + const __nv_bfloat16* rowp = W + (size_t)n * K; + uint4 r[4]; + r[0] = __ldcs(reinterpret_cast(rowp + kA + po)); + r[1] = __ldcs(reinterpret_cast(rowp + kA + po + 8)); + r[2] = __ldcs(reinterpret_cast(rowp + kB + po)); + r[3] = __ldcs(reinterpret_cast(rowp + kB + po + 8)); + const int nbN = N >> 7; + const float scA = __ldg(S + (kA >> 7) * nbN + (n >> 7)), scB = __ldg(S + (kB >> 7) * nbN + (n >> 7)); + const float invA = __frcp_rn(scA), invB = __frcp_rn(scB); + const int qrow = which < 2 ? ((n >> 7) * 256 + which * 128 + (n & 127)) : n; + uint8_t* dst = Q + (size_t)qrow * K + po; + const uint2 a0 = q8(r[0], invA), a1 = q8(r[1], invA), b0 = q8(r[2], invB), b1 = q8(r[3], invB); + st_evict_last(dst + kA, make_uint4(a0.x, a0.y, a1.x, a1.y), pol); + st_evict_last(dst + kB, make_uint4(b0.x, b0.y, b1.x, b1.y), pol); + if (po == 0 && (n & 127) == 0) { +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int k = h ? kB : kA; + const float sc = h ? scB : scA; + if (which < 2) { + a.sgu[(k >> 7) * (2 * a.I / 128) + 2 * (n >> 7) + which] = sc; + float* p = a.sgu64 + (k >> 7) * (2 * a.I / 64) + 4 * (n >> 7) + 2 * which; + p[0] = sc; p[1] = sc; + } else { + float* p = a.sd64 + (k >> 7) * (a.Hd / 64) + 2 * (n >> 7); + p[0] = sc; p[1] = sc; + float* p32 = a.sd32 + (k >> 7) * (a.Hd / 32) + 4 * (n >> 7); + p32[0] = sc; p32[1] = sc; p32[2] = sc; p32[3] = sc; + } + } + } +} +#ifndef SE_QCOAL +#define SE_QCOAL 137 // + bit 128 x reads evict-first. + bit 1 x-part coalesced mapping (4 lanes per 1x128 group, pieces l,l+4,l+8,l+12, 8 B stores); weight variant C +#endif +// kCoal bits: 1 x lane mapping, 2 weight variant B, 4 weight variant A, 8 weight variant C, 16/32 restrict to down / gate+up (0 = seed mapping) +template +__device__ __forceinline__ void quant_w_unit(const QuantArgs& a, int which, size_t idx, uint64_t pol) { + const __nv_bfloat16* W; const float* S; uint8_t* Q; int N, K; + if (which == 0) { W = a.gw; S = a.gs; Q = a.qgu; N = a.I; K = a.Hd; } + else if (which == 1) { W = a.uw; S = a.us; Q = a.qgu; N = a.I; K = a.Hd; } + else { W = a.dw; S = a.ds; Q = a.qd; N = a.Hd; K = a.I; } + int k32 = K >> 5; + if (idx >= (size_t)N * k32) return; + // bits 16 / 32: restrict the weight variant to the down weight / the gate+up weights (probe A/B) + const bool wsel = !((kCoal & 16) && which != 2) && !((kCoal & 32) && which == 2); + if (wsel && (kCoal & 8) && (K & 1023) == 0) { quant_w_c(W, S, Q, N, K, which, a, idx, pol); return; } + if (wsel && (kCoal & 4) && (K & 1023) == 0) { quant_w_coal(W, S, Q, N, K, which, a, idx, pol); return; } // warp-uniform + if (wsel && (kCoal & 2) && (K & 1023) == 0) { quant_w_grp(W, S, Q, N, K, which, a, idx, pol); return; } + int n = (int)(idx / k32); + int k = (int)(idx - (size_t)n * k32) * 32; + int nbN = N >> 7; + const uint4* src = reinterpret_cast(W + (size_t)n * K + k); + uint4 r0 = __ldcs(src), r1 = __ldcs(src + 1), r2 = __ldcs(src + 2), r3 = __ldcs(src + 3); // evict-first + float sc = __ldg(S + (k >> 7) * nbN + (n >> 7)); + const float inv = __frcp_rn(sc); + uint2 o0 = q8(r0, inv), o1 = q8(r1, inv), o2 = q8(r2, inv), o3 = q8(r3, inv); + const int qrow = which < 2 ? ((n >> 7) * 256 + which * 128 + (n & 127)) : n; + uint4* dst = reinterpret_cast(Q + (size_t)qrow * K + k); + st_evict_last(dst, make_uint4(o0.x, o0.y, o1.x, o1.y), pol); // keep fp8 weights L2-resident for the GEMM + st_evict_last(dst + 1, make_uint4(o2.x, o2.y, o3.x, o3.y), pol); + if (which < 2 && (k & 127) == 0 && (n & 127) == 0) + a.sgu[(k >> 7) * (2 * a.I / 128) + 2 * (n >> 7) + which] = sc; + if ((k & 127) == 0 && (n & 127) == 0) { + // 128x64-granular copy (MN-major [K/128][N/64]): each 128-wide N block's scale written twice + if (which < 2) { + float* p = a.sgu64 + (k >> 7) * (2 * a.I / 64) + 4 * (n >> 7) + 2 * which; + p[0] = sc; p[1] = sc; + } else { + float* p = a.sd64 + (k >> 7) * (a.Hd / 64) + 2 * (n >> 7); + p[0] = sc; p[1] = sc; + float* p32 = a.sd32 + (k >> 7) * (a.Hd / 32) + 4 * (n >> 7); + p32[0] = sc; p32[1] = sc; p32[2] = sc; p32[3] = sc; + } + } +} + + +// x-part lane mappings (kXV). All variants compute identical qx / sx bytes. +// 0: mapping (64 row-major units / block, 4 lanes per unit, 4 x 8 B stores per lane) +// 1: as 0, pieces exchanged between lane pairs (2 shfl.b64) -> 2 x 16 B stores per lane +// 2: 2-D tile mapping: block = 8 rows x 8 k blocks, warp = one k block x 8 rows (4 lanes per row) -> the 8 lane-0 +// sx stores of a warp hit 8 consecutive rows (one 32 B sector instead of 8 scattered 4 B writes) +// 3: 2 + 1 +// 4: 0 with 2 units per thread (8 x 16 B loads in flight), 128 units per block +#ifndef SE_XV +#define SE_XV 3 // probe (M3712, x part alone, us warm|flushed): v0 12.96|18.57, v3 12.43|17.40; full quant launch unchanged +#endif +// front fused-quant block size (was 256). 128-thread blocks -> twice the blocks, finer last-wave granularity in the +// DRAM-bound front pass; x tile = 8 rows x kFqKpb k blocks (one warp per k block), weight block = kFqTB 32-elem units +#ifndef SE_FQ_TB +#define SE_FQ_TB 128 +#endif +constexpr int kFqTB = SE_FQ_TB, kFqKpb = SE_FQ_TB / 32, kFqR = 256 / SE_FQ_TB; +static_assert(256 % SE_FQ_TB == 0 && SE_FQ_TB >= 32, "front quant block size divides the 256-thread weight unit accounting"); +// x blocks of the fused quant launch for mapping kXV +__host__ __device__ inline int xq_blocks(int xv, int M, int Hd) { + const int nkb = Hd >> 7; + if (xv == 2 || xv == 3) return ((M + 7) / 8) * ((nkb + kFqKpb - 1) / kFqKpb); + const long units = (long)M * nkb; + return (int)((units + (xv == 4 ? 127 : 63)) / (xv == 4 ? 128 : 64)); +} +template +__device__ __forceinline__ void quant_x_unit(const QuantArgs& a, int b, uint64_t pol) { + static_assert((kCoal & 1) != 0 && (kCoal & 64) == 0, "x variants assume the coalesced row-major mapping"); + const int nkb = a.Hd >> 7; + constexpr int NU = kXV == 4 ? 2 : 1; + const int lane = threadIdx.x & 3; + int row[NU], kb[NU]; + bool valid[NU]; + if constexpr (kXV == 2 || kXV == 3) { + const int nkt = (nkb + kFqKpb - 1) / kFqKpb; + const int tm = (int)((uint32_t)b / (uint32_t)nkt), tk = b - tm * nkt; + row[0] = tm * 8 + (int)((threadIdx.x & 31) >> 2); + kb[0] = tk * kFqKpb + (int)(threadIdx.x >> 5); + valid[0] = row[0] < a.M && kb[0] < nkb; + if (!valid[0]) { row[0] = 0; kb[0] = 0; } + } else { +#pragma unroll + for (int u = 0; u < NU; ++u) { + const long unit = (long)b * (64 * NU) + u * 64 + (threadIdx.x >> 2); + valid[u] = unit < (long)a.M * nkb; + row[u] = valid[u] ? (int)((uint32_t)unit / (uint32_t)nkb) : 0; + kb[u] = valid[u] ? (int)((uint32_t)unit - (uint32_t)row[u] * (uint32_t)nkb) : 0; + } + } + uint4 r[NU][4]; + size_t off[NU]; +#pragma unroll + for (int u = 0; u < NU; ++u) { + off[u] = (size_t)row[u] * a.Hd + kb[u] * 128 + lane * 8; +#pragma unroll + for (int i = 0; i < 4; ++i) r[u][i] = make_uint4(0, 0, 0, 0); + if (valid[u] && row[u] < a.Mr) { +#pragma unroll + for (int i = 0; i < 4; ++i) { + if constexpr ((kCoal & 128) != 0) r[u][i] = __ldcs(reinterpret_cast(a.x + off[u] + i * 32)); + else r[u][i] = __ldg(reinterpret_cast(a.x + off[u] + i * 32)); + } + } + } +#pragma unroll + for (int u = 0; u < NU; ++u) { + uint32_t mb = 0; +#pragma unroll + for (int i = 0; i < 4; ++i) { + mb = absmax_bits(mb, r[u][i].x); mb = absmax_bits(mb, r[u][i].y); + mb = absmax_bits(mb, r[u][i].z); mb = absmax_bits(mb, r[u][i].w); + } + float am = bits_amax_to_float(mb); + am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, 2)); + am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, 1)); + const float sc = fmaxf(am * (1.0f / 448.0f), 1e-12f); + const float inv = __frcp_rn(sc); + const uint2 o0 = q8(r[u][0], inv), o1 = q8(r[u][1], inv), o2 = q8(r[u][2], inv), o3 = q8(r[u][3], inv); + if constexpr (kXV == 1 || kXV == 3) { + // lane l holds output pieces l, l+4, l+8, l+12 (8 B each). Even lane: sends l+4, l+12, receives l+1, l+9 -> + // owns {l, l+1} and {l+8, l+9}; odd lane: sends l, l+8, receives l+3, l+11 (= partner's l-1+4, l-1+12) -> + // owns {l+3, l+4} and {l+11, l+12}. All 4 lanes of the unit take part (uniform control flow). + const bool odd = (lane & 1) != 0; + const uint2 s0 = odd ? o0 : o1, s1 = odd ? o2 : o3; + uint2 g0, g1; + g0.x = __shfl_xor_sync(0xffffffffu, s0.x, 1); g0.y = __shfl_xor_sync(0xffffffffu, s0.y, 1); + g1.x = __shfl_xor_sync(0xffffffffu, s1.x, 1); g1.y = __shfl_xor_sync(0xffffffffu, s1.y, 1); + if (valid[u]) { + // even lane l: pieces l (o0), l+1 (g0) at bytes 8l; l+8 (o2), l+9 (g1) at 8l + 64 + // odd lane l: pieces l+3 (g0), l+4 (o1) at bytes 8(l+3); l+11 (g1), l+12 (o3) at 8(l+3) + 64 + uint8_t* q = a.qx + off[u] + (odd ? 24 : 0); + const uint4 w0 = odd ? make_uint4(g0.x, g0.y, o1.x, o1.y) : make_uint4(o0.x, o0.y, g0.x, g0.y); + const uint4 w1 = odd ? make_uint4(g1.x, g1.y, o3.x, o3.y) : make_uint4(o2.x, o2.y, g1.x, g1.y); + st_evict_last(q, w0, pol); + st_evict_last(q + 64, w1, pol); + } + } else if (valid[u]) { + st_evict_last8(a.qx + off[u], o0, pol); + st_evict_last8(a.qx + off[u] + 32, o1, pol); + st_evict_last8(a.qx + off[u] + 64, o2, pol); + st_evict_last8(a.qx + off[u] + 96, o3, pol); + } + if (valid[u] && lane == 0) a.sx[(size_t)kb[u] * a.M + row[u]] = sc; + } +} + +template +__global__ void __launch_bounds__(SE_FQ_TB) fused_quant_kernel(QuantArgs a) { + pdl_trigger(); // dependents (gate_up GEMM) still griddepcontrol.wait for our full completion + const uint64_t pol = l2_evict_last_policy(); + // merged path: reset the per-M-block arrival counters. The previous call's merged kernel has fully completed + // (this is a normal stream-ordered launch) and the merged kernel of this call griddepcontrol.waits for us. + if (blockIdx.x == 0) + { + for (int i = threadIdx.x; i < a.n_mb; i += blockDim.x) a.mb_cnt[i] = 0; + for (int i = threadIdx.x; i < a.nz2; i += blockDim.x) a.z2[i] = (i >= a.z2a && i < a.z2b) ? 256 / se2wg::kCqRows : a.z2v; + } + int b = blockIdx.x; + if (b < a.nbx) { + if constexpr (kXV >= 0) { quant_x_unit(a, b, pol); return; } + // ---- x: 64 units of 4 threads per block ---- + int nkb = a.Hd >> 7; + long unit = (long)b * 64 + (threadIdx.x >> 2); + int lane = threadIdx.x & 3; + bool valid = unit < (long)a.M * nkb; + // kCoal bit 64: kb-major unit order (unit = kb * M + row) -> the lane-0 sx stores of consecutive units hit + // consecutive floats of the MN-major sx[kb][M] row (coalesced) instead of a 4 B store per M*4-byte stride + int row, kb; + if constexpr ((kCoal & 64) != 0) { + kb = valid ? (int)(unit / a.M) : 0; + row = valid ? (int)(unit - (long)kb * a.M) : 0; + } else { + // 32-bit division (unit < M * Hd / 128 < 2^31) + row = valid ? (int)((uint32_t)unit / (uint32_t)nkb) : 0; + kb = valid ? (int)((uint32_t)unit - (uint32_t)row * (uint32_t)nkb) : 0; + } + // kCoal: lane l of the unit's 4 threads loads 16 B pieces l, l+4, l+8, l+12 of the 256 B unit (each warp + // load instruction: 8 units x 64 contiguous bytes, full sectors) instead of 4 consecutive pieces (64 B lane stride) + size_t off = (size_t)row * a.Hd + kb * 128 + lane * ((kCoal & 1) ? 8 : 32); + constexpr int kStep = (kCoal & 1) ? 32 : 8; // elements between this thread's 16 B pieces + uint4 r[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) r[i] = make_uint4(0, 0, 0, 0); + if (valid && row < a.Mr) { // padding rows read as zeros -> qx = 0, scale = 1e-12 +#pragma unroll + for (int i = 0; i < 4; ++i) { + // kCoal bit 128: x is read exactly once -> evict-first (keeps the L2 for the fp8 outputs the GEMM reads) + if constexpr ((kCoal & 128) != 0) r[i] = __ldcs(reinterpret_cast(a.x + off + i * kStep)); + else r[i] = __ldg(reinterpret_cast(a.x + off + i * kStep)); + } + } + uint32_t mb = 0; +#pragma unroll + for (int i = 0; i < 4; ++i) { + mb = absmax_bits(mb, r[i].x); mb = absmax_bits(mb, r[i].y); + mb = absmax_bits(mb, r[i].z); mb = absmax_bits(mb, r[i].w); + } + float am = bits_amax_to_float(mb); + am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, 2)); + am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, 1)); + float sc = fmaxf(am * (1.0f / 448.0f), 1e-12f); + if (valid) { + const float inv = __frcp_rn(sc); // one divide per lane, then multiplies + uint2 o0 = q8(r[0], inv), o1 = q8(r[1], inv), o2 = q8(r[2], inv), o3 = q8(r[3], inv); + if constexpr ((kCoal & 1) != 0) { + st_evict_last8(a.qx + off, o0, pol); // 4 x 8 B (each warp store: 8 units x 32 contiguous bytes) + st_evict_last8(a.qx + off + 32, o1, pol); + st_evict_last8(a.qx + off + 64, o2, pol); + st_evict_last8(a.qx + off + 96, o3, pol); + } else { + uint4* dst = reinterpret_cast(a.qx + off); + st_evict_last(dst, make_uint4(o0.x, o0.y, o1.x, o1.y), pol); // keep qx L2-resident for the GEMM + st_evict_last(dst + 1, make_uint4(o2.x, o2.y, o3.x, o3.y), pol); + } + if (lane == 0) a.sx[(size_t)kb * a.M + row] = sc; // MN-major scales + } + return; + } + // ---- weights (reverse block order: the last-scheduled blocks produce weight wbase, rows near 0) ---- + // weight region counted in kFqTB-thread blocks (a.nbw is in 256-thread units -> kFqR blocks per unit) + b = (int)(gridDim.x - 1) - b; // in [0, nweights*nbw*kFqR) + const int nbwr = a.nbw * kFqR; + int which = a.wbase + b / nbwr; // 0 gate, 1 up, 2 down + b -= (which - a.wbase) * nbwr; + quant_w_unit(a, which, (size_t)b * kFqTB + threadIdx.x, pol); +} + +template +__global__ void __launch_bounds__(256) down_quant_pdl_kernel(QuantArgs a) { + pdl_trigger(); // the down GEMM may be scheduled early (its producers griddepcontrol.wait for our completion) + const uint64_t pol = l2_evict_last_policy(); + quant_w_unit(a, 2, (size_t)(blockIdx.x + a.dq_off) * blockDim.x + threadIdx.x, pol); + if (blockIdx.x == 0) pdl_wait(); +} + +struct DqLd { uint4 r[4]; float scA, scB; int n, kA, kB, po; bool ok; }; +__device__ __forceinline__ void dq_load(const QuantArgs& a, size_t idx, size_t lim, DqLd& u) { + u.ok = idx < lim; + if (!u.ok) return; + const int K = a.I, N = a.Hd; + const int lane = (int)(idx & 31); + const uint32_t w = (uint32_t)(idx >> 5), wpr = (uint32_t)K >> 10; + u.n = (int)(w / wpr); + const int kw = (int)((w - (uint32_t)u.n * wpr) << 10); + u.po = (lane & 7) * 16; + u.kA = kw + (lane >> 3) * 128; u.kB = u.kA + 512; + const __nv_bfloat16* rowp = a.dw + (size_t)u.n * K; + u.r[0] = __ldcs(reinterpret_cast(rowp + u.kA + u.po)); + u.r[1] = __ldcs(reinterpret_cast(rowp + u.kA + u.po + 8)); + u.r[2] = __ldcs(reinterpret_cast(rowp + u.kB + u.po)); + u.r[3] = __ldcs(reinterpret_cast(rowp + u.kB + u.po + 8)); + const int nbN = N >> 7; + u.scA = __ldg(a.ds + (u.kA >> 7) * nbN + (u.n >> 7)); + u.scB = __ldg(a.ds + (u.kB >> 7) * nbN + (u.n >> 7)); +} +__device__ __forceinline__ void dq_store(const QuantArgs& a, const DqLd& u, uint64_t pol) { + if (!u.ok) return; + const int K = a.I; + const float invA = __frcp_rn(u.scA), invB = __frcp_rn(u.scB); + uint8_t* dst = a.qd + (size_t)u.n * K + u.po; + const uint2 a0 = q8(u.r[0], invA), a1 = q8(u.r[1], invA), b0 = q8(u.r[2], invB), b1 = q8(u.r[3], invB); + st_evict_last(dst + u.kA, make_uint4(a0.x, a0.y, a1.x, a1.y), pol); + st_evict_last(dst + u.kB, make_uint4(b0.x, b0.y, b1.x, b1.y), pol); + if (u.po == 0 && (u.n & 127) == 0) { +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int k = h ? u.kB : u.kA; + const float sc = h ? u.scB : u.scA; + float* p = a.sd64 + (k >> 7) * (a.Hd / 64) + 2 * (u.n >> 7); + p[0] = sc; p[1] = sc; + float* p32 = a.sd32 + (k >> 7) * (a.Hd / 32) + 4 * (u.n >> 7); + p32[0] = sc; p32[1] = sc; p32[2] = sc; p32[3] = sc; + } + } +} +template +__global__ void __launch_bounds__(256) down_quant_persist_kernel(QuantArgs a) { + pdl_trigger(); + const uint64_t pol = l2_evict_last_policy(); + // kDqPf: DRAM is idle while the kPair gate_up runs (its operands are L2-resident): thread 0 issues bulk L2 + // prefetches of this block's whole grid-stride share of the bf16 down weight (dq block b = 16 KB contiguous bf16 at + // element (b + dq_off) * 8192), so the conversion loads below hit L2 instead of paying DRAM latency on 20 SMs. + // Pure L2 hint (no smem, no completion), weights are kernel inputs -> bit-identical. +#ifndef SE_DQ_PF +#define SE_DQ_PF 0 +#endif + if (SE_DQ_PF && threadIdx.x == 0) { + const size_t tot = (size_t)a.Hd * a.I * 2; // bf16 bytes of the down weight + const char* base = reinterpret_cast(a.dw); + for (int b = blockIdx.x; b < a.nbw; b += gridDim.x) { + const size_t off = (size_t)(b + a.dq_off) * blockDim.x * 64; // 32 bf16 per thread + if (off >= tot) break; + const size_t rem = tot - off; + const uint32_t sz = (uint32_t)(rem < (size_t)blockDim.x * 64 ? rem : (size_t)blockDim.x * 64) & ~15u; + if (sz) asm volatile("cp.async.bulk.prefetch.L2.global [%0], %1;" ::"l"(base + off), "r"(sz) : "memory"); + } + } + // kDq2: when the down weight takes the variant-C mapping (K % 1024 == 0), each iteration handles TWO grid-stride + // dq blocks (b, b + grid) and issues all 8 x 16 B bf16 loads (+ 4 scale loads) of both before any convert / store: + // 2x bytes in flight per thread on the 20 idle SMs (the flushed dq tail is DRAM-latency bound). Same units, same + // per-element variant-C math -> bit-identical qwd / scale tables. + if ((kCoal & 8) && !(kCoal & 32) && (a.I & 1023) == 0) { + const size_t lim = (size_t)a.Hd * (a.I >> 5); + for (int b = blockIdx.x; b < a.nbw; b += 2 * gridDim.x) { + const int b2 = b + (int)gridDim.x; + DqLd u0, u1; + dq_load(a, (size_t)(b + a.dq_off) * blockDim.x + threadIdx.x, lim, u0); + dq_load(a, (size_t)(b2 + a.dq_off) * blockDim.x + threadIdx.x, b2 < a.nbw ? lim : 0, u1); + dq_store(a, u0, pol); + dq_store(a, u1, pol); + } + } else + for (int b = blockIdx.x; b < a.nbw; b += gridDim.x) + quant_w_unit(a, 2, (size_t)(b + a.dq_off) * blockDim.x + threadIdx.x, pol); + if (blockIdx.x == 0) pdl_wait(); +} + +// kDqPair (non-persistent PDL dq kernel, e.g. the M384 chain bucket): each 256-thread block handles TWO adjacent +// dq blocks (2b, 2b+1: 32 KB contiguous bf16) and, on the variant-C path, issues all 8 x 16 B bf16 loads + 4 scale loads +// of both units before any convert / store (2x bytes in flight per thread, half the blocks). Same units, same variant-C +// math -> bit-identical qwd / scale tables. Block 0 alone waits on the primary (orders the down GEMM after gate_up). +template +__global__ void __launch_bounds__(256) down_quant_pair_kernel(QuantArgs a) { + pdl_trigger(); + const uint64_t pol = l2_evict_last_policy(); + const int b0 = 2 * (int)blockIdx.x, b1 = b0 + 1; + if ((kCoal & 8) && !(kCoal & 32) && (a.I & 1023) == 0) { + const size_t lim = (size_t)a.Hd * (a.I >> 5); + DqLd u0, u1; + dq_load(a, (size_t)(b0 + a.dq_off) * blockDim.x + threadIdx.x, b0 < a.nbw ? lim : 0, u0); + dq_load(a, (size_t)(b1 + a.dq_off) * blockDim.x + threadIdx.x, b1 < a.nbw ? lim : 0, u1); + dq_store(a, u0, pol); + dq_store(a, u1, pol); + } else { + if (b0 < a.nbw) quant_w_unit(a, 2, (size_t)(b0 + a.dq_off) * blockDim.x + threadIdx.x, pol); + if (b1 < a.nbw) quant_w_unit(a, 2, (size_t)(b1 + a.dq_off) * blockDim.x + threadIdx.x, pol); + } + if (blockIdx.x == 0) pdl_wait(); +} + +constexpr int g_qcoal = SE_QCOAL; +// launch the fused quant kernel with the selected lane mapping +// driver-API launch of a plain (non-cluster) kernel with the CUfunction resolved once (see drv_launch) +static int drv_launch_plain(const void* sym, CUfunction& fn, int& tried, dim3 grid, dim3 block, cudaStream_t st, + bool pdl, void** args) { + if (!tried) { + tried = 1; + cudaFunction_t f = nullptr; + if (cudaGetFuncBySymbol(&f, sym) == cudaSuccess) fn = (CUfunction)f; + else { fn = nullptr; cudaGetLastError(); } + } + if (!fn) { + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = grid; cfg.blockDim = block; cfg.stream = st; + cudaLaunchAttribute at[1]; + at[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + at[0].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = at; cfg.numAttrs = pdl ? 1 : 0; + return cudaLaunchKernelExC(&cfg, sym, args) == cudaSuccess ? 0 : 1; + } + CUlaunchConfig dc = {}; + dc.gridDimX = grid.x; dc.gridDimY = grid.y; dc.gridDimZ = grid.z; + dc.blockDimX = block.x; dc.blockDimY = block.y; dc.blockDimZ = block.z; + dc.hStream = (CUstream)st; + CUlaunchAttribute da[1]; + da[0].id = CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_STREAM_SERIALIZATION; + da[0].value.programmaticStreamSerializationAllowed = 1; + dc.attrs = da; dc.numAttrs = pdl ? 1 : 0; + return cuLaunchKernelEx(&dc, fn, args, nullptr) == CUDA_SUCCESS ? 0 : 1; +} +static void fq_launch(unsigned grid, cudaStream_t st, const QuantArgs& a) { + { + QuantArgs aa = a; + void* args[1] = {&aa}; + static CUfunction fn = nullptr; + static int tried = 0; + // grid is given as x blocks + weight blocks in 256-thread units; weight part re-expressed in kFqTB blocks + const unsigned g = (unsigned)a.nbx + (unsigned)kFqR * (grid - (unsigned)a.nbx); + drv_launch_plain((const void*)fused_quant_kernel, fn, tried, dim3(g), dim3(kFqTB), st, false, args); + } +} + +__device__ __forceinline__ float swiglu1(float g, float u) { + // fast exp + approximate divide: the result is rounded to bf16 immediately, fp32-ulp-level error is hidden + float sl = __bfloat162float(__float2bfloat16(__fdividef(g, 1.f + __expf(-g)))); + return __bfloat162float(__float2bfloat16(sl * u)); +} + +__global__ void __launch_bounds__(256) swiglu_quant_kernel(const __nv_bfloat16* __restrict__ H, + uint8_t* __restrict__ q, float* __restrict__ s, + int M, int I) { + pdl_trigger(); + const int lane = threadIdx.x & 31; + const long unit = (long)blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5); // warp-uniform + const int nkb = I >> 7; + if (unit >= (long)M * nkb) { pdl_wait(); return; } + const int row = (int)(unit / nkb); + const int kb = (int)(unit - (long)row * nkb); + const int hi = lane >> 4; // 0: gate half-warp, 1: up half-warp + const int c8 = (lane & 15) * 8; // 8-col chunk within the 128-col block + const uint4* src = reinterpret_cast(H + (size_t)row * (2 * I) + kb * 256 + hi * 128 + c8); + pdl_wait(); // H is produced by the gate_up GEMM + const uint4 w = __ldcs(src); // streamed once: evict-first + // swap: low lanes send gate words 2,3 (cols +4..+7), high lanes send up words 0,1 (cols +0..+3) + uint32_t s0 = hi ? w.x : w.z, s1 = hi ? w.y : w.w; + uint32_t r0 = __shfl_xor_sync(0xffffffffu, s0, 16), r1 = __shfl_xor_sync(0xffffffffu, s1, 16); + uint32_t g0 = hi ? r0 : w.x, g1 = hi ? r1 : w.y; // gate pairs for my 4 cols + uint32_t u0 = hi ? w.z : r0, u1 = hi ? w.w : r1; // up pairs for my 4 cols + float2 ga = bf2_to_f2(g0), gb = bf2_to_f2(g1), ua = bf2_to_f2(u0), ub = bf2_to_f2(u1); + float h0 = swiglu1(ga.x, ua.x), h1 = swiglu1(ga.y, ua.y), h2 = swiglu1(gb.x, ub.x), h3 = swiglu1(gb.y, ub.y); + float am = fmaxf(fmaxf(fabsf(h0), fabsf(h1)), fmaxf(fabsf(h2), fabsf(h3))); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, o)); + const float sc = fmaxf(am * (1.0f / 448.0f), 1e-12f); + const float inv = __frcp_rn(sc); + const uint32_t ov = (uint32_t)f2_to_fp8x2(h0 * inv, h1 * inv) | ((uint32_t)f2_to_fp8x2(h2 * inv, h3 * inv) << 16); + *reinterpret_cast(q + (size_t)row * I + kb * 128 + c8 + hi * 4) = ov; + if (lane == 0) s[(size_t)kb * M + row] = sc; +} + +// --------------------------------------------------------------------------------------------- +// CUTLASS SM100 blockwise-scaled FP8 GEMM: D[M,N] (bf16, row-major) = sum_kb sA[m,kb]*sB[kb,nb]*(A_kb B_kb^T) +// A: fp8 [M,K] row-major, B: fp8 [N,K] (column-major KxN), SFA 1x128 (MN-major), SFB 128x128 (MN-major). +// tcgen05 MMA accumulates each 128-K block in TMEM; the blockwise collective promotes with scales. +// ElementC = void: source-less epilogue (D = acc), so no C smem staging -> the freed smem goes to extra +// mainloop A/B stages via StageCountAutoCarveout. +// --------------------------------------------------------------------------------------------- +// kCq: extra carve-out of the converter ring beyond the seed MO kernel's smem slack (the seed's 4-stage MO kernel +// leaves 11 KB unused; halving the DN TMA-store staging frees 24 KB more: a 4 x 8 KB ring fits with 4 A/B stages) +#ifndef SE_CQ_CARVE +#define SE_CQ_CARVE 0 // 32 KB ring: halved DN staging frees 24 KB + 11 KB slack +#endif +template +struct BlockwiseGemm { + static constexpr bool kMerged = kMergedK; + static constexpr bool kSplitK = !cute::is_same_v; + static constexpr bool kFused = kFuse; + static constexpr bool kStatic = kStaticSched; + using ElementA = cutlass::float_e4m3_t; + using LayoutA = cutlass::layout::RowMajor; + static constexpr int AlignmentA = 16; + using ElementB = cutlass::float_e4m3_t; + using LayoutB = cutlass::layout::ColumnMajor; + static constexpr int AlignmentB = 16; + using ElementC = void; + using ElementD = cutlass::bfloat16_t; + using LayoutC = cutlass::layout::RowMajor; + static constexpr int AlignmentC = 8; + using ElementAcc = float; + using ElementCompute = float; + + using ScaleConfig = cutlass::detail::Sm100BlockwiseScaleConfig<1, SfN, 128, cute::UMMA::Major::MN, + cute::UMMA::Major::MN>; + using LayoutSFA = decltype(ScaleConfig::deduce_layoutSFA()); + using LayoutSFB = decltype(ScaleConfig::deduce_layoutSFB()); + + using CollectiveEpilogue = typename cutlass::epilogue::collective::CollectiveBuilder< + cutlass::arch::Sm100, cutlass::arch::OpClassTensorOp, MmaTileShape, ClusterShape, + cutlass::epilogue::collective::EpilogueTileAuto, ElementAcc, ElementCompute, + ElementC, LayoutC, AlignmentC, ElementD, LayoutC, AlignmentC, EpiSched>::CollectiveOp; + + using CollectiveMainloop = typename cutlass::gemm::collective::CollectiveBuilder< + cutlass::arch::Sm100, cutlass::arch::OpClassTensorOp, + ElementA, cute::tuple, AlignmentA, + ElementB, cute::tuple, AlignmentB, + ElementAcc, MmaTileShape, ClusterShape, + // 2WG kernel has no epilogue smem (direct register->global stores): no carveout + // (fused SwiGLU epilogue: 4 KB for the cross-warpgroup row-amax buffers) + cutlass::gemm::collective::StageCountAutoCarveout 0 ? kCarveN : 65536 + 1024 + 17408) : 0)) : static_cast( + sizeof(typename CollectiveEpilogue::SharedStorage))>, + KernelSched>::CollectiveOp; + + using GemmKernel = cute::conditional_t< + k2WG, + se2wg::Blockwise2WGKernel, CollectiveMainloop, CollectiveEpilogue, TileSched, kPP, kFuse, + kStaticSched, kTma, kMergedK, kStgK, kHalvesK, kPairK, kHalfTK, kTailSplitK, kJitK, kCqK, kRegsK, kTgK>, + cutlass::gemm::kernel::GemmUniversal, CollectiveMainloop, CollectiveEpilogue, + TileSched>>; + using Gemm = cutlass::gemm::device::GemmUniversalAdapter; + using StrideA = typename Gemm::GemmKernel::StrideA; + using StrideB = typename Gemm::GemmKernel::StrideB; + using StrideC = typename Gemm::GemmKernel::StrideC; + using StrideD = typename Gemm::GemmKernel::StrideD; +}; + +using Gemm1SM = BlockwiseGemm, Shape<_1, _1, _1>, + cutlass::gemm::KernelTmaWarpSpecializedBlockwise1SmSm100, + cutlass::epilogue::TmaWarpSpecialized1Sm>; +// v1: 2SM 256x128 (CTA pair: each CTA holds a 128-row A slice and half of the B tile) +using Gemm2SM = BlockwiseGemm, Shape<_2, _1, _1>, + cutlass::gemm::KernelTmaWarpSpecializedBlockwise2SmSm100, + cutlass::epilogue::TmaWarpSpecialized2Sm>; +// v2: 1SM 128x256 (A re-read halved, 256-column TMEM accumulator) +// v3: 2SM 256x256 (CTA pair, each CTA a 128x256 accumulator) + +// v4: 1SM 128x64 (small N tile -> 2x the CTAs of v0 for small-M occupancy). Its B scale granularity is +// 64(N)x128(K) (CUTLASS requires granularity <= tile), fed from the duplicated sgu64 / sd64 tables. +using Gemm1SMN64 = BlockwiseGemm, Shape<_1, _1, _1>, + cutlass::gemm::KernelTmaWarpSpecializedBlockwise1SmSm100, + cutlass::epilogue::TmaWarpSpecialized1Sm, void, /*SfN=*/64>; +using Gemm2SM2WGFused = BlockwiseGemm, Shape<_2, _1, _1>, + cutlass::gemm::KernelTmaWarpSpecializedBlockwise2SmSm100, + cutlass::epilogue::TmaWarpSpecialized2Sm, void, 128, /*k2WG=*/true, + /*kPP=*/false, /*kFuse=*/true>; +// 1SM 128x256 (cta_group::1, no cluster) with the same fused SwiGLU + fp8 requant epilogue as per CTA the +// identical 128x256 (gate block | up block) accumulator view, but 128-row M units (twice the unit count of ), +// CLC persistent scheduler. +using Gemm1SM2WGFused = BlockwiseGemm, Shape<_1, _1, _1>, + cutlass::gemm::KernelTmaWarpSpecializedBlockwise1SmSm100, + cutlass::epilogue::TmaWarpSpecialized1Sm, void, 128, /*k2WG=*/true, + /*kPP=*/false, /*kFuse=*/true>; +// (1SM 128x256 fused SwiGLU/requant) + the hybrid static schedule of with P = #SMs 1-CTA slots: at small +// M (T = M/128 x 16 tiles < 148) every tile is split along K into s = min(4, 148/T) units (M384: 48 x 3 = 144, +// M512: 64 x 2 = 128 units), each split publishes its fp32 128x256 partial (st.cg, L2), per-tile arrival counter, +// then the s splits sum the partials in fixed order j = 0..s-1 (deterministic) for disjoint row ranges and run +// the fused SwiGLU + 1x128 requant epilogue on complete rows. +// as hardware 2-CTA clusters (kPair, bw2wg.h): the two K splits of a tile are the two CTAs of a cluster, +// split-K fixup through DSMEM (st.async into the owner's smem), no global workspace / counters / polling. +using Gemm1SM2WGFusedPair = BlockwiseGemm, Shape<_1, _1, _1>, + cutlass::gemm::KernelTmaWarpSpecializedBlockwise1SmSm100, + cutlass::epilogue::TmaWarpSpecialized1Sm, void, 128, /*k2WG=*/true, + /*kPP=*/false, /*kFuse=*/true, /*kStaticSched=*/true, /*kTma=*/false, + /*kMerged=*/false, /*kStg=*/true, /*kHalves=*/true, /*kPair=*/true>; +// + hybrid schedule: host-computed work list (full waves data-parallel, the last partial wave's 256x256 +// tiles split along K into s<=4 units) handed out in order by the CLC scheduler; distributed fp32 fixup +// partitioned by ROWS so each split runs the fused SwiGLU/amax/fp8 epilogue on complete rows. +using Gemm2SM2WGFusedStatic = BlockwiseGemm, Shape<_2, _1, _1>, + cutlass::gemm::KernelTmaWarpSpecializedBlockwise2SmSm100, + cutlass::epilogue::TmaWarpSpecialized2Sm, void, 128, /*k2WG=*/true, + /*kPP=*/false, /*kFuse=*/true, /*kStaticSched=*/true>; +// v7 (1SM 128x128, 4 promotion WGs x 32 cols) + the same hybrid static schedule as full waves of +// 128x128 tiles data-parallel, the partial last wave (or, for small M, ALL tiles) split along K into s<=4 +// units, deterministic row-partitioned fp32 fixup, direct bf16 stores. Used for the down GEMM. +// v8 (2SM 256x256 4WG, plain bf16 D) with a TMA-store epilogue: each warpgroup stages its 128x64 bf16 slice +// in a 128B-swizzled 16 KB smem buffer and one elected thread issues a 2-D TMA store (bulk_group); the +// promotion warps immediately start the next tile (buffer reuse gated by cp.async.bulk.wait_group.read). +// with a 256x224 tile (7168 = 32 x 224 -> 32 instead of 28 N tiles: more SM pairs busy at small M); B scales +// at 32-col granularity (sd32) because a 224-col tile straddles 128-col weight blocks. +using Gemm2SM224Tma = BlockwiseGemm, Shape<_2, _1, _1>, + cutlass::gemm::KernelTmaWarpSpecializedBlockwise2SmSm100, + cutlass::epilogue::TmaWarpSpecialized2Sm, void, /*SfN=*/32, /*k2WG=*/true, + /*kPP=*/false, /*kFuse=*/false, /*kStaticSched=*/false, /*kTma=*/true>; +// 1SM 128x224 TMA-store down tile (same promotion / epilogue as, cta_group::1, 128-row M units) +// 1SM 128x160 TMA-store down tile (M384 bucket: 3 x 45 = 135 CTAs, one wave), sd32 B scales +#ifndef SE_C160 +#define SE_C160 (32768 + 1024 + 4096) +#endif +// 160-col TMA-store down tile with the carve-out trimmed to the staging it uses (2 x 16 KB) +using Gemm1SM160TmaC = BlockwiseGemm, Shape<_1, _1, _1>, + cutlass::gemm::KernelTmaWarpSpecializedBlockwise1SmSm100, + cutlass::epilogue::TmaWarpSpecialized1Sm, void, 32, true, false, false, false, true, + false, true, true, false, false, false, false, false, true, SE_C160>; +#ifndef SE_C224 +#define SE_C224 (24576 + 1024 + 4096 + 8192) +#endif +// 1SM 128x224 TMA-store down tile with a trimmed carve-out (24 KB halved staging, bw2wg.h kHalfStg): 4 A/B stages +using Gemm1SM224TmaC = BlockwiseGemm, Shape<_1, _1, _1>, + cutlass::gemm::KernelTmaWarpSpecializedBlockwise1SmSm100, + cutlass::epilogue::TmaWarpSpecialized1Sm, void, 32, true, false, false, false, true, + false, true, true, false, false, false, false, false, true, SE_C224>; +static_assert(Gemm1SM224TmaC::Gemm::GemmKernel::kHalfStg, "v264: trimmed 224 carve-out must give >= 4 A/B stages"); +using Gemm2SM2WGTma = BlockwiseGemm, Shape<_2, _1, _1>, + cutlass::gemm::KernelTmaWarpSpecializedBlockwise2SmSm100, + cutlass::epilogue::TmaWarpSpecialized2Sm, void, 128, /*k2WG=*/true, + /*kPP=*/false, /*kFuse=*/false, /*kStaticSched=*/false, /*kTma=*/true>; +using Gemm2SMMergedOldJitCQ = BlockwiseGemm, Shape<_2, _1, _1>, + cutlass::gemm::KernelTmaWarpSpecializedBlockwise2SmSm100, + cutlass::epilogue::TmaWarpSpecialized2Sm, void, 128, true, false, true, true, + false, true, /*kStg=*/false, /*kHalves=*/true, /*kPair=*/false, + /*kHalfT=*/false, /*kTailSplit=*/false, /*kJit=*/true, /*kCq=*/true>; +// Gemm2SMMergedOldJitCQ + compile-time kTailGrp (last 2 M blocks' GU tiles N-major), M1408 bucket only +using Gemm2SMMergedOldJitCQTg = BlockwiseGemm, Shape<_2, _1, _1>, + cutlass::gemm::KernelTmaWarpSpecializedBlockwise2SmSm100, + cutlass::epilogue::TmaWarpSpecialized2Sm, void, 128, true, false, true, true, + false, true, false, true, false, false, false, true, true, true, 0, + /*kTg=*/true>; +// MO kJit + wait-free tail K-split (kRedSplit) + in-kernel down-weight conversion (kCq), M in [1216, 1344) +using Gemm2SMMergedOldSplitJitCQ = BlockwiseGemm, Shape<_2, _1, _1>, + cutlass::gemm::KernelTmaWarpSpecializedBlockwise2SmSm100, + cutlass::epilogue::TmaWarpSpecialized2Sm, void, 128, true, false, true, true, + false, true, /*kStg=*/false, /*kHalves=*/true, /*kPair=*/false, + /*kHalfT=*/false, /*kTailSplit=*/true, /*kJit=*/true, /*kCq=*/true>; +using Gemm2SMMergedOldJit = BlockwiseGemm, Shape<_2, _1, _1>, + cutlass::gemm::KernelTmaWarpSpecializedBlockwise2SmSm100, + cutlass::epilogue::TmaWarpSpecialized2Sm, void, 128, true, false, true, true, + false, true, /*kStg=*/false, /*kHalves=*/true, /*kPair=*/false, + /*kHalfT=*/false, /*kTailSplit=*/false, /*kJit=*/true>; +#define RA_ALT 0 + +// Grow-only raw device workspace (never freed; no static tensor destructor at teardown). +static void* get_workspace(size_t bytes) { + static void* ptr = nullptr; + static size_t cap = 0; + if (bytes > cap) { + if (ptr) cudaFree(ptr); + cudaMalloc(&ptr, bytes); + cap = bytes; + } + return ptr; +} + +// Separate grow-only workspace for the split-K variants (reduction partials + tile locks). +static void* get_workspace_sk(size_t bytes) { + static void* ptr = nullptr; + static size_t cap = 0; + if (bytes > cap) { + if (ptr) cudaFree(ptr); + cudaMalloc(&ptr, bytes); + cap = bytes; + } + return ptr; +} + +// v9 split-K workspace: fp32 partials for at most P = SMs/2 split units x 2 CTAs x 128x256, plus 2 GEMMs x +// 2P x {arrive, done} counters (zeroed once at allocation; the kernel's last arriver resets each counter to 0). +// Raw device memory, allocated once, never freed. +struct SplitWs { float* part = nullptr; int* cnt = nullptr; int p = 0; }; +static int sm_count(); +// which = 0: gate_up (P = SMs/2 pair units x 2 CTAs x 128x256 fp32), which = 1: down (P = SMs units x +// 128x128 fp32). Separate buffers so consecutive GEMMs never share partials/counters. +static SplitWs& split_ws(int which = 0) { + static SplitWs& w0 = *new SplitWs(); + static SplitWs& w1 = *new SplitWs(); + SplitWs& w = which ? w1 : w0; + if (!w.part) { + w.p = which ? sm_count() : sm_count() / 2; + const size_t unit_floats = which ? (size_t)128 * 128 : (size_t)2 * 128 * 256; + // which 0 also serves (1SM 128x256 fused split-K): up to sm_count() units x 128x256 fp32 + const size_t nf = which ? (size_t)w.p * unit_floats : std::max((size_t)w.p * unit_floats, (size_t)sm_count() * 128 * 256); + cudaMalloc(&w.part, nf * sizeof(float)); + cudaMalloc(&w.cnt, (size_t)2 * 4 * w.p * sizeof(int)); + cudaMemset(w.cnt, 0, (size_t)2 * 4 * w.p * sizeof(int)); + } + return w; +} + +static int sm_count() { + static int c = 0; + if (c == 0) { + int dev; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&c, cudaDevAttrMultiProcessorCount, dev); + } + return c; +} + +// Max co-resident 2-CTA clusters of a kernel (cudaOccupancyMaxActiveClusters, cached per kernel type): the +// static schedule's pair-slot count P, so that every pair-cluster of the static grid is resident at once. +template +static int max_pair_clusters() { + static int c = -1; + if (c < 0) { + auto f = cutlass::device_kernel; + int n = 0; + cudaFuncSetAttribute(f, cudaFuncAttributeMaxDynamicSharedMemorySize, K::SharedStorageSize); + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3((unsigned)(sm_count() & ~1), 1, 1); + cfg.blockDim = K::get_block_shape(); + cfg.dynamicSmemBytes = K::SharedStorageSize; + cudaLaunchAttribute at[1]; + at[0].id = cudaLaunchAttributeClusterDimension; + at[0].val.clusterDim.x = 2; at[0].val.clusterDim.y = 1; at[0].val.clusterDim.z = 1; + cfg.attrs = at; + cfg.numAttrs = 1; + if (cudaOccupancyMaxActiveClusters(&n, f, &cfg) != cudaSuccess || n <= 0) { cudaGetLastError(); n = sm_count() / 2; } + if (n > sm_count() / 2) n = sm_count() / 2; + c = n; + } + return c; +} + +template +static int drv_launch(const cudaLaunchConfig_t& cfg, unsigned cluster_x, const typename K::Params* pp) { + static CUfunction fn = nullptr; + static bool tried = false; + if (!tried) { + tried = true; + cudaFunction_t f = nullptr; + if (cudaGetFuncBySymbol(&f, (const void*)cutlass::device_kernel) == cudaSuccess) fn = (CUfunction)f; + else { fn = nullptr; cudaGetLastError(); } + } + if (!fn) { // fallback: runtime launch (same configuration) + cudaLaunchConfig_t c = cfg; + return cudaLaunchKernelEx(&c, cutlass::device_kernel, *pp) == cudaSuccess ? 0 : 1; + } + CUlaunchConfig dc = {}; + dc.gridDimX = cfg.gridDim.x; dc.gridDimY = cfg.gridDim.y; dc.gridDimZ = cfg.gridDim.z; + dc.blockDimX = cfg.blockDim.x; dc.blockDimY = cfg.blockDim.y; dc.blockDimZ = cfg.blockDim.z; + dc.sharedMemBytes = (unsigned)cfg.dynamicSmemBytes; + dc.hStream = (CUstream)cfg.stream; + CUlaunchAttribute da[2]; + da[0].id = CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION; + da[0].value.clusterDim.x = cluster_x; da[0].value.clusterDim.y = 1; da[0].value.clusterDim.z = 1; + da[1].id = CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_STREAM_SERIALIZATION; + da[1].value.programmaticStreamSerializationAllowed = 1; + dc.attrs = da; + dc.numAttrs = 2; + void* kp[1] = {(void*)pp}; + return cuLaunchKernelEx(&dc, fn, kp, nullptr) == CUDA_SUCCESS ? 0 : 1; +} + +template +struct ParamCache { + static constexpr int kN = 4, kK = 28; + struct E { bool valid = false; int nk = 0; uintptr_t key[kK]; typename Gemm::GemmKernel::Params p; }; + E e[kN]; + int next = 0; +}; +template +static int cached_launch(typename Gemm::Arguments const& args, const uintptr_t* key, int nk, void* wsp, + cudaStream_t stream, bool cacheable = true) { + using K = typename Gemm::GemmKernel; + using C = ParamCache; + static C& c = *new C(); + static bool attr = false; + if (nk > C::kK) cacheable = false; + if (K::initialize_workspace(args, wsp, stream, nullptr) != cutlass::Status::kSuccess) return 2; + typename K::Params* pp = nullptr; + if (cacheable) + for (int i = 0; i < C::kN && !pp; ++i) + if (c.e[i].valid && c.e[i].nk == nk && memcmp(c.e[i].key, key, nk * sizeof(uintptr_t)) == 0) pp = &c.e[i].p; + static typename K::Params* scratch = new typename K::Params(); + if (!pp) { + if (Gemm::can_implement(args) != cutlass::Status::kSuccess) return 1; + if (cacheable) { + typename C::E& en = c.e[c.next]; + c.next = (c.next + 1) % C::kN; + en.valid = false; + en.p = K::to_underlying_arguments(args, wsp); + memcpy(en.key, key, nk * sizeof(uintptr_t)); + en.nk = nk; + en.valid = true; + pp = &en.p; + } else { + *scratch = K::to_underlying_arguments(args, wsp); + pp = scratch; + } + } + if (!attr) { + if (K::SharedStorageSize >= (48 << 10) && + cudaFuncSetAttribute(cutlass::device_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, + K::SharedStorageSize) != cudaSuccess) + return 2; + attr = true; + } + // PDL launch: the kernel's producer/epilogue warps griddepcontrol.wait before touching global memory. + // host trim: direct cudaLaunchKernelEx (static cluster shape + PDL attribute) instead of the adapter's + // GemmUniversalAdapter::run (ClusterLauncher path: per-launch attribute / validation host work). Same grid / block / + // smem / cluster / PDL launch configuration. + { + using CS = typename K::ClusterShape; + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = K::get_grid_shape(*pp); + cfg.blockDim = K::get_block_shape(); + cfg.dynamicSmemBytes = K::SharedStorageSize; + cfg.stream = stream; + cudaLaunchAttribute at[2]; + at[0].id = cudaLaunchAttributeClusterDimension; + at[0].val.clusterDim.x = (unsigned)cute::size<0>(CS{}); + at[0].val.clusterDim.y = (unsigned)cute::size<1>(CS{}); + at[0].val.clusterDim.z = (unsigned)cute::size<2>(CS{}); + at[1].id = cudaLaunchAttributeProgrammaticStreamSerialization; + at[1].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = at; + cfg.numAttrs = 2; + static_assert(cute::size<1>(CS{}) == 1 && cute::size<2>(CS{}) == 1, "1-D cluster shapes only"); + if (drv_launch(cfg, (unsigned)cute::size<0>(CS{}), pp)) return 3; + } + return 0; +} + +template +static int run_blockwise_gemm(const uint8_t* A, const uint8_t* B, const float* SFA, const float* SFB, + void* D, int m, int n, int k, cudaStream_t stream, int splits = 1, + float* fused_scale = nullptr, int dbg_s = 0) { + using Gemm = typename G::Gemm; + auto stride_A = cutlass::make_cute_packed_stride(typename G::StrideA{}, cute::make_shape(m, k, 1)); + auto stride_B = cutlass::make_cute_packed_stride(typename G::StrideB{}, cute::make_shape(n, k, 1)); + auto stride_C = cutlass::make_cute_packed_stride(typename G::StrideC{}, cute::make_shape(m, n, 1)); + auto stride_D = cutlass::make_cute_packed_stride(typename G::StrideD{}, cute::make_shape(m, n, 1)); + auto layout_SFA = G::ScaleConfig::tile_atom_to_shape_SFA(cute::make_shape(m, n, k, 1)); + auto layout_SFB = G::ScaleConfig::tile_atom_to_shape_SFB(cute::make_shape(m, n, k, 1)); + + using EA = typename G::ElementA; + using EB = typename G::ElementB; + using ED = typename G::ElementD; + typename Gemm::Arguments args{ + cutlass::gemm::GemmUniversalMode::kGemm, + {m, n, k, 1}, + {reinterpret_cast(A), stride_A, reinterpret_cast(B), stride_B, + SFA, layout_SFA, SFB, layout_SFB}, + {{}, nullptr, stride_C, reinterpret_cast(D), stride_D}}; // no C source tensor + args.epilogue.thread.alpha = 1.0f; + args.epilogue.thread.beta = 0.0f; + args.hw_info.sm_count = sm_count(); + if constexpr (G::kFused) args.fused_scale = fused_scale; // D = fp8 h [m, n/2], fused_scale = h scales + if constexpr (G::kStatic) { + SplitWs& w = split_ws(G::kFused ? 0 : 1); // fused = gate_up, plain = down + args.split_ws = w.part; + args.split_cnt = w.cnt; + // schedule P = resident clusters: 2SM pairs from the occupancy API, 1SM = one CTA per SM + if constexpr (Gemm::GemmKernel::kTwoSm) args.hw_info.sm_count = 2 * max_pair_clusters(); + else args.hw_info.sm_count = sm_count(); + args.st_force_s = dbg_s; // probe-only override (0 = auto) + } + if constexpr (G::kSplitK) { + args.scheduler.splits = splits; + args.scheduler.decomposition_mode = + cutlass::gemm::kernel::detail::PersistentTileSchedulerSm90StreamKParams::DecompositionMode::SplitK; + } + + uintptr_t ksw = 0, ksc = 0; + if constexpr (G::kStatic) { ksw = (uintptr_t)args.split_ws; ksc = (uintptr_t)args.split_cnt; } + size_t ws = Gemm::get_workspace_size(args); + void* wsp = ws ? (G::kSplitK ? get_workspace_sk(ws) : get_workspace(ws)) : nullptr; + const uintptr_t key[16] = {(uintptr_t)A, (uintptr_t)B, (uintptr_t)SFA, (uintptr_t)SFB, (uintptr_t)D, + (uintptr_t)m, (uintptr_t)n, (uintptr_t)k, (uintptr_t)splits, (uintptr_t)fused_scale, + (uintptr_t)dbg_s, (uintptr_t)wsp, (uintptr_t)ws, ksw, + ksc, (uintptr_t)args.hw_info.sm_count}; + return cached_launch(args, key, 16, wsp, stream); +} + +// kPair launch of the fused 1SM 128x256 gate_up GEMM with s = 2 (every tile split, all units in one grid): +// grid = 2 * tiles CTAs as clusters of 2 (cluster = one tile, rank = K split), PDL. The kernel object is launched +// directly (the CUTLASS adapter would launch with the static 1x1 cluster shape). +static int run_pair_gate_up(const uint8_t* A, const uint8_t* B, const float* SFA, const float* SFB, uint8_t* qh, + float* sh, int m, int n, int k, cudaStream_t stream) { + using G = Gemm1SM2WGFusedPair; + using K = typename G::Gemm::GemmKernel; + auto stride_A = cutlass::make_cute_packed_stride(typename G::StrideA{}, cute::make_shape(m, k, 1)); + auto stride_B = cutlass::make_cute_packed_stride(typename G::StrideB{}, cute::make_shape(n, k, 1)); + auto stride_C = cutlass::make_cute_packed_stride(typename G::StrideC{}, cute::make_shape(m, n, 1)); + auto stride_D = cutlass::make_cute_packed_stride(typename G::StrideD{}, cute::make_shape(m, n, 1)); + auto layout_SFA = G::ScaleConfig::tile_atom_to_shape_SFA(cute::make_shape(m, n, k, 1)); + auto layout_SFB = G::ScaleConfig::tile_atom_to_shape_SFB(cute::make_shape(m, n, k, 1)); + using EA = typename G::ElementA; + using EB = typename G::ElementB; + using ED = typename G::ElementD; + typename K::Arguments args{ + cutlass::gemm::GemmUniversalMode::kGemm, + {m, n, k, 1}, + {reinterpret_cast(A), stride_A, reinterpret_cast(B), stride_B, SFA, layout_SFA, SFB, + layout_SFB}, + {{}, nullptr, stride_C, reinterpret_cast(qh), stride_D}}; + args.epilogue.thread.alpha = 1.0f; + args.epilogue.thread.beta = 0.0f; + // schedule slot count P = 2 * tiles -> make_schedule splits every tile exactly 2 ways (the pair kernel needs no + // co-residency: the hardware co-schedules each cluster, nothing waits across clusters) + args.hw_info.sm_count = 2 * ((m + 127) / 128) * (n / 256); + args.fused_scale = sh; + SplitWs& w = split_ws(0); // only to enable the split schedule (the pair kernel never touches it) + args.split_ws = w.part; + args.split_cnt = w.cnt; + args.st_force_s = 2; + size_t ws = K::get_workspace_size(args); + void* wsp = ws ? get_workspace(ws) : nullptr; + if (K::initialize_workspace(args, wsp, stream) != cutlass::Status::kSuccess) return 2; + // Params cached by (pointers, shape, workspace) (see cached_launch); rebuilt + checked only on a miss + struct PE { bool valid = false; uintptr_t key[12]; typename K::Params p; }; + static PE* pc = new PE[4](); + static int pnext = 0; + const uintptr_t key[12] = {(uintptr_t)A, (uintptr_t)B, (uintptr_t)SFA, (uintptr_t)SFB, (uintptr_t)qh, (uintptr_t)sh, + (uintptr_t)m, (uintptr_t)n, (uintptr_t)k, (uintptr_t)wsp, (uintptr_t)w.part, + (uintptr_t)w.cnt}; + PE* hit = nullptr; + for (int i = 0; i < 4 && !hit; ++i) + if (pc[i].valid && memcmp(pc[i].key, key, sizeof(key)) == 0) hit = &pc[i]; + if (!hit) { + if (!K::can_implement(args)) return 1; + hit = &pc[pnext]; + pnext = (pnext + 1) % 4; + hit->valid = false; + hit->p = K::to_underlying_arguments(args, wsp); + memcpy(hit->key, key, sizeof(key)); + hit->valid = true; + } + typename K::Params& params = hit->p; + // the pair kernel requires: every tile split exactly 2 ways, unit u = 2 * tile + split + if (params.st_split != 2 || params.st_dp != 0 || (params.st_units & 1)) return 5; + static bool attr = false; + if (!attr) { + if (cudaFuncSetAttribute(cutlass::device_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, + K::SharedStorageSize) != cudaSuccess) + return 6; + attr = true; + } + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3((unsigned)params.st_units, 1, 1); + cfg.blockDim = K::get_block_shape(); + cfg.dynamicSmemBytes = K::SharedStorageSize; + cfg.stream = stream; + cudaLaunchAttribute at[2]; + at[0].id = cudaLaunchAttributeClusterDimension; + at[0].val.clusterDim.x = 2; at[0].val.clusterDim.y = 1; at[0].val.clusterDim.z = 1; + at[1].id = cudaLaunchAttributeProgrammaticStreamSerialization; + at[1].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = at; + cfg.numAttrs = 2; + if (drv_launch(cfg, 2u, ¶ms)) return 7; // driver-API launch (see drv_launch) + return 0; +} + +#define MG_LAG (1 << 20) +static int* merged_counters(int nmb) { + static int* flags = nullptr; + static int nflag = 0; + if (nmb > nflag) { + if (flags) cudaFree(flags); // implicit device sync; counters of older calls are dead + cudaMalloc(&flags, (size_t)nmb * sizeof(int)); + cudaMemset(flags, 0, (size_t)nmb * sizeof(int)); + nflag = nmb; + } + return flags; +} +// half last M block as wide M=128 units (Gemm2SMMergedOldHalf). g_mg_half: 0 never, 1 auto (use_half), +// 2 whenever the last block is half (probe) +int g_mg_half = 1; +static bool half_block(int M) { const int r = M & 255; return M >= 512 && r != 0 && r <= 128; } +#ifndef HALF_DISPATCH +#define HALF_DISPATCH(M) false +#endif +static bool use_half(int M) { return HALF_DISPATCH(M); } +int g_mo_jit = -1; // -1 auto, 0 off, 1 on (probe override) +static bool use_jit(int M) { + if (g_mo_jit >= 0) return g_mo_jit != 0; + return true; +} +#define SE_REG_THR (1 << 30) +int g_xs_split = -1; // probe override (-1 auto; 1 = plain kCq merged kernel) +static int mg_split_for(int M) { + if (g_xs_split >= 0) return g_xs_split; + // wait-free kJit tail split (Gemm2SMMergedOldSplitJit): M1280 (6 tail tiles) s=8 only + if (M >= 1216 && M < 1344) return 8; + // M1408 back to plain kJit MO + return 1; +} +template +static int run_merged(const uint8_t* qx, const uint8_t* qwgu, const float* sx, const float* sgu, uint8_t* qh, float* sh, + const uint8_t* qwd, const float* dws, void* out, int m, int Hd, int I, cudaStream_t stream, + int split_s = 1, const se2wg::CqArgs* cq = nullptr) { + using Gemm = typename G::Gemm; + int* flags = merged_counters(((m + 255) / 256) * (2 * I / 256)); // per gate_up tile; already allocated + zeroed (quant kernel) for this M + const int n1 = 2 * I, k1 = Hd, n2 = Hd, k2 = I; + auto sA1 = cutlass::make_cute_packed_stride(typename G::StrideA{}, cute::make_shape(m, k1, 1)); + auto sB1 = cutlass::make_cute_packed_stride(typename G::StrideB{}, cute::make_shape(n1, k1, 1)); + auto sC1 = cutlass::make_cute_packed_stride(typename G::StrideC{}, cute::make_shape(m, n1, 1)); + auto sD1 = cutlass::make_cute_packed_stride(typename G::StrideD{}, cute::make_shape(m, n1, 1)); + auto lA1 = G::ScaleConfig::tile_atom_to_shape_SFA(cute::make_shape(m, n1, k1, 1)); + auto lB1 = G::ScaleConfig::tile_atom_to_shape_SFB(cute::make_shape(m, n1, k1, 1)); + auto sA2 = cutlass::make_cute_packed_stride(typename G::StrideA{}, cute::make_shape(m, k2, 1)); + auto sB2 = cutlass::make_cute_packed_stride(typename G::StrideB{}, cute::make_shape(n2, k2, 1)); + auto lA2 = G::ScaleConfig::tile_atom_to_shape_SFA(cute::make_shape(m, n2, k2, 1)); + auto lB2 = G::ScaleConfig::tile_atom_to_shape_SFB(cute::make_shape(m, n2, k2, 1)); + using EA = typename G::ElementA; + using EB = typename G::ElementB; + using ED = typename G::ElementD; + typename Gemm::Arguments args{ + cutlass::gemm::GemmUniversalMode::kGemm, + {m, n1, k1, 1}, + {reinterpret_cast(qx), sA1, reinterpret_cast(qwgu), sB1, sx, lA1, sgu, lB1}, + {{}, nullptr, sC1, reinterpret_cast(qh), sD1}}; + args.epilogue.thread.alpha = 1.0f; + args.epilogue.thread.beta = 0.0f; + args.hw_info.sm_count = sm_count(); + args.fused_scale = sh; + args.mainloop_dn = {reinterpret_cast(qh), sA2, reinterpret_cast(qwd), sB2, sh, lA2, dws, lB2}; + args.out = reinterpret_cast(out); + args.dn_n = n2; + args.dn_k = k2; + args.mb_cnt = flags; + args.mg_lag = MG_LAG; + if (cq) args.cq = *cq; + if (Gemm::GemmKernel::kTailSplit && split_s > 1) { + const int P = max_pair_clusters(); + const int gu = ((m + 255) / 256) * (n1 / 256); + const int tail = gu % P; + if constexpr (Gemm::GemmKernel::kRedSplit) { + // wait-free reduction tiles: [tail tile][CTA rank] 128 x 256 fp32 + one counter each, zeroed once at allocation, + // re-zeroed by each tile's last arriver (raw device memory, never freed) + // TWO workspaces used by alternating split calls (parity). The last arriver no longer re-zeroes its tile; + // each tile's FIRST arriver zeroes the same slot of the other buffer (the next call's). Host tracks how many + // slots of each buffer may still be dirty (tail sets differ with M) and memsets that prefix if ever needed. + static float* rws = nullptr; + static int* rcnt = nullptr; + static int rcap = 0; + static int rpar = 0; + static int rdirty[2] = {0, 0}; // slots [0, rdirty[b]) of buffer b possibly non-zero + const size_t tile_f = (size_t)128 * 256; + const int s = split_s > 8 ? 8 : split_s; + // when every gate_up tile fits in ONE wave (gu <= P, small M), ALL gate_up tiles are split (t0 = 0) + const int tail = gu > P ? gu % P : gu; + if (tail > rcap) { + if (rws) { cudaFree(rws); cudaFree(rcnt); } + rcap = tail; + cudaMalloc(&rws, (size_t)2 * rcap * 2 * tile_f * sizeof(float)); + cudaMalloc(&rcnt, (size_t)rcap * 2 * sizeof(int)); + cudaMemsetAsync(rws, 0, (size_t)2 * rcap * 2 * tile_f * sizeof(float), stream); + cudaMemsetAsync(rcnt, 0, (size_t)rcap * 2 * sizeof(int), stream); + rdirty[0] = rdirty[1] = 0; + } + if (tail > 0 && rws && rcnt) { + const int b = rpar, a = rpar ^ 1; + float* cur = rws + (size_t)b * rcap * 2 * tile_f; + float* alt = rws + (size_t)a * rcap * 2 * tile_f; + if (rdirty[b] > 0) cudaMemsetAsync(cur, 0, (size_t)rdirty[b] * tile_f * sizeof(float), stream); + rdirty[b] = 2 * tail; // read, not re-zeroed + if (rdirty[a] <= 2 * tail) rdirty[a] = 0; // slots [0, 2 tail) zeroed by the first arrivers + rpar ^= 1; + args.mg_split = s; + args.mg_split_t0 = gu - tail; + args.split_ws = cur; + args.split_alt = alt; + args.split_cnt = rcnt; + } + } else { + SplitWs& w = split_ws(0); + const int s = split_s > 4 ? 4 : split_s; + if (gu > P && tail > 0 && tail * s <= P && tail * s <= w.p) { + args.mg_split = s; + args.mg_split_t0 = gu - tail; + args.split_ws = w.part; + args.split_cnt = w.cnt; + } + } + } + constexpr bool kHalfK = Gemm::GemmKernel::kHalfT; + args.mg_half = kHalfK ? 1 : 0; // only the kHalfT instantiation (Gemm2SMMergedOldHalf) has the wide-unit path + // the half path's extra TMA descriptors live in a device buffer (not in the kernel params). Rebuilt + copied + // (stream-ordered, after every earlier reader) only when its inputs change: the descriptors depend only on these. + using HalfExt = typename Gemm::GemmKernel::HalfExt; + static HalfExt* half_host = new HalfExt(); // heap, never freed + static HalfExt* half_dev = nullptr; + static uintptr_t half_key[8] = {0, 0, 0, 0, 0, 0, 0, 0}; + bool half_copy = false; + if (kHalfK && args.mg_half) { + if (!half_dev && cudaMalloc(&half_dev, sizeof(HalfExt)) != cudaSuccess) { half_dev = nullptr; cudaGetLastError(); } + const uintptr_t key[8] = {(uintptr_t)qx, (uintptr_t)qwgu, (uintptr_t)qh, (uintptr_t)qwd, + (uintptr_t)m, (uintptr_t)Hd, (uintptr_t)I, (uintptr_t)sizeof(HalfExt)}; + bool same = true; + for (int i = 0; i < 8; ++i) same &= key[i] == half_key[i]; + args.half_fill = !same; + half_copy = !same; + if (!same && half_dev) for (int i = 0; i < 8; ++i) half_key[i] = key[i]; + args.half_host = half_host; + args.half_dev = half_dev; + } + if (kHalfK) { // half-block instantiation (not dispatched): original uncached adapter path + Gemm gemm; + if (gemm.can_implement(args) != cutlass::Status::kSuccess) return 1; + size_t ws = Gemm::get_workspace_size(args); + void* wsp = ws ? get_workspace(ws) : nullptr; + if (gemm.initialize(args, wsp, stream) != cutlass::Status::kSuccess) return 2; + if (half_copy && half_dev) { + if (cudaMemcpyAsync(half_dev, half_host, sizeof(HalfExt), cudaMemcpyHostToDevice, stream) != cudaSuccess) { + half_key[0] = 0; + return 4; + } + } + if (gemm.run(stream, nullptr, /*launch_with_pdl=*/true) != cutlass::Status::kSuccess) return 3; + return 0; + } + size_t ws = Gemm::get_workspace_size(args); + void* wsp = ws ? get_workspace(ws) : nullptr; + const uintptr_t key[26] = {(uintptr_t)qx, (uintptr_t)qwgu, (uintptr_t)sx, (uintptr_t)sgu, (uintptr_t)qh, + (uintptr_t)sh, (uintptr_t)qwd, (uintptr_t)dws, (uintptr_t)out, (uintptr_t)m, + (uintptr_t)Hd, (uintptr_t)I, (uintptr_t)flags, (uintptr_t)args.mg_split, + (uintptr_t)args.mg_split_t0, (uintptr_t)args.split_ws, (uintptr_t)args.split_cnt, + (uintptr_t)wsp, (uintptr_t)ws, (uintptr_t)args.mg_lag, + // kCq: everything the converter params depend on (maps: x / dw pointer + Mr) + cq ? (uintptr_t)cq->xp : 0, cq ? (uintptr_t)cq->dwp : 0, cq ? (uintptr_t)cq->ds : 0, + cq ? (uintptr_t)cq->ready : 0, + cq ? ((uintptr_t)cq->Mr | ((uintptr_t)cq->r1 << 20) | ((uintptr_t)cq->rg << 40) | + ((uintptr_t)cq->on << 60) ^ ((uintptr_t)cq->cb << 52) ^ ((uintptr_t)(cq->nxr != 0) << 62) ^ ((uintptr_t)cq->ds0 << 32)) : 0, + cq ? ((uintptr_t)cq->xr0 | ((uintptr_t)cq->nxr << 24)) : 0}; + return cached_launch(args, key, 26, wsp, stream); +} + +// Variant dispatch (see header): v0 1SM 128x128, v1 2SM 256x128, v2 1SM 128x256, v3 2SM 256x256. +static int run_variant(int v, const uint8_t* A, const uint8_t* B, const float* SFA, const float* SFB, + const float* SFB64, void* D, + int m, int n, int k, cudaStream_t stream) { + switch (v) { + case 1: return run_blockwise_gemm(A, B, SFA, SFB, D, m, n, k, stream); + case 4: return run_blockwise_gemm(A, B, SFA, SFB64, D, m, n, k, stream); + case 15: return run_blockwise_gemm(A, B, SFA, SFB, D, m, n, k, stream); + case 19: return run_blockwise_gemm(A, B, SFA, SFB64, D, m, n, k, stream); // SFB64 = sd32 here + case 22: return run_blockwise_gemm(A, B, SFA, SFB64, D, m, n, k, stream); // trimmed carve-out + case 23: return run_blockwise_gemm(A, B, SFA, SFB64, D, m, n, k, stream); // 4-stage 224 + default: return run_blockwise_gemm(A, B, SFA, SFB, D, m, n, k, stream); + } +} + +static int pick_variant(int gid, int m, int /*n*/) { + static const int kM[19] = {128, 256, 384, 512, 640, 768, 1024, 1280, 1536, 1792, + 2048, 2304, 2560, 2816, 3072, 3328, 3456, 3712, 4096}; + static const int kGU[19] = {4, 4, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}; + static const int kDN[19] = {4, 0, 15, 15, 0, 1, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15}; + int best = 0; + for (int i = 1; i < 19; ++i) { + int dc = abs(m - kM[i]), db = abs(m - kM[best]); + if (dc <= db) best = i; // ties go to the larger bucket + } + return gid == 0 ? kGU[best] : kDN[best]; +} + +// --------------------------------------------------------------------------------------------- +// Host launcher +// --------------------------------------------------------------------------------------------- +#define PROBE_FORCE_S 0 +#define DS_FORCE_S PROBE_FORCE_S +static bool use_chain(int M) { return M > 192; } +// sixteenths of the down-weight quant moved from the PDL dq kernel (which only gets the SMs the gate_up GEMM leaves +// idle) into the front fused quant pass (non-merged chain path). 0 = all in the dq kernel. +static int dq_front16(int M) { + return (M + 127) / 128 == 4 ? 9 : 0; +} +static bool use_merged(int M) { + return M >= 704; +} +#ifndef SE_CQ_HINT +#define SE_CQ_HINT 6 +#endif +int g_cq = -1, g_cq_g1 = 0, g_cq_b = 0, g_cq_on = -1; +#ifndef CQ_DISPATCH +#define CQ_DISPATCH(M) ((M) >= 1344 || ((M) >= 704 && (M) < 1216)) // + mid-M merged range +#endif +#ifndef CQ_X_DISPATCH +#define CQ_X_DISPATCH(M) false +#endif +// first ds0 256-row down-weight slabs quantized by the front quant pass (rest in-kernel), see cq_ds0 +#ifndef CQ_DS0 +#define CQ_DS0(M) (((M) >= 1216 && (M) < 1344) ? 8 : ((M) >= 1344 && (M) < 1600) ? 1 : ((M) >= 704 && (M) < 1216) ? 4 /* mid-M merged kCq ds0 2 -> 4*/ : ((M) < 1600) ? 2 : ((M) >= 3136 && (M) < 3456) ? 0 /* M3200 bucket ds0 1 -> 0 (all down slabs in-kernel; M2816/M3072 already 0)*/ /* M3456 bucket [3456,3584) ds0 1 -> 0*/ : 0) +#endif +int g_cq_ds0 = -1; // probe override (-1 auto) +static int cq_ds0(int M, int Hd) { + int d = g_cq_ds0 >= 0 ? g_cq_ds0 : CQ_DS0(M); + if (d > Hd / 256) d = Hd / 256; + return d < 0 ? 0 : d; +} +// M1280 (kRedSplit s8, no kCq): front quant 0-24.2 (x + gate/up + DOWN weights, ~160 MB at ~6.6 TB/s = DRAM bound), +// merged 26.2-70.9 +int g_cqs = -1; // probe override (-1 auto) +static bool use_cqs(int M) { return g_cqs >= 0 ? g_cqs != 0 : (M >= 1216 && M < 1344); } +static bool use_cq(int M) { + if (g_xs_split == 1) return true; + if (g_cq >= 0) return g_cq != 0; + return CQ_DISPATCH(M); +} +// x converted in-kernel too (g_cq 3: probe, down weights only) +static bool cq_with_x(int M) { + if (g_cq >= 0) return g_cq != 3; + return CQ_X_DISPATCH(M); +} +#ifndef SE_XSPLIT_MIN +#define SE_XSPLIT_MIN 2752 // x split also at the M2816/3072/3200 buckets +#endif +// x0 / converter-order overrides (probe: -99 = auto) +int g_x0d = -99, g_cqord = -99, g_xforce = -1; // g_xforce: probe override of the x-split admission (-1 auto, 0 off, 1 on) +#ifndef SE_X0D +#define SE_X0D(M) (((M) >= 1664 && (M) < 1856) ? -4 : (M) < 1856 ? -5 : (M) < 2048 ? -3 /* M1920 bucket x split d -3 (x0 = 1792)*/ : ((M) >= 2048 && (M) < 2240) ? -3 /* M2176 bucket back to x0 = 1792*/ : (M) < 3136 ? -3 /* M2816 + M3072 buckets d -2 -> -3*/ : (M) < 3456 ? -3 : (M) < 3520 ? -4 /* M3456 bucket d -3 -> -4*/ : -3) /* M3712 bucket back to d -3; + M384 Gemm1SM160TmaC, M2816/M3072 d -3*/ +#endif +#ifndef SE_CQORD +#define SE_CQORD(M) 0 +#endif +#ifndef SE_XRG +#define SE_XRG (256 / se2wg::kCqRows) +#endif +// converter list order for the x split: 0 x rows first, 1 down slabs first, 2 half of the x rows before the down slabs +static int cq_ord(int M) { return g_cqord != -99 ? g_cqord : SE_CQORD(M); } +static int cq_x0(int M, int P, int gu_tn) { +#if defined(SE_XS_MID) && !defined(SE_XMID) +#define SE_XMID(M) ((M) >= 1344 && (M) < 2048) +#endif +#ifndef SE_XMID +#define SE_XMID(M) false /* M1792 bucket no longer x-split (see CQ_DS0)*/ +#endif + const bool lo_ok = (M >= 2048 && M < SE_XSPLIT_MIN) /* + M2304 bucket [2240, 2368), d -3*/ || SE_XMID(M) /* M1920 bucket x split*/ || ((M) >= 1216 && (M) < 1344); // / (+M1280 bucket: x0 = 0 at the default d) + if (g_xforce == 0) return 0; + if (g_cq >= 0 || (M < SE_XSPLIT_MIN && !lo_ok && g_xforce != 1)) return 0; + const int x0 = 256 * (2 * P / gu_tn + 1 + (g_x0d != -99 ? g_x0d : SE_X0D(M))); + // M3584 / M3712 buckets (M >= 3520): x0 shifted -128 rows (1792 -> 1664, tile aligned), with 2-M-block + // converter groups (see SE_XRG use below); dispatch-only, bit-identical + const int x0s = (g_x0d == -99 && M >= 3520) ? x0 - 128 : x0; + return x0s < M ? x0s : 0; +} +// bf16 [outer, inner] row-major TMA map, box 128 (inner) x kCqRows rows, no swizzle, OOB rows zero-filled. Cached per +// (pointer, shape): an encode only depends on address + geometry. +static bool cq_map(CUtensorMap* m, const void* ptr, int inner, int outer) { + struct E { const void* p; int i, o; CUtensorMap m; }; + static E* cache = new E[16](); + static int nxt = 0; + for (int k = 0; k < 16; ++k) + if (cache[k].p == ptr && cache[k].i == inner && cache[k].o == outer) { *m = cache[k].m; return true; } + const cuuint64_t gdim[2] = {(cuuint64_t)inner, (cuuint64_t)outer}; + const cuuint64_t gstr[1] = {(cuuint64_t)inner * 2}; + const cuuint32_t box[2] = {128, (cuuint32_t)se2wg::kCqRows}; + const cuuint32_t es[2] = {1, 1}; + if (cuTensorMapEncodeTiled(m, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, const_cast(ptr), gdim, gstr, 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) != CUDA_SUCCESS) + return false; + cache[nxt].p = ptr; cache[nxt].i = inner; cache[nxt].o = outer; cache[nxt].m = *m; + nxt = (nxt + 1) & 15; + return true; +} +// host critical path: the output pointer is obtained through get_out(ctx) only AFTER the first kernel (fused quant) +// has been enqueued, so the caller's output-tensor allocation overlaps the GPU's quant kernel instead of delaying it. +int launch_shared_expert_cb(const void* x, const void* gw, const float* gws, const void* uw, const float* uws, + const void* dw, const float* dws, void* (*get_out)(void*), void* out_ctx, + uint8_t* qx, float* sx, uint8_t* qwgu, float* sgu, uint8_t* qwd, + void* h1, uint8_t* qh, float* sh, int M, int Hd, int I, cudaStream_t stream, + int M_real) { + void* out = nullptr; + // M is the padded row count (multiple of 4: the MN-major 1x128 activation-scale tables sx / sh [K/128][M] need + // 16-byte aligned rows for the CUTLASS scale-factor loads, otherwise can_implement rejects odd M). Rows + // [M_real, M) of x are treated as zeros by the quant kernel; every later stage runs on M rows. + const int T = 256; + // 64-granular weight-scale tables for v4 (grow-only raw device buffers, never freed) + static float* sgu64 = nullptr; + static float* sd64 = nullptr; + static float* sd32 = nullptr; + static size_t sgu64_n = 0, sd64_n = 0, sd32_n = 0; + { + size_t ngu = (size_t)(Hd / 128) * (2 * I / 64), nd = (size_t)(I / 128) * (Hd / 64); + if (ngu > sgu64_n) { if (sgu64) cudaFree(sgu64); cudaMalloc(&sgu64, ngu * sizeof(float)); sgu64_n = ngu; } + if (nd > sd64_n) { if (sd64) cudaFree(sd64); cudaMalloc(&sd64, nd * sizeof(float)); sd64_n = nd; } + const size_t nd32 = 2 * nd + 64; // + slack (partial last 160-col tile's scale loads past the table end) + if (nd32 > sd32_n) { if (sd32) cudaFree(sd32); cudaMalloc(&sd32, nd32 * sizeof(float)); sd32_n = nd32; } + } + QuantArgs qd_args; + // down-weight quant placement. chain: PDL kernel between gate_up(/swiglu) and the down GEMM (no join); + // otherwise the old side stream (fork after quant1, event join before the down GEMM). + bool chain = use_chain(M); + // Side stream + fork/join events: created once, raw handles, never destroyed (no teardown destructor). + static cudaStream_t side = nullptr; + static cudaEvent_t ev_fork = nullptr, ev_join = nullptr; + if (!side) { + cudaStreamCreateWithFlags(&side, cudaStreamNonBlocking); + cudaEventCreateWithFlags(&ev_fork, cudaEventDisableTiming); + cudaEventCreateWithFlags(&ev_join, cudaEventDisableTiming); + } + // 1. fused quant launch (x + gate/up) (normal launch: must not overlap the previous call's down GEMM, + // which still reads qwd/qh). + { + QuantArgs a; + a.x = (const __nv_bfloat16*)x; a.qx = qx; a.sx = sx; a.M = M; a.Mr = M_real; a.Hd = Hd; a.I = I; + a.gw = (const __nv_bfloat16*)gw; a.gs = gws; + a.uw = (const __nv_bfloat16*)uw; a.us = uws; + a.dw = (const __nv_bfloat16*)dw; a.ds = dws; + a.qgu = qwgu; a.sgu = sgu; a.qd = qwd; a.sgu64 = sgu64; a.sd64 = sd64; a.sd32 = sd32; + long xunits = (long)M * (Hd / 128); // 64 units (4 threads each) per block + a.nbx = xq_blocks(SE_XV, M, Hd); // x blocks of the shipped x mapping (xunits units) + (void)xunits; + long wth = (long)I * Hd / 32; // threads per weight (32 elems each; all are I*Hd elements) + a.nbw = (int)((wth + T - 1) / T); + a.wbase = 0; + a.mb_cnt = nullptr; a.n_mb = 0; + a.z2 = nullptr; a.nz2 = 0; a.z2v = 0; a.z2a = a.z2b = 0; + a.dq_off = 0; + // merged path (large M): ONE quant launch for x + gate/up + down weights (the merged kernel needs qWd from + // its first down tile), then ONE persistent gate_up+down kernel. + bool merged = use_merged(M); + if (merged) { + a.n_mb = ((M + 255) / 256) * (2 * I / 256); // one counter per gate_up tile (kTileRdy), block-indexed otherwise + a.mb_cnt = merged_counters(a.n_mb); + const bool cq_split = mg_split_for(M) > 1 && use_cqs(M); + if ((use_cq(M) && mg_split_for(M) <= 1) || cq_split) { + // kCq: the down weights (and, cq_x, x) are converted inside the merged kernel by its converter warpgroup + // (bw2wg.h kCq); the quant kernel quantizes the gate/up weights (+ x unless cq_x) and zeroes this call's counters. + const int KB1 = Hd / 128, KB2 = I / 128; + const int nxc = ((M + 127) / 128) * KB1, ncnt = nxc + (Hd / 256) * KB2 + 1; + static int* cqc = nullptr; + static int cqn = 0; + if (ncnt > cqn) { + if (cqc) cudaFree(cqc); + if (cudaMalloc(&cqc, (size_t)ncnt * sizeof(int)) != cudaSuccess) { cqc = nullptr; cqn = 0; cudaGetLastError(); return 51; } + cqn = ncnt; + } + a.z2 = cqc; a.nz2 = ncnt; a.z2v = 0; + // cq_x: x converted in-kernel too (else the quant kernel quantizes x + gate/up, the kernel the down weights) + const bool cq_x = cq_with_x(M); + const int x0 = cq_x ? 0 : cq_x0(M, max_pair_clusters(), 2 * I / 256); + QuantArgs aq = a; + if (cq_x) aq.nbx = 0; // gate / up weights only + static_assert(SE_XV == 2 || SE_XV == 3, "v162 x split assumes the 8-row x tile mapping"); + if (x0 > 0) aq.nbx = (x0 / 8) * ((Hd / 128 + kFqKpb - 1) / kFqKpb); // x tiles of rows [0, x0) only + if (g_cq == 2) { aq = a; aq.z2v = 1 << 30; } // probe: full quant pass, conversion bypassed (prefilled) + // the front pass also quantizes down slabs [0, ds0) (its last-mapped weight blocks = down rows + // [0, 256 ds0), 64 blocks per slab at I = 2048); their readiness counters are preset ready (16 chunks) + const int ds0 = cq_ds0(M, Hd); + const int nfd = ds0 * (256 * I / 32 / 256); + aq.z2a = nxc; aq.z2b = nxc + ds0 * KB2; + fq_launch((unsigned)(aq.nbx + (g_cq == 2 ? 3 * aq.nbw : 2 * aq.nbw + nfd)), stream, aq); + out = get_out(out_ctx); + if (!out) return 50; + static se2wg::CqArgs& cqa = *new se2wg::CqArgs(); // heap, never freed (maps cached by pointer / shape) + if (!cq_map(&cqa.tm_x, x, Hd, M_real) || !cq_map(&cqa.tm_d, dw, I, Hd)) return 52; + cqa.ds = dws; cqa.qx = qx; cqa.sx = sx; cqa.qwd = qwd; + cqa.ready = cqc; cqa.ticket = cqc + ncnt - 1; + cqa.M = M; cqa.Hd = Hd; cqa.I = I; + const int nr = cq_x ? (M + se2wg::kCqRows - 1) / se2wg::kCqRows + : (x0 > 0 ? (M + se2wg::kCqRows - 1) / se2wg::kCqRows - x0 / se2wg::kCqRows : 0); + cqa.nxr = nr; + cqa.xr0 = x0 / se2wg::kCqRows; + cqa.cb = g_cq_b > 0 ? g_cq_b : (cq_x ? 2 : (M >= 3520 && M < 3648) ? 3 : (((M >= 1216 && M < 1344) || (M >= 1344 && M < 1600) /* M1408 bucket cb 4 -> 3*/ || (M >= 1664 && M < 1856) || (M >= 2048 && M < 2240) || (M >= 2240 && M < 2368) || M >= 2752) ? 3 : 4)) /* cb=3 for every merged kCq bucket M>=2816 */ /* cb=3 also M2304 bucket; also M3456 / M3712 buckets; also M3584 bucket [3520,3648)*/; + // x group = the 128-row tiles of the M blocks one wave of gate_up units covers (kb-major inside a group) + const int P = max_pair_clusters(); + const int mbw = (P + (2 * I / 256) - 1) / (2 * I / 256); + cqa.rg = std::max(1, std::min(std::max(nr, 1), mbw * 2 * (128 / se2wg::kCqRows))); + cqa.r1 = std::min(nr, cqa.rg * (g_cq_g1 > 0 ? g_cq_g1 : 2)); // down weights after the first x groups + if (x0 > 0 && nr > 0) { // x-split list order + const int od = cq_ord(M); + // x rows converted in GU CLC unit order: one 256-row M block (2 tiles) per group, + // kb-major inside, so the converters finish M block b (all k blocks) before b+1 -> just-in-time readiness for + // the GU wave that reaches x rows >= x0 (all x-split M ranges) + if (od == 0) { cqa.rg = std::max(1, std::min(nr, M >= 3520 ? 2 * SE_XRG : SE_XRG)); cqa.r1 = nr; } // 2 M blocks per group at M >= 3520 + else if (od == 1) cqa.r1 = 0; + else if (od == 2) { cqa.rg = std::max(1, (nr + 1) / 2); cqa.r1 = std::min(nr, cqa.rg); } + } + cqa.on = g_cq == 2 ? 0 : (g_cq_on >= 0 ? g_cq_on : (1 | SE_CQ_HINT | (((M >= 1664 && M < 2560) || (M >= 704 && M < 1216)) ? 8 : 0) /* + mid-M merged kCq range [704,1216): DN-weight conversion gates the first DN units there too*/)); // bit 3 = skip converter WAR proxy fence + cqa.ds0 = g_cq == 2 ? 0 : ds0; + cqa.xp = x; cqa.dwp = dw; cqa.Mr = M_real; + const int rc = cq_split ? run_merged(qx, qwgu, sx, sgu, qh, sh, qwd, dws, out, M, Hd, I, + stream, mg_split_for(M), &cqa) + : ((M >= 1344 && M < 1600) || (M >= 2368 && M < 2560)) /* kTg also at the M2432 bucket (160 GU tiles / 74 clusters: 12-tile tail now spans high-nt tiles of blocks 8 and 9 -> both blocks' DN units run 10 low k blocks during the tail instead of block 9 only 4)*/ + ? run_merged(qx, qwgu, sx, sgu, qh, sh, qwd, dws, out, M, Hd, I, stream, 1, &cqa) + : run_merged(qx, qwgu, sx, sgu, qh, sh, qwd, dws, out, M, Hd, I, stream, 1, &cqa); + return rc ? 40 + rc : 0; + } + fq_launch((unsigned)(a.nbx + 3 * a.nbw), stream, a); + out = get_out(out_ctx); // allocate the output after the first launch + if (!out) return 50; + int rm = run_merged(qx, qwgu, sx, sgu, qh, sh, qwd, dws, out, M, Hd, I, stream); + return rm ? 40 + rm : 0; + } + // main stream: x + gate/up (+ the first nf down-weight quant blocks, see dq_front16) + int nf = (int)(((long)a.nbw * dq_front16(M)) / 16); + if (nf > a.nbw - 1) nf = a.nbw - 1; // the PDL dq kernel keeps >= 1 block (its block 0 orders the down GEMM) + if (nf < 0 || chain == false) nf = 0; + fq_launch((unsigned)(a.nbx + 2 * a.nbw + nf), stream, a); + out = get_out(out_ctx); // allocate the output after the first launch + if (!out) return 50; + qd_args = a; // down-weight quant args (launched as a PDL kernel right before the down GEMM) + qd_args.nbx = 0; qd_args.wbase = 2; + qd_args.dq_off = nf; qd_args.nbw = a.nbw - nf; // dq kernel grid = remaining blocks + if (!chain) { + // fork: side stream waits for main (full completion of quant1, hence of the previous call's down GEMM + // that read qwd), then quantizes down_w only, overlapping the gate_up GEMM + swiglu. + cudaEventRecord(ev_fork, stream); + cudaStreamWaitEvent(side, ev_fork, 0); + fq_launch((unsigned)a.nbw, side, qd_args); + cudaEventRecord(ev_join, side); + } + } + // 2. gate_up GEMM (PDL) + int v = pick_variant(0, M, 2 * I); + if (v == 10) { + using K12 = typename Gemm2SM2WGFusedStatic::Gemm::GemmKernel; + typename K12::Params sp{}; + K12::make_schedule(sp, M, 2 * I, Hd, 2 * max_pair_clusters(), true); + if (sp.st_split >= 4) v = 12; + const int tn = (2 * I) / 256, pairs = ((M + 255) / 256) * tn, ctas = ((M + 127) / 128) * tn; + if (pairs > max_pair_clusters() && ctas <= sm_count()) v = 16; + if ((M + 127) / 128 <= 4 && ctas * 2 <= sm_count()) v = 17; + } + const bool fused = v == 10 || v == 12 || v == 16 || v == 17; + int r = v == 10 ? run_blockwise_gemm(qx, qwgu, sx, sgu, qh, M, 2 * I, Hd, stream, 1, sh) + : v == 16 ? run_blockwise_gemm(qx, qwgu, sx, sgu, qh, M, 2 * I, Hd, stream, 1, sh) + : v == 17 ? run_pair_gate_up(qx, qwgu, sx, sgu, qh, sh, M, 2 * I, Hd, stream) // DSMEM pair + : v == 12 ? run_blockwise_gemm(qx, qwgu, sx, sgu, qh, M, 2 * I, Hd, stream, 1, sh, + PROBE_FORCE_S) + : run_variant(v, qx, qwgu, sx, sgu, sgu64, h1, M, 2 * I, Hd, stream); + if (r) { if (!chain) cudaStreamWaitEvent(stream, ev_join, 0); return 10 + r; } // never leave a fork unjoined + // 3. SwiGLU + requant (PDL launch via cudaLaunchKernelEx) -- skipped when the GEMM epilogue fused it + if (!fused) { + long units = (long)M * (I / 128); // one warp per unit, 8 warps per block + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3((unsigned)((units + (T / 32) - 1) / (T / 32))); + cfg.blockDim = dim3(T); + cfg.dynamicSmemBytes = 0; + cfg.stream = stream; + cudaLaunchAttribute attr[1]; + attr[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attr[0].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = attr; + cfg.numAttrs = 1; + if (cudaLaunchKernelEx(&cfg, swiglu_quant_kernel, (const __nv_bfloat16*)h1, qh, sh, M, I) != cudaSuccess) { + if (!chain) cudaStreamWaitEvent(stream, ev_join, 0); + return 30; + } + } + // 4. down-weight quant (PDL, main stream; see down_quant_pdl_kernel) or the side-stream join, then the down GEMM + if (!chain) cudaStreamWaitEvent(stream, ev_join, 0); + else { + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3((unsigned)qd_args.nbw); + cfg.blockDim = dim3(T); + cfg.dynamicSmemBytes = 0; + cfg.stream = stream; + cudaLaunchAttribute attr[1]; + attr[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attr[0].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = attr; + cfg.numAttrs = 1; + { + void* dargs[1] = {&qd_args}; + static CUfunction fdq = nullptr; + static int tdq = 0; + // 4-M-tile kPair gate_up -> persistent dq grid sized to the SMs kPair leaves idle (see down_quant_persist_kernel) + int idle = 0; + if (v == 17 && (M + 127) / 128 == 4) idle = sm_count() - 2 * ((M + 127) / 128) * ((2 * I) / 256); + if (idle > 0) { + static int occ = 0; + if (occ <= 0) { + if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&occ, down_quant_persist_kernel, T, 0) != cudaSuccess || occ <= 0) { + cudaGetLastError(); occ = 1; + } + } + const unsigned g = (unsigned)std::min((long)qd_args.nbw, (long)idle * occ); + static CUfunction fdp = nullptr; + static int tdp = 0; + if (drv_launch_plain((const void*)down_quant_persist_kernel, fdp, tdp, dim3(g), cfg.blockDim, stream, true, + dargs)) return 31; + } else + if (drv_launch_plain((const void*)down_quant_pair_kernel, fdq, tdq, dim3((unsigned)((qd_args.nbw + 1) / 2)), + cfg.blockDim, stream, true, dargs)) return 31; // kDqPair + } + } + v = pick_variant(1, M, Hd); + // 256x224 down tile where the 256x256 one leaves SM pairs idle in a single wave (M <= 512 buckets) + // every non-merged bucket (M < 1344) whose 224-tile pair count needs no more waves than the 256-tile one + if (v == 15 && M < 1344 && Hd % 224 == 0) { + const int P = sm_count() / 2 > 0 ? sm_count() / 2 : 1, tmp = (M + 255) / 256; + const int w256 = (tmp * ((Hd + 255) / 256) + P - 1) / P, w224 = (tmp * (Hd / 224) + P - 1) / P; + if (w224 <= w256) v = 19; + // A/B: 1SM 128x224 (128-row units: no padded 128-row half of a pair tile) when its CTAs fit in one wave and + // the 256-row pair tiling would carry a half-empty last M block (M384 bucket) + const int tm1 = (M + 127) / 128; +#ifndef SE_USE_V20 +#define SE_USE_V20 0 // 4-M-tile bucket back to 2SM 256x224. Was: M384 bucket (3 odd 128-row tiles) -> 1SM 128x224 down tile (no padded half pair-tile) +#endif + if (SE_USE_V20 && v == 19 && M <= 576 && tm1 == 4 && tm1 * (Hd / 224) <= sm_count()) v = 20; + } + // <= 3 128-row M tiles (M384 bucket, 2SM pairs with a half-padded M block): 1SM 128x160 down tile when its + // CTAs fit one wave (3 x 45 = 135 <= 148 SMs) + if (v == 19 && (M + 127) / 128 == 3 && Hd % 32 == 0 && ((M + 127) / 128) * ((Hd + 159) / 160) <= sm_count()) v = 22; // Gemm1SM160TmaC (5 A/B stages instead of 3) + if ((v == 0 || v == 1 || v == 15 || v == 19) && (((M + 127) / 128 >= 6 && (M + 127) / 128 <= 9) || (M + 127) / 128 == 4 /* 4-tile bucket (M512): 1SM 128x224 4-stage, 4 x 32 = 128 CTAs (was 2SM 256x224 64 clusters)*/) && Hd % 224 == 0) v = 23; // 4-stage trimmed-carve-out build of + r = run_variant(v, qh, qwd, sh, dws, (v >= 19 && v <= 23) ? sd32 : sd64, out, M, Hd, I, stream); + if (r) return 20 + r; + return 0; +} + +// Legacy entry (probe code): fixed output pointer. +static void* se_fixed_out(void* p) { return p; } +int launch_shared_expert(const void* x, const void* gw, const float* gws, const void* uw, const float* uws, + const void* dw, const float* dws, void* out, + uint8_t* qx, float* sx, uint8_t* qwgu, float* sgu, uint8_t* qwd, + void* h1, uint8_t* qh, float* sh, int M, int Hd, int I, cudaStream_t stream, + int M_real) { + return launch_shared_expert_cb(x, gw, gws, uw, uws, dw, dws, se_fixed_out, out, qx, sx, qwgu, sgu, qwd, h1, qh, sh, + M, Hd, I, stream, M_real); +} + +// scratch-owning entry used by main.cpp. The fp8 / scale / H intermediates live in grow-only raw device buffers +// (allocated on first use / growth, never freed -> no static tensor destructors), so run() does NO allocation before +// the first kernel launch. Reuse across calls on one stream is safe: each call's first kernel is a normal (non-PDL) +// launch, which starts only after the previous call's kernels (the last readers of these buffers) have completed. +static void* se_grow(void*& p, size_t& cap, size_t bytes) { + if (bytes > cap) { + if (p) cudaFree(p); + if (cudaMalloc(&p, bytes) != cudaSuccess) { p = nullptr; cap = 0; cudaGetLastError(); return nullptr; } + cap = bytes; + } + return p; +} +int launch_shared_expert_auto(const void* x, const void* gw, const float* gws, const void* uw, const float* uws, + const void* dw, const float* dws, void* (*get_out)(void*), void* out_ctx, int M, int Hd, + int I, cudaStream_t stream, int M_real) { + static void* b[8] = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}; + static size_t c[8] = {0, 0, 0, 0, 0, 0, 0, 0}; + const size_t sz[8] = {(size_t)M * Hd, // qx + (size_t)(Hd / 128) * M * sizeof(float), // sx + (size_t)2 * I * Hd, // qwgu + (size_t)(Hd / 128) * (2 * I / 128) * sizeof(float), // sgu + (size_t)Hd * I, // qwd + (size_t)M * 2 * I * 2, // h1 (bf16 gate_up output, unfused paths) + (size_t)M * I, // qh + (size_t)(I / 128) * M * sizeof(float)}; // sh + for (int i = 0; i < 8; ++i) + if (!se_grow(b[i], c[i], sz[i])) return 60 + i; + return launch_shared_expert_cb(x, gw, gws, uw, uws, dw, dws, get_out, out_ctx, (uint8_t*)b[0], (float*)b[1], + (uint8_t*)b[2], (float*)b[3], (uint8_t*)b[4], b[5], (uint8_t*)b[6], (float*)b[7], M, Hd, + I, stream, M_real); +} + +bool smallm_supported(int M, int Hd, int I); +#ifndef SE_SMALL_MAX +#define SE_SMALL_MAX 128 +#endif +bool se_small_path(int M, int Hd, int I) { return M <= SE_SMALL_MAX && smallm_supported(M, Hd, I); } + + + + + + + + + + + + + + + diff --git a/kernels/Quant/017_fp8_shared_expert_mlp/src/kernel.h b/kernels/Quant/017_fp8_shared_expert_mlp/src/kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..39b7ae8ea5199c1403351afdf848a33f378b3180 --- /dev/null +++ b/kernels/Quant/017_fp8_shared_expert_mlp/src/kernel.h @@ -0,0 +1,21 @@ +#pragma once +#include +#include + +// Runs the full FP8 shared-expert MLP. Returns 0 on success, nonzero CUTLASS status code otherwise. +int launch_shared_expert(const void* x, const void* gw, const float* gws, const void* uw, const float* uws, + const void* dw, const float* dws, void* out, + uint8_t* qx, float* sx, uint8_t* qwgu, float* sgu, uint8_t* qwd, + void* h1, uint8_t* qh, float* sh, int M, int Hd, int I, cudaStream_t stream, + int M_real); // M = M_real rounded up to a multiple of 4 (buffers sized with M) + +// scratch-owning entry; get_out(out_ctx) is called once, after the first kernel launch, and must return the +// [M, Hd] bf16 output buffer (nullptr -> error). +int launch_shared_expert_auto(const void* x, const void* gw, const float* gws, const void* uw, const float* uws, + const void* dw, const float* dws, void* (*get_out)(void*), void* out_ctx, int M, int Hd, + int I, cudaStream_t stream, int M_real); +bool se_small_path(int M, int Hd, int I); // small-M weight-streaming path applies (smallm.cu) +// smallm.cu: x-quant + gate_up (front) and down launches +int launch_small_m_front(const void* x, const void* gw, const float* gws, const void* uw, const float* uws, + const void* dw, int M, int Hd, int I, cudaStream_t stream); +int launch_small_m_down(const void* dw, const float* dws, void* out, int M, int Hd, int I, cudaStream_t stream); diff --git a/kernels/Quant/017_fp8_shared_expert_mlp/src/main.cpp b/kernels/Quant/017_fp8_shared_expert_mlp/src/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4567f6a6cef2fe5d220a0e57bada1173dec514bd --- /dev/null +++ b/kernels/Quant/017_fp8_shared_expert_mlp/src/main.cpp @@ -0,0 +1,55 @@ +// Torch binding: allocates scratch buffers (fp8 activations/weights, scales, bf16 gate_up output) +// and calls the CUDA/CUTLASS pipeline in kernel.cu. +#include +#include +#include +#include "kernel.h" + + + +torch::Tensor run(torch::Tensor x, torch::Tensor gate_w, torch::Tensor gate_s, torch::Tensor up_w, + torch::Tensor up_s, torch::Tensor down_w, torch::Tensor down_s) { + if (!x.is_contiguous()) x = x.contiguous(); + if (!gate_w.is_contiguous()) gate_w = gate_w.contiguous(); + if (!up_w.is_contiguous()) up_w = up_w.contiguous(); + if (!down_w.is_contiguous()) down_w = down_w.contiguous(); + auto as_f32 = [](torch::Tensor& t) { + if (t.scalar_type() != torch::kFloat32 || !t.is_contiguous()) t = t.contiguous().to(torch::kFloat32); + }; + as_f32(gate_s); as_f32(up_s); as_f32(down_s); + const int Mr = (int)x.size(0), Hd = (int)x.size(1), I = (int)gate_w.size(0); + if (Mr == 0) return torch::empty({0, Hd}, x.options()); + cudaStream_t stream = at::cuda::getCurrentCUDAStream(); + if (se_small_path(Mr, Hd, I)) { + int r = launch_small_m_front(x.data_ptr(), gate_w.data_ptr(), gate_s.data_ptr(), up_w.data_ptr(), + up_s.data_ptr(), down_w.data_ptr(), Mr, Hd, I, stream); + TORCH_CHECK(r == 0, "shared expert small-M path failed, code ", 200 + r); + auto out = at::detail::empty_cuda({(int64_t)Mr, (int64_t)Hd}, x.scalar_type(), x.device(), c10::nullopt); + r = launch_small_m_down(down_w.data_ptr(), down_s.data_ptr(), out.data_ptr(), Mr, Hd, I, stream); + TORCH_CHECK(r == 0, "shared expert small-M path failed, code ", 200 + r); + return out; + } + // pad the token count to a multiple of 4 (16-byte aligned MN-major scale rows); the padding rows of the + // output are computed from zero inputs and dropped by the (contiguous) row view returned below. + const int M = (Mr + 3) & ~3; + struct OutCtx { torch::Tensor t; c10::ScalarType st; c10::Device dev; int64_t m, n; } ctx{torch::Tensor(), x.scalar_type(), x.device(), M, Hd}; + auto get_out = [](void* p) -> void* { + OutCtx* c = static_cast(p); + c->t = at::detail::empty_cuda({c->m, c->n}, c->st, c->dev, c10::nullopt); + return c->t.data_ptr(); + }; + int r = launch_shared_expert_auto(x.data_ptr(), gate_w.data_ptr(), gate_s.data_ptr(), up_w.data_ptr(), + up_s.data_ptr(), down_w.data_ptr(), down_s.data_ptr(), get_out, &ctx, + M, Hd, I, stream, Mr); + TORCH_CHECK(r == 0, "shared expert CUTLASS GEMM failed, code ", r); + return M == Mr ? ctx.t : ctx.t.narrow(0, 0, Mr); +} + + + + + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("run", &run, "FP8 shared expert MLP"); } + + + diff --git a/kernels/Quant/017_fp8_shared_expert_mlp/src/smallm.cu b/kernels/Quant/017_fp8_shared_expert_mlp/src/smallm.cu new file mode 100644 index 0000000000000000000000000000000000000000..6cec0774c35f4d26e0a343d005dbad345cee965f --- /dev/null +++ b/kernels/Quant/017_fp8_shared_expert_mlp/src/smallm.cu @@ -0,0 +1,1308 @@ +// --------------------------------------------------------------------------------------------------------- +// Small-M (num_tokens <= 128) weight-streaming path. The bf16 weights are quantized to fp8 INSIDE the GEMMs (no +// separate weight-quant pass, no fp8 weight round trip through global memory): the forward streams the 88 MB of bf16 +// weights from DRAM exactly once. Three kernels: +// +// 1. sm_xprep (normal launch: fully ordered after earlier stream work): one warp per (row, 128-col block): +// sx = max(amax/448, 1e-12), qx = fp8_e4m3(x/sx) (satfinite) -> qx [M,K] fp8 + sx [K/128][M]; also zeroes the +// gate_up split-K arrival counters of this call. +// 3. sm_dn (down, PDL launch): 64 output columns per CTA over the FULL K (no split-K, no reduction), 112 CTAs, +// decoupled converter / MMA / promoter warps, pipeline steps of 2 k blocks (see sm_dn). +// --------------------------------------------------------------------------------------------------------- +#include +#include +#include +#include +#include +#include +#include + +namespace smallm { + +__device__ __forceinline__ void pdl_wait() { asm volatile("griddepcontrol.wait;" ::: "memory"); } +__device__ __forceinline__ void pdl_trigger() { asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); } + + +// ---------------- mbarrier / cluster helpers ---------------- +__device__ __forceinline__ uint32_t smem_u32(const void* p) { return (uint32_t)__cvta_generic_to_shared(p); } +__device__ __forceinline__ void mbar_init(uint64_t* b, int cnt) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(smem_u32(b)), "r"(cnt) : "memory"); +} +__device__ __forceinline__ void mbar_expect_tx(uint64_t* b, uint32_t bytes) { + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(smem_u32(b)), "r"(bytes) : "memory"); +} +__device__ __forceinline__ void mbar_arrive_a(uint32_t a) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(a) : "memory"); +} +__device__ __forceinline__ void mbar_wait_a(uint32_t a, uint32_t parity) { + asm volatile( + "{\n\t.reg .pred p;\n\t" + "WAITA_%=:\n\t" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, 1000000;\n\t" + "@!p bra WAITA_%=;\n\t}" ::"r"(a), "r"(parity) + : "memory"); +} +// per-warp release (SE_SM_WREL): all lanes' prior smem / TMEM accesses (and their per-thread proxy / tcgen05 fences) +// ordered by __syncwarp, then ONE arrival by lane 0 (barrier counts divided by 32) +#ifndef SE_SM_WREL +#define SE_SM_WREL 1 +#endif +constexpr int kRelDiv = SE_SM_WREL ? 32 : 1; +__device__ __forceinline__ void warp_arrive_a(uint32_t a) { + if constexpr (SE_SM_WREL) { + __syncwarp(); + uint32_t l; + asm volatile("mov.u32 %0, %%laneid;" : "=r"(l)); + if (l == 0) mbar_arrive_a(a); + } else { + mbar_arrive_a(a); + } +} +__device__ __forceinline__ void mbar_arrive(uint64_t* b) { + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(smem_u32(b)) : "memory"); +} +__device__ __forceinline__ void mbar_wait(uint64_t* b, uint32_t parity) { + asm volatile( + "{\n\t.reg .pred p;\n\t" + "WAIT_%=:\n\t" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, 1000000;\n\t" + "@!p bra WAIT_%=;\n\t}" ::"r"(smem_u32(b)), + "r"(parity) + : "memory"); +} +__device__ __forceinline__ void cluster_sync() { + asm volatile("barrier.cluster.arrive.release;\n\tbarrier.cluster.wait.acquire;" ::: "memory"); +} +__device__ __forceinline__ uint32_t cluster_rank() { + uint32_t r; + asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(r)); + return r; +} +// address of the same smem location in cluster CTA `rank` (shared::cluster window) +__device__ __forceinline__ uint32_t mapa(uint32_t saddr, uint32_t rank) { + uint32_t r; + asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(r) : "r"(saddr), "r"(rank)); + return r; +} +__device__ __forceinline__ float4 ld_dsmem_f4(uint32_t addr) { + 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"(addr) + : "memory"); + return v; +} + +// ---------------- TMA ---------------- +__device__ __forceinline__ void tma_load_2d(void* dst, const CUtensorMap* map, uint64_t* bar, int c0, int c1, + uint64_t policy) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint" + " [%0], [%1, {%3, %4}], [%2], %5;" ::"r"(smem_u32(dst)), + "l"(map), "r"(smem_u32(bar)), "r"(c0), "r"(c1), "l"(policy) + : "memory"); +} +// 3-D tile load (bf16 weight chunk view {64 k, rows, k/64 chunks}): one box = R rows x 4 consecutive 64-k chunks, +// i.e. 512 contiguous global bytes per row; smem = [chunk][row][128 B] (SW128, each chunk slab 1024 B aligned) +__device__ __forceinline__ void tma_load_3d(void* dst, const CUtensorMap* map, uint64_t* bar, int c0, int c1, int c2, + uint64_t policy) { + asm volatile( + "cp.async.bulk.tensor.3d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint" + " [%0], [%1, {%3, %4, %5}], [%2], %6;" ::"r"(smem_u32(dst)), + "l"(map), "r"(smem_u32(bar)), "r"(c0), "r"(c1), "r"(c2), "l"(policy) + : "memory"); +} +// L2-only prefetch of one tensor-map box (no smem, no completion tracking) +__device__ __forceinline__ void tma_prefetch_2d(const CUtensorMap* map, int c0, int c1) { + asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile [%0, {%1, %2}];" ::"l"(map), "r"(c0), "r"(c1) + : "memory"); +} +__device__ __forceinline__ void tma_prefetch_2d_hint(const CUtensorMap* map, int c0, int c1, uint64_t policy) { + asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile.L2::cache_hint [%0, {%1, %2}], %3;" ::"l"(map), + "r"(c0), "r"(c1), "l"(policy) + : "memory"); +} +__device__ __forceinline__ void tma_load_2d_nohint(void* dst, const CUtensorMap* map, uint64_t* bar, int c0, int c1) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes" + " [%0], [%1, {%3, %4}], [%2];" ::"r"(smem_u32(dst)), + "l"(map), "r"(smem_u32(bar)), "r"(c0), "r"(c1) + : "memory"); +} +__device__ __forceinline__ uint64_t policy_evict_first() { + uint64_t p; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(p)); + return p; +} +__device__ __forceinline__ uint64_t policy_evict_last() { + uint64_t p; + asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(p)); + return p; +} + +// ---------------- tcgen05 ---------------- +// SM100 shared-memory matrix descriptor: K-major, SWIZZLE_128B (layout type 2 at bits 61-63), SBO = 1024 B (8 rows x +// 128 B), LBO unused for swizzled K-major (1), version 1 (bits 46-47), base offset 0 (tiles 1024 B aligned). +__device__ __forceinline__ uint64_t umma_desc_sw128(uint32_t saddr) { + uint64_t d = 0; + d |= (uint64_t)((saddr >> 4) & 0x3FFF); + d |= (uint64_t)1 << 16; + d |= (uint64_t)(1024 >> 4) << 32; + d |= (uint64_t)1 << 46; + d |= (uint64_t)2 << 61; + return d; +} +// instruction descriptor kind::f8f6f4: D f32 (bit 4), A/B E4M3 (format 0), K-major, N>>3 at bit 17, M>>4 at bit 24 +__host__ __device__ constexpr uint32_t umma_idesc_e4m3(int M, int N) { + return (1u << 4) | ((uint32_t)(N >> 3) << 17) | ((uint32_t)(M >> 4) << 24); +} +__device__ __forceinline__ void umma_e4m3(uint32_t dtmem, uint64_t da, uint64_t db, uint32_t idesc, uint32_t acc) { + asm volatile( + "{\n\t.reg .pred p;\n\tsetp.ne.b32 p, %4, 0;\n\t" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %3, p;\n\t}" ::"r"(dtmem), + "l"(da), "l"(db), "r"(idesc), "r"(acc) + : "memory"); +} +// lean MMA issue (small-M path): one 128-row x N x 128-k block = 4 x K=32 tcgen05.mma in ONE asm block. Descriptor +// = {lo, hi}: lo = start-address field (addr >> 4, 14 bits) | LBO 1 << 16, hi = SBO 1024 B (>> 4) | version bit 46 | +// SWIZZLE_128B layout 2 << 61 (constant) == umma_desc_sw128; K=32 step = +32 B -> lo + 2 (no carry: smem < 256 KB). +// Same 4 MMAs (first overwrites, rest accumulate) as the umma_desc_sw128 / umma_e4m3 loop -> bit-identical. +__device__ __forceinline__ uint32_t umma_lo(uint32_t saddr) { return ((saddr >> 4) & 0x3FFFu) | (1u << 16); } +__device__ __forceinline__ void umma4_lean(uint32_t d, uint32_t loA, uint32_t loB, uint32_t idesc) { + constexpr uint32_t kDescHi = (uint32_t)(1024 >> 4) | (1u << 14) | (2u << 29); + asm volatile( + "{\n\t.reg .b64 a0, a1, a2, a3, b0, b1, b2, b3;\n\t.reg .b32 la, lb;\n\t.reg .pred p0, p1;\n\t" + "setp.ne.b32 p0, %5, 0;\n\tsetp.eq.b32 p1, %5, 0;\n\t" + "mov.b64 a0, {%1, %3};\n\tmov.b64 b0, {%2, %3};\n\t" + "add.u32 la, %1, 2;\n\tadd.u32 lb, %2, 2;\n\tmov.b64 a1, {la, %3};\n\tmov.b64 b1, {lb, %3};\n\t" + "add.u32 la, %1, 4;\n\tadd.u32 lb, %2, 4;\n\tmov.b64 a2, {la, %3};\n\tmov.b64 b2, {lb, %3};\n\t" + "add.u32 la, %1, 6;\n\tadd.u32 lb, %2, 6;\n\tmov.b64 a3, {la, %3};\n\tmov.b64 b3, {lb, %3};\n\t" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], a0, b0, %4, p0;\n\t" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], a1, b1, %4, p1;\n\t" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], a2, b2, %4, p1;\n\t" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], a3, b3, %4, p1;\n\t}" + ::"r"(d), "r"(loA), "r"(loB), "r"(kDescHi), "r"(idesc), "r"(0u) + : "memory"); +} +__device__ __forceinline__ void umma_commit(uint64_t* bar) { + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(smem_u32(bar)) + : "memory"); +} +__device__ __forceinline__ void tc_fence_after() { asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); } +__device__ __forceinline__ void tc_fence_before() { asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory"); } +// tcgen05.ld 32 lanes x 32 bit x 16 columns (caller issues tmem_wait before using the registers) +__device__ __forceinline__ void tmem_ld16(uint32_t taddr, float* v) { + uint32_t* r = reinterpret_cast(v); + 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"(taddr)); +} +__device__ __forceinline__ void tmem_wait() { asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); } + +// packed (a0,a1) += (p0,p1) * s (fma.rn.f32x2) +__device__ __forceinline__ void fma2(float& a0, float& a1, float p0, float p1, float s) { + asm("{\n\t.reg .b64 ra, rp, rs;\n\t" + "mov.b64 ra, {%0, %1};\n\t" + "mov.b64 rp, {%2, %3};\n\t" + "mov.b64 rs, {%4, %4};\n\t" + "fma.rn.f32x2 ra, rp, rs, ra;\n\t" + "mov.b64 {%0, %1}, ra;\n\t}" + : "+f"(a0), "+f"(a1) + : "f"(p0), "f"(p1), "f"(s)); +} + +// ---------------- numerics helpers ---------------- +__device__ __forceinline__ float2 bf2f2(uint32_t u) { // bf16x2 word -> two fp32 (exact) + return make_float2(__uint_as_float(u << 16), __uint_as_float(u & 0xffff0000u)); +} +__device__ __forceinline__ uint32_t f2_e4m3x2(float a, float b) { + return (uint32_t)(uint16_t)__nv_cvt_float2_to_fp8x2(make_float2(a, b), __NV_SATFINITE, __NV_E4M3); +} +// (x0,x1) * s with one packed mul.rn.f32x2 (same RN fp32 products as two scalar multiplies) +__device__ __forceinline__ float2 mul2(float2 x, float s) { + float2 r; + asm("{\n\t.reg .b64 rx, rs;\n\tmov.b64 rx, {%2, %3};\n\tmov.b64 rs, {%4, %4};\n\t" + "mul.rn.f32x2 rx, rx, rs;\n\tmov.b64 {%0, %1}, rx;\n\t}" + : "=f"(r.x), "=f"(r.y) + : "f"(x.x), "f"(x.y), "f"(s)); + return r; +} +// 4 bf16 (two words) * inv -> 4 fp8 bytes +__device__ __forceinline__ uint32_t q4(uint32_t a, uint32_t b, float inv) { + const float2 x = mul2(bf2f2(a), inv), y = mul2(bf2f2(b), inv); + return f2_e4m3x2(x.x, x.y) | (f2_e4m3x2(y.x, y.y) << 16); +} + +// converter helpers (bit-identical to q4): explicit 32-bit shared-memory vector accesses (no generic 64-bit address +// math) and the bf16 -> fp32 unpack / packed mul.rn.f32x2 / cvt.rn.satfinite.e4m3x2 in one asm block, the two cvt +// results joined by mov.b32 {l, h} (ptxas: F2FP ... MERGE_C, no PRMT). +__device__ __forceinline__ uint4 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; +} +__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"); +} +__device__ __forceinline__ float lds32f(uint32_t a) { + float v; + asm volatile("ld.shared.f32 %0, [%1];" : "=f"(v) : "r"(a) : "memory"); + return v; +} +// 4 bf16 (words a = {e0, e1}, b = {e2, e3}) * inv -> 4 e4m3 bytes (byte i = element i); == q4(a, b, inv) +__device__ __forceinline__ uint32_t q4p(uint32_t a, uint32_t b, float inv) { + uint32_t r; + asm("{\n\t.reg .f32 x0, x1, y0, y1;\n\t.reg .b64 px, py, ps;\n\t.reg .b16 l, h;\n\t" + "shl.b32 x0, %1, 16;\n\tand.b32 x1, %1, 0xffff0000;\n\t" + "shl.b32 y0, %2, 16;\n\tand.b32 y1, %2, 0xffff0000;\n\t" + "mov.b64 ps, {%3, %3};\n\t" + "mov.b64 px, {x0, x1};\n\tmul.rn.f32x2 px, px, ps;\n\tmov.b64 {x0, x1}, px;\n\t" + "mov.b64 py, {y0, y1};\n\tmul.rn.f32x2 py, py, ps;\n\tmov.b64 {y0, y1}, py;\n\t" + "cvt.rn.satfinite.e4m3x2.f32 l, x1, x0;\n\t" // upper byte from the first operand + "cvt.rn.satfinite.e4m3x2.f32 h, y1, y0;\n\t" + "mov.b32 %0, {l, h};\n\t}" + : "=r"(r) : "r"(a), "r"(b), "f"(inv)); + return r; +} +// one converter item: 16 bf16 (two 16 B chunks lo = k 0-7, hv = k 8-15) -> 16 fp8 (one 16 B chunk) +__device__ __forceinline__ void cvt_store16(uint32_t dst, const uint4& lo, const uint4& hv, float iv) { + sts128(dst, q4p(lo.x, lo.y, iv), q4p(lo.z, lo.w, iv), q4p(hv.x, hv.y, iv), q4p(hv.z, hv.w, iv)); +} + +// silu(g) = g * sigmoid(g) = hg + hg * tanh(hg), hg = 0.5 g (one MUFU.TANH) +__device__ __forceinline__ float silu_t(float g) { + const float hg = 0.5f * g; + float t; + asm("tanh.approx.f32 %0, %1;" : "=f"(t) : "f"(hg)); + return fmaf(hg, t, hg); +} + +// ---------------- 1. x prep: qx fp8 [M,K] + sx [K/128][M] ---------------- +// one HALF-warp per (row, 128-col block) unit, 16 units per 256-thread block; lane: 8 elements (16 B load, +// 8 B store) -> each warp load instruction reads 512 contiguous bytes (2 consecutive units). Amax over the 16 lanes +// (order-independent max) -> output bit-identical to the 1-warp-per-unit mapping. +__global__ void __launch_bounds__(512) sm_xprep(const __nv_bfloat16* __restrict__ x, uint8_t* __restrict__ qx, + float* __restrict__ sx, int M, int K, int* __restrict__ cnt, int ncnt) { + pdl_trigger(); // let the gate_up GEMM start streaming weights (it waits for our completion before reading qx) + // reset this call's split-K arrival counters (the previous call's GEMMs have completed: this is a normal launch; + // this call's GEMMs only touch them after griddepcontrol.wait on this grid / its successor) + if (blockIdx.x == 0) + for (int i = threadIdx.x; i < ncnt; i += blockDim.x) cnt[i] = 0; + const int hl = threadIdx.x & 15; + const int nkb = K >> 7; + const long unit = (long)blockIdx.x * (blockDim.x >> 4) + (threadIdx.x >> 4); + const bool valid = unit < (long)M * nkb; // half-warp uniform; shuffles stay within the 16-lane group + const int row = valid ? (int)(unit / nkb) : 0, kb = valid ? (int)(unit - (long)row * nkb) : 0; + const size_t off = (size_t)row * K + kb * 128 + hl * 8; + uint4 v = make_uint4(0, 0, 0, 0); + if (valid) v = __ldg(reinterpret_cast(x + off)); + const float2 a = bf2f2(v.x), b = bf2f2(v.y), c2 = bf2f2(v.z), d = bf2f2(v.w); + float am = fmaxf(fmaxf(fmaxf(fabsf(a.x), fabsf(a.y)), fmaxf(fabsf(b.x), fabsf(b.y))), + fmaxf(fmaxf(fabsf(c2.x), fabsf(c2.y)), fmaxf(fabsf(d.x), fabsf(d.y)))); +#pragma unroll + for (int o = 8; o > 0; o >>= 1) am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, o)); + const float sc = fmaxf(am * (1.0f / 448.0f), 1e-12f); + const float inv = __frcp_rn(sc); + if (!valid) return; + *reinterpret_cast(qx + off) = make_uint2(q4p(v.x, v.y, inv), q4p(v.z, v.w, inv)); // packed cvt + if (hl == 0) sx[(size_t)kb * M + row] = sc; +} + +constexpr int ASUB = 128 * 128; // fp8 A tile: 128 rows x 128 k (SW128) + +// ---------------- 2/3. fused weight-quant GEMM with cluster split-K ---------------- +enum { EPI_SWIGLU = 0, EPI_BF16 = 1 }; + +struct GemmParams { + CUtensorMap tmA; // A fp8 [M, K], box 128 (k) x 128 rows, SW128 + CUtensorMap tmB0; // bf16 weight rows of tile rows [0, 128), box 64 (k) x 128 rows, SW128 + CUtensorMap tmB1; // bf16 weight rows of tile rows [128, 256) + const float* sA; // A scales [K/128][M] + const float* sB0; + const float* sB1; + int r1_off; // weight row of tile row 128 = nt * row_step + r1_off (in tmB1's tensor) + int row_step; // weight rows per tile in tmB0 / tmB1 (128 for gate_up, 256 for down) + int ldsB0, ldsB1; // n blocks per scale-table row + int M, KB; + // epilogue outputs + uint8_t* qh; // EPI_SWIGLU: fp8 h [M, I] + float* sh; // EPI_SWIGLU: h scales [I/128][M] + int I; + __nv_bfloat16* out; // EPI_BF16: [M, Nout] + int Nout; + CUtensorMap tmP; // optional (pf_n > 0): bf16 weight of the NEXT GEMM, box 64 x 128, prefetched into L2 + int pf_rows, pf_k; // rows per CTA slice (= box rows) / K (elements) + int pf_c0, pf_nrows; // first prefetching CTA, total rows of the prefetched weight + int pf_on; // 1: prefetch 1/gridDim of tmP after this CTA's own weight loads are issued + CUtensorMap tmPF0, tmPF1; // no-swizzle views of tmB0 / tmB1 with box 256 (k) x 32 rows (L2 prefetch only) + int pfo_on; + int wnohint; // 1: weight loads with the default L2 policy (0: evict_first) + float* ws; // split-K partials [tiles][S][128][256] fp32 + int* cnt; // per-tile arrival counters (zeroed every call by sm_xprep) + int probe_id, flags; // flags: probe-only ablations (0 = normal) +}; + +constexpr int kConv = 512; // converter / promoter / epilogue threads (warps 3..18) +constexpr int kThreads = 608; // + W producer (warp 0), MMA (warp 1), A producer (warp 2) +// MMA: per k block j one 128 x 128 x 128 product (4 x K=32) into TMEM cols t*256 + 128 j (t = step & 1). +// Promoter (row, part p): k block j = p & 1 of each step, 64 cols (p >> 1: gate / up, own block scale). +// Final: per-thread partials of the 2 k-block parities summed through smem staging, then red.add into the tile. +constexpr int KPS = 2; +constexpr int NW = 6, NA = 2, NKC = NW / 2; // W ring 192 KB (3 steps), A ring 2 k blocks (L2 hits) +constexpr int WST = 32 * 1024; // one slot: 2 k blocks x 128 rows x 64 k bf16 (== fp8 2 x 128 rows x 128 k) +constexpr int NTS = 2; // TMEM stages of 256 columns (2 k blocks x 128) +constexpr int OFF_A = NW * WST; // 192 KB +constexpr int OFF_BAR = OFF_A + NA * ASUB; // 224 KB +constexpr int OFF_SWS = OFF_BAR + 512; +constexpr int SMEM = OFF_SWS + 512 + 1024; // + 1 KB alignment slack +static_assert(SMEM <= 232448, "smem"); +static_assert(OFF_A >= 128 * 1024, "reduction staging [4][128][64] fp32 lives in the W ring"); +static_assert(NW == 2 * NKC, "even slots = w0 (fp8 in place), odd slots = w1"); + +template +__global__ void __maxnreg__(96) sm_gemm(const __grid_constant__ GemmParams p) { + static_assert(S == 8, "4 K splits x 2 N slices"); + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = reinterpret_cast(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023); + uint8_t* wring = smem; + uint8_t* aring = smem + OFF_A; + uint64_t* bars = reinterpret_cast(smem + OFF_BAR); + uint64_t* wfull = bars; // [NW] bf16 slot landed (tx) + uint64_t* wempty = wfull + NW; // [NW] even: MMA done with the in-place fp8 tiles (commit); odd: 512 converters + uint64_t* afull = wempty + NW; // [NA] A k block landed (tx) + uint64_t* aempty = afull + NA; // [NA] MMA done with the A stage (commit) + uint64_t* conv = aempty + NA; // [NKC] fp8 tiles of step i (slot 2(i % NKC)) written (512) + uint64_t* accfull = conv + NKC; // [NTS] TMEM stage holds a step's 4 k-block partials (commit) + uint64_t* accempty = accfull + NTS; // [NTS] promoters drained the TMEM stage (512) + uint32_t* tmem_slot = reinterpret_cast(accempty + NTS); + float* sws = reinterpret_cast(smem + OFF_SWS); // [2 kb + {0 gate, 1 up}] scales, [64 + ...] reciprocals + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const uint32_t rank = blockIdx.x % S; + const int nt = blockIdx.x / S; + const int ks = (int)(rank & 3u), jn = (int)(rank >> 2); + const int kb0 = ks * p.KB / 4, kb1 = (ks + 1) * p.KB / 4; + const int nkb = kb1 - kb0, nst = nkb / KPS; // host guarantees nkb % KPS == 0 + const int r0 = nt * p.row_step + 64 * jn, r1 = nt * p.row_step + p.r1_off + 64 * jn; // weight rows (gate / up) + + // W slot h (h = 2 step + gu): ONE 3-D box = 64 rows of the gate (gu 0, even slot w0) / up (gu 1, odd slot w1) + // weight x the step's 256 k (4 chunks of 64 k, 512 contiguous bytes per row); smem chunk c (k 64c..) at +8 KB c + auto issue_w = [&](int h, int s, uint64_t pol) { + mbar_expect_tx(wfull + s, WST); + const int st = h >> 1, gu = h & 1; + tma_load_3d(wring + s * WST, gu ? &p.tmB1 : &p.tmB0, wfull + s, 0, gu ? r1 : r0, (kb0 + st * KPS) * 2, pol); + }; + if (threadIdx.x == 0) { + for (int i = 0; i < NW; ++i) { mbar_init(wfull + i, 1); mbar_init(wempty + i, (i & 1) ? kConv / kRelDiv : 1); } + for (int i = 0; i < NA; ++i) { mbar_init(afull + i, 1); mbar_init(aempty + i, 1); } + for (int i = 0; i < NKC; ++i) mbar_init(conv + i, kConv / kRelDiv); + for (int i = 0; i < NTS; ++i) { mbar_init(accfull + i, 1); mbar_init(accempty + i, kConv / kRelDiv); } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + // thread 0 (= the W producer lane) issues the first NW weight slots before the setup block barrier + const uint64_t pol = policy_evict_first(); + const int h0 = 2 * nst < NW ? 2 * nst : NW; + for (int h = 0; h < h0; ++h) issue_w(h, h, pol); + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(smem_u32(tmem_slot)), + "n"(512) + : "memory"); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;" ::: "memory"); + } + if (threadIdx.x >= 96 && threadIdx.x < 96 + 128) { // stage the weight block scales (inputs: no PDL wait) + const int idx = threadIdx.x - 96; + if (idx < 2 * nkb) { + const int i = idx >> 1, b = idx & 1; + const float sc = b ? __ldg(p.sB1 + (kb0 + i) * p.ldsB1 + (r1 >> 7)) : __ldg(p.sB0 + (kb0 + i) * p.ldsB0 + (r0 >> 7)); + sws[idx] = sc; + sws[64 + idx] = __frcp_rn(sc); + } + } + tc_fence_before(); + __syncthreads(); + tc_fence_after(); + const uint32_t tmem = *tmem_slot; + + if (warp == 0) { + if (lane == 0) { + // ---------------- W producer: bf16 weight slots (no dependency on the previous kernel) ---------------- + const uint64_t pol = policy_evict_first(); // streamed exactly once + for (int h = NW; h < 2 * nst; ++h) { + const int s = h % NW; + mbar_wait(wempty + s, ((h / NW) & 1) ^ 1); + issue_w(h, s, pol); + } + // down-weight L2 prefetch. Once this CTA's LAST weight slot has landed (its DRAM stream is done), prefetch + // into L2 the bf16 down-weight slice [pf_rows * blockIdx, +pf_rows) x K that sm_dn CTA blockIdx streams later: + // the dn CTAs that replace the gate_up CTAs start only after the gate_up split-K tail, while DRAM sits idle. + // Slices of the dn CTAs that already run on the spare SMs (blockIdx < pf_c0) are skipped. Pure L2 hint: no + // smem / completion tracking, no effect on results. + if (p.pf_on && (int)blockIdx.x >= p.pf_c0 && nst > 0) { + const int hl = 2 * nst - 1; + mbar_wait(wfull + hl % NW, (hl / NW) & 1); + const int r0p = (int)blockIdx.x * p.pf_rows; + if (r0p < p.pf_nrows) + for (int k = 0; k < p.pf_k; k += 256) tma_prefetch_2d(&p.tmP, k, r0p); + } + } + } else if (warp == 2) { + if (lane == 0) { + // ---------------- A producer: fp8 activations, one k block per stage ---------------- + const uint64_t pol = policy_evict_last(); // re-read by every n tile + // prefetch the qx descriptor before the PDL wait (kernel-param map, no dependency on xprep), so the first + // A TMA after griddepcontrol.wait does not pay a descriptor miss on the critical path + asm volatile("prefetch.tensormap [%0];" ::"l"(&p.tmA) : "memory"); + pdl_wait(); + for (int g = 0; g < nkb; ++g) { + const int s = g % NA; + if (g >= NA) mbar_wait(aempty + s, ((g / NA) & 1) ^ 1); + mbar_expect_tx(afull + s, ASUB); + tma_load_2d(aring + s * ASUB, &p.tmA, afull + s, (kb0 + g) * 128, 0, pol); + } + } + } else if (warp == 1) { + if (lane == 0) { + // ---------------- MMA issuer: per step KPS k blocks, each 128 x 128 into its own 128 TMEM columns ---------------- + constexpr uint32_t idesc = umma_idesc_e4m3(128, 128); + for (int i = 0; i < nst; ++i) { + const int iq = i / NKC, s = i - iq * NKC, t = i % NTS; + mbar_wait(conv + s, iq & 1); + if (i >= NTS) mbar_wait(accempty + t, ((i / NTS) & 1) ^ 1); + const uint32_t sb = smem_u32(wring + (2 * s) * WST); // in-place fp8 tiles (w0 slot) +#pragma unroll + for (int j = 0; j < KPS; ++j) { + const int g = i * KPS + j, a = g % NA; + mbar_wait(afull + a, (g / NA) & 1); + tc_fence_after(); + const uint32_t sa = smem_u32(aring + a * ASUB); + umma4_lean(tmem + (uint32_t)(t * 256 + j * 128), umma_lo(sa), umma_lo(sb + (uint32_t)(j * 16384)), idesc); + umma_commit(aempty + a); // A stage reusable once these MMAs completed + } + umma_commit(wempty + 2 * s); // w0 slot (fp8 tiles) reusable + umma_commit(accfull + t); // partials of step i ready in TMEM stage t + } + } + } + + // promoted accumulators of warps 3..18: row = q*32 + lane (TMEM lane quarter q = warp % 4), part = k block of step + // kColSplit: promoter part p = (warp - 3) >> 2 owns 32 columns (gate/up group p >> 1, 32-col half p & 1) of + // BOTH k blocks of every step -> one running sum per element (32 accumulators), double-buffered x16 TMEM loads, and + // no parity pre-sum before the split-K red.add (fp32 summation order differs from summing two parity partials; + // the split-K red.add order is nondeterministic anyway) + float acc[32]; + const int t = (int)threadIdx.x - 96; + if (warp >= 3) { +#pragma unroll + for (int c = 0; c < 32; ++c) acc[c] = 0.f; + const uint32_t g_wbase = smem_u32(wring); + auto vtid = []() -> uint32_t { uint32_t v; asm volatile("mov.u32 %0, %%tid.x;" : "=r"(v)); return v; }; + auto vrow = [&]() -> int { const uint32_t v = vtid(); return (int)(((v >> 5) & 3u) * 32u + (v & 31u)); }; + auto vtmem = [&]() -> uint32_t { + uint32_t v; + asm volatile("ld.shared.u32 %0, [%1];" : "=r"(v) : "r"(g_wbase + (uint32_t)OFF_BAR + 8u * (2 * NW + 2 * NA + NKC + 2 * NTS)) : "memory"); + return v; + }; + const uint32_t b32 = g_wbase + (uint32_t)OFF_BAR, sws32 = g_wbase + (uint32_t)OFF_SWS; + constexpr uint32_t kWF = 0, kWE = 8 * NW, kCV = 8 * (2 * NW + 2 * NA), kAF = kCV + 8 * NKC, kAE = kAF + 8 * NTS; + bool pdl_done = false; + // A scale of this thread's row for its part's k block of step i (written by the previous kernel) + auto load_ps = [&](int i) -> float2 { // A scales of this row for both k blocks of step i + if (!pdl_done) { pdl_wait(); pdl_done = true; } + const uint32_t v = vtid(); + const int vr = (int)(((v >> 5) & 3u) * 32u + (v & 31u)); + if (vr >= p.M) return make_float2(0.f, 0.f); + const float* sp = p.sA + (size_t)(kb0 + i * KPS) * p.M + vr; + return make_float2(__ldg(sp), __ldg(sp + p.M)); + }; + (void)vrow; + auto promote = [&](int i, float2 ps2) { // step i: TMEM stage i % NTS, this part's 32 cols of both k blocks + const int tt = i % NTS; + mbar_wait_a(b32 + kAF + 8u * (uint32_t)tt, (uint32_t)(i / NTS) & 1u); + tc_fence_after(); + const uint32_t pw = vtid() >> 5, pq = pw & 3u, ppart = (pw - 3u) >> 2, pch = ppart & 1u, pcg = ppart >> 1; + const uint32_t g0 = (uint32_t)(i * KPS); + const float sc0 = ps2.x * lds32f(sws32 + 8u * g0 + 4u * pcg); // pcg 0: gate cols, 1: up cols + const float sc1 = ps2.y * lds32f(sws32 + 8u * (g0 + 1u) + 4u * pcg); + // k block j of the step at TMEM cols tt*256 + 128 j; gate cols +0..63, up +64..127; this half +32 pch + const uint32_t tb = vtmem() + (pq * 32u << 16) + (uint32_t)(tt * 256) + pcg * 64u + pch * 32u; + float pa[16], pb[16]; + tmem_ld16(tb, pa); + tmem_wait(); + tmem_ld16(tb + 16u, pb); +#pragma unroll + for (int e = 0; e < 16; e += 2) fma2(acc[e], acc[e + 1], pa[e], pa[e + 1], sc0); + tmem_wait(); + tmem_ld16(tb + 128u, pa); +#pragma unroll + for (int e = 0; e < 16; e += 2) fma2(acc[16 + e], acc[16 + e + 1], pb[e], pb[e + 1], sc0); + tmem_wait(); + tmem_ld16(tb + 144u, pb); +#pragma unroll + for (int e = 0; e < 16; e += 2) fma2(acc[e], acc[e + 1], pa[e], pa[e + 1], sc1); + tmem_wait(); + tc_fence_before(); + warp_arrive_a(b32 + kAE + 8u * (uint32_t)tt); // stage drained (all loads landed) +#pragma unroll + for (int e = 0; e < 16; e += 2) fma2(acc[16 + e], acc[16 + e + 1], pb[e], pb[e + 1], sc1); + }; + // one step: convert step i (4 k blocks), then promote step i-1 (whose MMAs overlapped the conversion) + auto body = [&](int i, float2& pc, float2& pn) { + if (i < nst) { + if (i >= 2) pn = load_ps(i); + const int iq = i / NKC, s = i - iq * NKC; + const int w0 = 2 * s, w1 = 2 * s + 1; + const uint32_t wpar = (uint32_t)(iq & 1); + // kGateFirst: convert the gate items (jb 0, 2: read w0 only) as soon as w0 landed, then wait for w1 + mbar_wait_a(b32 + kWF + 8u * (uint32_t)w0, wpar); + const uint32_t slot0 = g_wbase + (uint32_t)(w0 * WST); // fp8 tiles written in place over this bf16 slot + uint32_t c_ld0, c_ld1, c_st; + { + uint32_t tid; + asm volatile("mov.u32 %0, %%tid.x;" : "=r"(tid)); + const uint32_t tc = tid - 96u, cc8 = tc & 7u, chh = cc8 >> 2, cj2 = cc8 & 3u; + const uint32_t crq = (tc >> 3) ^ chh, csw = crq & 7u; // row within the k block's 64 rows + const uint32_t cb = chh * 8192u + crq * 128u; // k half chh = chunk 2j + chh of the matrix slot + c_ld0 = cb + (((2u * cj2) ^ csw) << 4); + c_ld1 = cb + (((2u * cj2 + 1u) ^ csw) << 4); + c_st = crq * 128u + ((cc8 ^ csw) << 4); + } +#pragma unroll + for (int jo = 0; jo < 2 * KPS; ++jo) { // order 0, 2, 1, 3 (gate items first) + const int jb = jo < KPS ? 2 * jo : 2 * (jo - KPS) + 1; + if (jo == KPS) mbar_wait_a(b32 + kWF + 8u * (uint32_t)w1, wpar); + // item jb: slot rows 64 jb + crq = k block jb >> 1, gate (jb even) / up + // bf16 source: matrix jb & 1 (w0 gate / w1 up), chunks 2 (jb >> 1) + {0, 1} (16 KB per k block) + const uint32_t so = slot0 + (uint32_t)((jb & 1) * WST + (jb >> 1) * 16384); + const uint4 lo = lds128(so + c_ld0); + const uint4 hv = lds128(so + c_ld1); + // in-place WAR: the fp8 store of item jb (w0 + 8 KB jb, row crq) overwrites bf16 gate chunk jb, which was read + // by item jb (jb even) or jb - 1 (jb odd) of lanes of THIS warp (rows crq / crq ^ 1 of the same 8-lane groups) + __syncwarp(); + const float iv = lds32f(sws32 + 4u * (uint32_t)(64 + 2 * (i * KPS + (jb >> 1)) + (jb & 1))); + cvt_store16(slot0 + c_st + (uint32_t)(jb * 8192), lo, hv, iv); + } + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // generic smem accesses <-> async proxy + warp_arrive_a(b32 + kWE + 8u * (uint32_t)w1); // w0 is released by the MMA commit (it holds the fp8 tiles) + warp_arrive_a(b32 + kCV + 8u * (uint32_t)s); + } + if (i == 1) { pc = load_ps(0); if (1 < nst) pn = load_ps(1); } + if (i > 0) promote(i - 1, pc); + }; + float2 psA = make_float2(0.f, 0.f), psB = make_float2(0.f, 0.f); + for (int i = 0; i <= nst; i += 2) { + body(i, psB, psA); + if (i + 1 <= nst) body(i + 1, psA, psB); + } + pdl_trigger(); + // ---- per-thread partial (row, part) -> smem staging [part][128][32] fp32 (row stride 128 B, 16 B chunk c of row + // r at (c ^ (r & 7)): conflict-free), in the idle W ring ---- + { + const uint32_t et = vtid(), ew = et >> 5, erow = (ew & 3u) * 32u + (et & 31u), epart = (ew - 3u) >> 2; + const uint32_t srow = g_wbase + epart * 16384u + erow * 128u; // [part][128][32] fp32, chunk c at c ^ (r & 7) +#pragma unroll + for (int c = 0; c < 8; ++c) + sts128(srow + (((uint32_t)c ^ (erow & 7u)) << 4), __float_as_uint(acc[4 * c]), __float_as_uint(acc[4 * c + 1]), + __float_as_uint(acc[4 * c + 2]), __float_as_uint(acc[4 * c + 3])); + } + asm volatile("bar.sync 1, %0;" ::"n"(kConv) : "memory"); + uint32_t e_cta; + asm volatile("mov.u32 %0, %%ctaid.x;" : "=r"(e_cta)); + const int e_nt = (int)(e_cta / (uint32_t)S), e_rank = (int)(e_cta % (uint32_t)S); + const int e_jn = e_rank >> 2; + const int e_t = (int)vtid() - 96; + float* wsp = p.ws + (size_t)e_nt * (128 * 256); + const int mrows = p.M < 128 ? p.M : 128; + const int e_tot = mrows * 32; + const int e_rot = (e_rank & 3) * (((mrows + 3) >> 2) * 32); + for (int it0 = e_t; it0 < e_tot; it0 += kConv) { + int it = it0 + e_rot; + while (it >= e_tot) it -= e_tot; + const int rr = it >> 5, ch = it & 31, cg = ch >> 4, c16 = ch & 15; + // part cg*2 + (c16 >> 3) holds cols [32 (c16 >> 3), +32) of gate (cg 0) / up (cg 1) + const uint32_t a = g_wbase + (uint32_t)((cg * 2 + (c16 >> 3)) * 16384 + rr * 128) + + ((uint32_t)((c16 & 7) ^ (rr & 7)) << 4); + const uint4 v0 = lds128(a); + const int col = cg * 128 + 64 * e_jn + 4 * c16; + asm volatile("red.relaxed.gpu.global.add.v4.f32 [%0], {%1, %2, %3, %4};" ::"l"(wsp + rr * 256 + col), + "f"(__uint_as_float(v0.x)), "f"(__uint_as_float(v0.y)), "f"(__uint_as_float(v0.z)), + "f"(__uint_as_float(v0.w)) : "memory"); + } + // publish: CTA barrier, one release add on the tile's arrival counter; wait until all S CTAs of the tile have + // published (grid <= SMs, 1 CTA / SM: all co-resident, no deadlock) + asm volatile("bar.sync 1, %0;" ::"n"(kConv) : "memory"); + if (e_t == 0) { + int* cnt = p.cnt + e_nt; + asm volatile("red.release.gpu.global.add.s32 [%0], 1;" ::"l"(cnt) : "memory"); + int seen; + while (true) { + asm volatile("ld.acquire.gpu.global.s32 %0, [%1];" : "=r"(seen) : "l"(cnt) : "memory"); + if (seen >= S) break; // tight acquire poll (no nanosleep): split-K tail wait is on the critical path + } + } + asm volatile("bar.sync 1, %0;" ::"n"(kConv) : "memory"); + // ---- distributed epilogue: CTA rank r owns tile rows rr = r + S*k of the reduced tile ---- + float* wst = p.ws + (size_t)e_nt * (128 * 256); + const int nt = e_nt; + const uint32_t rank = (uint32_t)e_rank; + const int lane = e_t & 31, warp = (e_t >> 5) + 3; + static_assert(EPI == EPI_SWIGLU, "gate_up epilogue only"); + // one warp per row, lane -> h cols [4 lane, +4) = gate cols [4 lane, +4) + up cols [128 + 4 lane, +4) + for (int rr = (int)rank + S * (warp - 3); rr < mrows; rr += S * 16) { + float4* src = reinterpret_cast(wst + (size_t)rr * 256); + const float4 g = __ldcg(src + lane); + const float4 u = __ldcg(src + 32 + lane); + const __nv_bfloat162 g01 = __floats2bfloat162_rn(g.x, g.y), g23 = __floats2bfloat162_rn(g.z, g.w); + const __nv_bfloat162 u01 = __floats2bfloat162_rn(u.x, u.y), u23 = __floats2bfloat162_rn(u.z, u.w); + const float2 ga = bf2f2(*reinterpret_cast(&g01)), gb2 = bf2f2(*reinterpret_cast(&g23)); + // silu via one MUFU.TANH per element (hg + hg*tanh(hg)) instead of IEEE expf + true division on the + // post-reduction critical path (same form as the merged kernels' fused epilogue); rounded to bf16 right after + const __nv_bfloat162 s01 = __floats2bfloat162_rn(silu_t(ga.x), silu_t(ga.y)); + const __nv_bfloat162 s23 = __floats2bfloat162_rn(silu_t(gb2.x), silu_t(gb2.y)); + const __nv_bfloat162 h01 = __hmul2(s01, u01), h23 = __hmul2(s23, u23); + const uint32_t hw0 = *reinterpret_cast(&h01), hw1 = *reinterpret_cast(&h23); + const uint32_t mb = __vmaxu2(hw0 & 0x7fff7fffu, hw1 & 0x7fff7fffu); + float am = __uint_as_float(max(mb & 0xffffu, mb >> 16) << 16); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, o)); + const float sc = fmaxf(am * (1.0f / 448.0f), 1e-12f); // 1x128 requant scale of h + const float inv = __frcp_rn(sc); + *reinterpret_cast(p.qh + (size_t)rr * p.I + nt * 128 + lane * 4) = q4p(hw0, hw1, inv); + if (lane == 0) p.sh[(size_t)nt * p.M + rr] = sc; + } + } + (void)t; + tc_fence_before(); + __syncthreads(); + if (warp == 1) { + tc_fence_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tmem), "n"(512) : "memory"); + } +} + + + + +#ifndef SE_DN_OUT +#define SE_DN_OUT 56 +#endif +constexpr int DN_OUT_SHIP = SE_DN_OUT; +int g_dn_out = DN_OUT_SHIP; // probe override (host) +int g_dn_pf = 1; +int g_xp_bs = 512; +constexpr int DN_BN = 64, DN_CONV = 256, DN_PROM = 128, DN_THREADS = 96 + DN_CONV + DN_PROM; // 480 +constexpr int DN_KPS = 2; // k blocks per pipeline step +constexpr int DN_NW = 3, DN_NK = 3, DN_NA = 2, DN_NT = 4; +#ifndef SE_DN_MC1 +#define SE_DN_MC1 1 // one MMA completion commit per sm_dn step (see the MMA issuer) +#endif +static_assert(DN_NT > DN_NA && DN_NT > DN_NK, "single commit ring: parity safety"); +constexpr int DN_WST = DN_KPS * DN_BN * 256; // bf16 64 rows x (KPS x 128 k) = 32 KB +constexpr int DN_B8 = DN_KPS * DN_BN * 128; // fp8 KPS x [64 rows x 128 k] = 16 KB +constexpr int DN_AST = DN_KPS * ASUB; // fp8 KPS x [128 rows x 128 k] = 32 KB +constexpr int DN_OFF_B8 = DN_NW * DN_WST; +constexpr int DN_OFF_A = DN_OFF_B8 + DN_NK * DN_B8; +constexpr int DN_OFF_BAR = DN_OFF_A + DN_NA * DN_AST; +constexpr int DN_OFF_SWS = DN_OFF_BAR + 512; +constexpr int DN_KBMAX = 16; // K = I <= 2048 (activation scales staged in smem) +constexpr int DN_OFF_SSA = DN_OFF_SWS + 512; // sh of this CTA's 128 rows: [kb][128] fp32 +constexpr int DN_SMEM = DN_OFF_SSA + DN_KBMAX * 128 * 4 + 1024; +static_assert(DN_SMEM <= 232448, "dn smem"); +static_assert(DN_OFF_B8 % 1024 == 0 && DN_OFF_A % 1024 == 0, "SW128 tiles need 1024 B alignment"); +static_assert(DN_NT * DN_KPS * DN_BN == 512, "TMEM alloc: power of 2 columns"); +static_assert(2 * (DN_NW + DN_NA + DN_NK + DN_NT) * 8 + 4 <= 512, "barrier region"); + +struct DnParams { + CUtensorMap tmA; // qh fp8 [M, K], box 128 x 128, SW128 + CUtensorMap tmB; // down weight bf16 [Nout, K], box 64 (k) x 64 rows, SW128 + const float* sA; // sh [K/128][M] + const float* sB; // down block scales [K/128][Nout/128] + int ldsB, M, KB, Nout; + __nv_bfloat16* out; + int flags; // probe-only ordering knobs (0 = shipped) + float4* zws; // gate_up reduction workspace of the OTHER call parity, zeroed here (off the critical path) + int zn; // its size in float4 +}; + +// audit: 128 regs, 8 B local; __maxnreg__(136) (local 0) fails to launch at 480 threads (out of resources) +template +__global__ void __launch_bounds__(DN_THREADS, 1) sm_dn(const __grid_constant__ DnParams p) { + extern __shared__ uint8_t smem_raw[]; + uint8_t* smem = reinterpret_cast(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023); + uint8_t* wring = smem; + uint8_t* b8ring = smem + DN_OFF_B8; + uint8_t* aring = smem + DN_OFF_A; + uint64_t* bars = reinterpret_cast(smem + DN_OFF_BAR); + uint64_t* wfull = bars; // [NW] tx + uint64_t* wempty = wfull + DN_NW; // [NW] 256 converter arrivals + uint64_t* afull = wempty + DN_NW; // [NA] tx + uint64_t* aempty = afull + DN_NA; // [NA] MMA commit + uint64_t* conv = aempty + DN_NA; // [NK] 256 converter arrivals + uint64_t* kempty = conv + DN_NK; // [NK] MMA commit + uint64_t* accfull = kempty + DN_NK; // [NT] MMA commit + uint64_t* accempty = accfull + DN_NT; // [NT] 128 promoter arrivals + uint32_t* tmem_slot = reinterpret_cast(accempty + DN_NT); + float* sws = reinterpret_cast(smem + DN_OFF_SWS); // [0,64) block scales, [64,128) reciprocals + float* ssa = reinterpret_cast(smem + DN_OFF_SSA); // activation (h) scales [kb][row] + + pdl_trigger(); + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int n0 = blockIdx.x * DN_OUT; + // the 56 rows may straddle a 128-row weight scale block: rows >= bnd use the next block's scale + const int sb0 = n0 >> 7, bnd = 128 - (n0 & 127); + const int sb1 = (sb0 + 1) < (p.Nout >> 7) ? sb0 + 1 : sb0; + const int KB = p.KB, NS = KB / DN_KPS; // k blocks, pipeline steps + const int rot = (int)(blockIdx.x % (unsigned)NS); + auto stp = [&](int j) { const int t = j + rot; return t >= NS ? t - NS : t; }; // step j -> k-step index + if (threadIdx.x == 0) { + for (int i = 0; i < DN_NW; ++i) { mbar_init(wfull + i, 1); mbar_init(wempty + i, DN_CONV / kRelDiv); } + for (int i = 0; i < DN_NA; ++i) { mbar_init(afull + i, 1); mbar_init(aempty + i, 1); } + for (int i = 0; i < DN_NK; ++i) { mbar_init(conv + i, DN_CONV / kRelDiv); mbar_init(kempty + i, 1); } + for (int i = 0; i < DN_NT; ++i) { mbar_init(accfull + i, 1); mbar_init(accempty + i, DN_PROM / kRelDiv); } + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + // thread 0 (= the W producer lane) issues the first DN_NW bf16 weight stages (empty ring, no slot wait) + // right after barrier init, before the setup block barrier (scale loads + TMEM alloc). The down weights are kernel + // inputs (no dependency on gate_up): only the qh (A) loads and the sh reads wait on griddepcontrol.wait. + { + const uint64_t pol = policy_evict_first(); + const int j0 = NS < DN_NW ? NS : DN_NW; + for (int j = 0; j < j0; ++j) { + const int kb = stp(j) * DN_KPS; + mbar_expect_tx(wfull + j, 2 * DN_KPS * DN_OUT * 128); + tma_load_3d(wring + j * DN_WST, &p.tmB, wfull + j, 0, n0, kb * 2, pol); // 4 chunks x DN_OUT rows + } + } + } + if (warp == 1) { + asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(smem_u32(tmem_slot)), + "n"(512) : "memory"); + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;" ::: "memory"); + } + if (threadIdx.x >= 96 && threadIdx.x < 96 + 64) { // weight block scales of this CTA's 64 rows (one 128-row block) + const int i = threadIdx.x - 96; + if (i < 2 * KB) { // [2 kb + j]: scale of block sb0 (j=0) / sb1 (j=1); reciprocals at +64 + const int kb = i >> 1; + const float sc = __ldg(p.sB + kb * p.ldsB + ((i & 1) ? sb1 : sb0)); + sws[i] = sc; + sws[64 + i] = __frcp_rn(sc); + } + } + tc_fence_before(); + __syncthreads(); + tc_fence_after(); + // register audit: the TMEM base is re-read from smem (volatile 32-bit ld.shared) at each use instead of being + // kept live across the role loops (ptxas spilled it + the promoter's lane base: 8 B local) + const uint32_t tslot32 = smem_u32(tmem_slot); + auto ld_tmem = [&]() -> uint32_t { + uint32_t v; + asm volatile("ld.shared.u32 %0, [%1];" : "=r"(v) : "r"(tslot32) : "memory"); + return v; + }; + + if (warp == 0) { + if (lane == 0) { + const uint64_t pol = policy_evict_first(); // streamed exactly once + for (int j = DN_NW; j < NS; ++j) { // j < DN_NW issued at setup (above) + const int s = j % DN_NW, kb = stp(j) * DN_KPS; + mbar_wait(wempty + s, ((j / DN_NW) & 1) ^ 1); + mbar_expect_tx(wfull + s, 2 * DN_KPS * DN_OUT * 128); // 4 boxes of 56 rows x 128 B +#pragma unroll + // ONE 3-D box: DN_OUT rows x 256 k (512 contiguous bytes per row), chunk c at +DN_OUT*128 c + tma_load_3d(wring + s * DN_WST, &p.tmB, wfull + s, 0, n0, kb * 2, pol); + } + } + } else if (warp == 2) { + if (lane == 0) { + const uint64_t pol = policy_evict_last(); // qh re-read by all 112 CTAs + asm volatile("prefetch.tensormap [%0];" ::"l"(&p.tmA) : "memory"); // qh descriptor before the PDL wait + pdl_wait(); + for (int j = 0; j < NS; ++j) { + const int s = j % DN_NA, kb = stp(j) * DN_KPS; + if (j >= DN_NA) { + if (SE_DN_MC1) { // A stage of step j - DN_NA free once that step's MMAs completed (single commit ring) + const int k = j - DN_NA; + mbar_wait(accfull + k % DN_NT, (k / DN_NT) & 1); + } else { + mbar_wait(aempty + s, ((j / DN_NA) & 1) ^ 1); + } + } + mbar_expect_tx(afull + s, DN_AST); +#pragma unroll + for (int b = 0; b < DN_KPS; ++b) + tma_load_2d(aring + s * DN_AST + b * ASUB, &p.tmA, afull + s, (kb + b) * 128, 0, pol); + } + } + } else if (warp == 1) { + if (lane == 0) { + constexpr uint32_t idesc = umma_idesc_e4m3(128, DN_BN); + const uint32_t tmem = ld_tmem(); + for (int j = 0; j < NS; ++j) { + const int s = j % DN_NK, a = j % DN_NA, t = j % DN_NT; + mbar_wait(afull + a, (j / DN_NA) & 1); + mbar_wait(conv + s, (j / DN_NK) & 1); + if (j >= DN_NT) mbar_wait(accempty + t, ((j / DN_NT) & 1) ^ 1); + tc_fence_after(); +#pragma unroll + for (int b = 0; b < DN_KPS; ++b) { + const uint32_t sa = smem_u32(aring + a * DN_AST + b * ASUB); + const uint32_t sb = smem_u32(b8ring + s * DN_B8 + b * (DN_BN * 128)); + // 4 x K=32 inside the 128 B swizzle atom, lean issue + umma4_lean(tmem + (uint32_t)((t * DN_KPS + b) * DN_BN), umma_lo(sa), umma_lo(sb), idesc); + } + // ONE tcgen05.commit per step on accfull[j % DN_NT]; the A producer and the converters wait on + // the same completion (parity-safe: slot j % DN_NT completes again only at step j + DN_NT, which needs those + // waiters to have progressed, since DN_NT > DN_NA and DN_NT > DN_NK) + if (!SE_DN_MC1) { + umma_commit(aempty + a); // A stage reusable + umma_commit(kempty + s); // B8 slot reusable + } + umma_commit(accfull + t); // partials of the step's k blocks in TMEM stage t + } + } + } else if (warp < 3 + DN_CONV / 32) { + // ---------------- converters ---------------- + const int tt = (int)threadIdx.x - 96; // 0..255 + const int c8 = tt & 7, hh = c8 >> 2, j2 = c8 & 3; + const int rA = (tt >> 3) ^ hh, rB = rA + DN_CONV / 8; // tile rows of item 0 / item 1 (same r & 7) + const uint32_t sw = (uint32_t)(rA & 7); + const uint32_t ld0 = (uint32_t)(hh * (DN_OUT * 128) + rA * 128) + ((((uint32_t)(2 * j2)) ^ sw) << 4); + const uint32_t ld1 = (uint32_t)(hh * (DN_OUT * 128) + rA * 128) + ((((uint32_t)(2 * j2 + 1)) ^ sw) << 4); + const uint32_t sto = (uint32_t)(rA * 128) + (((uint32_t)c8 ^ sw) << 4); + constexpr uint32_t kItemOff = (DN_CONV / 8) * 128; // item 1: +32 rows + // padded tile rows (r >= DN_OUT, never loaded by the TMA): rows >= 56 = item 1 of threads tt >= 192 (warp-uniform) + const bool padB = rB >= DN_OUT; + // scale-table addresses: sws[64 + 2 kb + (row >= bnd)] (reciprocals); rA / rB lie on the same side of bnd as R + const uint32_t ivA = smem_u32(sws + 64) + 4u * (uint32_t)(rA >= bnd ? 1 : 0); + const uint32_t ivB = smem_u32(sws + 64) + 4u * (uint32_t)(rB >= bnd ? 1 : 0); + const uint32_t wbase = smem_u32(wring), b8base = smem_u32(b8ring); + for (int j = 0; j < NS; ++j) { + const int s = j % DN_NK, w = j % DN_NW, kb = stp(j) * DN_KPS; + if (j >= DN_NK) { // MMA done with this B8 slot's previous step + if (SE_DN_MC1) { + const int k = j - DN_NK; + mbar_wait(accfull + k % DN_NT, (k / DN_NT) & 1); + } else { + mbar_wait(kempty + s, ((j / DN_NK) & 1) ^ 1); + } + } + mbar_wait(wfull + w, (j / DN_NW) & 1); + const uint32_t src = wbase + (uint32_t)(w * DN_WST); + const uint32_t dst = b8base + (uint32_t)(s * DN_B8); + uint4 lo[2 * DN_KPS], hv[2 * DN_KPS]; + // kDnIvHoist: the step's reciprocal block scales are read together with the bf16 LDS (all in flight at + // once) instead of one serialized volatile ld.shared right before each k block's convert; same values + float ivs[2 * DN_KPS]; +#pragma unroll + for (int b = 0; b < DN_KPS; ++b) { + ivs[2 * b] = lds32f(ivA + 8u * (uint32_t)(kb + b)); + ivs[2 * b + 1] = padB ? 0.f : lds32f(ivB + 8u * (uint32_t)(kb + b)); + } +#pragma unroll + for (int b = 0; b < DN_KPS; ++b) { + const uint32_t bs = src + (uint32_t)(b * 2 * DN_OUT * 128); // boxes 2b (k 0-63), 2b+1 (k 64-127) + lo[2 * b] = lds128(bs + ld0); + hv[2 * b] = lds128(bs + ld1); + if (!padB) { + lo[2 * b + 1] = lds128(bs + ld0 + kItemOff); + hv[2 * b + 1] = lds128(bs + ld1 + kItemOff); + } + } +#pragma unroll + for (int b = 0; b < DN_KPS; ++b) { + // fp8 tile of k block b: 64 rows x 128 B, SW128 K-major (16 B chunk c8 of row r at (c8 ^ (r & 7))) + const uint32_t ds = dst + (uint32_t)(b * DN_BN * 128) + sto; + cvt_store16(ds, lo[2 * b], hv[2 * b], ivs[2 * b]); + // kPadOnce: padded weight rows (56..63) of a B8 slot are never written by anything else, so their fp8 zeros + // are stored once, at the slot's first use (j < DN_NK) + if (padB) { if (j < DN_NK) sts128(ds + kItemOff, 0u, 0u, 0u, 0u); } + else cvt_store16(ds + kItemOff, lo[2 * b + 1], hv[2 * b + 1], ivs[2 * b + 1]); + } + // race fix (WAR on the bf16 W ring): release the W slot only AFTER the loaded values were consumed (fp8 + // stores issued, data dependence) and after the proxy fence. Releasing it right after issuing the ld.shared + // (previous code) let the next TMA (async proxy) overwrite the slot before some loads had read it: a 200-call + // warm-L2 probe of sm_dn alone gave a wrong output column in 121-154/300 calls; with this order 0/300. + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // generic smem accesses <-> async proxy (TMA/MMA) + warp_arrive_a(smem_u32(wempty + w)); // bf16 stage consumed -> producer refills + warp_arrive_a(smem_u32(conv + s)); + } + } else { + // ---------------- promoters + epilogue ---------------- + // register audit (sm_dn local 16 -> 0 B): the per-thread / per-CTA constants that were kept live across the + // promotion k loop (and spilled at the 128-register cap: row, the CTA's output column base, the scale-block boundary) + // are re-derived from VOLATILE %tid.x / %ctaid.x reads at their uses (cannot be hoisted -> short live ranges). + auto vtid = []() -> uint32_t { uint32_t v; asm volatile("mov.u32 %0, %%tid.x;" : "=r"(v)); return v; }; + auto vcta = []() -> uint32_t { uint32_t v; asm volatile("mov.u32 %0, %%ctaid.x;" : "=r"(v)); return v; }; + const int q = warp & 3; // TMEM lane quarter accessible by this warp + const int row = q * 32 + lane; + // sh is written by the gate_up kernel: wait, then stage ALL k blocks' scales of this row in smem (loads first, then + // the smem stores, so the 16 L2 loads are in flight together) + // zero the other-parity gate_up split-K reduction workspace (used by the NEXT call's gate_up; its last + // reader, the previous call's gate_up, completed before this call's normal-launched xprep) while waiting for qh + if (p.zws) { + const int pt0 = (int)threadIdx.x - (96 + DN_CONV); + for (int i = (int)blockIdx.x * DN_PROM + pt0; i < p.zn; i += (int)gridDim.x * DN_PROM) + __stcg(p.zws + i, make_float4(0.f, 0.f, 0.f, 0.f)); + } + pdl_wait(); + { + float v[DN_KBMAX]; +#pragma unroll + for (int kb = 0; kb < DN_KBMAX; ++kb) v[kb] = (kb < KB && row < p.M) ? __ldg(p.sA + (size_t)kb * p.M + row) : 0.f; +#pragma unroll + for (int kb = 0; kb < DN_KBMAX; ++kb) if (kb < KB) ssa[kb * 128 + row] = v[kb]; + } + const uint32_t sws32 = smem_u32(sws); // ssa = sws + (DN_OFF_SSA - DN_OFF_SWS) + float acc[64]; +#pragma unroll + for (int c = 0; c < 64; ++c) acc[c] = 0.f; + for (int j = 0; j < NS; ++j) { + const int t = j % DN_NT, kb = stp(j) * DN_KPS; + mbar_wait(accfull + t, (j / DN_NT) & 1); + tc_fence_after(); + const uint32_t tb_step = ld_tmem() + ((uint32_t)(q * 32) << 16) + (uint32_t)(t * DN_KPS * DN_BN); + // kDnDB16 (sm_dn promoters): the step's 2 k blocks x 64 TMEM columns are promoted as 8 x16 chunks through + // TWO 16-reg buffers, software-pipelined: the load of chunk c+1 is in flight while chunk c is FMA'd (was: per + // 32-col half 2 x16 loads -> wait -> 16 FMA2, 4 serialized TMEM round trips per step). Same 32 partial regs, + // same per-element FMA order (k block 0 then 1, same scales) -> bit-identical. Stage released once the last + // chunk's load landed (as before: before the final FMAs). + float scl[DN_KPS][2]; + const int vbnd = 128 - (int)((vcta() * (uint32_t)DN_OUT) & 127u); // == bnd (multiple of 8) +#pragma unroll + for (int b = 0; b < DN_KPS; ++b) { + const float sa_ = lds32f(sws32 + (uint32_t)(DN_OFF_SSA - DN_OFF_SWS) + 4u * (vtid() & 127u) + 4u * (uint32_t)((kb + b) * 128)); + scl[b][0] = sa_ * lds32f(sws32 + 8u * (uint32_t)(kb + b)); + scl[b][1] = sa_ * lds32f(sws32 + 8u * (uint32_t)(kb + b) + 4u); + } + constexpr int kNC = DN_KPS * 4; // x16 chunks per step: chunk c = k block c >> 2, cols ((c & 3) * 16, +16) + float pa[16], pb[16]; + tmem_ld16(tb_step, pa); +#pragma unroll + for (int c = 0; c < kNC; ++c) { + tmem_wait(); // chunk c landed (only load in flight) + float* cur = (c & 1) ? pb : pa; + if (c + 1 < kNC) { + tmem_ld16(tb_step + (uint32_t)(((c + 1) >> 2) * DN_BN + ((c + 1) & 3) * 16), (c & 1) ? pa : pb); + } else { + tc_fence_before(); + warp_arrive_a(smem_u32(accempty + t)); // TMEM stage drained (all loads landed) + } + const int b = c >> 2, c0 = (c & 3) * 16; +#pragma unroll + for (int e = 0; e < 16; e += 2) { + const float s = (8 * ((c0 + e) >> 3)) >= vbnd ? scl[b][1] : scl[b][0]; + fma2(acc[c0 + e], acc[c0 + e + 1], cur[e], cur[e + 1], s); + } + } + } + // coalesced output store: each promoter thread writes its row's 56 bf16 (112 B) into a staging tile in the + // (now idle: every MMA of this CTA completed, all conversions done) B8 ring, row r at bytes [112 r, +112) + // (16 B chunks of 8 consecutive rows hit 8 distinct bank groups), then the 128 promoters copy it out with + // consecutive threads on consecutive 16 B chunks (each warp store = ~4.5 rows x 112 contiguous bytes instead of + // 32 rows x 16 B). + { + const uint32_t stg = smem_u32(b8ring); +#pragma unroll + for (int c = 0; c < DN_OUT / 8; ++c) { + __nv_bfloat162 b0 = __floats2bfloat162_rn(acc[8 * c], acc[8 * c + 1]); + __nv_bfloat162 b1 = __floats2bfloat162_rn(acc[8 * c + 2], acc[8 * c + 3]); + __nv_bfloat162 b2 = __floats2bfloat162_rn(acc[8 * c + 4], acc[8 * c + 5]); + __nv_bfloat162 b3 = __floats2bfloat162_rn(acc[8 * c + 6], acc[8 * c + 7]); + sts128(stg + (vtid() & 127u) * (uint32_t)(DN_OUT * 2) + (uint32_t)(c * 16), *reinterpret_cast(&b0), + *reinterpret_cast(&b1), *reinterpret_cast(&b2), *reinterpret_cast(&b3)); + } + asm volatile("bar.sync 2, %0;" ::"n"(DN_PROM) : "memory"); // promoters only + constexpr int kCh = DN_OUT / 8; // 16 B chunks per row + const int pt = (int)vtid() - (96 + DN_CONV); + const int vn0 = (int)vcta() * DN_OUT; // == n0 + const int mrows = p.M < 128 ? p.M : 128; + for (int i = pt; i < mrows * kCh; i += DN_PROM) { + const int r = i / kCh, c = i - r * kCh; + const uint4 v = lds128(stg + (uint32_t)(i * 16)); + *reinterpret_cast(p.out + (size_t)r * p.Nout + vn0 + c * 8) = v; + } + } + } + tc_fence_before(); + __syncthreads(); + if (warp == 1) { + tc_fence_after(); + asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(ld_tmem()), "n"(512) : "memory"); + } +} + +// ---------------- host ---------------- +static void* grow(void*& p, size_t& cap, size_t bytes) { + if (bytes > cap) { + if (p) cudaFree(p); + cudaMalloc(&p, bytes); + cap = bytes; + } + return p; +} + +// 2-D tensor map, SWIZZLE_128B, box = {box_inner elements, box_outer rows} +static bool make_map_raw(CUtensorMap* m, CUtensorMapDataType dt, int esize, const void* ptr, int inner, int outer, + int box_inner, int box_outer, bool swz = true) { + const cuuint64_t gdim[2] = {(cuuint64_t)inner, (cuuint64_t)outer}; + const cuuint64_t gstr[1] = {(cuuint64_t)inner * esize}; + const cuuint32_t box[2] = {(cuuint32_t)box_inner, (cuuint32_t)box_outer}; + const cuuint32_t es[2] = {1, 1}; + return cuTensorMapEncodeTiled(m, dt, 2, const_cast(ptr), gdim, gstr, box, es, CU_TENSOR_MAP_INTERLEAVE_NONE, + swz ? CU_TENSOR_MAP_SWIZZLE_128B : CU_TENSOR_MAP_SWIZZLE_NONE, + CU_TENSOR_MAP_L2_PROMOTION_L2_256B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE) == CUDA_SUCCESS; +} +// encoded maps cached by (pointer, shape, box): the host encode is a measurable part of the small-M launch cost. +// A map only encodes address + geometry, so a cache hit is valid whatever the current contents are. +struct MapKey { const void* ptr; int dt, inner, outer, bi, bo, swz; }; +struct MapEntry { MapKey k; CUtensorMap m; }; +static bool make_map(CUtensorMap* m, CUtensorMapDataType dt, int esize, const void* ptr, int inner, int outer, + int box_inner, int box_outer, bool swz = true) { + constexpr int kN = 32; + static MapEntry* cache = new MapEntry[kN](); // heap, never freed (plain data) + static int next = 0; + const MapKey k{ptr, (int)dt, inner, outer, box_inner, box_outer, (int)swz}; + for (int i = 0; i < kN; ++i) { + const MapKey& c = cache[i].k; + if (c.ptr == k.ptr && c.dt == k.dt && c.inner == k.inner && c.outer == k.outer && c.bi == k.bi && c.bo == k.bo && + c.swz == k.swz) { + *m = cache[i].m; + return true; + } + } + if (!make_map_raw(m, dt, esize, ptr, inner, outer, box_inner, box_outer, swz)) return false; + cache[next].k = k; + cache[next].m = *m; + next = (next + 1) % kN; + return true; +} + + +// bf16 weight [rows, K] viewed as 3-D {64 k, rows (stride 2K B), K/64 chunks (stride 128 B)}, box {64, box_rows, 4} +// = box_rows rows x 256 k (512 contiguous bytes per row), SWIZZLE_128B. Cached by (pointer, shape, box rows). +static bool make_map3(CUtensorMap* m, const void* ptr, int K, int rows, int box_rows) { + struct E { const void* p; int k, r, b; CUtensorMap m; }; + constexpr int kN = 16; + static E* cache = new E[kN](); + static int next = 0; + for (int i = 0; i < kN; ++i) + if (cache[i].p == ptr && cache[i].k == K && cache[i].r == rows && cache[i].b == box_rows) { *m = cache[i].m; return true; } + const cuuint64_t gdim[3] = {64, (cuuint64_t)rows, (cuuint64_t)(K / 64)}; + const cuuint64_t gstr[2] = {(cuuint64_t)K * 2, 128}; + const cuuint32_t box[3] = {64, (cuuint32_t)box_rows, 4}; + const cuuint32_t es[3] = {1, 1, 1}; + if (cuTensorMapEncodeTiled(m, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 3, const_cast(ptr), gdim, gstr, 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) != CUDA_SUCCESS) + return false; + cache[next].p = ptr; cache[next].k = K; cache[next].r = rows; cache[next].b = box_rows; cache[next].m = *m; + next = (next + 1) % kN; + return true; +} + +// host trim: small-M kernels launched through the DRIVER API (cuLaunchKernelEx) with the CUfunction resolved +// once per kernel (cudaGetFuncBySymbol), instead of cudaLaunchKernelExC / <<<>>> (runtime per-launch host work). +// Same grid / block / smem / PDL attribute. Falls back to the runtime launch if the function lookup fails. +static int drv_launch_k(const void* sym, CUfunction& fn, int& tried, dim3 grid, dim3 block, unsigned smem, + cudaStream_t st, bool pdl, void** args) { + if (!tried) { + tried = 1; + cudaFunction_t f = nullptr; + if (cudaGetFuncBySymbol(&f, sym) == cudaSuccess) fn = (CUfunction)f; + else { fn = nullptr; cudaGetLastError(); } + } + if (!fn) { + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = grid; cfg.blockDim = block; cfg.dynamicSmemBytes = smem; cfg.stream = st; + cudaLaunchAttribute at[1]; + at[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + at[0].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = at; cfg.numAttrs = pdl ? 1 : 0; + return cudaLaunchKernelExC(&cfg, sym, args) == cudaSuccess ? 0 : 1; + } + CUlaunchConfig dc = {}; + dc.gridDimX = grid.x; dc.gridDimY = grid.y; dc.gridDimZ = grid.z; + dc.blockDimX = block.x; dc.blockDimY = block.y; dc.blockDimZ = block.z; + dc.sharedMemBytes = smem; + dc.hStream = (CUstream)st; + CUlaunchAttribute da[1]; + da[0].id = CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_STREAM_SERIALIZATION; + da[0].value.programmaticStreamSerializationAllowed = 1; + dc.attrs = da; dc.numAttrs = pdl ? 1 : 0; + return cuLaunchKernelEx(&dc, fn, args, nullptr) == CUDA_SUCCESS ? 0 : 1; +} + +// PDL launch of sm_gemm over n_tiles * S CTAs (<= SM count: all co-resident, required by the split-K wait) +template +static int launch_gemm(GemmParams& p, int n_tiles, cudaStream_t st) { + static bool attr = false; + if (!attr) { + cudaFuncSetAttribute(sm_gemm, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM); + attr = true; + } + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3((unsigned)(n_tiles * S)); + cfg.blockDim = dim3(kThreads); + cfg.dynamicSmemBytes = SMEM; + cfg.stream = st; + cudaLaunchAttribute at[1]; + at[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + at[0].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = at; + cfg.numAttrs = 1; + void* args[1] = {&p}; + static CUfunction fn = nullptr; + static int tried = 0; + return drv_launch_k((const void*)sm_gemm, fn, tried, cfg.gridDim, cfg.blockDim, SMEM, st, cfg.numAttrs > 0, + args) ? 4 : 0; +} + +constexpr int S_GU = 8; + +static int launch_small_m_impl(const void* x, const void* gw, const float* gws, const void* uw, const float* uws, + const void* dw, const float* dws, void* out, int M, int Hd, int I, cudaStream_t stream, + int only) { + // grow-only raw device scratch (never freed: no static tensor destructors at teardown) + static void *qx = nullptr, *sx = nullptr, *qh = nullptr, *sh = nullptr, *ws1 = nullptr, *cnt = nullptr; + static size_t c_qx = 0, c_sx = 0, c_qh = 0, c_sh = 0, c_ws1 = 0, c_cnt = 0; + const int ntg = I / 128; // gate_up tiles (128 h columns each) + const int ncnt = ntg; // split arrival counter per tile (zeroed every call by sm_xprep) + // TWO fp32 reduction workspaces [ntg][128][256] used by alternating calls (parity ws_par). The gate_up epilogue + // only reads its tile (no re-zero stores on the critical path); the down kernel of the same call zeroes the other + // parity's buffer (the next call's) while it waits for qh. Both zeroed at allocation. + static int ws_par = 0; + const size_t ws_half = (size_t)ntg * 128 * 256 * 4; + { + const size_t need = 2 * ws_half; + if (need > c_ws1) { grow(ws1, c_ws1, need); cudaMemsetAsync(ws1, 0, need, stream); } + } + float* ws_cur = (float*)((char*)ws1 + (size_t)ws_par * ws_half); + float* ws_alt = (float*)((char*)ws1 + (size_t)(ws_par ^ 1) * ws_half); + grow(cnt, c_cnt, (size_t)ncnt * 4); + const int KB1 = Hd / 128, KB2 = I / 128; + grow(qx, c_qx, (size_t)M * Hd); + grow(sx, c_sx, (size_t)M * KB1 * 4); + grow(qh, c_qh, (size_t)M * I); + grow(sh, c_sh, (size_t)M * KB2 * 4); + int r = 0; + // 2. gate_up (sm_gemm): tile nt = gate rows [128 nt, +128) ++ up rows [128 nt, +128), split-K + const bool do_x = only < 0 || only == 0 || only == 3; + const bool do_gu = only < 0 || only == 1 || only == 3; + GemmParams p; + if (do_gu) { + memset(&p, 0, sizeof(p)); + // down-weight L2 prefetch map (box 256 k x pf_rows rows, no swizzle), one slice per gate_up CTA + if (dw && g_dn_pf) { + const int G = ntg * 8, rows = (Hd + G - 1) / G; + static int nsm = 0; // SM count queried once (was cudaGetDevice + attribute query every call) + if (!nsm) { + int dev = 0; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&nsm, cudaDevAttrMultiProcessorCount, dev); + } + if (rows <= 256 && I % 256 == 0 && make_map(&p.tmP, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, dw, I, Hd, 256, rows, false)) { + p.pf_rows = rows; p.pf_k = I; p.pf_nrows = Hd; p.pf_on = 1; + p.pf_c0 = nsm > G ? nsm - G : 0; + } + } + if (!make_map(&p.tmA, CU_TENSOR_MAP_DATA_TYPE_UINT8, 1, qx, Hd, M, 128, 128)) return 1; + if (!make_map3(&p.tmB0, gw, Hd, I, 64)) return 2; + if (!make_map3(&p.tmB1, uw, Hd, I, 64)) return 3; + p.sA = (const float*)sx; + p.sB0 = gws; p.sB1 = uws; + p.r1_off = 0; p.row_step = 128; + p.ldsB0 = p.ldsB1 = I / 128; + p.M = M; p.KB = KB1; + p.qh = (uint8_t*)qh; p.sh = (float*)sh; p.I = I; + p.ws = ws_cur; p.cnt = (int*)cnt; + p.probe_id = 0; + } + // 1. x quant (normal launch: fully ordered after the previous call) + if (do_x) + { + const __nv_bfloat16* xa = (const __nv_bfloat16*)x; uint8_t* qa = (uint8_t*)qx; float* sa = (float*)sx; + int Ma = M, Ka = Hd; int* ca = (int*)cnt; int na = ncnt; + void* xargs[7] = {&xa, &qa, &sa, &Ma, &Ka, &ca, &na}; + static CUfunction fx = nullptr; + static int tx = 0; + if (drv_launch_k((const void*)sm_xprep, fx, tx, dim3((unsigned)(((long)M * KB1 + (g_xp_bs / 16) - 1) / (g_xp_bs / 16))), dim3(g_xp_bs), 0, stream, + false, xargs)) return 9; + } + // 2. gate_up launch, immediately after xprep + if (do_gu) { + const int r = launch_gemm(p, ntg, stream); + if (r) return 10 + r; + } + // 3. down (sm_dn): 64 output columns per CTA over the full K, bf16 output, PDL launch + if (only < 0 || only == 2) { + DnParams p; + memset(&p, 0, sizeof(p)); + if (!make_map(&p.tmA, CU_TENSOR_MAP_DATA_TYPE_UINT8, 1, qh, I, M, 128, 128)) return 21; + const int DN_OUT = (g_dn_out == 64 && Hd % 64 == 0) ? 64 : DN_OUT_SHIP; + if (!make_map3(&p.tmB, dw, I, Hd, DN_OUT)) return 22; + p.sA = (const float*)sh; + p.sB = dws; + p.ldsB = Hd / 128; + p.M = M; p.KB = KB2; p.Nout = Hd; + p.out = (__nv_bfloat16*)out; + p.zws = reinterpret_cast(ws_alt); + p.zn = (int)(ws_half / 16); + ws_par ^= 1; // flip after the down launch: front (gate_up) + down of one call share the parity + static bool attr = false; + if (!attr) { + cudaFuncSetAttribute(sm_dn<56>, cudaFuncAttributeMaxDynamicSharedMemorySize, DN_SMEM); + cudaFuncSetAttribute(sm_dn<64>, cudaFuncAttributeMaxDynamicSharedMemorySize, DN_SMEM); + attr = true; + } + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = dim3((unsigned)(Hd / DN_OUT)); + cfg.blockDim = dim3(DN_THREADS); + cfg.dynamicSmemBytes = DN_SMEM; + cfg.stream = stream; + cudaLaunchAttribute at[1]; + at[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + at[0].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = at; + cfg.numAttrs = 1; + void* args[1] = {&p}; + static CUfunction fd[2] = {nullptr, nullptr}; + static int td[2] = {0, 0}; + const int di = DN_OUT == 64 ? 1 : 0; + if (drv_launch_k(di ? (const void*)sm_dn<64> : (const void*)sm_dn<56>, fd[di], td[di], cfg.gridDim, cfg.blockDim, + DN_SMEM, stream, cfg.numAttrs > 0, args)) return 34; + } + return 0; +} + +} // namespace smallm + +// dispatch condition (kernel.cu): one 128-row A tile; every split CTA of each GEMM co-resident (1 CTA / SM) +bool smallm_supported(int M, int Hd, int I) { + static int sm = 0; + if (!sm) { + int dev; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&sm, cudaDevAttrMultiProcessorCount, dev); + } + const int kb1 = Hd / 128, kb2 = I / 128; + // gate_up (sm_gemm, S_GU splits of 256-row tiles): every split CTA co-resident (1 CTA / SM: the split-K wait relies + // on it), 4 K quarters of whole KPS steps, <= 32 k blocks each (scale staging); down (sm_dn): K = I in whole pipeline steps, scales staged. + return M >= 1 && M <= 128 && Hd % 128 == 0 && I % 128 == 0 && kb1 % (4 * smallm::KPS) == 0 && kb1 / 4 <= 32 && (I / 128) * smallm::S_GU <= sm && + kb2 <= smallm::DN_KBMAX && kb2 % smallm::DN_KPS == 0 && Hd % smallm::DN_OUT_SHIP == 0; +} + +int launch_small_m_front(const void* x, const void* gw, const float* gws, const void* uw, const float* uws, + const void* dw, int M, int Hd, int I, cudaStream_t stream) { + return smallm::launch_small_m_impl(x, gw, gws, uw, uws, dw, nullptr, nullptr, M, Hd, I, stream, 3); +} +int launch_small_m_down(const void* dw, const float* dws, void* out, int M, int Hd, int I, cudaStream_t stream) { + return smallm::launch_small_m_impl(nullptr, nullptr, nullptr, nullptr, nullptr, dw, dws, out, M, Hd, I, stream, 2); +} + +// Host entry (kernel.cu dispatches here when smallm_supported). Returns 0 on success. +int launch_small_m(const void* x, const void* gw, const float* gws, const void* uw, const float* uws, const void* dw, + const float* dws, void* out, int M, int Hd, int I, cudaStream_t stream) { + return smallm::launch_small_m_impl(x, gw, gws, uw, uws, dw, dws, out, M, Hd, I, stream, -1); +} + + + diff --git a/kernels/Quant/018_nvfp4_attention_output_projection_with_residual/README.md b/kernels/Quant/018_nvfp4_attention_output_projection_with_residual/README.md new file mode 100644 index 0000000000000000000000000000000000000000..78e309ee798b07eb2153b27e4a3452cb2be55658 --- /dev/null +++ b/kernels/Quant/018_nvfp4_attention_output_projection_with_residual/README.md @@ -0,0 +1,10 @@ +# NVFP4 attention output projection with residual (Quant 018) + +Attention output projection in NVFP4: quantizes the bf16 attention output to NVFP4, multiplies by an NVFP4 weight (block and global scales), and adds the residual. + +- Language: CUDA C++. Entry point: `main.cpp::run`. Files: 4 (5,920 lines). +- Idea: Front kernel quantizes to NVFP4 (global amax by grid barrier, or a DSMEM cluster gather when small); CUTLASS block-scaled FP4 GEMM adds the residual in its epilogue +- Result: SOL score 0.938; speedup 12.65x over the benchmark's baseline (geometric mean). Public SOL-ExecBench results as of 2026-11-11. +- Origin: search agent (Claude). +- Comments edited; the code that runs is identical to the scored submission. +- Generated by Claude via Amazon Bedrock. Verified on the SOL-ExecBench site; not production-ready. diff --git a/kernels/Quant/018_nvfp4_attention_output_projection_with_residual/kernel.json b/kernels/Quant/018_nvfp4_attention_output_projection_with_residual/kernel.json new file mode 100644 index 0000000000000000000000000000000000000000..b341616c4f1de1bd5ba18c6c59cecebc00deb49b --- /dev/null +++ b/kernels/Quant/018_nvfp4_attention_output_projection_with_residual/kernel.json @@ -0,0 +1,72 @@ +{ + "board": "Quant", + "id": "018_nvfp4_attention_output_projection_with_residual", + "name": "NVFP4 attention output projection with residual", + "language": "CUDA C++", + "files": [ + { + "path": "src/collective_anyn.hpp", + "lines": 1102, + "bytes": 53020 + }, + { + "path": "src/kernel.cu", + "lines": 4461, + "bytes": 227878 + }, + { + "path": "src/kernel.h", + "lines": 28, + "bytes": 1386 + }, + { + "path": "src/main.cpp", + "lines": 329, + "bytes": 15889 + } + ], + "origin": "search agent (Claude)", + "result": { + "public": true, + "sol_score": 0.938069, + "speedup": 12.6459, + "board_row": true, + "note": "the row the public SOL-ExecBench board shows for this problem, as of 2026-11-11" + }, + "idea": "Front kernel quantizes to NVFP4 (global amax by grid barrier, or a DSMEM cluster gather when small); CUTLASS block-scaled FP4 GEMM adds the residual in its epilogue", + "spec": { + "languages": [ + "cuda_cpp" + ], + "target_hardware": [ + "B200", + "LOCAL" + ], + "entry_point": "main.cpp::run", + "binding": "torch", + "destination_passing_style": false, + "dependencies": [], + "compile_options": { + "cuda_cflags": [ + "-std=c++17", + "-O3", + "-gencode=arch=compute_100a,code=sm_100a", + "--expt-relaxed-constexpr", + "-I/usr/local/cutlass/include", + "-DNDEBUG", + "-DCUTLASS_ENABLE_GDC_FOR_SM100=1", + "-Xptxas", + "-O3", + "-Xptxas", + "--allow-expensive-optimizations=true" + ], + "ld_flags": [] + }, + "sources": [ + "kernel.h", + "collective_anyn.hpp", + "kernel.cu", + "main.cpp" + ] + } +} diff --git a/kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/collective_anyn.hpp b/kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/collective_anyn.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4bc1b1a9fe480b116bb5d5f2588c2c90245924db --- /dev/null +++ b/kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/collective_anyn.hpp @@ -0,0 +1,1102 @@ +// collective_anyn.hpp -- verbatim copy of CUTLASS 4.4.1 +// cutlass/gemm/collective/sm100_blockscaled_mma_warpspecialized.hpp (CollectiveMma for +// MainloopSm100TmaUmmaWarpSpecializedBlockScaled), renamed to the primary template +// CollectiveMmaAnyN. Only edit: the CTA-N static_assert also accepts 224 and 176 (see [AnyN edit]). +// Used for the 2SM 256x224 tile (37 N tiles over N=8192 -> exact waves of 74 clusters). +#pragma once +#include "cutlass/gemm/collective/collective_builder.hpp" +#include "cutlass/detail/sm100_tmem_helper.hpp" +namespace cutlass::gemm::collective { +using namespace cute; + +namespace detail { +// [AnyN] The blockscaled builder's 2SM tiled-MMA factory only accepts N in {64,128,192,256} +// although SM100_MMA_MXF4_2x1SM_SS accepts any N % 16 == 0 <= 256. This more specialized partial +// specialization supplies the 2SM NVF4 MMA for the 256x224x256 and 256x176x256 tiles (everything else in the +// builder -- smem selectors, SF smem atoms (SFB rounded up to 256 rows), stage count, 2 acc +// stages -- is generic in N). +#define ANYN_SPECIALIZE(ANYN_N) \ +template \ +struct TrivialBlockscaledMma, _256>, \ + ClusterShape_MNK, UmmaMajorA, UmmaMajorB, Instr, BuilderScheduleTag, \ + true /*Is2SM*/> { \ + static_assert(Instr == detail::blockscaled::BlockScaledInstr::MXF4_NVF4, "AnyN: NVF4 only"); \ + using ElementSF = typename detail::blockscaled::blockscaled_type::sf_type; \ + using ElementA = typename detail::blockscaled::blockscaled_type::data_type; \ + using ElementB = typename detail::blockscaled::blockscaled_type::data_type; \ + static constexpr uint32_t VSA = detail::blockscaled::blockscaled_type::SfVectorSize; \ + static constexpr uint32_t VSB = detail::blockscaled::blockscaled_type::SfVectorSize; \ + static constexpr int SfVectorSize = VSA > VSB ? VSA : VSB; \ + using ElementAMma = decltype(cutlass::gemm::collective::detail::sm1xx_kernel_input_element_to_mma_input_element()); \ + using ElementBMma = decltype(cutlass::gemm::collective::detail::sm1xx_kernel_input_element_to_mma_input_element()); \ + using type = decltype(make_tiled_mma(cute::SM100_MMA_MXF4_2x1SM_SS{})); \ +}; +ANYN_SPECIALIZE(224) +ANYN_SPECIALIZE(176) +ANYN_SPECIALIZE(112) +#undef ANYN_SPECIALIZE +} // namespace detail +// WarpSpecialized Mainloop +// Both DMA Load and MMA methods of this class must be run by a single thread that's picked by elect_one +template < + int Stages, + int SchedulerPipelineStageCount, + int AccumulatorPipelineStageCount, + class ClusterShape, // Static cluster shape or dynamic (int, int, _1) + class TileShape_, // (MmaAtomShapeM, MmaAtomShapeN, TileK) + class ElementPairA_, + class StridePairA_, + class ElementPairB_, + class StridePairB_, + class TiledMma_, + class GmemTiledCopyPairA_, + class SmemLayoutAtomPairA_, + class SmemCopyAtomA_, + class TransformA_, + class GmemTiledCopyPairB_, + class SmemLayoutAtomPairB_, + class SmemCopyAtomB_, + class TransformB_> +struct CollectiveMmaAnyN +{ + static constexpr bool kAccFirstSkip = true; + // + // Type Aliases + // + using TiledMma = TiledMma_; + using AtomThrShapeMNK = Shape(typename TiledMma::ThrLayoutVMNK{})), _1, _1>; + + using DispatchPolicy = MainloopSm100TmaUmmaWarpSpecializedBlockScaled< + Stages, + SchedulerPipelineStageCount, + AccumulatorPipelineStageCount, + ClusterShape>; + using TileShape = TileShape_; + using TiledMMA_SF = TiledMMA, + Layout>, + Tile>; + + static constexpr bool IsDynamicCluster = not cute::is_static_v; + static constexpr int SFVecSize = TiledMma::SFVecSize; + static constexpr bool IsOverlappingAccum = DispatchPolicy::IsOverlappingAccum; + static constexpr bool kDirectRelease = cute::is_static_v && (size(ClusterShape{}) == 2) && !IsOverlappingAccum; + + CUTE_STATIC_ASSERT_V(evenly_divides(TileShape{}, tile_shape(TiledMma{})), + "Static cluster shape used: TileShape should be evenly divided by TiledMma"); + + using CtaShape_MNK = decltype(shape_div(TileShape{}, AtomThrShapeMNK{})); + // [AnyN edit] also allow CTA N = 224. CTA_N_SF below rounds it up to 256, so every N tile n + // reads SF rows [256n, 256n+256) of the SFB tensor with NO TMEM shift: the CALLER must supply a + // weight-SF tensor in the PADDED layout (N tile n's 224 rows at padded rows 256n.., rest zero). + static_assert(shape<1>(CtaShape_MNK{}) == 192 or shape<1>(CtaShape_MNK{}) == 64 or + shape<1>(CtaShape_MNK{}) == 128 or shape<1>(CtaShape_MNK{}) == 256 or + shape<1>(CtaShape_MNK{}) == 224 or shape<1>(CtaShape_MNK{}) == 176 or shape<1>(CtaShape_MNK{}) == 112, + "Cta N should be one of 64/128/176/192/224/256"); + + using ClusterTileShape = decltype(make_shape(get<0>(TileShape{})*get<0>(ClusterShape{}),get<1>(TileShape{})*get<1>(ClusterShape{}),get<2>(TileShape{})*get<2>(ClusterShape{}))); + using Sm1xxBlkScaledConfig = cutlass::detail::Sm1xxBlockScaledConfig; + using Blk_MN = typename Sm1xxBlkScaledConfig::Blk_MN; + static constexpr int IsCtaN192 = shape<1>(CtaShape_MNK{}) == 192; + static constexpr int IsCtaN64 = shape<1>(CtaShape_MNK{}) == 64; + static int constexpr CTA_N_SF = cutlass::ceil_div(size<1>(CtaShape_MNK{}), Blk_MN{}) * Blk_MN{}; + // Tile shape used for partitioning Scale Factor B. + // The M-dim does not affect the SFB, so just set it as the original TileShape; + using TileShape_SF = decltype(make_shape(get<0>(CtaShape_MNK{}), + Int{} * shape<2>(typename TiledMma::ThrLayoutVMNK()), + get<2>(TileShape{}))); + + // Define A and B block shapes for reduced size TMA_LOADs + using MmaShapeA_MK = decltype(partition_shape_A(TiledMma{}, make_shape(size<0>(TileShape{}), size<2>(TileShape{})))); + using MmaShapeB_NK = decltype(partition_shape_B(TiledMma{}, make_shape(size<1>(TileShape{}), size<2>(TileShape{})))); + + using ElementPairA = ElementPairA_; + using ElementPairB = ElementPairB_; + using ElementAMma = typename TiledMma::ValTypeA; + using ElementBMma = typename TiledMma::ValTypeB; + using StridePairA = StridePairA_; + using StridePairB = StridePairB_; + using SmemLayoutAtomPairA = SmemLayoutAtomPairA_; + using SmemLayoutAtomPairB = SmemLayoutAtomPairB_; + static_assert(cute::is_same_v(ElementPairA{}))>, + remove_cvref_t(ElementPairB{}))>>, "SFA and SFB data types should be the same"); + + // A and B matrices + using ElementA = remove_cvref_t(ElementPairA{}))>; + using StrideA = remove_cvref_t(StridePairA{}))>; + + using ElementB = remove_cvref_t(ElementPairB{}))>; + using StrideB = remove_cvref_t(StridePairB{}))>; + + static constexpr bool IsRuntimeDataTypeA = cutlass::gemm::collective::detail::is_sm10x_runtime_f8f6f4(); + static constexpr bool IsRuntimeDataTypeB = cutlass::gemm::collective::detail::is_sm10x_runtime_f8f6f4(); + + static_assert((IsRuntimeDataTypeA && IsRuntimeDataTypeB) || + (!IsRuntimeDataTypeA && !IsRuntimeDataTypeB), + "ElementA and ElementB should be both runtime or both static."); + + static constexpr bool IsRuntimeDataType = IsRuntimeDataTypeA && IsRuntimeDataTypeB; + + // SFA and SFB + using ElementSF = remove_cvref_t(ElementPairA{}))>; + using LayoutSFA = remove_cvref_t(StridePairA{}))>; + using LayoutSFB = remove_cvref_t(StridePairB{}))>; + + using ElementAccumulator = typename TiledMma::ValTypeC; + using GmemTiledCopyPairA = GmemTiledCopyPairA_; + using GmemTiledCopyPairB = GmemTiledCopyPairB_; + using GmemTiledCopyA = remove_cvref_t(GmemTiledCopyPairA{}))>; + using GmemTiledCopySFA = remove_cvref_t(GmemTiledCopyPairA{}))>; + using GmemTiledCopyB = remove_cvref_t(GmemTiledCopyPairB{}))>; + using GmemTiledCopySFB = remove_cvref_t(GmemTiledCopyPairB{}))>; + + using SmemLayoutAtomA = remove_cvref_t(SmemLayoutAtomPairA{}))>; + using SmemLayoutAtomSFA = remove_cvref_t(SmemLayoutAtomPairA{}))>; + using SmemLayoutAtomB = remove_cvref_t(SmemLayoutAtomPairB{}))>; + using SmemLayoutAtomSFB = remove_cvref_t(SmemLayoutAtomPairB{}))>; + + using SmemCopyAtomA = SmemCopyAtomA_; + using SmemCopyAtomB = SmemCopyAtomB_; + using TransformA = TransformA_; + using TransformB = TransformB_; + using ArchTag = typename DispatchPolicy::ArchTag; + + using MainloopPipeline = cutlass::PipelineTmaUmmaAsync< + DispatchPolicy::Stages, + ClusterShape, + AtomThrShapeMNK>; + using MainloopPipelineState = typename MainloopPipeline::PipelineState; + + static_assert(rank(SmemLayoutAtomA{}) == 2, "SmemLayoutAtom must be rank 2 (M/N, K)"); + static_assert((size<0>(TileShape{}) % size<0>(SmemLayoutAtomA{})) == 0, "SmemLayoutAtomA must evenly divide the tile shape."); + static_assert((size<2>(TileShape{}) % size<1>(SmemLayoutAtomA{})) == 0, "SmemLayoutAtomA must evenly divide the tile shape."); + static_assert(cute::is_void_v, + "SM100 UMMA cannot have a non-void copy atom for smem sourced instructions."); + + static_assert(rank(SmemLayoutAtomB{}) == 2, "SmemLayoutAtom must be rank 2 (M/N, K)"); + static_assert((size<1>(TileShape{}) % size<0>(SmemLayoutAtomB{})) == 0, "SmemLayoutAtomB must evenly divide the tile shape."); + static_assert((size<2>(TileShape{}) % size<1>(SmemLayoutAtomB{})) == 0, "SmemLayoutAtomB must evenly divide the tile shape."); + static_assert(cute::is_void_v, + "SM100 UMMA cannot have a non-void copy atom for smem sourced instructions."); + + // Tile along K mode first before tiling over MN. PIPE mode last as usual. + // This maximizes TMA boxes due to better smem-K vectorization, reducing total issued TMAs. + // (MMA_TILE_M,MMA_TILE_K),MMA_M,MMA_K,PIPE) + using SmemLayoutA = decltype(UMMA::tile_to_mma_shape( + SmemLayoutAtomA{}, + append(MmaShapeA_MK{}, Int{}), + cute::conditional_t(), Step<_2,_1,_3>, Step<_1,_2,_3>>{})); + // (MMA_TILE_N,MMA_TILE_K),MMA_N,MMA_K,PIPE) + using SmemLayoutB = decltype(UMMA::tile_to_mma_shape( + SmemLayoutAtomB{}, + append(MmaShapeB_NK{}, Int{}), + cute::conditional_t(), Step<_2,_1,_3>, Step<_1,_2,_3>>{})); + + // SmemLayoutAtomSFA and SmemLayoutAtomSFB are for whole CTA tiles. We add the number of pipeline stages here. + // The number of pipeline stages is the same as the number of pipeline stages from AB Load <-> MainLoop + using SmemLayoutSFA = decltype(make_layout( + append(shape(SmemLayoutAtomSFA{}), Int{}), + append(stride(SmemLayoutAtomSFA{}), size(filter_zeros(SmemLayoutAtomSFA{}))) + )); + using SmemLayoutSFB = decltype(make_layout( + append(shape(SmemLayoutAtomSFB{}), Int{}), + append(stride(SmemLayoutAtomSFB{}), size(filter_zeros(SmemLayoutAtomSFB{}))) + )); + + static_assert(cute::is_base_of::value && + cute::is_base_of::value, + "MMA atom must source both A and B operand from smem_desc for this mainloop."); + static_assert( + (size(AtomThrShapeMNK{}) == 1 && + (cute::is_same_v || cute::is_same_v)) || + (size(AtomThrShapeMNK{}) == 2 && + (cute::is_same_v || cute::is_same_v)), + "GmemTiledCopy - invalid TMA copy atom specified."); + static_assert( + (size(AtomThrShapeMNK{}) == 1 && + (cute::is_same_v || cute::is_same_v)) || + (size(AtomThrShapeMNK{}) == 2 && + (cute::is_same_v || cute::is_same_v)), + "GmemTiledCopy - invalid TMA copy atom specified."); + + static constexpr bool IsF8F6F4 = detail::is_sm100_mma_f8f6f4(); + + using TmaInternalElementA = cute::conditional_t; + using TmaInternalElementB = cute::conditional_t; + + using SmemAllocTypeA = cute::conditional_t < 8, uint8_t, ElementAMma>; + using SmemAllocTypeB = cute::conditional_t < 8, uint8_t, ElementBMma>; + + using BitTypeElementA = cute::uint_bit_t>; + using BitTypeElementB = cute::uint_bit_t>; + + using ArrayElementA = cute::conditional_t; + using ArrayElementB = cute::conditional_t; + + using RuntimeDataTypeA = typename detail::sm10x_block_scale_runtime_input_t::Type; + using RuntimeDataTypeB = typename detail::sm10x_block_scale_runtime_input_t::Type; + + struct SharedStorage { + struct TensorStorage : cute::aligned_struct<128, _0> { + cute::ArrayEngine> smem_A; + cute::ArrayEngine> smem_B; + cute::ArrayEngine> smem_SFA; + cute::ArrayEngine> smem_SFB; + } tensors; + + using PipelineStorage = typename MainloopPipeline::SharedStorage; + PipelineStorage pipeline; + }; + + // Expose shared storage for tensors/pipelines separately to allow kernel layer to reorder them. + using TensorStorage = typename SharedStorage::TensorStorage; + using PipelineStorage = typename SharedStorage::PipelineStorage; + + // Only one thread issues the TMA and updates the barriers in a 2SM MMA, adjust bytes accordingly + static constexpr uint32_t SFTransactionBytes = + cutlass::bits_to_bytes(size(AtomThrShapeMNK{}) * cosize(take<0,3>(SmemLayoutSFA{})) * cute::sizeof_bits_v) + + cutlass::bits_to_bytes(size(AtomThrShapeMNK{}) * cosize(take<0,3>(SmemLayoutSFB{})) * cute::sizeof_bits_v); + static constexpr uint32_t ABTmaTransactionBytes = + cutlass::bits_to_bytes(size(AtomThrShapeMNK{}) * cosize(take<0,3>(SmemLayoutA{})) * cute::sizeof_bits_v) + + cutlass::bits_to_bytes(size(AtomThrShapeMNK{}) * cosize(take<0,3>(SmemLayoutB{})) * cute::sizeof_bits_v); + static constexpr uint32_t TmaTransactionBytes = ABTmaTransactionBytes + SFTransactionBytes; + + template + struct TmemStorage { + AccTensor accumulators; + SfaTensor tCtSFA; + SfbTensor tCtSFB; + }; + + template < + class KTileCount, + class GTensorPartitionedA, class GTensorPartitionedB, + class STensorA, class STensorB, + class GTensorPartitionedSFA, class GTensorPartitionedSFB, + class STensorSFA, class STensorSFB + > + struct LoadParams { + // for scheduler + KTileCount k_tiles; + // for input tensor values + GTensorPartitionedA tAgA_mkl; + GTensorPartitionedB tBgB_nkl; + STensorA tAsA; + STensorB tBsB; + // for scale factor tensor values + GTensorPartitionedSFA tAgSFA_mkl; + GTensorPartitionedSFB tBgSFB_nkl; + STensorSFA tAsSFA; + STensorSFB tBsSFB; + // the TMA multicast masks + uint16_t mcast_mask_a; + uint16_t mcast_mask_b; + uint16_t mcast_mask_sfa; + uint16_t mcast_mask_sfb; + + CUTLASS_DEVICE + LoadParams ( + KTileCount k_tiles_, + GTensorPartitionedA tAgA_mkl_, GTensorPartitionedB tBgB_nkl_, + STensorA tAsA_, STensorB tBsB_, + GTensorPartitionedSFA tAgSFA_mkl_, GTensorPartitionedSFB tBgSFB_nkl_, + STensorSFA tAsSFA_, STensorSFB tBsSFB_, + uint16_t mcast_mask_a_, uint16_t mcast_mask_b_, + uint16_t mcast_mask_sfa_, uint16_t mcast_mask_sfb_) + : k_tiles(k_tiles_) + , tAgA_mkl(tAgA_mkl_), tBgB_nkl(tBgB_nkl_) + , tAsA(tAsA_), tBsB(tBsB_) + , tAgSFA_mkl(tAgSFA_mkl_), tBgSFB_nkl(tBgSFB_nkl_) + , tAsSFA(tAsSFA_), tBsSFB(tBsSFB_) + , mcast_mask_a(mcast_mask_a_), mcast_mask_b(mcast_mask_b_) + , mcast_mask_sfa(mcast_mask_sfa_), mcast_mask_sfb(mcast_mask_sfb_) {} + }; + + template < + class TiledMma, + class FragmentA, class FragmentB, + class FragmentSFA, class FragmentSFB, + class SFATiledCopy, class SmemFrgSFA, class TmemFrgSFA, + class SFBTiledCopy, class SmemFrgSFB, class TmemFrgSFB + > + struct MmaParams { + TiledMma tiled_mma; + FragmentA tCrA; + FragmentB tCrB; + FragmentSFA tCtSFA; + FragmentSFB tCtSFB; + SFATiledCopy tiled_copy_s2t_SFA; + SmemFrgSFA thr_tCsSFA_s2t; + TmemFrgSFA thr_tCtSFA_s2t; + SFBTiledCopy tiled_copy_s2t_SFB; + SmemFrgSFB thr_tCsSFB_s2t; + TmemFrgSFB thr_tCtSFB_s2t; + + CUTLASS_DEVICE + MmaParams ( + TiledMma tiled_mma_, + FragmentA tCrA_, FragmentB tCrB_, FragmentSFA tCtSFA_, FragmentSFB tCtSFB_, + SFATiledCopy tiled_copy_s2t_SFA_, SmemFrgSFA thr_tCsSFA_s2t_, TmemFrgSFA thr_tCtSFA_s2t_, + SFBTiledCopy tiled_copy_s2t_SFB_, SmemFrgSFB thr_tCsSFB_s2t_, TmemFrgSFB thr_tCtSFB_s2t_) + : tiled_mma(tiled_mma_) + , tCrA(tCrA_), tCrB(tCrB_), tCtSFA(tCtSFA_), tCtSFB(tCtSFB_) + , tiled_copy_s2t_SFA(tiled_copy_s2t_SFA_), thr_tCsSFA_s2t(thr_tCsSFA_s2t_), thr_tCtSFA_s2t(thr_tCtSFA_s2t_) + , tiled_copy_s2t_SFB(tiled_copy_s2t_SFB_), thr_tCsSFB_s2t(thr_tCsSFB_s2t_), thr_tCtSFB_s2t(thr_tCtSFB_s2t_) {} + }; + + // Host side kernel arguments + struct Arguments { + ArrayElementA const* ptr_A{nullptr}; + StrideA dA{}; + ArrayElementB const* ptr_B{nullptr}; + StrideB dB{}; + ElementSF const* ptr_SFA{nullptr}; + LayoutSFA layout_SFA{}; + ElementSF const* ptr_SFB{nullptr}; + LayoutSFB layout_SFB{}; + RuntimeDataTypeA runtime_data_type_a{}; + RuntimeDataTypeB runtime_data_type_b{}; + }; + + // Device side kernel params + struct Params { + using ClusterLayout_VMNK = + decltype(tiled_divide(make_layout(conditional_return(make_shape(uint32_t(0), uint32_t(0), Int<1>{}), + ClusterShape{})), make_tile(typename TiledMma::AtomThrID{}))); + + using ClusterLayoutSfb_VMNK = + decltype(tiled_divide(make_layout(conditional_return(make_shape(uint32_t(0), uint32_t(0), Int<1>{}), + ClusterShape{})), make_tile(typename TiledMMA_SF::AtomThrID{}))); + + using TMA_A = decltype(make_tma_atom_A_sm100( + GmemTiledCopyA{}, + make_tensor(recast_ptr(nullptr), repeat_like(StrideA{}, int32_t(0)), StrideA{}), + SmemLayoutA{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + ClusterLayout_VMNK{}) + ); + + using TMA_B = decltype(make_tma_atom_B_sm100( + GmemTiledCopyB{}, + make_tensor(recast_ptr(nullptr), repeat_like(StrideB{}, int32_t(0)), StrideB{}), + SmemLayoutB{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + ClusterLayout_VMNK{}) + ); + + using TMA_SFA = decltype(make_tma_atom_A_sm100( + GmemTiledCopySFA{}, + make_tensor(static_cast(nullptr), LayoutSFA{}), + SmemLayoutSFA{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + ClusterLayout_VMNK{}) + ); + + using TMA_SFB = decltype(make_tma_atom_B_sm100( + GmemTiledCopySFB{}, + make_tensor(static_cast(nullptr), LayoutSFB{}), + SmemLayoutSFB{}(_,_,_,cute::Int<0>{}), + TileShape_SF{}, + TiledMMA_SF{}, + ClusterLayoutSfb_VMNK{}) + ); + + TMA_A tma_load_a; + TMA_B tma_load_b; + TMA_SFA tma_load_sfa; + TMA_SFB tma_load_sfb; + TMA_A tma_load_a_fallback; + TMA_B tma_load_b_fallback; + TMA_SFA tma_load_sfa_fallback; + TMA_SFB tma_load_sfb_fallback; + LayoutSFA layout_SFA; + LayoutSFB layout_SFB; + dim3 cluster_shape_fallback; + RuntimeDataTypeA runtime_data_type_a; + RuntimeDataTypeB runtime_data_type_b; + }; + + CUTLASS_DEVICE + CollectiveMmaAnyN(Params const& params, ClusterShape cluster_shape, uint32_t block_rank_in_cluster) + : cluster_shape_(cluster_shape) + , block_rank_in_cluster_(block_rank_in_cluster) + , layout_SFA_(params.layout_SFA) + , layout_SFB_(params.layout_SFB) + , runtime_data_type_a_(params.runtime_data_type_a) + , runtime_data_type_b_(params.runtime_data_type_b) { + if constexpr (IsDynamicCluster) { + const bool is_fallback_cluster = (cute::size<0>(cluster_shape_) == params.cluster_shape_fallback.x && + cute::size<1>(cluster_shape_) == params.cluster_shape_fallback.y); + observed_tma_load_a_ = is_fallback_cluster ? ¶ms.tma_load_a_fallback : ¶ms.tma_load_a; + observed_tma_load_b_ = is_fallback_cluster ? ¶ms.tma_load_b_fallback : ¶ms.tma_load_b; + observed_tma_load_sfa_ = is_fallback_cluster ? ¶ms.tma_load_sfa_fallback : ¶ms.tma_load_sfa; + observed_tma_load_sfb_ = is_fallback_cluster ? ¶ms.tma_load_sfb_fallback : ¶ms.tma_load_sfb; + } + else { + observed_tma_load_a_ = ¶ms.tma_load_a; + observed_tma_load_b_ = ¶ms.tma_load_b; + observed_tma_load_sfa_ = ¶ms.tma_load_sfa; + observed_tma_load_sfb_ = ¶ms.tma_load_sfb; + } + } + + template + static constexpr Params + to_underlying_arguments( + ProblemShape const& problem_shape, + Arguments const& args, + [[maybe_unused]] void* workspace, + cutlass::KernelHardwareInfo const& hw_info = cutlass::KernelHardwareInfo{}) { + + // Optionally append 1s until problem shape is rank-4 (MNKL), in case it is only rank-3 (MNK) + auto problem_shape_MNKL = append<4>(problem_shape, 1); + auto [M,N,K,L] = problem_shape_MNKL; + + auto ptr_A = recast_ptr(args.ptr_A); + auto ptr_B = recast_ptr(args.ptr_B); + + Tensor tensor_a = make_tensor(ptr_A, make_layout(make_shape(M,K,L), args.dA)); + Tensor tensor_b = make_tensor(ptr_B, make_layout(make_shape(N,K,L), args.dB)); + auto cluster_shape = cutlass::detail::select_cluster_shape(ClusterShape{}, hw_info.cluster_shape); + + // Cluster layout for TMA construction + auto cluster_layout_vmnk = tiled_divide(make_layout(cluster_shape), make_tile(typename TiledMma::AtomThrID{})); + auto cluster_shape_fallback = cutlass::detail::select_cluster_shape(ClusterShape{}, hw_info.cluster_shape_fallback); + auto cluster_layout_vmnk_fallback = tiled_divide(make_layout(cluster_shape_fallback), make_tile(typename TiledMma::AtomThrID{})); + Tensor tensor_sfa = make_tensor(args.ptr_SFA, args.layout_SFA); + Tensor tensor_sfb = make_tensor(args.ptr_SFB, args.layout_SFB); + + // Cluster layout for TMA construction of SFB + auto cluster_layout_sfb_vmnk = tiled_divide(make_layout(cluster_shape), make_tile(typename TiledMMA_SF::AtomThrID{})); + auto cluster_layout_sfb_vmnk_fallback = tiled_divide(make_layout(cluster_shape_fallback), make_tile(typename TiledMMA_SF::AtomThrID{})); + + typename Params::TMA_A tma_load_a = make_tma_atom_A_sm100( + GmemTiledCopyA{}, + tensor_a, + SmemLayoutA{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + cluster_layout_vmnk); + + typename Params::TMA_B tma_load_b = make_tma_atom_B_sm100( + GmemTiledCopyB{}, + tensor_b, + SmemLayoutB{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + cluster_layout_vmnk); + + typename Params::TMA_A tma_load_a_fallback = make_tma_atom_A_sm100( + GmemTiledCopyA{}, + tensor_a, + SmemLayoutA{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + cluster_layout_vmnk_fallback); + + typename Params::TMA_B tma_load_b_fallback = make_tma_atom_B_sm100( + GmemTiledCopyB{}, + tensor_b, + SmemLayoutB{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + cluster_layout_vmnk_fallback); + + typename Params::TMA_SFA tma_load_sfa = make_tma_atom_A_sm100( + GmemTiledCopySFA{}, + tensor_sfa, + SmemLayoutSFA{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + cluster_layout_vmnk); + + typename Params::TMA_SFB tma_load_sfb = make_tma_atom_B_sm100( + GmemTiledCopySFB{}, + tensor_sfb, + SmemLayoutSFB{}(_,_,_,cute::Int<0>{}), + TileShape_SF{}, + TiledMMA_SF{}, + cluster_layout_sfb_vmnk); + + typename Params::TMA_SFA tma_load_sfa_fallback = make_tma_atom_A_sm100( + GmemTiledCopySFA{}, + tensor_sfa, + SmemLayoutSFA{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + cluster_layout_vmnk_fallback); + + typename Params::TMA_SFB tma_load_sfb_fallback = make_tma_atom_B_sm100( + GmemTiledCopySFB{}, + tensor_sfb, + SmemLayoutSFB{}(_,_,_,cute::Int<0>{}), + TileShape_SF{}, + TiledMMA_SF{}, + cluster_layout_sfb_vmnk_fallback); + + return { + tma_load_a, + tma_load_b, + tma_load_sfa, + tma_load_sfb, + tma_load_a_fallback, + tma_load_b_fallback, + tma_load_sfa_fallback, + tma_load_sfb_fallback, + args.layout_SFA, + args.layout_SFB, + hw_info.cluster_shape_fallback, + args.runtime_data_type_a, + args.runtime_data_type_b + }; + } + + template + static bool + can_implement( + ProblemShape const& problem_shape, + [[maybe_unused]] Arguments const& args) { + auto problem_shape_MNKL = append<4>(problem_shape, 1); + auto [M,N,K,L] = problem_shape_MNKL; + + constexpr int tma_alignment_bits_A = cutlass::detail::get_input_alignment_bits(); + constexpr int tma_alignment_bits_B = cutlass::detail::get_input_alignment_bits(); + + bool implementable = true; + constexpr int min_tma_aligned_elements_A = tma_alignment_bits_A / cute::sizeof_bits::value; + implementable = implementable && cutlass::detail::check_alignment(cute::make_shape(M,K,L), StrideA{}); + constexpr int min_tma_aligned_elements_B = tma_alignment_bits_B / cute::sizeof_bits::value; + implementable = implementable && cutlass::detail::check_alignment(cute::make_shape(N,K,L), StrideB{}); + + // Check for SFA SFB layout requirement + const auto layout_sfa_ref = take<0,2>(Sm1xxBlkScaledConfig::tile_atom_to_shape_SFA(problem_shape_MNKL)); + const auto layout_sfb_ref = take<0,2>(Sm1xxBlkScaledConfig::tile_atom_to_shape_SFB(problem_shape_MNKL)); + + implementable = implementable && (layout_sfa_ref == take<0,2>(args.layout_SFA)); + if (!implementable) { + CUTLASS_TRACE_HOST(" CAN IMPLEMENT: layout_SFA mismatch, layout_SFA needs to be K-major\n"); + } + + implementable = implementable && (layout_sfb_ref == take<0,2>(args.layout_SFB)); + if (!implementable) { + CUTLASS_TRACE_HOST(" CAN IMPLEMENT: layout_SFB mismatch, layout_SFB needs to be K-major\n"); + } + + if (!implementable) { + CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Problem Size doesn't meet the minimum alignment requirements for TMA.\n"); + } + return implementable; + } + + /// Issue Tma Descriptor Prefetch -- ideally from a single thread for best performance + CUTLASS_DEVICE void + prefetch_tma_descriptors() { + cute::prefetch_tma_descriptor(observed_tma_load_a_->get_tma_descriptor()); + cute::prefetch_tma_descriptor(observed_tma_load_b_->get_tma_descriptor()); + cute::prefetch_tma_descriptor(observed_tma_load_sfa_->get_tma_descriptor()); + cute::prefetch_tma_descriptor(observed_tma_load_sfb_->get_tma_descriptor()); + } + + /// Construct A Single Stage's Accumulator Shape + CUTLASS_DEVICE static + auto + partition_accumulator_shape() { + auto acc_shape = partition_shape_C(TiledMma{}, take<0,2>(TileShape{})); // ((MMA_TILE_M,MMA_TILE_N),MMA_M,MMA_N) + + return acc_shape; + } + + template + CUTLASS_DEVICE static + auto + slice_accumulator(TmemStorage tmem_storage, int stage) { + return cute::make_tuple(tmem_storage.accumulators(_,_,_,stage)); + } + + template + CUTLASS_DEVICE static + auto + init_tmem_tensors(EpilogueTile epi_tile) { + TiledMma tiled_mma; + auto acc_shape = partition_accumulator_shape(); + // ((MMA_TILE_M,MMA_TILE_N),MMA_M,MMA_N,ACC_PIPE) where ACC_PIPE=2 so we can double buffer our accumulators for mainloop and epilogue. + Tensor accumulators = cutlass::detail::make_sm100_accumulator( + tiled_mma, acc_shape, EpilogueTile{}); + Tensor tCtSFA = make_tensor(shape(SmemLayoutAtomSFA{})); + Tensor tCtSFB = make_tensor(shape(SmemLayoutAtomSFB{})); + + TmemStorage tmem_storage; + tmem_storage.accumulators = accumulators; + tmem_storage.tCtSFA = tCtSFA; + tmem_storage.tCtSFB = tCtSFB; + + return tmem_storage; + } + + template + CUTLASS_DEVICE static + void + set_tmem_offsets(TmemStorage& tmem_storage, uint32_t tmem_base_addr) { + tmem_storage.accumulators.data() = tmem_base_addr; + tmem_storage.tCtSFA.data() = tmem_storage.accumulators.data().get() + cutlass::detail::find_tmem_tensor_col_offset(tmem_storage.accumulators); + tmem_storage.tCtSFB.data() = tmem_storage.tCtSFA.data().get() + cutlass::detail::find_tmem_tensor_col_offset(tmem_storage.tCtSFA); + } + + /// Set up the data needed by this collective for load. + /// Return tuple element contain + /// gA_mkl - The tiled tma tensor for input A + /// gB_nkl - The tiled tma tensor for input B + /// tAgA_mkl - partitioned gmem tensor for A + /// tBgB_nkl - partitioned gmem tensor for B + /// tAsA - partitioned smem tensor for A + /// tBsB - partitioned smem tensor for B + /// tAgSFA_mkl - partitioned gmem tensor for SFA + /// tBgSFB_nkl - partitioned gmem tensor for SFB + /// tAsSFA - partitioned tmem tensor for SFA + /// tAsSFB - partitioned tmem tensor for SFB + /// mcast_mask_a - tma multicast mask for A + /// mcast_mask_b - tma multicast mask for B + /// mcast_mask_sfa - tma multicast mask for SFA + /// mcast_mask_sfb - tma multicast mask for SFB + template + CUTLASS_DEVICE auto + load_init( + ProblemShape_MNKL const& problem_shape_MNKL, + TensorStorage& shared_tensors) const { + using X = Underscore; + + // Separate out problem shape for convenience + auto [M,N,K,L] = problem_shape_MNKL; + + // Represent the full tensors -- get these from TMA + Tensor mA_mkl = observed_tma_load_a_->get_tma_tensor(make_shape(M,K,L)); + Tensor mB_nkl = observed_tma_load_b_->get_tma_tensor(make_shape(N,K,L)); + + // Tile the tensors and defer the slice + Tensor gA_mkl = local_tile(mA_mkl, TileShape{}, make_coord(_,_,_), Step<_1, X,_1>{}); // (BLK_M, BLK_K, m, k, l) + Tensor gB_nkl = local_tile(mB_nkl, TileShape{}, make_coord(_,_,_), Step< X,_1,_1>{}); // (BLK_N, BLK_K, n, k, l) + + // Represent the full tensor of Scale factors + Tensor mSFA_mkl = observed_tma_load_sfa_->get_tma_tensor(shape(layout_SFA_)); + auto mSFB_nkl = [=](){ + if constexpr (IsCtaN192) { + Tensor mSFB_tmp = observed_tma_load_sfb_->get_tma_tensor(shape(layout_SFB_)); + auto x = stride<0,1>(mSFB_tmp); + auto y = ceil_div(shape<0,1>(mSFB_tmp), 4); + auto new_shape = make_shape (make_shape( shape<0,0>(mSFB_tmp), + make_shape( make_shape(_2{}, _2{}), y)), shape<1>(mSFB_tmp), shape<2>(mSFB_tmp)); + auto new_stride = make_stride(make_stride(stride<0,0>(mSFB_tmp), + make_stride(make_stride( x, x), x*3)), stride<1>(mSFB_tmp), stride<2>(mSFB_tmp)); + return make_tensor(mSFB_tmp.data(), make_layout(new_shape, new_stride)); + } + else if constexpr (IsCtaN64) { + Tensor mSFB_tmp = observed_tma_load_sfb_->get_tma_tensor(shape(layout_SFB_)); + auto new_shape = make_shape(make_shape(shape<0,0>(mSFB_tmp), + make_shape(_2{} , shape<0,1>(mSFB_tmp))), shape<1>(mSFB_tmp), shape<2>(mSFB_tmp)); + auto new_stride = make_stride(make_stride(stride<0,0>(mSFB_tmp), + make_stride(_0{}, stride<0,1>(mSFB_tmp))), stride<1>(mSFB_tmp), stride<2>(mSFB_tmp)); + return make_tensor(mSFB_tmp.data(), make_layout(new_shape, new_stride)); + } + else { + return observed_tma_load_sfb_->get_tma_tensor(shape(layout_SFB_)); + } + }(); + + Tensor gSFA_mkl = local_tile(mSFA_mkl, TileShape{}, make_coord(_,_,_), Step<_1, X,_1>{}); // (TILE_M,TILE_K,m,k,l) + Tensor gSFB_nkl = local_tile(mSFB_nkl, TileShape_SF{}, make_coord(_,_,_), Step< X,_1,_1>{}); // (TILE_N,TILE_K,n,k,l) + + // Partition for this CTA + ThrMMA cta_mma = TiledMma{}.get_slice(blockIdx.x % size(typename TiledMma::AtomThrID{})); + + Tensor tCgA_mkl = cta_mma.partition_A(gA_mkl); // (MMA, MMA_M, MMA_K, m, k, l) + Tensor tCgB_nkl = cta_mma.partition_B(gB_nkl); // (MMA, MMA_N, MMA_K, n, k, l) + + Tensor sA = make_tensor(make_smem_ptr(shared_tensors.smem_A.begin()), SmemLayoutA{}); // (MMA,MMA_M,MMA_K,PIPE) + Tensor sB = make_tensor(make_smem_ptr(shared_tensors.smem_B.begin()), SmemLayoutB{}); // (MMA,MMA_N,MMA_K,PIPE) + + ThrMMA cta_mma_sfb = TiledMMA_SF{}.get_slice(blockIdx.x % size(typename TiledMMA_SF::AtomThrID{})); + Tensor tCgSFA_mkl = cta_mma.partition_A(gSFA_mkl); // (MMA, MMA_M, MMA_K, m, k, l) + Tensor tCgSFB_nkl = cta_mma_sfb.partition_B(gSFB_nkl); // (MMA, MMA_N, MMA_K, n, k, l) + + Tensor sSFA = make_tensor(make_smem_ptr(shared_tensors.smem_SFA.begin()), SmemLayoutSFA{}); + Tensor sSFB = make_tensor(make_smem_ptr(shared_tensors.smem_SFB.begin()), SmemLayoutSFB{}); + + // Define the CTA-in-cluster Layout and Coord + Layout cta_layout_mnk = make_layout(cluster_shape_); + Layout cta_layout_vmnk = tiled_divide(cta_layout_mnk, make_tile(typename TiledMma::AtomThrID{})); + auto cta_coord_vmnk = cta_layout_vmnk.get_flat_coord(block_rank_in_cluster_); + + Layout cta_layout_sfb_vmnk = tiled_divide(cta_layout_mnk, make_tile(typename TiledMMA_SF::AtomThrID{})); + auto cta_coord_sfb_vmnk = cta_layout_sfb_vmnk.get_flat_coord(block_rank_in_cluster_); + + // Project the cta_layout for tma_a along the n-modes + auto [tAgA_mkl, tAsA] = tma_partition(*observed_tma_load_a_, + get<2>(cta_coord_vmnk), make_layout(size<2>(cta_layout_vmnk)), + group_modes<0,3>(sA), group_modes<0,3>(tCgA_mkl)); + + // Project the cta_layout for tma_b along the m-modes + auto [tBgB_nkl, tBsB] = tma_partition(*observed_tma_load_b_, + get<1>(cta_coord_vmnk), make_layout(size<1>(cta_layout_vmnk)), + group_modes<0,3>(sB), group_modes<0,3>(tCgB_nkl)); + + // Project the cta_layout for tma_a along the n-modes + auto [tAgSFA_mkl, tAsSFA] = tma_partition(*observed_tma_load_sfa_, + get<2>(cta_coord_vmnk), make_layout(size<2>(cta_layout_vmnk)), + group_modes<0,3>(sSFA), group_modes<0,3>(tCgSFA_mkl)); + + // Project the cta_layout for tma_b along the m-modes + auto [tBgSFB_nkl, tBsSFB] = tma_partition(*observed_tma_load_sfb_, + get<1>(cta_coord_sfb_vmnk), make_layout(size<1>(cta_layout_sfb_vmnk)), + group_modes<0,3>(sSFB), group_modes<0,3>(tCgSFB_nkl)); + + // TMA Multicast Masks + uint16_t mcast_mask_a = create_tma_multicast_mask<2>(cta_layout_vmnk, cta_coord_vmnk); + uint16_t mcast_mask_b = create_tma_multicast_mask<1>(cta_layout_vmnk, cta_coord_vmnk); + uint16_t mcast_mask_sfa = create_tma_multicast_mask<2>(cta_layout_vmnk, cta_coord_vmnk); + uint16_t mcast_mask_sfb = create_tma_multicast_mask<1>(cta_layout_sfb_vmnk, cta_coord_sfb_vmnk); + + return LoadParams{ + size<3>(gA_mkl), // for scheduler + tAgA_mkl, tBgB_nkl, tAsA, tBsB, // for input tensor values + tAgSFA_mkl, tBgSFB_nkl, tAsSFA, tBsSFB, // for input scale factor tensor values + mcast_mask_a, mcast_mask_b, mcast_mask_sfa, mcast_mask_sfb}; // multicast masks + } + + /// Set up the data needed by this collective for mma compute. + template + CUTLASS_DEVICE auto + mma_init( + TmemStorage tmem_storage, + TensorStorage& shared_tensors) const { + + // Allocate "fragments/descriptors" for A and B matrices + Tensor sA = make_tensor(make_smem_ptr(shared_tensors.smem_A.begin()), SmemLayoutA{}); // (BLK_M,BLK_K,PIPE) + Tensor sB = make_tensor(make_smem_ptr(shared_tensors.smem_B.begin()), SmemLayoutB{}); // (BLK_N,BLK_K,PIPE) + + // Allocate "fragments/descriptors" for A and B matrices + Tensor tCrA = TiledMma::make_fragment_A(sA); // (MMA,MMA_M,MMA_K,PIPE) + Tensor tCrB = TiledMma::make_fragment_B(sB); // (MMA,MMA_N,MMA_K,PIPE) + + CUTE_STATIC_ASSERT_V(Int{} == size<3>(sA)); // PIPE + CUTE_STATIC_ASSERT_V(Int{} == size<3>(sB)); // PIPE + + // + // Scale Factor + // + Tensor tCtSFA = tmem_storage.tCtSFA; + Tensor tCtSFB = tmem_storage.tCtSFB; + // Setup smem descriptors for UTCCP + Tensor tCsSFA = make_tensor(make_smem_ptr(shared_tensors.smem_SFA.begin()), SmemLayoutSFA{}); + Tensor tCsSFB = make_tensor(make_smem_ptr(shared_tensors.smem_SFB.begin()), SmemLayoutSFB{}); + + // Make SMEM and TMEM tensors compact removing the zero strides to eliminate unnecessary copy instructions. + auto tCsSFA_compact = make_tensor(tCsSFA.data(), filter_zeros(tCsSFA.layout())); + auto tCtSFA_compact = make_tensor(tCtSFA.data(), filter_zeros(tCtSFA.layout())); + auto tCsSFB_compact = make_tensor(tCsSFB.data(), filter_zeros(tCsSFB.layout())); + auto tCtSFB_compact = make_tensor(tCtSFB.data(), filter_zeros(tCtSFB.layout())); + + // Create the SMEM to TMEM copy operations based on the MMA atom used (1CTA vs 2CTA) + using AtomThrID = typename TiledMma::AtomThrID; + using UtccpOp = cute::conditional_t<(decltype(cute::size(AtomThrID{}) == Int<2>{})::value), + SM100_UTCCP_4x32dp128bit_2cta, SM100_UTCCP_4x32dp128bit_1cta>; + auto tiled_copy_s2t_SFA = make_utccp_copy(UtccpOp{}, tCtSFA_compact); + auto tiled_copy_s2t_SFB = make_utccp_copy(UtccpOp{}, tCtSFB_compact); + + auto thr_copy_s2t_SFA = tiled_copy_s2t_SFA.get_slice(0); + auto thr_tCsSFA_compact_s2t_ = thr_copy_s2t_SFA.partition_S(tCsSFA_compact); + // SMEM to TMEM copy operation requires source SMEM operand to be an SMEM descriptor + auto thr_tCsSFA_compact_s2t = get_utccp_smem_desc_tensor(thr_tCsSFA_compact_s2t_); + auto thr_tCtSFA_compact_s2t = thr_copy_s2t_SFA.partition_D(tCtSFA_compact); + + auto thr_copy_s2t_SFB = tiled_copy_s2t_SFB.get_slice(0); + auto thr_tCsSFB_compact_s2t_ = thr_copy_s2t_SFB.partition_S(tCsSFB_compact); + // SMEM to TMEM copy operation requires source SMEM operand to be an SMEM descriptor + auto thr_tCsSFB_compact_s2t = get_utccp_smem_desc_tensor(thr_tCsSFB_compact_s2t_); + auto thr_tCtSFB_compact_s2t = thr_copy_s2t_SFB.partition_D(tCtSFB_compact); + + TiledMma tiled_mma; + + if constexpr (IsRuntimeDataType) { + // Update instruction descriptor according to runtime argument. + // Applying bitmask (0b111) to help compiler deduce that the conversion and assignment are safe. + tiled_mma.idesc_.a_format_ = uint8_t(runtime_data_type_a_) & 0b111; + tiled_mma.idesc_.b_format_ = uint8_t(runtime_data_type_b_) & 0b111; + } + + return MmaParams{ + tiled_mma, + tCrA, tCrB, tCtSFA, tCtSFB, + tiled_copy_s2t_SFA, thr_tCsSFA_compact_s2t, thr_tCtSFA_compact_s2t, + tiled_copy_s2t_SFB, thr_tCsSFB_compact_s2t, thr_tCtSFB_compact_s2t}; + } + + /// Perform a collective-scoped matrix multiply-accumulate + /// Producer Perspective + template < + class LoadParams, + class TileCoordMNKL, + class KTileIterator + > + CUTLASS_DEVICE auto + load( + MainloopPipeline mainloop_pipeline, + MainloopPipelineState mainloop_pipe_producer_state, + LoadParams const& load_inputs, + TileCoordMNKL const& cta_coord_mnkl, + KTileIterator k_tile_iter, int k_tile_count) { + + auto [unused_k_tiles, + tAgA_mkl, tBgB_nkl, tAsA, tBsB, + tAgSFA_mkl, tBgSFB_nkl, tAsSFA, tBsSFB, + mcast_mask_a, mcast_mask_b, mcast_mask_sfa, mcast_mask_sfb] = load_inputs; + + // slice out the work coord from partitioned tensors + Tensor tAgA = tAgA_mkl(_, get<0>(cta_coord_mnkl) / size(typename TiledMma::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgB = tBgB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + Tensor tAgSFA = tAgSFA_mkl(_, get<0>(cta_coord_mnkl) / size(typename TiledMma::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgSFB = tBgSFB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + + auto barrier_token = mainloop_pipeline.producer_try_acquire(mainloop_pipe_producer_state); + + // Issue the Mainloop loads + CUTLASS_PRAGMA_NO_UNROLL + while (k_tile_count > 0) { + // LOCK mainloop_pipe_producer_state for _writing_ + mainloop_pipeline.producer_acquire(mainloop_pipe_producer_state, barrier_token); + // Note: We don't synchronize the sf_pipeline for "Buffer_Empty". We use mainloop pipeline + // to do the synchronization at once. + + using BarrierType = typename MainloopPipeline::ProducerBarrierType; + BarrierType* tma_barrier = mainloop_pipeline.producer_get_barrier(mainloop_pipe_producer_state); + + int write_stage = mainloop_pipe_producer_state.index(); + ++mainloop_pipe_producer_state; + barrier_token = mainloop_pipeline.producer_try_acquire(mainloop_pipe_producer_state); + + if (cute::elect_one_sync()) { + copy(observed_tma_load_a_->with(*tma_barrier, mcast_mask_a), tAgA(_,*k_tile_iter), tAsA(_,write_stage)); + copy(observed_tma_load_b_->with(*tma_barrier, mcast_mask_b), tBgB(_,*k_tile_iter), tBsB(_,write_stage)); + copy(observed_tma_load_sfa_->with(*tma_barrier, mcast_mask_sfa), tAgSFA(_,*k_tile_iter), tAsSFA(_,write_stage)); + copy(observed_tma_load_sfb_->with(*tma_barrier, mcast_mask_sfb), tBgSFB(_,*k_tile_iter), tBsSFB(_,write_stage)); + } + + --k_tile_count; + ++k_tile_iter; + } + + return cute::make_tuple(mainloop_pipe_producer_state, k_tile_iter); + } + + /// Perform a Producer Epilogue to prevent early exit of ctas in a Cluster + CUTLASS_DEVICE void + load_tail(MainloopPipeline mainloop_pipeline, MainloopPipelineState mainloop_pipe_producer_state) { + // Issue the epilogue waits + // This helps avoid early exit of ctas in Cluster + // Waits for all stages to either be released (all + // Consumer UNLOCKs), or if the stage was never used + // then would just be acquired since the phase was + // still inverted from make_producer_start_state + mainloop_pipeline.producer_tail(mainloop_pipe_producer_state); + } + + /// Perform a collective-scoped matrix multiply-accumulate + /// Consumer Perspective + template < + class AccumulatorPipeline, + class FrgEngine, class FrgLayout, + class MmaParams, + class CtaTileCoord + > + CUTLASS_DEVICE auto + mma(cute::tuple pipelines, + cute::tuple pipeline_states, + cute::tuple> const& accumulators_pair, + MmaParams const& mma_inputs, + CtaTileCoord cta_tile_coord, + int k_tile_count, + bool acc_first_use = false, + int elect_in = -1, + uint32_t empty_bar_base = 0u + ) { + static_assert(is_tmem::value, "Accumulator must be tmem resident."); + static_assert(rank(FrgLayout{}) == 3, "Accumulator must be MMA-partitioned: (MMA, MMA_M, MMA_N)"); + + auto accumulators = get<0>(accumulators_pair); + auto [tiled_mma, + tCrA, tCrB, tCtSFA, tCtSFB, + tiled_copy_s2t_SFA, thr_tCsSFA_s2t, + thr_tCtSFA_s2t, tiled_copy_s2t_SFB, + thr_tCsSFB_s2t, thr_tCtSFB_s2t] = mma_inputs; + + auto [mainloop_pipeline, accumulator_pipeline] = pipelines; + auto [mainloop_pipe_consumer_state, accumulator_pipe_producer_state] = pipeline_states; + + auto tCtSFB_mma = [tCtSFB = tCtSFB, cta_tile_coord]() { + if constexpr (IsCtaN192) { + // If this is an ODD tile, shift the TMEM start address for N=192 case by two words (ignores first 64 columns of SFB) + auto tCtSFB_tmp = tCtSFB; + if (size<1>(cta_tile_coord) % 2 == 1) { + tCtSFB_tmp.data() = tCtSFB_tmp.data().get() + 2; + } + return tCtSFB_tmp; + } + else if constexpr (IsCtaN64) { + // Move in increments of 64 columns of SFB + auto tCtSFB_tmp = tCtSFB; + tCtSFB_tmp.data() = tCtSFB_tmp.data().get() + (size<1>(cta_tile_coord) % 2) * 2; + return tCtSFB_tmp; + } + else { + return tCtSFB; + } + }(); + + uint32_t skip_wait = k_tile_count <= 0; + auto barrier_token = mainloop_pipeline.consumer_try_wait(mainloop_pipe_consumer_state, skip_wait); + + // + // PIPELINED MAIN LOOP + // + tiled_mma.accumulate_ = UMMA::ScaleOut::Zero; + if constexpr (IsOverlappingAccum) { + // first iteration manual unroll for tmem overlap kernel + if (k_tile_count > 0) { + // WAIT on mainloop_pipe_consumer_state until its data are available + // (phase bit flips from mainloop_pipe_consumer_state.phase() value) + mainloop_pipeline.consumer_wait(mainloop_pipe_consumer_state, barrier_token); + + // Compute on k_tile + int read_stage = mainloop_pipe_consumer_state.index(); + // Save current mainlop pipeline read state + auto curr_mainloop_pipe_consumer_state = mainloop_pipe_consumer_state; + + // Advance mainloop_pipe + ++mainloop_pipe_consumer_state; + --k_tile_count; + skip_wait = k_tile_count <= 0; + // Peek at next iteration + barrier_token = mainloop_pipeline.consumer_try_wait(mainloop_pipe_consumer_state, skip_wait); + + if (cute::elect_one_sync()) { + copy(tiled_copy_s2t_SFA, thr_tCsSFA_s2t(_,_,_,_,read_stage), thr_tCtSFA_s2t); + copy(tiled_copy_s2t_SFB, thr_tCsSFB_s2t(_,_,_,_,read_stage), thr_tCtSFB_s2t); + } + + // Wait for tmem accumulator buffer to become empty with a flipped phase + accumulator_pipeline.producer_acquire(accumulator_pipe_producer_state); + + // Unroll the K mode manually so we can set scale C to 1 + CUTLASS_PRAGMA_UNROLL + for (int k_block = 0; k_block < size<2>(tCrA); ++k_block) { + // (V,M) x (V,N) => (V,M,N) + cute::gemm(tiled_mma.with(tiled_mma.accumulate_, + tCtSFA(_,_,k_block), + tCtSFB_mma(_,_,k_block)), + tCrA(_,_,k_block,read_stage), + tCrB(_,_,k_block,read_stage), + accumulators); + tiled_mma.accumulate_ = UMMA::ScaleOut::One; + } + + mainloop_pipeline.consumer_release(curr_mainloop_pipe_consumer_state); + } + } + else { + // Wait for tmem accumulator buffer to become empty with a flipped phase. + if (!acc_first_use) accumulator_pipeline.producer_acquire(accumulator_pipe_producer_state); + } + + const bool elect_leader = elect_in >= 0 ? (elect_in != 0) : cute::elect_one_sync(); + CUTLASS_PRAGMA_NO_UNROLL + while (k_tile_count > 0) { + // WAIT on mainloop_pipe_consumer_state until its data are available + // (phase bit flips from mainloop_pipe_consumer_state.phase() value) + mainloop_pipeline.consumer_wait(mainloop_pipe_consumer_state, barrier_token); + + // Compute on k_tile + int read_stage = mainloop_pipe_consumer_state.index(); + // Save current mainlop pipeline read state + auto curr_mainloop_pipe_consumer_state = mainloop_pipe_consumer_state; + + // Advance mainloop_pipe + ++mainloop_pipe_consumer_state; + --k_tile_count; + skip_wait = k_tile_count <= 0; + + if (elect_leader) { + copy(tiled_copy_s2t_SFA, thr_tCsSFA_s2t(_,_,_,_,read_stage), thr_tCtSFA_s2t); + copy(tiled_copy_s2t_SFB, thr_tCsSFB_s2t(_,_,_,_,read_stage), thr_tCtSFB_s2t); + } + + // Unroll the K mode manually so we can set scale C to 1 + CUTLASS_PRAGMA_UNROLL + for (int k_block = 0; k_block < size<2>(tCrA); ++k_block) { + // (V,M) x (V,N) => (V,M,N) + cute::gemm(tiled_mma.with(tiled_mma.accumulate_, + tCtSFA(_,_,k_block), + tCtSFB_mma(_,_,k_block)), + tCrA(_,_,k_block,read_stage), + tCrB(_,_,k_block,read_stage), + accumulators); + tiled_mma.accumulate_ = UMMA::ScaleOut::One; + } + + if constexpr (kDirectRelease) { + if (empty_bar_base != 0u && elect_in >= 0) { + if (elect_leader) { + const uint32_t bar = empty_bar_base + uint32_t(curr_mainloop_pipe_consumer_state.index()) * 8u; + const uint16_t mask = 0x3; + if constexpr (size(AtomThrShapeMNK{}) == 2) { + asm volatile("tcgen05.commit.cta_group::2.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%0], %1;" + :: "r"(bar), "h"(mask) : "memory"); + } else { + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%0], %1;" + :: "r"(bar), "h"(mask) : "memory"); + } + } + } else { + mainloop_pipeline.consumer_release(curr_mainloop_pipe_consumer_state); + } + } else { + mainloop_pipeline.consumer_release(curr_mainloop_pipe_consumer_state); + } + barrier_token = mainloop_pipeline.consumer_try_wait(mainloop_pipe_consumer_state, skip_wait); + } + + return mainloop_pipe_consumer_state; + } + +protected: + + typename Params::TMA_A const* observed_tma_load_a_{nullptr}; + typename Params::TMA_B const* observed_tma_load_b_{nullptr}; + typename Params::TMA_SFA const* observed_tma_load_sfa_{nullptr}; + typename Params::TMA_SFB const* observed_tma_load_sfb_{nullptr}; + + LayoutSFA layout_SFA_; + LayoutSFB layout_SFB_; + RuntimeDataTypeA runtime_data_type_a_{}; + RuntimeDataTypeB runtime_data_type_b_{}; + + ClusterShape cluster_shape_; + uint32_t block_rank_in_cluster_; +}; + +///////////////////////////////////////////////////////////////////////////////////////////////// + + +// Rebind a builder-produced CollectiveMma, ..> +// to CollectiveMmaAnyN with identical template arguments (the builder alias is never instantiated). +template struct RebindAnyN; +template +struct RebindAnyN, Rest...>> { + using type = CollectiveMmaAnyN; +}; +} // namespace cutlass::gemm::collective diff --git a/kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/kernel.cu b/kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/kernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..703b074d9e09c031d85624d13c29d3e0b10d10a0 --- /dev/null +++ b/kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/kernel.cu @@ -0,0 +1,4461 @@ +constexpr int kNoiseCalibUnused343 = 0; +// +// 1. amax_wsf_kernel : grid-stride max|x| over bf16 activations: packed bf16x2 integer +// abs-max (&0x7FFF7FFF, __vmaxu2), one atomicMax/CTA. +// For M < 2048 it also carries the weight-SF swizzle role (blocks +// [0,nW)); for M >= 2048 nW = 0 -> a pure DRAM stream. +// W-SF swizzle role : weight SF (row-major) -> 128x4 blocked SF layout via a smem transpose +// with 16 B loads (all in flight) and 16 B stores. Independent of +// attn_output. For M >= 2048 these CTAs are the FIRST rows of +// act_quant's grid (scheduled first, loads issued before the PDL wait, +// stores after it) so act_quant's tail wave absorbs them. +// Cfg3 (M >= 1024): 2SM 256x192x256 (MMA N=192 -> 2 TMEM accumulator stages, unlike +// N=256 which CUTLASS limits to 1), epilogue subtile 128x16. N=8192 = 42*192+128: the +// last N tile is partial (TMA bounds-checked). +// Cfg3 raster: AlongM (swizzle 1 for M in [2048,3072), 4 for [4096,8192)), else AlongN s1. +// + +#ifndef CUTLASS_ENABLE_GDC_FOR_SM100 +#define CUTLASS_ENABLE_GDC_FOR_SM100 1 +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cutlass/cutlass.h" +#include "cute/tensor.hpp" +#include "cutlass/numeric_types.h" +#include "cutlass/arch/grid_dependency_control.h" +#include "cutlass/epilogue/thread/linear_combination.h" +#include "cutlass/epilogue/thread/activation.h" +#include "cutlass/gemm/dispatch_policy.hpp" +#include "cutlass/gemm/collective/collective_builder.hpp" +#include "cutlass/epilogue/collective/collective_builder.hpp" +#include "cutlass/epilogue/fusion/operations.hpp" +#include "cutlass/epilogue/fusion/sm90_visitor_tma_warpspecialized.hpp" +#include "cutlass/epilogue/fusion/sm90_visitor_load_tma_warpspecialized.hpp" +#include "cutlass/epilogue/fusion/sm90_visitor_compute_tma_warpspecialized.hpp" +#include "cutlass/detail/sm100_blockscaled_layout.hpp" +#include "cutlass/gemm/device/gemm_universal_adapter.h" +#include "cutlass/gemm/kernel/gemm_universal.hpp" +#include "cutlass/version.h" + +#include "kernel.h" +#include "collective_anyn.hpp" + +// Safety: the GEMM is launched with PDL, so its device code MUST contain the GDC wait. +#if defined(__CUDA_ARCH__) && !defined(CUTLASS_GDC_ENABLED) +#error "CUTLASS GDC (griddepcontrol) not enabled in device code; PDL launch would race" +#endif + +using namespace cute; + +// PDL primitives (sm_90+) +__device__ __forceinline__ void pdl_wait() { asm volatile("griddepcontrol.wait;" ::: "memory"); } +__device__ __forceinline__ void pdl_launch_dependents() { + asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); +} + +// plain relaxed gpu-scope load (amax read after griddepcontrol.wait / the grid barrier) +__device__ __forceinline__ uint32_t ld_relaxed_gpu(const unsigned int* p) { + uint32_t v; + asm volatile("ld.relaxed.gpu.global.u32 %0, [%1];" : "=r"(v) : "l"(p) : "memory"); + return v; +} + +// ---------------- weight SF swizzle (one CTA of 256 threads = one 128-row x 32-word tile) ---- +// Smem transpose (pitch 129 words, s must hold 32*129 words). One CTA = 128 rows x 32 SF words +// (128 SF bytes per row). Loads: 16 B (4 words) per thread-iteration, 8 lanes cover one row's +// 128 contiguous bytes; all 4 loads per thread are issued before any smem store (one DRAM round +// trip). Stores: 4 consecutive words of the contiguous destination atom stream as one 16 B +// store. Vector path requires g4 % 4 == 0 (K % 256 == 0) and a 16 B aligned source; else scalar. +// WAIT_BEFORE_STORE: issue griddepcontrol.wait between the read-only loads and the first +// global store to wdst (used when the role runs inside act_quant: wdst may still be read by +// the previous call's GEMM until the PDL dependency resolves). +// Requires K % 64 == 0 (Ksf % 4 == 0) so the source rows are uint32-aligned. +// wtn (padded-tile layout, used by the 256x224 GEMM config): 0 = plain layout (dest row = weight +// row); 224 = destination row rd holds weight row (rd/256)*224 + rd%256 when rd%256 < 224, else a +// zero pad row -> N tile n (224 rows) owns padded SF rows [256n, 256n+256) = 2 whole 128-row atoms. +__device__ __forceinline__ uint4 ldg128_wsf(const uint32_t* p) { + uint4 v; + asm volatile("ld.global.nc.L1::no_allocate.L2::256B.v4.u32 {%0,%1,%2,%3}, [%4];" + : "=r"(v.x), "=r"(v.y), "=r"(v.z), "=r"(v.w) : "l"(p)); + return v; +} +__device__ __forceinline__ int wsf_sg(int row, int gran) { return row * 128 + ((gran ^ ((row >> 2) & 7)) << 2); } +__device__ __forceinline__ void wsf_st4(uint32_t* s, int w, int gran, uint4 a, uint4 b, uint4 c, uint4 d) { + *reinterpret_cast(s + wsf_sg(w + 0, gran)) = make_uint4(a.x, b.x, c.x, d.x); + *reinterpret_cast(s + wsf_sg(w + 1, gran)) = make_uint4(a.y, b.y, c.y, d.y); + *reinterpret_cast(s + wsf_sg(w + 2, gran)) = make_uint4(a.z, b.z, c.z, d.z); + *reinterpret_cast(s + wsf_sg(w + 3, gran)) = make_uint4(a.w, b.w, c.w, d.w); +} +__device__ __forceinline__ int wsf_src_row(int rd, int wtn, int N) { + if (wtn == 0) return rd < N ? rd : -1; + // pad stride = SFB tile rows of the AnyN collective: 128 for wtn <= 128 (112), else 256 + const int sh = wtn <= 128 ? 7 : 8; + const int q = rd >> sh, o = rd & ((1 << sh) - 1); + const int r = q * wtn + o; + return (o < wtn && r < N) ? r : -1; +} +template +__device__ __forceinline__ void wsf_swizzle_cta_impl(int t, uint32_t* s, const uint8_t* __restrict__ wsrc, + uint8_t* __restrict__ wdst, int N, int K_, int wtn) { + const int K = KC ? KC : K_; + const int ksf = K / 16, g4 = ksf / 4; + const int ntile_k = (g4 + 31) / 32; + const int rb = t / ntile_k, kg0 = (t % ntile_k) * 32; + const int nw = min(32, g4 - kg0); + const uint32_t* src = reinterpret_cast(wsrc); + uint32_t* dst = reinterpret_cast(wdst) + ((size_t)rb * g4 + kg0) * 128; + if ((g4 & 3) == 0 && (reinterpret_cast(wsrc) & 15) == 0) { + uint4 v[4]; +#pragma unroll + for (int u = 0; u < 4; ++u) { // idx in [0,1024): row rr = idx/8, word group w4 = idx%8 + const int idx = threadIdx.x + u * 256; + const int rr = idx >> 3, w = (idx & 7) * 4; + const int r = wsf_src_row(rb * 128 + rr, wtn, N); // -1: OOB / pad row -> zeros + v[u] = make_uint4(0u, 0u, 0u, 0u); + if (r >= 0 && w < nw) // nw % 4 == 0 here, so the whole 16 B group is valid + v[u] = ldg128_wsf(src + (size_t)r * g4 + kg0 + w); + } + // blocked position inside the 512 B atom: c = (threadIdx.x>>3)*4 + u -> granule threadIdx.x>>3 + wsf_st4(s, (threadIdx.x & 7) * 4, threadIdx.x >> 3, v[0], v[1], v[2], v[3]); + __syncthreads(); + if (WAIT_BEFORE_STORE) pdl_wait(); + uint4* dst4 = reinterpret_cast(dst); + for (int o4 = threadIdx.x; o4 < nw * 32; o4 += 256) { + const int o = o4 * 4; // 4 consecutive words of one atom (same w = o >> 7) + dst4[o4] = *reinterpret_cast(s + wsf_sg(o >> 7, (o & 127) >> 2)); + } + } else { +#pragma unroll 4 + for (int idx = threadIdx.x; idx < 4096; idx += 256) { + const int rr = idx >> 5, w = idx & 31; + const int r = wsf_src_row(rb * 128 + rr, wtn, N); + uint32_t v = 0; + if (r >= 0 && w < nw) v = __ldg(src + (size_t)r * g4 + kg0 + w); + s[w * 129 + (rr & 31) * 4 + (rr >> 5)] = v; + } + __syncthreads(); + if (WAIT_BEFORE_STORE) pdl_wait(); + for (int o = threadIdx.x; o < nw * 128; o += 256) dst[o] = s[(o >> 7) * 129 + (o & 127)]; + } +} + +template +__device__ __forceinline__ void wsf_swizzle_cta(int t, uint32_t* s, const uint8_t* __restrict__ wsrc, + uint8_t* __restrict__ wdst, int N, int K, int wtn) { + if (K == 8192) wsf_swizzle_cta_impl(t, s, wsrc, wdst, N, K, wtn); + else wsf_swizzle_cta_impl(t, s, wsrc, wdst, N, K, wtn); +} + + +template +__device__ __forceinline__ bool wsf_swizzle_cta_bulk_impl(int t, uint32_t* s, const uint8_t* __restrict__ wsrc, + uint8_t* __restrict__ wdst, int N, int K_, int wtn) { + const int K = KC ? KC : K_; + const int ksf = K / 16, g4 = ksf / 4; + if (!((g4 & 3) == 0 && (reinterpret_cast(wsrc) & 15) == 0 && + (reinterpret_cast(wdst) & 15) == 0)) { + wsf_swizzle_cta_impl(t, s, wsrc, wdst, N, K_, wtn); + return false; + } + const int ntile_k = (g4 + 31) / 32; + const int rb = t / ntile_k, kg0 = (t % ntile_k) * 32; + const int nw = min(32, g4 - kg0); + const uint32_t* src = reinterpret_cast(wsrc); + uint32_t* dst = reinterpret_cast(wdst) + ((size_t)rb * g4 + kg0) * 128; + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int rr0 = (lane & 7) + 8 * (warp & 3); + const int w = ((lane >> 3) + 4 * (warp >> 2)) * 4; + uint4 v[4]; +#pragma unroll + for (int u = 0; u < 4; ++u) { + const int r = wsf_src_row(rb * 128 + rr0 + 32 * u, wtn, N); + v[u] = make_uint4(0u, 0u, 0u, 0u); + if (r >= 0 && w < nw) v[u] = ldg128_wsf(src + (size_t)r * g4 + kg0 + w); + } + // blocked column c = rr0*4 + u (row rr = rr0 + 32u), word rows w..w+3 -> linear granule rr0 + *reinterpret_cast(s + (w + 0) * 128 + rr0 * 4) = make_uint4(v[0].x, v[1].x, v[2].x, v[3].x); + *reinterpret_cast(s + (w + 1) * 128 + rr0 * 4) = make_uint4(v[0].y, v[1].y, v[2].y, v[3].y); + *reinterpret_cast(s + (w + 2) * 128 + rr0 * 4) = make_uint4(v[0].z, v[1].z, v[2].z, v[3].z); + *reinterpret_cast(s + (w + 3) * 128 + rr0 * 4) = make_uint4(v[0].w, v[1].w, v[2].w, v[3].w); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncthreads(); + if (threadIdx.x == 0) { + const uint32_t sa = (uint32_t)__cvta_generic_to_shared(s); + asm volatile("cp.async.bulk.global.shared::cta.bulk_group [%0], [%1], %2;" + :: "l"(dst), "r"(sa), "r"((uint32_t)nw * 512u) : "memory"); + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + return true; + } + return false; +} + +// 256-bit amax load: L1 no-allocate, L2 256 B sector promotion (default eviction priority). +__device__ __forceinline__ void amax_ldg256(const uint4* p, uint32_t (&w)[8]) { + asm volatile("ld.global.nc.L1::no_allocate.L2::256B.v8.b32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];" + : "=r"(w[0]), "=r"(w[1]), "=r"(w[2]), "=r"(w[3]), "=r"(w[4]), "=r"(w[5]), + "=r"(w[6]), "=r"(w[7]) + : "l"(p)); +} + +__device__ __forceinline__ void amax_ldg256_el(const uint4* p, uint32_t (&w)[8]) { + asm volatile("ld.global.nc.L1::no_allocate.L2::evict_last.L2::256B.v8.b32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];" + : "=r"(w[0]), "=r"(w[1]), "=r"(w[2]), "=r"(w[3]), "=r"(w[4]), "=r"(w[5]), + "=r"(w[6]), "=r"(w[7]) + : "l"(p)); +} + +// ---------------- 1. amax (|| weight SF swizzle when nW > 0) ---------------- +__global__ void __launch_bounds__(256) amax_wsf_kernel( + const uint4* __restrict__ x, size_t n_vec, unsigned int* amax, int nW, int nA, + const uint8_t* __restrict__ wsrc, uint8_t* __restrict__ wdst, int N, int K, int wtn) { + // PDL: trigger first so act_quant CTAs are scheduled as soon as every CTA of this grid is + // resident (act_quant only reads the read-only input before its own griddepcontrol.wait, + // which waits for this grid's full completion -> transitively for the previous GEMM). + pdl_wait(); // previous stream work (e.g. last call's GEMM reading wdst) done + pdl_launch_dependents(); + if ((int)blockIdx.x < nW) { + __shared__ uint32_t s[32 * 129]; + wsf_swizzle_cta(blockIdx.x, s, wsrc, wdst, N, K, wtn); + return; + } + // amax role: packed bf16x2 integer abs-max (exact; NaN sorts above Inf). + // 256-bit loads (ld.global.nc.L1::no_allocate.L2::256B.v8 = 16 bf16 / 32 B per load), + // 4 loads (128 B) in flight per thread, grid-stride over 32 B units. No L2 evict hint: x is + // re-read by act_quant and should stay in L2. 16 B fallback when x is not 32 B aligned. + const int ab = blockIdx.x - nW; + uint32_t mu0 = 0u, mu1 = 0u; +#define AMAX_ACC8(w) \ + mu0 = __vmaxu2(mu0, __vmaxu2(__vmaxu2(w[0] & 0x7fff7fffu, w[1] & 0x7fff7fffu), \ + __vmaxu2(w[2] & 0x7fff7fffu, w[3] & 0x7fff7fffu))); \ + mu1 = __vmaxu2(mu1, __vmaxu2(__vmaxu2(w[4] & 0x7fff7fffu, w[5] & 0x7fff7fffu), \ + __vmaxu2(w[6] & 0x7fff7fffu, w[7] & 0x7fff7fffu))); + if ((reinterpret_cast(x) & 31) == 0) { + const size_t n32 = n_vec / 2; // 32 B units + const size_t stride = (size_t)nA * blockDim.x; + size_t i = ab * (size_t)blockDim.x + threadIdx.x; + for (; i + 3 * stride < n32; i += 4 * stride) { + uint32_t w0[8], w1[8], w2[8], w3[8]; + amax_ldg256(x + 2 * i, w0); + amax_ldg256(x + 2 * (i + stride), w1); + amax_ldg256(x + 2 * (i + 2 * stride), w2); + amax_ldg256(x + 2 * (i + 3 * stride), w3); + AMAX_ACC8(w0) AMAX_ACC8(w1) AMAX_ACC8(w2) AMAX_ACC8(w3) + } + { + uint32_t w0[8] = {0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u}; + uint32_t w1[8] = {0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u}; + uint32_t w2[8] = {0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u}; + if (i < n32) amax_ldg256(x + 2 * i, w0); + if (i + stride < n32) amax_ldg256(x + 2 * (i + stride), w1); + if (i + 2 * stride < n32) amax_ldg256(x + 2 * (i + 2 * stride), w2); + AMAX_ACC8(w0) AMAX_ACC8(w1) AMAX_ACC8(w2) + } + // odd trailing 16 B unit (n_vec odd): handled by CTA 0 thread 0 + if ((n_vec & 1) && ab == 0 && threadIdx.x == 0) { + const uint4 v = __ldg(x + n_vec - 1); + mu0 = __vmaxu2(mu0, __vmaxu2(v.x & 0x7fff7fffu, v.y & 0x7fff7fffu)); + mu1 = __vmaxu2(mu1, __vmaxu2(v.z & 0x7fff7fffu, v.w & 0x7fff7fffu)); + } + } else { + const size_t stride = (size_t)nA * blockDim.x; + for (size_t i = ab * (size_t)blockDim.x + threadIdx.x; i < n_vec; i += stride) { + const uint4 v = __ldg(x + i); + mu0 = __vmaxu2(mu0, __vmaxu2(v.x & 0x7fff7fffu, v.y & 0x7fff7fffu)); + mu1 = __vmaxu2(mu1, __vmaxu2(v.z & 0x7fff7fffu, v.w & 0x7fff7fffu)); + } + } +#undef AMAX_ACC8 + uint32_t mu = __vmaxu2(mu0, mu1); + uint32_t mb = max(mu & 0xffffu, mu >> 16) << 16; // bf16 bits -> fp32 bits (exact) +#pragma unroll + for (int o = 16; o > 0; o >>= 1) mb = max(mb, __shfl_xor_sync(0xffffffffu, mb, o)); + __shared__ uint32_t sm[32]; + int lane = threadIdx.x & 31, wid = threadIdx.x >> 5; + if (lane == 0) sm[wid] = mb; + __syncthreads(); + if (wid == 0) { + mb = (lane < (int)(blockDim.x >> 5)) ? sm[lane] : 0u; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) mb = max(mb, __shfl_xor_sync(0xffffffffu, mb, o)); + // single relaxed reduction per CTA (no return value needed); act_quant's + // griddepcontrol.wait waits for this grid's completion + memory flush -> ordering. + if (lane == 0) // non-neg floats order as uint + asm volatile("red.relaxed.gpu.global.max.u32 [%0], %1;" :: "l"(amax), "r"(mb) : "memory"); + } +} + +__device__ __forceinline__ uint32_t bmax_xa(uint32_t a, uint32_t b) { + uint32_t d; + asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(d) : "r"(a), "r"(b)); + return d; +} +__device__ __forceinline__ uint32_t bf16x8_absmax(const uint32_t (&w)[8]) { + const uint32_t m = bmax_xa(bmax_xa(bmax_xa(w[0], w[1]), bmax_xa(w[2], w[3])), + bmax_xa(bmax_xa(w[4], w[5]), bmax_xa(w[6], w[7]))); + return m & 0x7fff7fffu; +} +__device__ __forceinline__ uint32_t bf16x8_absmax_raw(const uint32_t (&w)[8]) { + return bmax_xa(bmax_xa(bmax_xa(w[0], w[1]), bmax_xa(w[2], w[3])), + bmax_xa(bmax_xa(w[4], w[5]), bmax_xa(w[6], w[7]))); +} +__device__ __forceinline__ void bf16x8_absmax_pair(const uint32_t (&wa)[8], const uint32_t (&wb)[8], + uint32_t& oa, uint32_t& ob) { + const uint32_t ra = bf16x8_absmax_raw(wa), rb = bf16x8_absmax_raw(wb); + const uint32_t lo = __byte_perm(ra, rb, 0x5410), hi = __byte_perm(ra, rb, 0x7632); + const uint32_t m = bmax_xa(lo, hi) & 0x7fff7fffu; + oa = m << 16; + ob = m & 0xffff0000u; +} +__device__ __forceinline__ uint32_t bf16x8_absmax_acc(uint32_t mu, const uint32_t (&w)[8]) { + return bmax_xa(mu, bmax_xa(bmax_xa(bmax_xa(w[0], w[1]), bmax_xa(w[2], w[3])), + bmax_xa(bmax_xa(w[4], w[5]), bmax_xa(w[6], w[7])))); +} +__device__ __forceinline__ float global_encode_from_amax(float amax) { + float ge = __fdiv_rn(2688.0f, amax); // 448*6/amax + ge = fminf(ge, FLT_MAX); + if (ge == 0.0f) ge = 1.0f; + return ge; +} + + +__device__ __forceinline__ void f32x2_mul(float a0, float a1, float b, float& o0, float& o1) { + asm("{\n\t.reg .b64 ra, rb, rd;\n\t" + "mov.b64 ra, {%2, %3};\n\t" + "mov.b64 rb, {%4, %4};\n\t" + "mul.rn.f32x2 rd, ra, rb;\n\t" + "mov.b64 {%0, %1}, rd;\n\t}" + : "=f"(o0), "=f"(o1) : "f"(a0), "f"(a1), "f"(b)); +} + +__device__ __forceinline__ void enc_pair_e4m3(unsigned short p2, float gd, float& e0, float& e1) { + asm("{\n\t.reg .b32 dh;\n\t.reg .b16 h0, h1;\n\t.reg .f32 f0, f1, q0, q1;\n\t.reg .b64 ra, rb, rd;\n\t" + "cvt.rn.f16x2.e4m3x2 dh, %2;\n\t" + "mov.b32 {h0, h1}, dh;\n\t" + "cvt.f32.f16 f0, h0;\n\t" + "cvt.f32.f16 f1, h1;\n\t" + "mov.b64 ra, {f0, f1};\n\t" + "mov.b64 rb, {%3, %3};\n\t" + "mul.rn.f32x2 rd, ra, rb;\n\t" + "mov.b64 {q0, q1}, rd;\n\t" + "rcp.rn.f32 q0, q0;\n\t" + "rcp.rn.f32 q1, q1;\n\t" + "min.f32 %0, q0, 0f7F7FFFFF;\n\t" + "min.f32 %1, q1, 0f7F7FFFFF;\n\t}" + : "=f"(e0), "=f"(e1) : "h"(p2), "f"(gd)); +} +template +__device__ __forceinline__ void block_scales(const float (&bm)[R], float ge, float gd, + unsigned short (&dsc)[R], float (&esv)[R]) { + static_assert(R % 2 == 0, "pairs"); + const float inv6 = 1.0f / 6.0f; +#pragma unroll + for (int j = 0; j < R; j += 2) { + float t0, t1, d0, d1; + f32x2_mul(bm[j], bm[j + 1], inv6, t0, t1); + f32x2_mul(t0, t1, ge, d0, d1); + unsigned short p2; // low byte = e4m3(d0), high byte = e4m3(d1) + asm("cvt.rn.satfinite.e4m3x2.f32 %0, %1, %2;" : "=h"(p2) : "f"(d1), "f"(d0)); + dsc[j] = p2 & 0xffu; + dsc[j + 1] = p2 >> 8; + uint32_t dh; // low half = f16(code j), high half = f16(code j+1), exact + asm("cvt.rn.f16x2.e4m3x2 %0, %1;" : "=r"(dh) : "h"(p2)); + const float f0 = __half2float(__ushort_as_half((unsigned short)(dh & 0xffffu))); + const float f1 = __half2float(__ushort_as_half((unsigned short)(dh >> 16))); + float q0, q1; + f32x2_mul(f0, f1, gd, q0, q1); + float e0, e1; + asm("rcp.rn.f32 %0, %1;" : "=f"(e0) : "f"(q0)); + asm("rcp.rn.f32 %0, %1;" : "=f"(e1) : "f"(q1)); + esv[j] = fminf(e0, FLT_MAX); + esv[j + 1] = fminf(e1, FLT_MAX); + } +} + +// 8 fp32 -> 8 packed e2m1 nibbles (element 0 in the low nibble), RN-even + saturate to +-6. +__device__ __forceinline__ uint32_t f32x8_to_e2m1x8(const float* s) { + uint32_t p; + asm("{\n\t.reg .b8 b0, b1, b2, b3;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 b0, %2, %1;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 b1, %4, %3;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 b2, %6, %5;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 b3, %8, %7;\n\t" + "mov.b32 %0, {b0, b1, b2, b3};\n\t}" + : "=r"(p) + : "f"(s[0]), "f"(s[1]), "f"(s[2]), "f"(s[3]), "f"(s[4]), "f"(s[5]), "f"(s[6]), + "f"(s[7])); + return p; +} + +// packed bf16x2 word w -> two fp32 (exact), each multiplied by es with mul.rn.f32x2 +// (bit-identical to two scalar __fmul_rn). +__device__ __forceinline__ void bf16x2_mul_f32x2(uint32_t w, float es, float& o0, float& o1) { + const float a = __uint_as_float(w << 16), b = __uint_as_float(w & 0xffff0000u); + asm("{\n\t.reg .b64 ra, rb, rd;\n\t" + "mov.b64 ra, {%2, %3};\n\t" + "mov.b64 rb, {%4, %4};\n\t" + "mul.rn.f32x2 rd, ra, rb;\n\t" + "mov.b64 {%0, %1}, rd;\n\t}" + : "=f"(o0), "=f"(o1) + : "f"(a), "f"(b), "f"(es)); +} + +__device__ __forceinline__ uint64_t pack_f32x2_same(float x) { + uint64_t r; + asm("mov.b64 %0, {%1, %1};" : "=l"(r) : "f"(x)); + return r; +} +__device__ __forceinline__ void bf16x2_mul_f32x2a(uint32_t w, uint64_t es2, float& o0, float& o1) { + const float a = __uint_as_float(w << 16), b = __uint_as_float(w & 0xffff0000u); + asm("{\n\t.reg .b64 ra, rd;\n\t" + "mov.b64 ra, {%2, %3};\n\t" + "mul.rn.f32x2 rd, ra, %4;\n\t" + "mov.b64 {%0, %1}, rd;\n\t}" + : "=f"(o0), "=f"(o1) + : "f"(a), "f"(b), "l"(es2)); +} + +__device__ __forceinline__ void bf16x2_mul_f32x2u(uint32_t w, uint64_t es2, float& o0, float& o1) { + asm("{\n\t.reg .b32 lo, hi;\n\t.reg .b64 ra, rd;\n\t" + "shl.b32 lo, %2, 16;\n\t" + "and.b32 hi, %2, 0xffff0000;\n\t" + "mov.b64 ra, {lo, hi};\n\t" + "mul.rn.f32x2 rd, ra, %3;\n\t" + "mov.b64 {%0, %1}, rd;\n\t}" + : "=f"(o0), "=f"(o1) : "r"(w), "l"(es2)); +} + + +__device__ __forceinline__ uint2 quant16_e2m1(const uint32_t (&w)[8], uint64_t es2) { + uint2 p; + asm("{\n\t.reg .b32 lo, hi;\n\t.reg .b64 ra, rd;\n\t.reg .f32 f0, f1;\n\t" + ".reg .b8 b0, b1, b2, b3, b4, b5, b6, b7;\n\t" +#define Q16_STEP(W, B) \ + "shl.b32 lo, " W ", 16;\n\t" \ + "and.b32 hi, " W ", 0xffff0000;\n\t" \ + "mov.b64 ra, {lo, hi};\n\t" \ + "mul.rn.f32x2 rd, ra, %10;\n\t" \ + "mov.b64 {f0, f1}, rd;\n\t" \ + "cvt.rn.satfinite.e2m1x2.f32 " B ", f1, f0;\n\t" + Q16_STEP("%2", "b0") Q16_STEP("%3", "b1") Q16_STEP("%4", "b2") Q16_STEP("%5", "b3") + Q16_STEP("%6", "b4") Q16_STEP("%7", "b5") Q16_STEP("%8", "b6") Q16_STEP("%9", "b7") +#undef Q16_STEP + "mov.b32 %0, {b0, b1, b2, b3};\n\t" + "mov.b32 %1, {b4, b5, b6, b7};\n\t}" + : "=r"(p.x), "=r"(p.y) + : "r"(w[0]), "r"(w[1]), "r"(w[2]), "r"(w[3]), "r"(w[4]), "r"(w[5]), "r"(w[6]), "r"(w[7]), "l"(es2)); + return p; +} + +// 256-bit read-only global load (sm_100): 16 bf16 = one SF block. Address must be 32B aligned. +__device__ __forceinline__ void ldg256(const void* p, uint32_t (&w)[8]) { + asm volatile("ld.global.nc.v8.b32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];" + : "=r"(w[0]), "=r"(w[1]), "=r"(w[2]), "=r"(w[3]), "=r"(w[4]), "=r"(w[5]), + "=r"(w[6]), "=r"(w[7]) + : "l"(p)); +} + +// 256-bit streaming load: L1 no-allocate + L2 evict_first (x is read exactly once; keeps the +// FP4/SF outputs that the GEMM reads next resident in L2). Same recipe in fused + persistent quant. +__device__ __forceinline__ void ldg256_ef(const void* p, uint32_t (&w)[8]) { + asm volatile("ld.global.nc.L1::no_allocate.L2::evict_first.L2::256B.v8.b32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];" + : "=r"(w[0]), "=r"(w[1]), "=r"(w[2]), "=r"(w[3]), "=r"(w[4]), "=r"(w[5]), + "=r"(w[6]), "=r"(w[7]) + : "l"(p)); +} + +// ---------------- 2. activation quant (tile = 128 rows x 64*CA cols) [+ W-SF swizzle] ------- +// Lane mapping: LPR = 4*CA lanes share one row (lane%LPR = SF block within the tile row), +// RPI = 32/LPR rows per warp instruction, R = 2*CA instructions per thread -> each warp +// covers 16 consecutive rows, the 8 warps the 128-row SF atom block. +// WSF: the first wy grid rows (blockIdx.y < wy) are W-SF swizzle CTAs (linear id < nW does +// one tile, the rest idle) -- lowest block ids, so they are dispatched first. Quant tiles use +// blockIdx.y - wy as the 128-row block. +// Requires K % (64*CA) == 0. Rows >= M load zeros and emit zero scale bytes (padded atoms). +// FUSED (single pass, replaces kernel 1): the CTA's block maxima (already in registers) +// are reduced to a CTA max, atomicMax'ed into amax_bufs[parity], then a grid-wide barrier +// (arrival counter amax_bufs[4 + parity]) makes the global amax final; the CTA then quantizes +// from the SAME registers -> x is read from DRAM exactly once. Requires every quant CTA to be +// co-resident (host checks occupancy * #SMs >= #quant CTAs; __launch_bounds__(256,4) caps +// registers) and the launch is COOPERATIVE (driver-guaranteed co-residency, else the host +// falls back to the 2-launch path). PDL trigger at entry is deadlock-free: the dependent GEMM grid launches only +// after EVERY CTA of this grid has executed the trigger, i.e. all are already resident. +// Both paths reset the slots (amax, counter) of parity^1 that the next call will use. +template +__global__ void __launch_bounds__(256, FUSED ? 4 : 1) act_quant_tile_kernel( + const __nv_bfloat16* __restrict__ x, int M, int K, + unsigned int* __restrict__ amax_bufs, int parity, float w_global_decode, + float* __restrict__ alpha, uint8_t* __restrict__ q, uint8_t* __restrict__ sf, + int wy, int nW, const uint8_t* __restrict__ wsrc, uint8_t* __restrict__ wdst, int N, int rev, + int wtn) { + constexpr int LPR = 4 * CA, RPI = 32 / LPR, R = 2 * CA; + // smem: CA blocked SF atoms of this tile; for WSF the same buffer is the transpose tile. + constexpr int SMEM_WORDS = WSF ? (32 * 129) : (CA * 128); + __shared__ __align__(16) uint32_t s_raw[SMEM_WORDS]; + uint8_t* s_sf = reinterpret_cast(s_raw); + __shared__ float s_ge, s_gd; + + // PDL: let the GEMM grid launch (prologue: barrier init, TMEM alloc, descriptor prefetch) + // as early as possible; its griddepcontrol.wait still waits for this grid to complete. + pdl_launch_dependents(); + + int by = blockIdx.y; + if constexpr (WSF) { + if (by < wy) { + const int t = by * gridDim.x + blockIdx.x; + // loads before the PDL wait (read-only input), stores to wdst after it (kernel 1 done, + // which itself waited for the previous call's GEMM that reads wdst). + if (t < nW) wsf_swizzle_cta(t, s_raw, wsrc, wdst, N, K, wtn); + return; + } + by -= wy; + } + // rev (large M): quant row blocks in reverse order -> the tail of x, read last by the amax + // pass and still resident in L2, is quantized first. + if (rev) by = (int)gridDim.y - (WSF ? wy : 0) - 1 - by; + + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int cb = lane % LPR, rsub = lane / LPR; + const int row0 = by * 128; + const int col0 = blockIdx.x * (64 * CA); + const int rl0 = warp * (RPI * R) + rsub; // tile-local row for j = 0 (step RPI) + + // Prologue overlapping kernel 1's tail: x is read-only. All R 32 B loads in flight. + uint32_t v[R][8]; +#pragma unroll + for (int j = 0; j < R; ++j) { + const int r = row0 + rl0 + j * RPI; + if (r < M) { + if constexpr (FUSED) ldg256_ef(x + (size_t)r * K + col0 + cb * 16, v[j]); // (c) streaming recipe + else ldg256(x + (size_t)r * K + col0 + cb * 16, v[j]); + } else { +#pragma unroll + for (int e = 0; e < 8; ++e) v[j][e] = 0u; + } + } + // exact block abs-max on packed bf16 bit patterns -> fp32 + float bm[R]; +#pragma unroll + for (int j = 0; j < R; ++j) { + const uint32_t m = bf16x8_absmax(v[j]); + bm[j] = __uint_as_float(max(m & 0xffffu, m >> 16) << 16); + } + + // Wait for kernel 1 (amax) [FUSED: the previous stream work] to complete before + // reading amax / writing q, sf. + pdl_wait(); + if constexpr (FUSED) { + __shared__ uint32_t s_red[8]; + uint32_t tm = 0u; +#pragma unroll + for (int j = 0; j < R; ++j) tm = max(tm, __float_as_uint(bm[j])); // non-neg: uint order + tm = __reduce_max_sync(0xffffffffu, tm); + if (lane == 0) s_red[warp] = tm; + __syncthreads(); + if (threadIdx.x == 0) { + uint32_t m = s_red[0]; +#pragma unroll + for (int w = 1; w < 8; ++w) m = max(m, s_red[w]); + const unsigned int nq = gridDim.x * (gridDim.y - (WSF ? wy : 0)); + unsigned int* cnt = amax_bufs + 4 + parity; + // barrier: relaxed red.max of the CTA max, then ONE red.release.gpu arrival (the + // release orders the preceding max before the arrival; replaces __threadfence + + // atomicAdd), then a tight ld.acquire.gpu poll (no __nanosleep: every CTA is + // co-resident and only thread 0 polls). The acquire makes all CTAs' maxima visible to + // this thread's subsequent amax read. + asm volatile("red.relaxed.gpu.global.max.u32 [%0], %1;" :: "l"(&amax_bufs[parity]), "r"(m) : "memory"); + asm volatile("red.release.gpu.global.add.u32 [%0], 1;" :: "l"(cnt) : "memory"); + unsigned int c; + do { + asm volatile("ld.acquire.gpu.global.u32 %0, [%1];" : "=r"(c) : "l"(cnt) : "memory"); + } while (c < nq); + } + } + if (threadIdx.x == 0) { + const float amax = __uint_as_float(ld_relaxed_gpu(&amax_bufs[parity])); + const float ge = global_encode_from_amax(amax); + const float gd = __fdiv_rn(1.0f, ge); + s_ge = ge; + s_gd = gd; + if (blockIdx.x == 0 && by == 0) { + *alpha = __fmul_rn(gd, w_global_decode); + amax_bufs[parity ^ 1] = 0u; // reset the slot the next call accumulates into + amax_bufs[4 + (parity ^ 1)] = 0u; // and its fused-barrier counter + *reinterpret_cast(amax_bufs + 32 + 32 * (parity ^ 1)) = 0ull; + } + } + __syncthreads(); + const float ge = s_ge, gd = s_gd; + const float inv6 = 1.0f / 6.0f; + + unsigned short dsc[R]; + float esv[R]; + block_scales(bm, ge, gd, dsc, esv); +#pragma unroll + for (int j = 0; j < R; ++j) { + const int rl = rl0 + j * RPI; + const int r = row0 + rl; + const unsigned short ds2 = dsc[j]; + const float es = esv[j]; + float s[16]; +#pragma unroll + for (int e = 0; e < 8; ++e) bf16x2_mul_f32x2(v[j][e], es, s[2 * e], s[2 * e + 1]); + uint2 p; + p.x = f32x8_to_e2m1x8(s); + p.y = f32x8_to_e2m1x8(s + 8); + if (r < M) // 16 fp4 = 8 B, lanes of a row contiguous + *reinterpret_cast(q + ((size_t)r * K + col0 + cb * 16) / 2) = p; + // SF byte -> smem atom (cb/4), blocked position of (rl, cb%4) + s_sf[(cb >> 2) * 512 + (rl & 31) * 16 + (rl >> 5) * 4 + (cb & 3)] = (uint8_t)(ds2 & 0xffu); + } + __syncthreads(); + // CA contiguous 512 B atoms -> coalesced 16 B stores + if (threadIdx.x < 32 * CA) { + const int nkb4 = K / 64; + uint8_t* dst = sf + ((size_t)by * nkb4 + (size_t)(col0 >> 6)) * 512; + reinterpret_cast(dst)[threadIdx.x] = reinterpret_cast(s_sf)[threadIdx.x]; + } +} + +// ---------------- 2c. CLUSTER front (M <= 128): ONE thread-block cluster of K/512 CTAs ------- +// Replaces the cooperative grid-barrier front for M <= 128 (single 128-row SF atom block). +// grid = cluster = (K/512) CTAs of 1024 threads (16 CTAs at K = 8192, non-portable cluster +// size). Thread group g = threadIdx.x/256 of CTA c quantizes the 128-row x 128-col tile +// bx = 4c + g with exactly the CA=2 lane mapping / numerics of act_quant_tile_kernel (each +// thread 4 SF blocks = 4 x 32 B nc loads, all in flight). Global amax: CTA max (registers -> +// warp shuffle -> smem) is all-gathered over DSMEM (thread 0 st.shared::cluster its max into +// slot [rank] of every CTA's s_all), then barrier.cluster arrive.release / wait.acquire -> each +// CTA reduces its local slots (same max as the global reduction: exact, order-free). No global +// atomics / grid barrier. An initial relaxed cluster arrive (wait right before the DSMEM +// stores) guarantees every CTA of the cluster has started before remote smem is written. +// PDL: launch_dependents at entry (the Cfg2 GEMM's CTAs become resident on the other SMs and +// run their weight-first prologue); griddepcontrol.wait before any global store. +template +__global__ void __launch_bounds__(1024, 1) act_quant_cluster_kernel( + const __nv_bfloat16* __restrict__ x, int M_rt, int K_rt, + unsigned int* __restrict__ amax_bufs, int parity, float w_global_decode, + float* __restrict__ alpha, uint8_t* __restrict__ q, uint8_t* __restrict__ sf) { + const int K = KC > 0 ? KC : K_rt; + const int M = MC > 0 ? MC : M_rt; + constexpr int CA = 2, LPR = 4 * CA, RPI = 32 / LPR, R = 2 * CA, NG = 4; + __shared__ __align__(16) uint32_t s_raw[NG][CA * 128]; // SF atoms of each group's tile + __shared__ uint32_t s_red[32]; + __shared__ __align__(16) uint32_t s_all[16]; // DSMEM all-gather slots (one per cluster rank) + __shared__ __align__(8) uint64_t s_mbar; + pdl_wait(); pdl_launch_dependents(); + const uint32_t mbar = (uint32_t)__cvta_generic_to_shared(&s_mbar); + if (threadIdx.x == 0) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], 1;" :: "r"(mbar) : "memory"); + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" :: "r"(mbar), "r"(gridDim.x * 4u) : "memory"); + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + } + asm volatile("barrier.cluster.arrive.release.aligned;" ::: "memory"); + + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int col0 = blockIdx.x * (NG * 64 * CA); // CTA's 512-col slice + const int rl0 = warp * R; // rows rl0 + j, j < R + + uint32_t v[R][8]; + const bool full_t = M >= 128; + const size_t e0 = (size_t)rl0 * K + col0 + lane * 16; + const __nv_bfloat16* xp = x + e0; + if (full_t) { + if (warp & 1) { +#pragma unroll + for (int j = R - 1; j >= 0; --j) ldg256_ef(xp + (size_t)j * K, v[j]); + } else { +#pragma unroll + for (int j = 0; j < R; ++j) ldg256_ef(xp + (size_t)j * K, v[j]); + } + } else { +#pragma unroll + for (int j = 0; j < R; ++j) { + const int r = rl0 + j; + if (r < M) ldg256_ef(xp + (size_t)j * K, v[j]); + else { +#pragma unroll + for (int e = 0; e < 8; ++e) v[j][e] = 0u; + } + } + } + float bm[R]; + uint32_t tm = 0u; +#pragma unroll + for (int j = 0; j < R; j += 2) { + uint32_t ma, mb; + bf16x8_absmax_pair(v[j], v[j + 1], ma, mb); + bm[j] = __uint_as_float(ma); + bm[j + 1] = __uint_as_float(mb); + tm = max(tm, max(ma, mb)); // non-neg floats order as uint + } + float t6[R]; + auto t6_calc = [&]() { +#pragma unroll + for (int j = 0; j < R; j += 2) { + asm volatile("{\n\t.reg .b64 ra, rb, rd;\n\t" + "mov.b64 ra, {%2, %3};\n\t" + "mov.b64 rb, {%4, %4};\n\t" + "mul.rn.f32x2 rd, ra, rb;\n\t" + "mov.b64 {%0, %1}, rd;\n\t}" + : "=f"(t6[j]), "=f"(t6[j + 1]) : "f"(bm[j]), "f"(bm[j + 1]), "f"(1.0f / 6.0f)); + } + }; + tm = __reduce_max_sync(0xffffffffu, tm); + if (lane == 0) s_red[threadIdx.x >> 5] = tm; + if (threadIdx.x >= 32) { asm volatile("bar.arrive 5, 1024;" ::: "memory"); t6_calc(); } + else { t6_calc(); asm volatile("bar.sync 5, 1024;" ::: "memory"); } + const unsigned int nc = gridDim.x; // == cluster size + // all CTAs of the cluster started (arrive at entry) before remote smem stores + asm volatile("barrier.cluster.wait.aligned;" ::: "memory"); + if (threadIdx.x < 32) { + uint32_t m = s_red[lane]; + m = __reduce_max_sync(0xffffffffu, m); + if (lane < (int)nc) { // lane r stores this CTA's max into slot [my rank] of CTA r + uint32_t my_rank; + asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(my_rank)); + const uint32_t la = (uint32_t)__cvta_generic_to_shared(&s_all[my_rank]); + uint32_t ra, rb; + asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(ra) : "r"(la), "r"((uint32_t)lane)); + asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(rb) : "r"(mbar), "r"((uint32_t)lane)); + asm volatile("st.async.shared::cluster.mbarrier::complete_tx::bytes.u32 [%0], %1, [%2];" + :: "r"(ra), "r"(m), "r"(rb) : "memory"); + } + } + uint64_t up0[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) + asm volatile("{\n\t.reg .b32 lo, hi;\n\t" + "shl.b32 lo, %1, 16;\n\t" + "and.b32 hi, %1, 0xffff0000;\n\t" + "mov.b64 %0, {lo, hi};\n\t}" + : "=l"(up0[e]) : "r"(v[0][e])); + uint32_t am = 0u; + if (lane == 0) { + uint32_t done = 0; + do { + asm volatile("{\n\t.reg .pred p;\n\t" + "mbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 p, [%1], 0;\n\t" + "selp.u32 %0, 1, 0, p;\n\t}" + : "=r"(done) : "r"(mbar) : "memory"); + } while (!done); + if (nc == 16) { + const volatile uint4* s4 = reinterpret_cast(s_all); + const uint4 a0 = const_cast(s4[0]), a1 = const_cast(s4[1]); + const uint4 a2 = const_cast(s4[2]), a3 = const_cast(s4[3]); + am = max(max(max(a0.x, a0.y), max(a0.z, a0.w)), max(max(a1.x, a1.y), max(a1.z, a1.w))); + am = max(am, max(max(max(a2.x, a2.y), max(a2.z, a2.w)), max(max(a3.x, a3.y), max(a3.z, a3.w)))); + } else { + for (unsigned int r = 0; r < nc; ++r) am = max(am, s_all[r]); + } + } + am = __shfl_sync(0xffffffffu, am, 0); + const float amax = __uint_as_float(am); + const float ge = global_encode_from_amax(amax); + float gd; + asm("rcp.rn.f32 %0, %1;" : "=f"(gd) : "f"(ge)); + + if (blockIdx.x == 0 && threadIdx.x == 0) { + *alpha = __fmul_rn(gd, w_global_decode); + amax_bufs[parity ^ 1] = 0u; // keep the 2-launch / fused paths' slot protocol + amax_bufs[4 + (parity ^ 1)] = 0u; + *reinterpret_cast(amax_bufs + 32 + 32 * (parity ^ 1)) = 0ull; + } + uint8_t* s_sf = reinterpret_cast(&s_raw[0][0] + warp * 32); // per-warp 128 B slot (4 rows x 8 atoms) + uint64_t q_pol; + asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(q_pol)); +#pragma unroll + for (int j = 0; j < R; j += 2) { + float d0, d1; + f32x2_mul(t6[j], t6[j + 1], ge, d0, d1); + unsigned short p2; // low byte = e4m3(d0), high byte = e4m3(d1) + asm("cvt.rn.satfinite.e4m3x2.f32 %0, %1, %2;" : "=h"(p2) : "f"(d1), "f"(d0)); + float esp[2]; + enc_pair_e4m3(p2, gd, esp[0], esp[1]); +#pragma unroll + for (int u = 0; u < 2; ++u) { + const int jj = j + u; + const int rl = rl0 + jj; + float s[16]; + const uint64_t es2 = pack_f32x2_same(esp[u]); +#pragma unroll + if (jj == 0) { +#pragma unroll + for (int e = 0; e < 8; ++e) + asm("{\n\t.reg .b64 rd;\n\t" + "mul.rn.f32x2 rd, %2, %3;\n\t" + "mov.b64 {%0, %1}, rd;\n\t}" + : "=f"(s[2 * e]), "=f"(s[2 * e + 1]) : "l"(up0[e]), "l"(es2)); + } else { +#pragma unroll + for (int e = 0; e < 8; ++e) bf16x2_mul_f32x2u(v[jj][e], es2, s[2 * e], s[2 * e + 1]); + } + uint2 p; + p.x = f32x8_to_e2m1x8(s); + p.y = f32x8_to_e2m1x8(s + 8); + if (full_t || rl < M) + asm volatile("st.global.L2::cache_hint.v2.b32 [%0], {%1, %2}, %3;" + :: "l"(q + e0 / 2 + (size_t)jj * (K / 2)), "r"(p.x), "r"(p.y), "l"(q_pol) : "memory"); + s_sf[((jj * 8 + (lane >> 2)) << 2) + (lane & 3)] = (uint8_t)(u ? (p2 >> 8) : (p2 & 0xffu)); + } + } + __syncwarp(); + { + const int i = lane >> 3, a = lane & 7; // word lane = (row j = i, atom a) + const int rl = rl0 + i; + uint8_t* dst = sf + (size_t)((col0 >> 6) + a) * 512 + (rl & 31) * 16 + (rl >> 5) * 4; + asm volatile("st.global.L2::cache_hint.b32 [%0], %1, %2;" + :: "l"(dst), "r"(reinterpret_cast(s_sf)[lane]), "l"(q_pol) : "memory"); + } +} + +template +__device__ __forceinline__ void wsf_swizzle_grp_impl(int t, int tid, int barid, uint32_t* s, + const uint8_t* __restrict__ wsrc, + uint8_t* __restrict__ wdst, int N, int K_, int wtn) { + const int K = KC ? KC : K_; + const int ksf = K / 16, g4 = ksf / 4; + const int ntile_k = (g4 + 31) / 32; + const int rb = t / ntile_k, kg0 = (t % ntile_k) * 32; + const int nw = (KC > 0 && (KC / 64) % 32 == 0) ? 32 : min(32, g4 - kg0); + const uint32_t* src = reinterpret_cast(wsrc); + uint32_t* dst = reinterpret_cast(wdst) + ((size_t)rb * g4 + kg0) * 128; + if ((g4 & 3) == 0 && (reinterpret_cast(wsrc) & 15) == 0) { + const int rr0 = tid >> 3, w = (tid & 7) * 4; + const int c0 = rr0 * 4; + const bool w_ok = w < nw; + uint4 v[4]; +#pragma unroll + for (int u = 0; u < 4; ++u) { + const int r = wsf_src_row(rb * 128 + rr0 + 32 * u, wtn, N); + v[u] = make_uint4(0u, 0u, 0u, 0u); + if (r >= 0 && w_ok) v[u] = ldg128_wsf(src + (size_t)r * g4 + kg0 + w); + } + wsf_st4(s, w, c0 >> 2, v[0], v[1], v[2], v[3]); + asm volatile("bar.sync %0, 256;" :: "r"(barid) : "memory"); + if (WAIT_BEFORE_STORE) pdl_wait(); + uint4* dst4 = reinterpret_cast(dst); +#pragma unroll 4 + for (int o4 = tid; o4 < nw * 32; o4 += 256) { + const int o = o4 * 4; + dst4[o4] = *reinterpret_cast(s + wsf_sg(o >> 7, (o & 127) >> 2)); + } + } else { + for (int idx = tid; idx < 4096; idx += 256) { + const int rr = idx >> 5, w = idx & 31; + const int r = wsf_src_row(rb * 128 + rr, wtn, N); + uint32_t v = 0; + if (r >= 0 && w < nw) v = __ldg(src + (size_t)r * g4 + kg0 + w); + s[w * 129 + (rr & 31) * 4 + (rr >> 5)] = v; + } + asm volatile("bar.sync %0, 256;" :: "r"(barid) : "memory"); + if (WAIT_BEFORE_STORE) pdl_wait(); + for (int o = tid; o < nw * 128; o += 256) dst[o] = s[(o >> 7) * 129 + (o & 127)]; + } +} +template +__device__ __forceinline__ void wsf_swizzle_grp(int t, int tid, int barid, uint32_t* s, + const uint8_t* __restrict__ wsrc, + uint8_t* __restrict__ wdst, int N, int K, int wtn) { + if (K == 8192) wsf_swizzle_grp_impl(t, tid, barid, s, wsrc, wdst, N, K, wtn); + else wsf_swizzle_grp_impl(t, tid, barid, s, wsrc, wdst, N, K, wtn); +} +constexpr int kFused1kSmem = 4 * 32 * 129 * 4; +template +__device__ __forceinline__ bool wsf_swizzle_grp2_impl(int t0, int t1, int tid, int barid, uint32_t* s, + const uint8_t* __restrict__ wsrc, + uint8_t* __restrict__ wdst, int N, int K_, int wtn) { + const int K = KC ? KC : K_; + const int ksf = K / 16, g4 = ksf / 4; + if (!((g4 & 3) == 0 && (reinterpret_cast(wsrc) & 15) == 0)) return false; + const int ntile_k = (g4 + 31) / 32; + const uint32_t* src = reinterpret_cast(wsrc); + const int rr0 = tid >> 3, w = (tid & 7) * 4; + const int c0 = rr0 * 4; + const int tt[2] = {t0, t1}; + uint4 v[2][4]; +#pragma unroll + for (int k = 0; k < 2; ++k) { + const int rb = tt[k] / ntile_k, kg0 = (tt[k] % ntile_k) * 32; + const int nw = min(32, g4 - kg0); + const bool w_ok = w < nw && tt[k] >= 0; +#pragma unroll + for (int u = 0; u < 4; ++u) { + v[k][u] = make_uint4(0u, 0u, 0u, 0u); + if (w_ok) { + const int r = wsf_src_row(rb * 128 + rr0 + 32 * u, wtn, N); + if (r >= 0) v[k][u] = ldg128_wsf(src + (size_t)r * g4 + kg0 + w); + } + } + } +#pragma unroll + for (int k = 0; k < 2; ++k) { + if (tt[k] < 0) break; // group-uniform + const int rb = tt[k] / ntile_k, kg0 = (tt[k] % ntile_k) * 32; + const int nw = min(32, g4 - kg0); + if (k > 0) asm volatile("bar.sync %0, 256;" :: "r"(barid) : "memory"); // tile 0 smem reads done + wsf_st4(s, w, c0 >> 2, v[k][0], v[k][1], v[k][2], v[k][3]); + asm volatile("bar.sync %0, 256;" :: "r"(barid) : "memory"); + uint4* dst4 = reinterpret_cast(reinterpret_cast(wdst) + ((size_t)rb * g4 + kg0) * 128); + for (int o4 = tid; o4 < nw * 32; o4 += 256) { + const int o = o4 * 4; + dst4[o4] = *reinterpret_cast(s + wsf_sg(o >> 7, (o & 127) >> 2)); + } + } + return true; +} + + +template +__global__ void __launch_bounds__(1024, 1) act_quant_fused1k_kernel( + const __nv_bfloat16* __restrict__ x, int M_rt, int K_rt, + unsigned int* __restrict__ amax_bufs, int parity, float w_global_decode, + float* __restrict__ alpha, uint8_t* __restrict__ q, uint8_t* __restrict__ sf, + int nWc, int nW, int wpg, const uint8_t* __restrict__ wsrc, uint8_t* __restrict__ wdst, int N_rt, int wtn, + int qf) { + const int K = KC > 0 ? KC : K_rt; + const int N = NC > 0 ? NC : N_rt; + const int M = MC > 0 ? MC : M_rt; + constexpr int CA = 2, LPR = 4 * CA, RPI = 32 / LPR, R = 2 * CA, NG = 4; + extern __shared__ __align__(16) uint32_t dsm[]; + __shared__ uint32_t s_red[32]; + __shared__ __align__(8) float2 s_g2; + const int tid = threadIdx.x & 255, g = threadIdx.x >> 8; + const int nq_ = (int)gridDim.x - nWc; + const int bid = !qf ? (int)blockIdx.x + : ((int)blockIdx.x < nq_ ? (int)blockIdx.x + nWc : (int)blockIdx.x - nq_); + const bool is_wsf = bid < nWc; + constexpr int CA_ = 2, LPR_ = 4 * CA_, RPI_ = 32 / LPR_, R_ = 2 * CA_; + const int lane = threadIdx.x & 31, warp = tid >> 5; + const int cb = lane % LPR_, rsub = lane / LPR_; + const int gx = K / (64 * CA_); // % 4 == 0 -> all 4 groups of a CTA share one row block + const int mblk_f = (M + 127) >> 7; + const int qc = bid - nWc; + const int by = qc % mblk_f; + const int col0 = ((qc / mblk_f) * 4 + g) * (64 * CA_); + const int row0 = by * 128; + const int rl0 = warp * (RPI_ * R_) + rsub; + const int nrem = M - (row0 + rl0); + const size_t e0 = (size_t)(row0 + rl0) * K + col0 + cb * 16; + const __nv_bfloat16* xp = x + e0; + const bool full_t = (MC > 0 && MC % 128 == 0) || row0 + 128 <= M; + pdl_wait(); pdl_launch_dependents(); + uint32_t v[R_][8]; + if (!is_wsf) { + if (full_t) { + if (warp & 1) { +#pragma unroll + for (int j = R_ - 1; j >= 0; --j) ldg256_ef(xp + (size_t)j * RPI_ * K, v[j]); + } else { +#pragma unroll + for (int j = 0; j < R_; ++j) ldg256_ef(xp + (size_t)j * RPI_ * K, v[j]); + } + } else { +#pragma unroll + for (int j = 0; j < R_; ++j) { + if (j * RPI_ < nrem) ldg256_ef(xp + (size_t)j * RPI_ * K, v[j]); + else { +#pragma unroll + for (int e = 0; e < 8; ++e) v[j][e] = 0u; + } + } + } + } + if (is_wsf) { // W-SF swizzle CTA: no grid-barrier participation + if (bid == 0 && threadIdx.x == 0) { + amax_bufs[parity ^ 1] = 0u; + amax_bufs[4 + (parity ^ 1)] = 0u; + *reinterpret_cast(amax_bufs + 32 + 32 * (parity ^ 1)) = 0ull; + } + // wpg swizzle tiles per 256-thread group (4*wpg per CTA; wpg = 2 when the 4-per-CTA + // grid would exceed one co-resident wave, e.g. M = 768). Group g handles tiles + // (blockIdx.x*wpg + k)*NG + g, k < wpg; its smem transpose tile is reused across k + // (named barrier before the next tile's smem writes: all reads of the previous one done). + if (wpg == 2) { + const int ta = (bid * 2 + 0) * NG + g, tb = (bid * 2 + 1) * NG + g; + if (ta >= nW) return; + const bool ok = (K == 8192) + ? wsf_swizzle_grp2_impl<8192>(ta, tb < nW ? tb : -1, tid, 1 + g, dsm + g * (32 * 129), wsrc, wdst, N, K, wtn) + : wsf_swizzle_grp2_impl<0>(ta, tb < nW ? tb : -1, tid, 1 + g, dsm + g * (32 * 129), wsrc, wdst, N, K, wtn); + if (ok) return; + } + for (int k = 0; k < wpg; ++k) { + const int t = (bid * wpg + k) * NG + g; + if (t >= nW) break; + if (k > 0) asm volatile("bar.sync %0, 256;" :: "r"(1 + g) : "memory"); + wsf_swizzle_grp(t, tid, 1 + g, dsm + g * (32 * 129), wsrc, wdst, N, K, wtn); + } + return; + } + float bm[R]; + uint32_t tm = 0u; +#pragma unroll + for (int j = 0; j < R; j += 2) { + uint32_t ma, mb; + bf16x8_absmax_pair(v[j], v[j + 1], ma, mb); + bm[j] = __uint_as_float(ma); + bm[j + 1] = __uint_as_float(mb); + tm = max(tm, max(ma, mb)); // non-neg floats order as uint + } + float t6[R]; + auto t6_calc = [&]() { +#pragma unroll + for (int j = 0; j < R; j += 2) { + asm volatile("{\n\t.reg .b64 ra, rb, rd;\n\t" + "mov.b64 ra, {%2, %3};\n\t" + "mov.b64 rb, {%4, %4};\n\t" + "mul.rn.f32x2 rd, ra, rb;\n\t" + "mov.b64 {%0, %1}, rd;\n\t}" + : "=f"(t6[j]), "=f"(t6[j + 1]) : "f"(bm[j]), "f"(bm[j + 1]), "f"(1.0f / 6.0f)); + } + }; + tm = __reduce_max_sync(0xffffffffu, tm); + if (lane == 0) s_red[threadIdx.x >> 5] = tm; + if (threadIdx.x >= 32) { asm volatile("bar.arrive 5, 1024;" ::: "memory"); t6_calc(); } + else { t6_calc(); asm volatile("bar.sync 5, 1024;" ::: "memory"); } + if (threadIdx.x < 32) { + uint32_t m = __reduce_max_sync(0xffffffffu, s_red[lane]); + if (lane == 0) { + const unsigned int nq = gridDim.x - (unsigned)nWc; + unsigned int* pair = amax_bufs + 32 + 32 * parity; + asm volatile("red.relaxed.gpu.global.max.u32 [%0], %1;" :: "l"(pair), "r"(m) : "memory"); + asm volatile("red.relaxed.gpu.global.add.u32 [%0], 1;" :: "l"(pair + 1) : "memory"); + unsigned long long pv, pa, pb, pc; + asm volatile("ld.relaxed.gpu.global.b64 %0, [%1];" : "=l"(pa) : "l"(pair) : "memory"); + { + const long long t0 = clock64(); + while (clock64() - t0 < 95) { } + } + asm volatile("ld.relaxed.gpu.global.b64 %0, [%1];" : "=l"(pb) : "l"(pair) : "memory"); + { + const long long t0 = clock64(); + while (clock64() - t0 < 95) { } + } + asm volatile("ld.relaxed.gpu.global.b64 %0, [%1];" : "=l"(pc) : "l"(pair) : "memory"); + while (true) { + if ((unsigned int)(pa >> 32) >= nq) { pv = pa; break; } + asm volatile("ld.relaxed.gpu.global.b64 %0, [%1];" : "=l"(pa) : "l"(pair) : "memory"); + if ((unsigned int)(pb >> 32) >= nq) { pv = pb; break; } + asm volatile("ld.relaxed.gpu.global.b64 %0, [%1];" : "=l"(pb) : "l"(pair) : "memory"); + if ((unsigned int)(pc >> 32) >= nq) { pv = pc; break; } + asm volatile("ld.relaxed.gpu.global.b64 %0, [%1];" : "=l"(pc) : "l"(pair) : "memory"); + } + const float amax = __uint_as_float((unsigned int)(pv & 0xffffffffull)); + const float ge = global_encode_from_amax(amax); + float gd; + asm("rcp.rn.f32 %0, %1;" : "=f"(gd) : "f"(ge)); + s_g2 = make_float2(ge, gd); + if (bid == nWc) { + *alpha = __fmul_rn(gd, w_global_decode); + if (nWc == 0) { + amax_bufs[parity ^ 1] = 0u; + amax_bufs[4 + (parity ^ 1)] = 0u; + *reinterpret_cast(amax_bufs + 32 + 32 * (parity ^ 1)) = 0ull; + } + } + } + } + __syncthreads(); + const float2 g2 = s_g2; + const float ge = g2.x, gd = g2.y; + const float inv6 = 1.0f / 6.0f; + uint32_t* s_w = dsm + g * (CA * 128); + uint8_t* s_sf = reinterpret_cast(s_w); + static_assert(RPI * R == 16 && RPI == 4, "fused1k: 16 rows per warp, 4 per instruction"); + uint8_t* qp = q + e0 / 2; + const int sf_off0 = (cb >> 2) * 512 + ((warp & 1) * 16 + rsub) * 16 + (warp >> 1) * 4 + (cb & 3); +#pragma unroll + for (int j = 0; j < R; j += 2) { + float d0, d1; + f32x2_mul(t6[j], t6[j + 1], ge, d0, d1); + unsigned short p2; // low byte = e4m3(d0), high byte = e4m3(d1) + asm("cvt.rn.satfinite.e4m3x2.f32 %0, %1, %2;" : "=h"(p2) : "f"(d1), "f"(d0)); + float esp[2]; + enc_pair_e4m3(p2, gd, esp[0], esp[1]); +#pragma unroll + for (int u = 0; u < 2; ++u) { + const int jj = j + u; + const float es = esp[u]; + float s[16]; + const uint64_t es2 = pack_f32x2_same(es); +#pragma unroll + for (int e = 0; e < 8; ++e) bf16x2_mul_f32x2u(v[jj][e], es2, s[2 * e], s[2 * e + 1]); + uint2 p; + p.x = f32x8_to_e2m1x8(s); + p.y = f32x8_to_e2m1x8(s + 8); + if (full_t || jj * RPI < nrem) *reinterpret_cast(qp + (size_t)jj * RPI * (K / 2)) = p; + s_sf[sf_off0 + 64 * jj] = (uint8_t)(u ? (p2 >> 8) : (p2 & 0xffu)); + } + } + asm volatile("bar.sync %0, 256;" :: "r"(1 + g) : "memory"); + if (tid < 64) { + const int nkb4 = K / 64; + uint8_t* dst = sf + ((size_t)by * nkb4 + (size_t)(col0 >> 6)) * 512; // 2 contiguous atoms + reinterpret_cast(dst)[tid] = reinterpret_cast(s_w)[tid]; + } +} + +// ---------------- 2b. PERSISTENT activation quant (M >= 2048) [+ W-SF swizzle items] ------- +// grid = min(#tiles, occupancy * #SMs) CTAs; CTA c owns quant tiles q = c, c+G, c+2G, ... +// (static striping; concurrently resident CTAs cover consecutive tiles -> DRAM locality). +// Tile = 128 rows x 128 cols (CA=2 layout of act_quant_tile_kernel: each thread 4 SF blocks of +// 16 bf16 = 4 x 32 B loads). Software pipeline in registers: the NEXT tile's 4 loads are issued +// before the current tile is quantized, so every thread keeps loads in flight while computing +// (no per-CTA load -> wait -> compute bubble, no CTA launch/tail per tile). x loads use +// L1::no_allocate + L2::evict_first (x is not re-read; keeps the FP4/SF outputs, which the GEMM +// reads next, resident in L2). ge/gd/alpha computed once per CTA. SF atoms staged in two +// alternating smem buffers (one __syncthreads per tile). CTAs c < nW first perform W-SF swizzle +// tile c (loads before the PDL wait, stores after), as in act_quant_tile_kernel<.., WSF>. +// Numerics are identical to act_quant_tile_kernel (same per-block math). + +template +__global__ void __launch_bounds__(256, 2) act_quant_persist_kernel( + const __nv_bfloat16* __restrict__ x, int M_rt, int K_rt, + unsigned int* __restrict__ amax_bufs, int parity, float w_global_decode, + float* __restrict__ alpha, uint8_t* __restrict__ q, uint8_t* __restrict__ sf, + int nW, const uint8_t* __restrict__ wsrc, uint8_t* __restrict__ wdst, int N_rt, int rev, int wtn) { + const int K = KC > 0 ? KC : K_rt; + const int N = NC > 0 ? NC : N_rt; + const int M = MC > 0 ? MC : M_rt; + constexpr int CA = 2, LPR = 4 * CA, RPI = 32 / LPR, R = 2 * CA; + __shared__ __align__(16) uint32_t s_w[32 * 129]; // W-SF transpose tile + __shared__ __align__(16) uint32_t s_sfw[4][CA * 128]; + __shared__ float s_es[128]; // encode scale per e4m3 decode-scale code (bm >= 0 -> code < 128) + __shared__ float s_ge; + + const int gx = K / (64 * CA); + const int mblk = (M + 127) / 128; + const int ntiles = gx * mblk; + const int G = gridDim.x; + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int cb = lane % LPR, rsub = lane / LPR; + const int rl0 = warp * (RPI * R) + rsub; + const int sf_off_q = (cb >> 2) * 512 + (rl0 & 31) * 16 + (rl0 >> 5) * 4 + (cb & 3); + + auto tile_rc = [&](int t, int& row0, int& col0, int& by) { + by = t / gx; + const int bx = t - by * gx; + if (rev) by = mblk - 1 - by; + row0 = by * 128; + col0 = bx * (64 * CA); + }; + auto load_tile = [&](int t, uint32_t (&v)[R][8]) { + int row0, col0, by; + tile_rc(t, row0, col0, by); + const __nv_bfloat16* xp = x + (size_t)(row0 + rl0) * K + col0 + cb * 16; + if (row0 + 128 <= M) { +#pragma unroll + for (int j = 0; j < R; ++j) ldg256_ef(xp + (size_t)j * RPI * K, v[j]); + return; + } +#pragma unroll + for (int j = 0; j < R; ++j) { + const int r = row0 + rl0 + j * RPI; + if (r < M) { + ldg256_ef(xp + (size_t)j * RPI * K, v[j]); + } else { +#pragma unroll + for (int e = 0; e < 8; ++e) v[j][e] = 0u; + } + } + }; + + int t = blockIdx.x; + uint32_t v[R][8]; + __shared__ uint32_t s_amax; + float t6[R]; +#pragma unroll + for (int j = 0; j < R; ++j) t6[j] = 0.f; + uint32_t vB[R][8]; + bool held = false; + bool bulk_pend = false; + extern __shared__ __align__(16) uint4 dsm_px[]; + bool sm_hold = false; + bool sm_hold2 = false; + const int t0_ = blockIdx.x; + if constexpr (FUSED) { + // first kernel of the chain (PDL-launched): no global access before the preceding work completes + pdl_wait(); + pdl_launch_dependents(); + __shared__ __align__(16) uint32_t s_red[8]; +#pragma unroll + for (int j = 0; j < R; ++j) +#pragma unroll + for (int e = 0; e < 8; ++e) v[j][e] = 0u; + const int nt = (t < ntiles) ? (ntiles - 1 - t) / G + 1 : 0; + const int tl = t + (nt > 0 ? nt - 1 : 0) * G; + if (nt > 0) load_tile(tl, v); // pass-2 first tile: final read (evict_first) + { + uint32_t dsz; + asm volatile("mov.u32 %0, %%dynamic_smem_size;" : "=r"(dsz)); + sm_hold = (dsz >= 32768u) && nt >= 3; + sm_hold2 = (dsz >= 65536u) && nt >= 4; // index 1 != nt-2 (register-held) only when nt >= 4 + } + uint32_t mu = 0u; + { + uint32_t wA[R][8], wB[R][8]; + const bool l2fit = (size_t)M * (size_t)K <= ((size_t)32 << 20); // x <= 64 MB + auto load_el = [&](int tt, uint32_t (&w)[R][8]) { + int row0, col0, by; + tile_rc(tt, row0, col0, by); + const __nv_bfloat16* xp = x + (size_t)(row0 + rl0) * K + col0 + cb * 16; + const bool l2split = (size_t)M * (size_t)K > ((size_t)24 << 20); + const bool el = l2fit && (!l2split || 2 * ((tt - (int)blockIdx.x) / G) >= nt - 1); + const bool held_t = (tt == tl - G) || (sm_hold && tt == t0_) || (sm_hold2 && tt == t0_ + G); + auto ld1 = [&](const __nv_bfloat16* p, uint32_t (&ww)[8]) { + if (held_t) ldg256_ef(p, ww); + else if (el) amax_ldg256_el(reinterpret_cast(p), ww); + else amax_ldg256(reinterpret_cast(p), ww); + }; + if (row0 + 128 <= M) { +#pragma unroll + for (int j = 0; j < R; ++j) + ld1(xp + (size_t)j * RPI * K, w[j]); + } else { +#pragma unroll + for (int j = 0; j < R; ++j) { + if (row0 + rl0 + j * RPI < M) ld1(xp + (size_t)j * RPI * K, w[j]); + else { +#pragma unroll + for (int e = 0; e < 8; ++e) w[j][e] = 0u; + } + } + } + }; + int t1 = t; + if (nt > 0 && t1 < tl) load_el(t1, wA); + if (nt > 0 && t1 + G < tl) load_el(t1 + G, wB); +#pragma unroll + for (int j = 0; j < R; ++j) mu = bf16x8_absmax_acc(mu, v[j]); + bool first_i = true; + bool first_b = true; + while (nt > 0 && t1 < tl) { +#pragma unroll + for (int j = 0; j < R; ++j) mu = bf16x8_absmax_acc(mu, wA[j]); + if (first_i && sm_hold) { +#pragma unroll + for (int j = 0; j < R; ++j) { + dsm_px[(j * 2 + 0) * 256 + threadIdx.x] = make_uint4(wA[j][0], wA[j][1], wA[j][2], wA[j][3]); + dsm_px[(j * 2 + 1) * 256 + threadIdx.x] = make_uint4(wA[j][4], wA[j][5], wA[j][6], wA[j][7]); + } + } + first_i = false; + t1 += G; // wB holds t1 (if t1 < tl) + if (t1 + G < tl) load_el(t1 + G, wA); + if (t1 >= tl) break; +#pragma unroll + for (int j = 0; j < R; ++j) mu = bf16x8_absmax_acc(mu, wB[j]); + if (first_b && sm_hold2) { +#pragma unroll + for (int j = 0; j < R; ++j) { + dsm_px[2048 + (j * 2 + 0) * 256 + threadIdx.x] = make_uint4(wB[j][0], wB[j][1], wB[j][2], wB[j][3]); + dsm_px[2048 + (j * 2 + 1) * 256 + threadIdx.x] = make_uint4(wB[j][4], wB[j][5], wB[j][6], wB[j][7]); + } + } + first_b = false; + t1 += G; // wA holds t1 (if t1 < tl) + if (t1 + G < tl) load_el(t1 + G, wB); + } + // pass-1 tile index i (0..nt-2) sits in wA for even i, wB for odd i; tl - G = index nt-2 + if (nt >= 2) { + if (((nt - 2) & 1) == 0) { +#pragma unroll + for (int j = 0; j < R; ++j) +#pragma unroll + for (int e = 0; e < 8; ++e) vB[j][e] = wA[j][e]; + } else { +#pragma unroll + for (int j = 0; j < R; ++j) +#pragma unroll + for (int e = 0; e < 8; ++e) vB[j][e] = wB[j][e]; + } + held = true; + } + } + if (nt > 0) t = tl; // pass 2 starts at the register-held last tile, walks backwards + { + float bq[R]; +#pragma unroll + for (int j = 0; j < R; j += 2) { + uint32_t ma, mb; + bf16x8_absmax_pair(v[j], v[j + 1], ma, mb); + bq[j] = __uint_as_float(ma); + bq[j + 1] = __uint_as_float(mb); + } +#pragma unroll + for (int j = 0; j < R; j += 2) f32x2_mul(bq[j], bq[j + 1], 1.0f / 6.0f, t6[j], t6[j + 1]); + } + uint32_t mb = bmax_xa(mu, __byte_perm(mu, mu, 0x1032)) & 0x7fff0000u; + mb = __reduce_max_sync(0xffffffffu, mb); + if (lane == 0) s_red[warp] = mb; + if (threadIdx.x >= 32) asm volatile("bar.arrive 5, 256;" ::: "memory"); + else asm volatile("bar.sync 5, 256;" ::: "memory"); + unsigned int* pair = amax_bufs + 32 + 32 * parity; + if (threadIdx.x == 0) { + const uint4 sa = reinterpret_cast(s_red)[0], sb = reinterpret_cast(s_red)[1]; + const uint32_t m = max(max(max(sa.x, sa.y), max(sa.z, sa.w)), max(max(sb.x, sb.y), max(sb.z, sb.w))); + asm volatile("red.relaxed.gpu.global.max.u32 [%0], %1;" :: "l"(pair), "r"(m) : "memory"); + asm volatile("red.relaxed.gpu.global.add.u32 [%0], 1;" :: "l"(pair + 1) : "memory"); + } + if ((int)blockIdx.x >= G - nW) + bulk_pend = (K == 8192) ? wsf_swizzle_cta_bulk_impl<8192>(G - 1 - (int)blockIdx.x, s_w, wsrc, wdst, N, K, wtn) + : wsf_swizzle_cta_bulk_impl<0>(G - 1 - (int)blockIdx.x, s_w, wsrc, wdst, N, K, wtn); + if (threadIdx.x == 0) { + unsigned long long pv; + do { + asm volatile("ld.relaxed.gpu.global.b64 %0, [%1];" : "=l"(pv) : "l"(pair) : "memory"); + if ((unsigned int)(pv >> 32) >= (unsigned)G) break; + if (M >= 2048) __nanosleep(128); else if (M >= 1536) __nanosleep(32); + } while (true); + s_amax = (unsigned int)(pv & 0xffffffffull); + } + __syncthreads(); + } else { + if (t < ntiles) load_tile(t, v); // first tile in flight before anything else + if ((int)blockIdx.x < nW) { + wsf_swizzle_cta(blockIdx.x, s_w, wsrc, wdst, N, K, wtn); // contains the PDL wait + } + pdl_wait(); // kernel 1 (amax) complete + pdl_launch_dependents(); + } + // threads 0..127 each derive ge/gd (same amax word -> identical values) and fill the + // encode-scale table entry of e4m3 code c = tid: es(c) = clamp(1/(dec(c)*gd), FLT_MAX) -- + // exactly the per-block expression of the original code, now evaluated once per CTA per code + // (removes the per-block IEEE division). Block maxima are >= 0 so the code's sign bit is 0. + float gd_f = 0.f, ge_f = 0.f; + if constexpr (FUSED) { + ge_f = global_encode_from_amax(__uint_as_float(s_amax)); + asm("rcp.rn.f32 %0, %1;" : "=f"(gd_f) : "f"(ge_f)); + if (threadIdx.x == 0 && blockIdx.x == 0) { + *alpha = __fmul_rn(gd_f, w_global_decode); + amax_bufs[parity ^ 1] = 0u; + amax_bufs[4 + (parity ^ 1)] = 0u; + *reinterpret_cast(amax_bufs + 32 + 32 * (parity ^ 1)) = 0ull; + } + } + if (!FUSED && threadIdx.x < 128) { + const float amax = __uint_as_float(FUSED ? s_amax : ld_relaxed_gpu(&amax_bufs[parity])); + const float ge = global_encode_from_amax(amax); + float gd; + asm("rcp.rn.f32 %0, %1;" : "=f"(gd) : "f"(ge)); + const unsigned short c2 = (unsigned short)threadIdx.x; + uint32_t dh; // e4m3 -> f16 (exact) + asm("cvt.rn.f16x2.e4m3x2 %0, %1;" : "=r"(dh) : "h"(c2)); + const float dsf = __half2float(__ushort_as_half((unsigned short)(dh & 0xffffu))); + float e_; + asm("rcp.rn.f32 %0, %1;" : "=f"(e_) : "f"(__fmul_rn(dsf, gd))); // == __fdiv_rn(1, x) + s_es[threadIdx.x] = fminf(e_, FLT_MAX); + if (threadIdx.x == 0) { + s_ge = ge; + if (blockIdx.x == 0) { + *alpha = __fmul_rn(gd, w_global_decode); + amax_bufs[parity ^ 1] = 0u; + amax_bufs[4 + (parity ^ 1)] = 0u; + *reinterpret_cast(amax_bufs + 32 + 32 * (parity ^ 1)) = 0ull; + } + } + } + if constexpr (!FUSED) __syncthreads(); + const float ge = FUSED ? ge_f : s_ge; + const float inv6 = 1.0f / 6.0f; + const int nkb4 = K / 64; + + uint8_t* pend_dst = nullptr; + int pend_buf = 0; + const int sf_c = lane & 3; + const uint32_t sf_sel1 = (sf_c >> 1) ? 0x3276u : 0x5410u; + const uint32_t sf_sel2 = (sf_c & 1) ? 0x3715u : 0x6240u; + const int sf_rlw = rl0 + sf_c * RPI; + const int sf_off_w = (cb >> 2) * 512 + (sf_rlw & 31) * 16 + (sf_rlw >> 5) * 4; + auto flush_sf = [&](uint8_t* dst, int buf) { + if (threadIdx.x < 32 * CA) + reinterpret_cast(dst)[threadIdx.x] = reinterpret_cast(s_sfw[buf])[threadIdx.x]; + }; + auto quant_tile = [&](int t, const uint32_t (&v)[R][8], int buf, bool pre, bool flush) { + int row0, col0, by; + tile_rc(t, row0, col0, by); + const bool full = row0 + 128 <= M; + uint32_t pcode[R / 2]; + uint8_t* qp = q + ((size_t)(row0 + rl0) * K + col0 + cb * 16) / 2; // row r_j = row0+rl0+j*RPI + // block abs-max with native packed max.u16x2 (sm_90+), decode scales of block pairs + // (j, j+1) with mul.rn.f32x2 (two RN fp32 products, bit-identical to scalar __fmul_rn) and + // ONE cvt.rn.satfinite.e4m3x2 for both; encode scale from the per-CTA smem table. + #pragma unroll + for (int j = 0; j < R; j += 2) { + float t0, t1, d0, d1; + if (pre) { t0 = t6[j]; t1 = t6[j + 1]; } + else { + uint32_t ma, mb2; + bf16x8_absmax_pair(v[j], v[j + 1], ma, mb2); + const float b0 = __uint_as_float(ma); + const float b1 = __uint_as_float(mb2); + f32x2_mul(b0, b1, inv6, t0, t1); + } + f32x2_mul(t0, t1, ge, d0, d1); + unsigned short p2; // low byte = e4m3(d0), high byte = e4m3(d1) + asm("cvt.rn.satfinite.e4m3x2.f32 %0, %1, %2;" : "=h"(p2) : "f"(d1), "f"(d0)); + pcode[j >> 1] = (uint32_t)p2; + float esp0 = 0.f, esp1 = 0.f; + if constexpr (FUSED) { + enc_pair_e4m3(p2, gd_f, esp0, esp1); + } + #pragma unroll + for (int u = 0; u < 2; ++u) { + const int jj = j + u; + const int rl = rl0 + jj * RPI; + const int r = row0 + rl; + const unsigned short ds2 = u ? (p2 >> 8) : (p2 & 0xffu); + float es; + if constexpr (FUSED) { + es = u ? esp1 : esp0; + } else { + es = s_es[ds2]; + } + const uint64_t es2 = pack_f32x2_same(es); + const uint2 p = quant16_e2m1(v[jj], es2); + if (full || r < M) + *reinterpret_cast(qp + (size_t)jj * RPI * (K / 2)) = p; + } + } + { + const uint32_t x = __byte_perm(pcode[0], pcode[1], 0x5410); + const uint32_t y = __shfl_xor_sync(0xffffffffu, x, 2); + const uint32_t r1 = __byte_perm(x, y, sf_sel1); + const uint32_t z = __shfl_xor_sync(0xffffffffu, r1, 1); + const uint32_t wv = __byte_perm(r1, z, sf_sel2); + uint8_t* dst = sf + ((size_t)by * nkb4 + (size_t)(col0 >> 6)) * 512 + sf_off_w; + *reinterpret_cast(dst) = wv; + } + (void)buf; (void)flush; + }; + uint32_t (&vA)[R][8] = v; + const int step = FUSED ? -G : G; + auto valid = [&](int tt) { return tt >= 0 && tt < ntiles; }; + bool pre = FUSED; + int pb = 0; + auto load_p2 = [&](int tt, uint32_t (&w)[R][8]) { + if (FUSED && ((sm_hold && tt == t0_) || (sm_hold2 && tt == t0_ + G))) { + const int sb = (tt == t0_) ? 0 : 2048; +#pragma unroll + for (int j = 0; j < R; ++j) { + const uint4 a = dsm_px[sb + (j * 2 + 0) * 256 + threadIdx.x], b = dsm_px[sb + (j * 2 + 1) * 256 + threadIdx.x]; + w[j][0] = a.x; w[j][1] = a.y; w[j][2] = a.z; w[j][3] = a.w; + w[j][4] = b.x; w[j][5] = b.y; w[j][6] = b.z; w[j][7] = b.w; + } + } else { + load_tile(tt, w); + } + }; + while (valid(t)) { + int tn = t + step; + if (valid(tn) && !held) load_p2(tn, vB); // next tile in flight during this tile + held = false; + quant_tile(t, vA, pb, pre, false); + pre = false; + t = tn; + if (!valid(t)) break; + tn = t + step; + if (valid(tn)) load_p2(tn, vA); + quant_tile(t, vB, pb + 1, false, true); + pb ^= 2; + t = tn; + } + if (pend_dst != nullptr) { + __syncthreads(); + flush_sf(pend_dst, pend_buf); + } + if (bulk_pend) asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); +} + +// ---------------- 3a. PDL weight-first GEMM kernel (derived from CUTLASS 4.2) ---------------- + +#if !(CUTLASS_MAJOR == 4 && CUTLASS_MINOR >= 2 && CUTLASS_MINOR <= 4) +#error "PdlWeightFirstKernel body is copied from CUTLASS 4.2 (identical in 4.4.1) sm100_gemm_tma_warpspecialized.hpp" +#endif +// ---- CustomEpi helpers ---- +// 32 lanes x 32 consecutive TMEM columns (32-bit) -> 32 regs per thread (thread = lane). +__device__ __forceinline__ void tmem_ld_32x32b_x32(uint32_t taddr, uint32_t (&f)[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"(f[0]), "=r"(f[1]), "=r"(f[2]), "=r"(f[3]), "=r"(f[4]), "=r"(f[5]), + "=r"(f[6]), "=r"(f[7]), "=r"(f[8]), "=r"(f[9]), "=r"(f[10]), "=r"(f[11]), + "=r"(f[12]), "=r"(f[13]), "=r"(f[14]), "=r"(f[15]), "=r"(f[16]), "=r"(f[17]), + "=r"(f[18]), "=r"(f[19]), "=r"(f[20]), "=r"(f[21]), "=r"(f[22]), "=r"(f[23]), + "=r"(f[24]), "=r"(f[25]), "=r"(f[26]), "=r"(f[27]), "=r"(f[28]), "=r"(f[29]), + "=r"(f[30]), "=r"(f[31]) + : "r"(taddr) : "memory"); +} +__device__ __forceinline__ void tmem_ld_32x32b_x64p(uint32_t taddr, uint32_t* f) { + asm volatile("tcgen05.ld.sync.aligned.32x32b.x64.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,%33,%34,%35,%36,%37,%38,%39,%40,%41,%42,%43,%44,%45,%46,%47,%48,%49,%50,%51,%52,%53,%54,%55,%56,%57,%58,%59,%60,%61,%62,%63}, [%64];" + : "=r"(f[0]), "=r"(f[1]), "=r"(f[2]), "=r"(f[3]), "=r"(f[4]), "=r"(f[5]), "=r"(f[6]), "=r"(f[7]), "=r"(f[8]), "=r"(f[9]), "=r"(f[10]), "=r"(f[11]), "=r"(f[12]), "=r"(f[13]), "=r"(f[14]), "=r"(f[15]), "=r"(f[16]), "=r"(f[17]), "=r"(f[18]), "=r"(f[19]), "=r"(f[20]), "=r"(f[21]), "=r"(f[22]), "=r"(f[23]), "=r"(f[24]), "=r"(f[25]), "=r"(f[26]), "=r"(f[27]), "=r"(f[28]), "=r"(f[29]), "=r"(f[30]), "=r"(f[31]), "=r"(f[32]), "=r"(f[33]), "=r"(f[34]), "=r"(f[35]), "=r"(f[36]), "=r"(f[37]), "=r"(f[38]), "=r"(f[39]), "=r"(f[40]), "=r"(f[41]), "=r"(f[42]), "=r"(f[43]), "=r"(f[44]), "=r"(f[45]), "=r"(f[46]), "=r"(f[47]), "=r"(f[48]), "=r"(f[49]), "=r"(f[50]), "=r"(f[51]), "=r"(f[52]), "=r"(f[53]), "=r"(f[54]), "=r"(f[55]), "=r"(f[56]), "=r"(f[57]), "=r"(f[58]), "=r"(f[59]), "=r"(f[60]), "=r"(f[61]), "=r"(f[62]), "=r"(f[63]) + : "r"(taddr) : "memory"); +} +__device__ __forceinline__ void tmem_ld_32x32b_x16p(uint32_t taddr, uint32_t* f) { + 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"(f[0]), "=r"(f[1]), "=r"(f[2]), "=r"(f[3]), "=r"(f[4]), "=r"(f[5]), + "=r"(f[6]), "=r"(f[7]), "=r"(f[8]), "=r"(f[9]), "=r"(f[10]), "=r"(f[11]), + "=r"(f[12]), "=r"(f[13]), "=r"(f[14]), "=r"(f[15]) + : "r"(taddr) : "memory"); +} +// two fp32 -> packed bf16x2 (lo in the low half), round-to-nearest-even +__device__ __forceinline__ uint32_t pack_bf16x2_rn(float lo, float hi) { + uint32_t d; + asm("cvt.rn.bf16x2.f32 %0, %1, %2;" : "=r"(d) : "f"(hi), "f"(lo)); + return d; +} +__device__ __forceinline__ uint32_t alpha_bf16x2(float alpha) { + uint32_t d; + asm("cvt.rn.bf16x2.f32 %0, %1, %1;" : "=r"(d) : "f"(alpha)); + return d; +} +__device__ __forceinline__ uint32_t epi_core_bf16(uint32_t t1w, uint32_t cw, uint32_t ab2) { + uint32_t t2, d; + asm("mul.rn.bf16x2 %0, %1, %2;" : "=r"(t2) : "r"(t1w), "r"(ab2)); + // residual add as ONE add.rn.bf16x2 (single RN of the exact-or-dominated sum, == fp32 add + RN cvt) + asm("add.rn.bf16x2 %0, %1, %2;" : "=r"(d) : "r"(t2), "r"(cw)); + return d; +} +__device__ __forceinline__ uint32_t epi_combine(uint32_t t1w, uint32_t cw, float alpha) { + return epi_core_bf16(t1w, cw, alpha_bf16x2(alpha)); +} +__device__ __forceinline__ uint32_t epi_combine_x2(uint32_t t1w, uint32_t cw, float alpha) { + return epi_core_bf16(t1w, cw, alpha_bf16x2(alpha)); +} +// packed multiplier built once per thread: low 32 bits = {bf16(alpha), bf16(alpha)} +__device__ __forceinline__ uint64_t pack_alpha2(float alpha) { + const uint32_t ab2 = alpha_bf16x2(alpha); + return (uint64_t(ab2) << 32) | uint64_t(ab2); +} +__device__ __forceinline__ uint32_t epi_combine_x2a(uint32_t t1w, uint32_t cw, uint64_t a2) { + return epi_core_bf16(t1w, cw, uint32_t(a2)); +} +// straight from the two fp32 accumulators: t1 pair = ONE cvt.rn.bf16x2.f32 (lo = acc0) +__device__ __forceinline__ uint32_t epi_combine_acc2(uint32_t f0, uint32_t f1, uint32_t cw, uint64_t a2) { + uint32_t t1w; + asm("cvt.rn.bf16x2.f32 %0, %1, %2;" : "=r"(t1w) : "f"(__uint_as_float(f1)), "f"(__uint_as_float(f0))); + return epi_core_bf16(t1w, cw, uint32_t(a2)); +} +__device__ __forceinline__ uint32_t epi_combine_acc2f(uint32_t f0, uint32_t f1, uint32_t cw, uint32_t ab2) { + uint32_t d; + asm("{\n\t.reg .b32 t1, t2;\n\t" + "cvt.rn.bf16x2.f32 t1, %2, %1;\n\t" + "mul.rn.bf16x2 t2, t1, %4;\n\t" + "add.rn.bf16x2 %0, t2, %3;\n\t}" + : "=r"(d) : "f"(__uint_as_float(f0)), "f"(__uint_as_float(f1)), "r"(cw), "r"(ab2)); + return d; +} +// 32 B read-only residual load (L1 no-allocate, L2 evict_first) / 32 B output store (L2 evict_first): +// streamed once, must not evict the EVICT_LAST weight. 32 B aligned. +__device__ __forceinline__ void ldg256_na(const void* p, uint32_t (&w)[8]) { + asm volatile("ld.global.nc.L1::no_allocate.L2::evict_first.v8.b32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];" + : "=r"(w[0]), "=r"(w[1]), "=r"(w[2]), "=r"(w[3]), "=r"(w[4]), "=r"(w[5]), + "=r"(w[6]), "=r"(w[7]) + : "l"(p)); +} +__device__ __forceinline__ void stg256(void* p, const uint32_t (&w)[8]) { + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + asm volatile("st.global.L2::cache_hint.v8.b32 [%0], {%1,%2,%3,%4,%5,%6,%7,%8}, %9;" + :: "l"(p), "r"(w[0]), "r"(w[1]), "r"(w[2]), "r"(w[3]), "r"(w[4]), "r"(w[5]), + "r"(w[6]), "r"(w[7]), "l"(pol) : "memory"); +} +__device__ __forceinline__ uint64_t make_ef_policy() { + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + return pol; +} +__device__ __forceinline__ void stg256p(void* p, const uint32_t (&w)[8], uint64_t pol) { + asm volatile("st.global.L1::no_allocate.L2::cache_hint.v8.b32 [%0], {%1,%2,%3,%4,%5,%6,%7,%8}, %9;" + :: "l"(p), "r"(w[0]), "r"(w[1]), "r"(w[2]), "r"(w[3]), "r"(w[4]), "r"(w[5]), + "r"(w[6]), "r"(w[7]), "l"(pol) : "memory"); +} + +__device__ __forceinline__ void mbar_wait_sleep(uint32_t addr, uint32_t phase) { + asm volatile("{\n\t.reg .pred p;\n\t" + "LAB_WAIT_S:\n\t" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1, %2;\n\t" + "@!p bra LAB_WAIT_S;\n\t}" + :: "r"(addr), "r"(phase), "r"(10000000u) : "memory"); +} + +namespace cutlass::gemm::kernel { + +template struct HasAccFirstSkip : std::false_type {}; +template struct HasAccFirstSkip> : std::true_type {}; + +// Raw (row-major [rows][K/16] e4m3) weight-SF source for the RawW mainloop. +struct RawWsf { + const uint8_t* src; // weight_scale as given (row-major, ld = ksf bytes) + int rows; // weight rows (= N of the problem) + int ksf; // K / 16 + uint32_t smem; // shared address of the weight-SF smem buffer (stage 0) + uint32_t empty = 0u; +}; + +// Derived CUTLASS block-scaled mainloop: adds the two halves of CollectiveMma::load() used for +// the first work tile (identical TMA copies, just split by operand and around the PDL wait). +// load_weight_pre : producer_acquire (arms the full barrier with ALL stage bytes) + weight TMA +// load_rest_post : NO acquire (already done) + activation, SFA, SFB TMA on the same stages +// RawW (only WeightIsA + 1SM, i.e. swap-AB with weight = MMA-A): the weight SF is NOT loaded +// by TMA from a pre-swizzled buffer. Instead the 4 epilogue warps gather it straight from the +// raw row-major weight_scale into the stage's blocked smem atom layout +// smem(r, kq, c) = kq*512 + (r%32)*16 + (r/32)*4 + c (r < 128 rows, kq = 4-SF group, c < 4) +// (identical bytes to what the TMA of the swizzled buffer delivered, so tcgen05.cp / MMA are +// untouched). Completion is tracked on the SAME full mbarrier as the TMAs: its expected arrival +// count is 1 (producer arrive_and_expect_tx) + 128 (gather threads, plain mbarrier.arrive after +// st.shared + fence.proxy.async), so the phase cannot complete before the SF bytes are in smem +// and the TMA bytes have landed. The pipeline's expect_tx bytes exclude this SF (kernel). +// (A TMA box cannot produce this layout: its pieces are 4 B, below the 16 B TMA inner-box +// minimum; and the TMEM SF layout is replicated per subpartition, so raw 16 B rows + +// tcgen05.cp 128x128b would not match what the MMA reads.) +template +struct PdlWeightFirstMainloop : Base { + using Base::Base; + using MainloopPipeline = typename Base::MainloopPipeline; + using MainloopPipelineState = typename Base::MainloopPipelineState; + using TiledMma = typename Base::TiledMma; + using SmemLayoutSFA = typename Base::SmemLayoutSFA; + using SmemLayoutAtomSFA = typename Base::SmemLayoutAtomSFA; + using TileShape = typename Base::TileShape; + + // bytes of one stage of the weight SF (MMA-A SF) buffer + static constexpr uint32_t RawStageBytes = uint32_t(cute::cosize(take<0,3>(SmemLayoutSFA{}))); + static_assert(!RawW || (WeightIsA && size(typename TiledMma::AtomThrID{}) == 1 && + size<0>(TileShape{}) == 128 && size<2>(TileShape{}) == 256), + "RawW: only 1SM swap-AB with a 128 x 256 weight tile"); + static_assert(!RawW || RawStageBytes == 2048, "RawW: unexpected SFA stage size"); + // Check (at compile time) that CUTLASS's SFA smem atom is the assumed blocked layout: + // coordinate ((((i, j), _), (e, c)), _, (_, kq)) of row 32j+i, SF 4kq+c -> 16i + 4j + c + 512kq + static constexpr bool check_sfa_atom() { + if constexpr (RawW) { + for (int i = 0; i < 32; ++i) + for (int j = 0; j < 4; ++j) + for (int c = 0; c < 4; ++c) + for (int kq = 0; kq < 4; ++kq) + if (int(SmemLayoutAtomSFA{}(make_coord(make_coord(make_coord(make_coord(i, j), 0), make_coord(0, c)), + 0, make_coord(0, kq)))) != + 16 * i + 4 * j + c + 512 * kq) + return false; + } + return true; + } + static_assert(check_sfa_atom(), "RawW: SFA smem atom layout differs from the assumed blocked layout"); + static_assert(!RawW || cute::stride<3>(SmemLayoutSFA{}) == 2048, "RawW: SFA stage stride"); + + // [L2 residency] weight (FP4 + weight SF) TMA tiles: L2 EVICT_LAST (the 36 MB weight stays + // L2-resident across back-to-back calls); activation operands: default policy (re-read by the + // other N tiles). hA applies to the MMA-A operand + SFA, hB to MMA-B + SFB. + // (WHint converts to the hint enum of the 1SM (Sm90) or 2SM (Sm100) TMA copy traits.) + struct WHint { + int code; + CUTLASS_HOST_DEVICE constexpr operator cute::TMA::CacheHintSm90() const { + return code == 1 ? cute::TMA::CacheHintSm90::EVICT_LAST + : code == 2 ? cute::TMA::CacheHintSm90::EVICT_FIRST : cute::TMA::CacheHintSm90::EVICT_NORMAL; + } + CUTLASS_HOST_DEVICE constexpr operator cute::TMA::CacheHintSm100() const { + return code == 1 ? cute::TMA::CacheHintSm100::EVICT_LAST + : code == 2 ? cute::TMA::CacheHintSm100::EVICT_FIRST : cute::TMA::CacheHintSm100::EVICT_NORMAL; + } + }; + static constexpr int kWCode = WFirst ? 2 : 1; + static constexpr int kACode = (ActLast || WFirst) ? 1 : 0; + static constexpr int kHA = WeightIsA ? kWCode : kACode; // MMA-A operand + SFA + static constexpr int kHB = WeightIsA ? kACode : kWCode; // MMA-B operand + SFB + + static constexpr int kGatherD = 8; + static_assert(kGatherD % 2 == 0, "pairs"); + CUTLASS_DEVICE static uint4 raw_wsf_load(RawWsf const& rw, int r, int kt) { + uint4 v = make_uint4(0u, 0u, 0u, 0u); + if (r >= rw.rows) return v; + const int c = kt * 16; + const uint8_t* p = rw.src + (size_t)r * rw.ksf + c; + if ((rw.ksf & 15) == 0 && c + 16 <= rw.ksf) { // 16 B aligned (ksf % 16 == 0, c % 16 == 0) + asm volatile("ld.global.nc.v4.u32 {%0,%1,%2,%3}, [%4];" + : "=r"(v.x), "=r"(v.y), "=r"(v.z), "=r"(v.w) : "l"(p)); + } else { // ragged K tail (ksf % 4 == 0 required): 4 B words, OOB -> 0 + const uint32_t* q = reinterpret_cast(p); + if (c + 4 <= rw.ksf) v.x = __ldg(q + 0); + if (c + 8 <= rw.ksf) v.y = __ldg(q + 1); + if (c + 12 <= rw.ksf) v.z = __ldg(q + 2); + if (c + 16 <= rw.ksf) v.w = __ldg(q + 3); + } + return v; + } + CUTLASS_DEVICE static void raw_wsf_load2(RawWsf const& rw, int r, int kt, uint4& a, uint4& b) { + const int c = kt * 16; + if (r < rw.rows && (kt & 1) == 0 && (rw.ksf & 31) == 0 && c + 32 <= rw.ksf && + (reinterpret_cast(rw.src) & 31) == 0) { + const uint8_t* p = rw.src + (size_t)r * rw.ksf + c; + asm volatile("ld.global.nc.v8.u32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];" + : "=r"(a.x), "=r"(a.y), "=r"(a.z), "=r"(a.w), + "=r"(b.x), "=r"(b.y), "=r"(b.z), "=r"(b.w) : "l"(p)); + } else { + a = raw_wsf_load(rw, r, kt); + b = raw_wsf_load(rw, r, kt + 1); + } + } + // Write one row's 16 SF bytes of a stage into the blocked smem atoms (word kq = SFs 4kq..4kq+3 + // -> atom kq at (i%32)*16 + (i/32)*4), make the generic-proxy writes visible to the async + // proxy (tcgen05.cp reads them), then arrive on the stage's FULL barrier (expected count + // 1 producer + 128 gather threads, see kernel). + CUTLASS_DEVICE static void raw_wsf_store_arrive(RawWsf const& rw, uint4 v, int i, int stage, uint64_t* bar) { + const uint32_t a = rw.smem + uint32_t(stage) * RawStageBytes + uint32_t((i & 31) * 16 + (i >> 5) * 4); + asm volatile("st.shared.b32 [%0], %1;" :: "r"(a), "r"(v.x) : "memory"); + asm volatile("st.shared.b32 [%0], %1;" :: "r"(a + 512u), "r"(v.y) : "memory"); + asm volatile("st.shared.b32 [%0], %1;" :: "r"(a + 1024u), "r"(v.z) : "memory"); + asm volatile("st.shared.b32 [%0], %1;" :: "r"(a + 1536u), "r"(v.w) : "memory"); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + // ONE arrival per gather warp (full barrier count 1 + 4) instead of 32 same-address + // per-lane arrivals: every lane's st.shared + proxy fence is ordered before lane 0's + // (release) arrive by __syncwarp (memory-ordering among the warp's threads). + __syncwarp(); + if ((threadIdx.x & 31) == 0) + asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" + :: "r"(cute::cast_smem_ptr_to_uint(bar)) : "memory"); + } + + static constexpr int kWPrefDist = WPrefDist; // per-config (Cfg10: 12) + template + CUTLASS_DEVICE static void prefetch_w(TW const* tma, GW const& tWgW, int kt) { + auto crd = tWgW(_, kt)(0); + constexpr int R = int(cute::tuple_size::value); + const uint64_t desc = reinterpret_cast(tma->get_tma_descriptor()); + const uint64_t pol = uint64_t(cute::TMA::CacheHintSm90::EVICT_LAST); + if constexpr (R == 2) { + asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile.L2::cache_hint [%0, {%1, %2}], %3;" + :: "l"(desc), "r"(int32_t(get<0>(crd))), "r"(int32_t(get<1>(crd))), "l"(pol) : "memory"); + } else if constexpr (R == 3) { + asm volatile("cp.async.bulk.prefetch.tensor.3d.L2.global.tile.L2::cache_hint [%0, {%1, %2, %3}], %4;" + :: "l"(desc), "r"(int32_t(get<0>(crd))), "r"(int32_t(get<1>(crd))), "r"(int32_t(get<2>(crd))), + "l"(pol) : "memory"); + } else if constexpr (R == 4) { + asm volatile("cp.async.bulk.prefetch.tensor.4d.L2.global.tile.L2::cache_hint [%0, {%1, %2, %3, %4}], %5;" + :: "l"(desc), "r"(int32_t(get<0>(crd))), "r"(int32_t(get<1>(crd))), "r"(int32_t(get<2>(crd))), + "r"(int32_t(get<3>(crd))), "l"(pol) : "memory"); + } else if constexpr (R == 5) { + asm volatile("cp.async.bulk.prefetch.tensor.5d.L2.global.tile.L2::cache_hint [%0, {%1, %2, %3, %4, %5}], %6;" + :: "l"(desc), "r"(int32_t(get<0>(crd))), "r"(int32_t(get<1>(crd))), "r"(int32_t(get<2>(crd))), + "r"(int32_t(get<3>(crd))), "r"(int32_t(get<4>(crd))), "l"(pol) : "memory"); + } else { + cute::prefetch(*tma, tWgW(_, kt)); + } + } + + bool pref_on_ = true; + int mirror_n_ = -1; + template + CUTLASS_DEVICE void prefetch_w_head(LoadParams const& li, Coord const& c, int nk) const { + if constexpr (!WeightIsA) { + Tensor tBgB = li.tBgB_nkl(_, get<1>(c), _, get<3>(c)); + const int nkt = int(size<1>(tBgB)); + for (int i = 0; i < nk && i < nkt; ++i) prefetch_w(this->observed_tma_load_b_, tBgB, i); + } + } + template + CUTLASS_DEVICE void set_w(TW const* w, TS const* sfa) { + if constexpr (WeightIsA) this->observed_tma_load_a_ = w; else this->observed_tma_load_b_ = w; + if constexpr (RawW) this->observed_tma_load_sfa_ = sfa; + } + + template + CUTLASS_DEVICE void + load_weight_pre(MainloopPipeline mainloop_pipeline, MainloopPipelineState state, + LoadParams const& load_inputs, TileCoordMNKL const& cta_coord_mnkl, + KTileIterator k_tile_iter, int k_tile_count, RawWsf const& rw) { + auto [unused_k_tiles, + tAgA_mkl, tBgB_nkl, tAsA, tBsB, + tAgSFA_mkl, tBgSFB_nkl, tAsSFA, tBsSFB, + mcast_mask_a, mcast_mask_b, mcast_mask_sfa, mcast_mask_sfb] = load_inputs; + Tensor tAgA = tAgA_mkl(_, get<0>(cta_coord_mnkl) / size(typename TiledMma::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgB = tBgB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + const bool elect_leader = cute::elect_one_sync(); + const int k0_pre = int(cute::get<0>(cute::wrap(*k_tile_iter))); + const int n_pre_ = k_tile_count; + CUTLASS_PRAGMA_NO_UNROLL + while (k_tile_count > 0) { + mainloop_pipeline.producer_acquire(state, decltype(mainloop_pipeline.producer_try_acquire(state)){cutlass::BarrierStatus::WaitDone}); + using BarrierType = typename MainloopPipeline::ProducerBarrierType; + BarrierType* tma_barrier = mainloop_pipeline.producer_get_barrier(state); + int write_stage = state.index(); + ++state; + // (RawW: the weight SF of this stage is gathered by the epilogue warps, not here) + if (elect_leader) { + if constexpr (WeightIsA) { + copy(this->observed_tma_load_a_->with(*tma_barrier, mcast_mask_a, WHint{kHA}), tAgA(_,*k_tile_iter), tAsA(_,write_stage)); + } else { + copy(this->observed_tma_load_b_->with(*tma_barrier, mcast_mask_b, WHint{kHB}), tBgB(_,*k_tile_iter), tBsB(_,write_stage)); + } + if constexpr (WPref && !WeightIsA && !DeferPref) { + const int kp = int(cute::get<0>(cute::wrap(*k_tile_iter))) + kWPrefDist; + if (pref_on_ && kp < int(size<1>(tBgB))) prefetch_w(this->observed_tma_load_b_, tBgB, kp); + } + if constexpr (WPref && WeightIsA) { // swap-AB: weight = MMA-A + const int kp = int(cute::get<0>(cute::wrap(*k_tile_iter))) + kWPrefDist; + if (kp < int(size<1>(tAgA))) prefetch_w(this->observed_tma_load_a_, tAgA, kp); + } + } + --k_tile_count; + ++k_tile_iter; + } + if constexpr (!WeightIsA) { + if (mirror_n_ >= 0 && elect_leader) { + Tensor tBgBm = tBgB_nkl(_, mirror_n_, _, get<3>(cta_coord_mnkl)); + for (int i = 0; i < 2 * n_pre_; ++i) + if (k0_pre + i < int(size<1>(tBgBm))) prefetch_w(this->observed_tma_load_b_, tBgBm, k0_pre + i); + } + } + } + + template + CUTLASS_DEVICE auto + load_rest_post(MainloopPipeline mainloop_pipeline, MainloopPipelineState state, + LoadParams const& load_inputs, TileCoordMNKL const& cta_coord_mnkl, + KTileIterator k_tile_iter, int k_tile_count) { + auto [unused_k_tiles, + tAgA_mkl, tBgB_nkl, tAsA, tBsB, + tAgSFA_mkl, tBgSFB_nkl, tAsSFA, tBsSFB, + mcast_mask_a, mcast_mask_b, mcast_mask_sfa, mcast_mask_sfb] = load_inputs; + Tensor tAgA = tAgA_mkl(_, get<0>(cta_coord_mnkl) / size(typename TiledMma::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgB = tBgB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + Tensor tAgSFA = tAgSFA_mkl(_, get<0>(cta_coord_mnkl) / size(typename TiledMma::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgSFB = tBgSFB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + const bool elect_leader = cute::elect_one_sync(); + CUTLASS_PRAGMA_NO_UNROLL + while (k_tile_count > 0) { + using BarrierType = typename MainloopPipeline::ProducerBarrierType; + BarrierType* tma_barrier = mainloop_pipeline.producer_get_barrier(state); + int write_stage = state.index(); + ++state; + if (elect_leader) { + if constexpr (WeightIsA) { + if constexpr (!RawW) { // RawW: weight SF (= SFA) gathered by the epilogue warps + copy(this->observed_tma_load_sfa_->with(*tma_barrier, mcast_mask_sfa, WHint{kHA}), tAgSFA(_,*k_tile_iter), tAsSFA(_,write_stage)); + } + copy(this->observed_tma_load_b_->with(*tma_barrier, mcast_mask_b, WHint{kHB}), tBgB(_,*k_tile_iter), tBsB(_,write_stage)); + copy(this->observed_tma_load_sfb_->with(*tma_barrier, mcast_mask_sfb, WHint{kHB}), tBgSFB(_,*k_tile_iter), tBsSFB(_,write_stage)); + } else { + copy(this->observed_tma_load_sfb_->with(*tma_barrier, mcast_mask_sfb, WHint{kHB}), tBgSFB(_,*k_tile_iter), tBsSFB(_,write_stage)); + copy(this->observed_tma_load_a_->with(*tma_barrier, mcast_mask_a, WHint{kHA}), tAgA(_,*k_tile_iter), tAsA(_,write_stage)); + copy(this->observed_tma_load_sfa_->with(*tma_barrier, mcast_mask_sfa, WHint{kHA}), tAgSFA(_,*k_tile_iter), tAsSFA(_,write_stage)); + if constexpr (WPref && DeferPref) { + const int kp = int(cute::get<0>(cute::wrap(*k_tile_iter))) + kWPrefDist; + if (pref_on_ && kp < int(size<1>(tBgB))) prefetch_w(this->observed_tma_load_b_, tBgB, kp); + } + } + } + --k_tile_count; + ++k_tile_iter; + } + return cute::make_tuple(state, k_tile_iter); + } + + // Steady-state load for WPref: CollectiveMma::load (identical TMAs) + the weight L2 prefetch + template + CUTLASS_DEVICE auto + load_std(MainloopPipeline mainloop_pipeline, MainloopPipelineState state, + LoadParams const& load_inputs, TileCoordMNKL const& cta_coord_mnkl, + KTileIterator k_tile_iter, int k_tile_count) { + auto [unused_k_tiles, + tAgA_mkl, tBgB_nkl, tAsA, tBsB, + tAgSFA_mkl, tBgSFB_nkl, tAsSFA, tBsSFB, + mcast_mask_a, mcast_mask_b, mcast_mask_sfa, mcast_mask_sfb] = load_inputs; + Tensor tAgA = tAgA_mkl(_, get<0>(cta_coord_mnkl) / size(typename TiledMma::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgB = tBgB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + Tensor tAgSFA = tAgSFA_mkl(_, get<0>(cta_coord_mnkl) / size(typename TiledMma::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgSFB = tBgSFB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + auto barrier_token = mainloop_pipeline.producer_try_acquire(state); + const bool elect_leader = cute::elect_one_sync(); + CUTLASS_PRAGMA_NO_UNROLL + while (k_tile_count > 0) { + mainloop_pipeline.producer_acquire(state, barrier_token); + using BarrierType = typename MainloopPipeline::ProducerBarrierType; + BarrierType* tma_barrier = mainloop_pipeline.producer_get_barrier(state); + int write_stage = state.index(); + ++state; + barrier_token = mainloop_pipeline.producer_try_acquire(state); + if (elect_leader) { + if constexpr (!WeightIsA) { + copy(this->observed_tma_load_b_->with(*tma_barrier, mcast_mask_b, WHint{kHB}), tBgB(_,*k_tile_iter), tBsB(_,write_stage)); + copy(this->observed_tma_load_sfb_->with(*tma_barrier, mcast_mask_sfb, WHint{kHB}), tBgSFB(_,*k_tile_iter), tBsSFB(_,write_stage)); + copy(this->observed_tma_load_a_->with(*tma_barrier, mcast_mask_a, WHint{kHA}), tAgA(_,*k_tile_iter), tAsA(_,write_stage)); + copy(this->observed_tma_load_sfa_->with(*tma_barrier, mcast_mask_sfa, WHint{kHA}), tAgSFA(_,*k_tile_iter), tAsSFA(_,write_stage)); + } else { + copy(this->observed_tma_load_a_->with(*tma_barrier, mcast_mask_a, WHint{kHA}), tAgA(_,*k_tile_iter), tAsA(_,write_stage)); + copy(this->observed_tma_load_sfa_->with(*tma_barrier, mcast_mask_sfa, WHint{kHA}), tAgSFA(_,*k_tile_iter), tAsSFA(_,write_stage)); + copy(this->observed_tma_load_b_->with(*tma_barrier, mcast_mask_b, WHint{kHB}), tBgB(_,*k_tile_iter), tBsB(_,write_stage)); + copy(this->observed_tma_load_sfb_->with(*tma_barrier, mcast_mask_sfb, WHint{kHB}), tBgSFB(_,*k_tile_iter), tBsSFB(_,write_stage)); + } + const int kp = int(cute::get<0>(cute::wrap(*k_tile_iter))) + kWPrefDist; + if (pref_on_ && kp < int(size<1>(tBgB))) prefetch_w(this->observed_tma_load_b_, tBgB, kp); + } + --k_tile_count; + ++k_tile_iter; + } + return cute::make_tuple(state, k_tile_iter); + } + + // Steady-state load with the L2 cache hints (replaces CollectiveMma::load): identical TMAs + template + CUTLASS_DEVICE auto + load_hint(MainloopPipeline mainloop_pipeline, MainloopPipelineState state, + LoadParams const& load_inputs, TileCoordMNKL const& cta_coord_mnkl, + KTileIterator k_tile_iter, int k_tile_count) { + auto [unused_k_tiles, + tAgA_mkl, tBgB_nkl, tAsA, tBsB, + tAgSFA_mkl, tBgSFB_nkl, tAsSFA, tBsSFB, + mcast_mask_a, mcast_mask_b, mcast_mask_sfa, mcast_mask_sfb] = load_inputs; + Tensor tAgA = tAgA_mkl(_, get<0>(cta_coord_mnkl) / size(typename TiledMma::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgB = tBgB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + Tensor tAgSFA = tAgSFA_mkl(_, get<0>(cta_coord_mnkl) / size(typename TiledMma::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgSFB = tBgSFB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + auto barrier_token = mainloop_pipeline.producer_try_acquire(state); + const bool elect_leader = cute::elect_one_sync(); + CUTLASS_PRAGMA_NO_UNROLL + while (k_tile_count > 0) { + mainloop_pipeline.producer_acquire(state, barrier_token); + using BarrierType = typename MainloopPipeline::ProducerBarrierType; + BarrierType* tma_barrier = mainloop_pipeline.producer_get_barrier(state); + int write_stage = state.index(); + ++state; + barrier_token = mainloop_pipeline.producer_try_acquire(state); + if (elect_leader) { + if constexpr (!WeightIsA) { + copy(this->observed_tma_load_b_->with(*tma_barrier, mcast_mask_b, WHint{kHB}), tBgB(_,*k_tile_iter), tBsB(_,write_stage)); + copy(this->observed_tma_load_sfb_->with(*tma_barrier, mcast_mask_sfb, WHint{kHB}), tBgSFB(_,*k_tile_iter), tBsSFB(_,write_stage)); + copy(this->observed_tma_load_a_->with(*tma_barrier, mcast_mask_a, WHint{kHA}), tAgA(_,*k_tile_iter), tAsA(_,write_stage)); + copy(this->observed_tma_load_sfa_->with(*tma_barrier, mcast_mask_sfa, WHint{kHA}), tAgSFA(_,*k_tile_iter), tAsSFA(_,write_stage)); + } else { + copy(this->observed_tma_load_a_->with(*tma_barrier, mcast_mask_a, WHint{kHA}), tAgA(_,*k_tile_iter), tAsA(_,write_stage)); + copy(this->observed_tma_load_sfa_->with(*tma_barrier, mcast_mask_sfa, WHint{kHA}), tAgSFA(_,*k_tile_iter), tAsSFA(_,write_stage)); + copy(this->observed_tma_load_b_->with(*tma_barrier, mcast_mask_b, WHint{kHB}), tBgB(_,*k_tile_iter), tBsB(_,write_stage)); + copy(this->observed_tma_load_sfb_->with(*tma_barrier, mcast_mask_sfb, WHint{kHB}), tBgSFB(_,*k_tile_iter), tBsSFB(_,write_stage)); + } + } + --k_tile_count; + ++k_tile_iter; + } + return cute::make_tuple(state, k_tile_iter); + } + + // Steady-state load (replaces CollectiveMma::load when RawW): A (weight), B, SFB by TMA; + // the weight SF (SFA) of the same stage is gathered by the epilogue warps (raw_wsf_stage_epi). + template + CUTLASS_DEVICE auto + load_raw(MainloopPipeline mainloop_pipeline, MainloopPipelineState state, + LoadParams const& load_inputs, TileCoordMNKL const& cta_coord_mnkl, + KTileIterator k_tile_iter, int k_tile_count, RawWsf const& rw) { + auto [unused_k_tiles, + tAgA_mkl, tBgB_nkl, tAsA, tBsB, + tAgSFA_mkl, tBgSFB_nkl, tAsSFA, tBsSFB, + mcast_mask_a, mcast_mask_b, mcast_mask_sfa, mcast_mask_sfb] = load_inputs; + Tensor tAgA = tAgA_mkl(_, get<0>(cta_coord_mnkl) / size(typename TiledMma::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgB = tBgB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + Tensor tBgSFB = tBgSFB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + const bool elect_leader = cute::elect_one_sync(); + CUTLASS_PRAGMA_NO_UNROLL + while (k_tile_count > 0) { + if (rw.empty != 0u) { + mbar_wait_sleep(rw.empty + uint32_t(state.index()) * 8u, state.phase()); + mainloop_pipeline.producer_acquire(state, decltype(mainloop_pipeline.producer_try_acquire(state)){cutlass::BarrierStatus::WaitDone}); + } else { + mainloop_pipeline.producer_acquire(state); + } + using BarrierType = typename MainloopPipeline::ProducerBarrierType; + BarrierType* tma_barrier = mainloop_pipeline.producer_get_barrier(state); + int write_stage = state.index(); + ++state; + if (elect_leader) { + copy(this->observed_tma_load_a_->with(*tma_barrier, mcast_mask_a, WHint{kHA}), tAgA(_,*k_tile_iter), tAsA(_,write_stage)); + copy(this->observed_tma_load_b_->with(*tma_barrier, mcast_mask_b, WHint{kHB}), tBgB(_,*k_tile_iter), tBsB(_,write_stage)); + copy(this->observed_tma_load_sfb_->with(*tma_barrier, mcast_mask_sfb, WHint{kHB}), tBgSFB(_,*k_tile_iter), tBsSFB(_,write_stage)); + if constexpr (WPref) { // weight (MMA-A) L2 prefetch kWPrefDist k-tiles ahead + const int kp = int(cute::get<0>(cute::wrap(*k_tile_iter))) + kWPrefDist; + if (kp < int(size<1>(tAgA))) prefetch_w(this->observed_tma_load_a_, tAgA, kp); + } + } + --k_tile_count; + ++k_tile_iter; + } + return cute::make_tuple(state, k_tile_iter); + } +}; + +// Derived kernel: same Params / SharedStorage / launch config as the CUTLASS kernel; only +// operator() is replaced (copied verbatim from CUTLASS 4.2 apart from the [PDL weight-first] +// edits in the mainloop-load warp and the derived collective type). +template +struct PdlWeightFirstKernel : Base { + static constexpr uint32_t kTmaStSmemOff = (uint32_t(Base::SharedStorageSize) + 1023u) & ~1023u; + static constexpr uint32_t kTmaStBufs = 3u; + static constexpr uint32_t kTmaStSmemBytes = TmaSt ? uint32_t(EpiWG) * 4u * kTmaStBufs * 1024u : 0u; + static constexpr uint32_t kSmemTotal = kTmaStSmemOff + kTmaStSmemBytes; + static constexpr bool kRs = CustomEpi && (EpiWG == 2) && WPrefFirst && !TmaSt && !WeightIsA && !RawW; + static constexpr uint32_t kRsSmemOff = (uint32_t(Base::SharedStorageSize) + 127u) & ~127u; + static constexpr uint32_t kRsSmemTotal = kRsSmemOff + 4u * 1024u + 64u; + static_assert(EpiWG == 1 || (EpiWG == 2 && CustomEpi), "EpiWG=2 requires CustomEpi"); + static constexpr uint32_t MaxThreadsPerBlock = Base::MaxThreadsPerBlock + uint32_t(EpiWG - 1) * 128u; + static constexpr uint32_t MinBlocksPerMultiprocessor = Base::MinBlocksPerMultiprocessor; + static dim3 get_block_shape() { return dim3(MaxThreadsPerBlock, 1, 1); } + // Arguments / Params extended with the raw weight-SF pointer (RawW); everything else is the + // CUTLASS kernel's (base-class conversions are used by the device adapter's static helpers). + struct Arguments : Base::Arguments { + const uint8_t* raw_wsf = nullptr; + const uint8_t* resid = nullptr; // residual (= C, row-major [tokens][cols] bf16) for L2 prefetch + uint8_t* out = nullptr; // CustomEpi: D (row-major [tokens][cols] bf16) + const float* alpha = nullptr; // CustomEpi: device scalar alpha + }; + struct Params : Base::Params { + const uint8_t* raw_wsf = nullptr; + int raw_rows = 0; + int raw_ksf = 0; + const uint8_t* resid = nullptr; + int res_tokens = 0; // output rows (tokens) + int res_cols = 0; // output cols (= residual leading dimension) + uint8_t* out = nullptr; + const float* alpha = nullptr; + int tma_st = 0; // TmaSt: out_tmap valid + CUtensorMap out_tmap; // TmaSt: D as 2D bf16 {cols, tokens}, box {16, 32} + }; + struct NoSfa {}; + using TmaW = std::conditional_t; + using TmaSfaK = std::conditional_t; + struct CallParams { + TmaW w_tma; + TmaSfaK sfa_tma; + typename Base::CollectiveEpilogue::Params epilogue; + const uint8_t* raw_wsf; + const uint8_t* resid; + uint8_t* out; + const float* alpha; + }; + static void make_call(CallParams& c, Params const& p) { + if constexpr (WeightIsA) c.w_tma = p.mainloop.tma_load_a; else c.w_tma = p.mainloop.tma_load_b; + if constexpr (RawW) c.sfa_tma = p.mainloop.tma_load_sfa; + c.epilogue = p.epilogue; + c.raw_wsf = p.raw_wsf; c.resid = p.resid; c.out = p.out; c.alpha = p.alpha; + } + static Params to_underlying_arguments(Arguments const& args, void* workspace) { + Params p; + static_cast(p) = Base::to_underlying_arguments(args, workspace); + p.raw_wsf = args.raw_wsf; + p.raw_rows = WeightIsA ? int(get<0>(args.problem_shape)) : int(get<1>(args.problem_shape)); + p.raw_ksf = int(get<2>(args.problem_shape)) / 16; + p.resid = args.resid; + p.res_tokens = WeightIsA ? int(get<1>(args.problem_shape)) : int(get<0>(args.problem_shape)); + p.res_cols = WeightIsA ? int(get<0>(args.problem_shape)) : int(get<1>(args.problem_shape)); + p.out = args.out; + p.alpha = args.alpha; + p.tma_st = 0; + std::memset(&p.out_tmap, 0, sizeof(p.out_tmap)); + if constexpr (TmaSt) { + if (args.out != nullptr && p.res_cols % 16 == 0 && (reinterpret_cast(args.out) & 15) == 0) { + cuuint64_t gdim[2] = {cuuint64_t(p.res_cols), cuuint64_t(p.res_tokens)}; + cuuint64_t gstr[1] = {cuuint64_t(p.res_cols) * 2u}; + cuuint32_t box[2] = {16u, 32u}; + cuuint32_t es[2] = {1u, 1u}; + CUresult r = CUTLASS_CUDA_DRIVER_WRAPPER_CALL(cuTensorMapEncodeTiled)( + &p.out_tmap, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, (void*)args.out, gdim, gstr, 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); + p.tma_st = (r == CUDA_SUCCESS) ? 1 : 0; + } + } + return p; + } + static void patch_epi(Params& p, Arguments const& args) { + p.resid = args.resid; + p.out = args.out; + p.alpha = args.alpha; + p.tma_st = 0; + std::memset(&p.out_tmap, 0, sizeof(p.out_tmap)); + if constexpr (TmaSt) { + if (args.out != nullptr && p.res_cols % 16 == 0 && (reinterpret_cast(args.out) & 15) == 0) { + cuuint64_t gdim[2] = {cuuint64_t(p.res_cols), cuuint64_t(p.res_tokens)}; + cuuint64_t gstr[1] = {cuuint64_t(p.res_cols) * 2u}; + cuuint32_t box[2] = {16u, 32u}; + cuuint32_t es[2] = {1u, 1u}; + CUresult r = CUTLASS_CUDA_DRIVER_WRAPPER_CALL(cuTensorMapEncodeTiled)( + &p.out_tmap, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, (void*)args.out, gdim, gstr, 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); + p.tma_st = (r == CUDA_SUCCESS) ? 1 : 0; + } + } + } + + // [Residual L2 prefetch] One warp (lane = 0..31) issues cp.async.bulk.prefetch.L2 for the + // residual rows of the CTA tile at cta coordinate `coord` (one row segment of CtaN/CtaM bf16 + // = 256 B per token row; 16 B aligned, size multiple of 16 since cols % 8 == 0). The residual + // is a read-only kernel input, so this is legal before griddepcontrol.wait; it is only a hint + // (no completion tracking) -> the epilogue's residual TMA later hits L2 instead of DRAM. + template + CUTLASS_DEVICE static void prefetch_residual(Params const& params, const uint8_t* resid, Coord const& coord, int lane) { + if (resid == nullptr) return; + constexpr int CM = int(size<0>(CtaShape_MNK{})), CN = int(size<1>(CtaShape_MNK{})); + int tok0, ntok, col0, ncol; + if constexpr (WeightIsA) { // swap-AB: MMA-M = output cols, MMA-N = tokens + col0 = int(get<0>(coord)) * CM; ncol = CM; tok0 = int(get<1>(coord)) * CN; ntok = CN; + } else { + tok0 = int(get<0>(coord)) * CM; ntok = CM; col0 = int(get<1>(coord)) * CN; ncol = CN; + } + const int nc = min(ncol, params.res_cols - col0); + if (nc <= 0 || (nc & 7) != 0) return; + const uint32_t bytes = uint32_t(nc) * 2u; + for (int t = lane; t < ntok; t += 32) { + const int r = tok0 + t; + if (r >= params.res_tokens) break; + const uint8_t* p = resid + ((size_t)r * params.res_cols + col0) * 2; + asm volatile("cp.async.bulk.prefetch.L2.global [%0], %1;" :: "l"(p), "r"(bytes) : "memory"); + } + } + using ProblemShape = typename Base::ProblemShape; + using WarpCategory = typename Base::WarpCategory; + using IsParticipant = typename Base::IsParticipant; + using SharedStorage = typename Base::SharedStorage; + using CollectiveMainloop = typename Base::CollectiveMainloop; + using CollectiveEpilogue = typename Base::CollectiveEpilogue; + using PdlMainloop = PdlWeightFirstMainloop; + using TiledMma = typename Base::TiledMma; + using TileShape = typename Base::TileShape; + using AtomThrShapeMNK = typename Base::AtomThrShapeMNK; + using CtaShape_MNK = typename Base::CtaShape_MNK; + using ClusterShape = typename Base::ClusterShape; + using EpilogueTile = typename Base::EpilogueTile; + using TileScheduler = typename Base::TileScheduler; + using MainloopPipeline = typename Base::MainloopPipeline; + using MainloopPipelineState = typename Base::MainloopPipelineState; + using EpiLoadPipeline = typename Base::EpiLoadPipeline; + using EpiLoadPipelineState = typename Base::EpiLoadPipelineState; + using EpiStorePipeline = typename Base::EpiStorePipeline; + using EpiStorePipelineState = typename Base::EpiStorePipelineState; + using LoadOrderBarrier = typename Base::LoadOrderBarrier; + using AccumulatorPipeline = typename Base::AccumulatorPipeline; + using AccumulatorPipelineState = typename Base::AccumulatorPipelineState; + using CLCPipeline = typename Base::CLCPipeline; + using CLCPipelineState = typename Base::CLCPipelineState; + using CLCThrottlePipeline = typename Base::CLCThrottlePipeline; + using CLCThrottlePipelineState = typename Base::CLCThrottlePipelineState; + using TmemAllocator = typename Base::TmemAllocator; + static constexpr bool IsComplex = Base::IsComplex; + static constexpr bool IsOverlappingAccum = Base::IsOverlappingAccum; + static constexpr bool IsSchedDynamicPersistent = Base::IsSchedDynamicPersistent; + static constexpr uint32_t NumSchedThreads = Base::NumSchedThreads; + static constexpr uint32_t NumMMAThreads = Base::NumMMAThreads; + static constexpr uint32_t NumMainloopLoadThreads = Base::NumMainloopLoadThreads; + static constexpr uint32_t NumEpilogueLoadThreads = Base::NumEpilogueLoadThreads; + static constexpr uint32_t NumEpilogueThreads = Base::NumEpilogueThreads; + static constexpr uint32_t NumEpiThr = NumEpilogueThreads * uint32_t(EpiWG); // all epilogue warps + static constexpr uint32_t CLCResponseSize = Base::CLCResponseSize; + + template + CUTLASS_DEVICE + void + impl(Params const& params, KP const& kp, char* smem_buf) { + + using namespace cute; + using X = Underscore; + + auto problem_shape_MNKL = append<4>(params.problem_shape, Int<1>{}); + auto [M,N,K,L] = problem_shape_MNKL; + + int warp_idx = canonical_warp_idx_sync(); + WarpCategory warp_category = warp_idx < static_cast(WarpCategory::Epilogue) ? WarpCategory(warp_idx) + : WarpCategory::Epilogue; + + uint32_t lane_predicate = cute::elect_one_sync(); + auto cluster_shape = cutlass::detail::select_cluster_shape(ClusterShape{}); + int cluster_size = size(cluster_shape); + uint32_t cta_rank_in_cluster = cute::block_rank_in_cluster(); + bool is_first_cta_in_cluster = cta_rank_in_cluster == 0; + int cta_coord_v = cta_rank_in_cluster % size<0>(typename TiledMma::AtomThrID{}); + bool is_mma_leader_cta = cta_coord_v == 0; + constexpr bool has_mma_peer_cta = size(AtomThrShapeMNK{}) == 2; + [[maybe_unused]] uint32_t mma_peer_cta_rank = has_mma_peer_cta ? cta_rank_in_cluster ^ 1 : cta_rank_in_cluster; + + SharedStorage& shared_storage = *reinterpret_cast(smem_buf); + + PdlMainloop collective_mainloop(params.mainloop, cluster_shape, cta_rank_in_cluster); + if constexpr (std::is_same_v) collective_mainloop.set_w(&kp.w_tma, &kp.sfa_tma); + CollectiveEpilogue collective_epilogue(kp.epilogue, shared_storage.tensors.epilogue); + + if ((warp_category == WarpCategory::Sched) && lane_predicate) { + collective_mainloop.prefetch_tma_descriptors(); + } + if constexpr (!CustomEpi) { + if ((warp_category == WarpCategory::EpilogueLoad) && lane_predicate) { + collective_epilogue.prefetch_tma_descriptors(kp.epilogue); + } + } + + // CustomEpi: no epilogue TMA loads; the epilogue-load warp still runs (residual L2 prefetch + // only) and therefore consumes CLC responses like the other warps. + constexpr bool kPeerMmaIdle = CustomEpi && EpiWG == 2 && has_mma_peer_cta && !IsOverlappingAccum; + bool is_epi_load_needed = CustomEpi ? false : collective_epilogue.is_producer_load_needed(); + constexpr bool kNextResPref = CustomEpi && EpiWG == 2 && WPrefFirst && !WeightIsA; + const bool epi_load_active = CustomEpi ? kNextResPref : is_epi_load_needed; + IsParticipant is_participant = { + (warp_category == WarpCategory::MMA), // mma + (warp_category == WarpCategory::Sched) && is_first_cta_in_cluster, // sched + (warp_category == WarpCategory::MainloopLoad), // main_load + (warp_category == WarpCategory::EpilogueLoad) && epi_load_active, // epi_load + (warp_category == WarpCategory::Epilogue) // epilogue + }; + + typename MainloopPipeline::Params mainloop_pipeline_params; + if (WarpCategory::MainloopLoad == warp_category) { + mainloop_pipeline_params.role = MainloopPipeline::ThreadCategory::Producer; + } + if (WarpCategory::MMA == warp_category) { + mainloop_pipeline_params.role = MainloopPipeline::ThreadCategory::Consumer; + } + mainloop_pipeline_params.is_leader = lane_predicate && is_mma_leader_cta && is_participant.main_load; + // RawW: the weight SF arrives by st.shared from the epilogue warps (tracked as mbarrier arrivals, not tx bytes) + mainloop_pipeline_params.transaction_bytes = + CollectiveMainloop::TmaTransactionBytes - (RawW ? PdlMainloop::RawStageBytes : 0u); + mainloop_pipeline_params.initializing_warp = 0; + MainloopPipeline mainloop_pipeline(shared_storage.pipelines.mainloop, + mainloop_pipeline_params, + cluster_shape, + cute::true_type{}, // Perform barrier init + cute::false_type{}); // Delay mask calculation + if constexpr (RawW) { + // Full barriers expect 1 (producer arrive_and_expect_tx) + NumEpilogueThreads + // (mbarrier.arrive of the epilogue-warp weight-SF gather, after its st.shared + proxy fence) arrivals. + // Same warp as the pipeline's barrier init (initializing_warp 0), before the cluster + // init fence / sync below. + if (warp_idx == 0) { + __syncwarp(); + if (lane_predicate) { + CUTLASS_PRAGMA_UNROLL + for (int st = 0; st < MainloopPipeline::Stages; ++st) + shared_storage.pipelines.mainloop.full_barrier_[st].init(1 + NumEpilogueThreads / 32); // 1 arrive per gather warp + } + cutlass::arch::fence_barrier_init(); + } + } + + typename EpiLoadPipeline::Params epi_load_pipeline_params; + if (WarpCategory::EpilogueLoad == warp_category) { + epi_load_pipeline_params.role = EpiLoadPipeline::ThreadCategory::Producer; + } + if (WarpCategory::Epilogue == warp_category) { + epi_load_pipeline_params.role = EpiLoadPipeline::ThreadCategory::Consumer; + } + epi_load_pipeline_params.dst_blockid = cta_rank_in_cluster; + epi_load_pipeline_params.producer_arv_count = NumEpilogueLoadThreads; + epi_load_pipeline_params.consumer_arv_count = NumEpilogueThreads; + epi_load_pipeline_params.transaction_bytes = CollectiveEpilogue::TmaTransactionBytes; + epi_load_pipeline_params.initializing_warp = 1; + EpiLoadPipeline epi_load_pipeline(shared_storage.pipelines.epi_load, epi_load_pipeline_params); + + typename EpiStorePipeline::Params epi_store_pipeline_params; + epi_store_pipeline_params.always_wait = true; + EpiStorePipeline epi_store_pipeline(epi_store_pipeline_params); + + typename LoadOrderBarrier::Params load_order_barrier_params; + load_order_barrier_params.group_id = (warp_category == WarpCategory::MainloopLoad) ? 0 : 1; + load_order_barrier_params.group_size = NumMainloopLoadThreads; + load_order_barrier_params.initializing_warp = 3; + LoadOrderBarrier load_order_barrier(shared_storage.pipelines.load_order, load_order_barrier_params); + + typename CLCPipeline::Params clc_pipeline_params; + if (WarpCategory::Sched == warp_category) { + clc_pipeline_params.role = CLCPipeline::ThreadCategory::ProducerConsumer; + } + else { + clc_pipeline_params.role = CLCPipeline::ThreadCategory::Consumer; + } + clc_pipeline_params.producer_blockid = 0; + clc_pipeline_params.producer_arv_count = 1; + clc_pipeline_params.consumer_arv_count = NumSchedThreads + cluster_size * + (NumMainloopLoadThreads + NumEpiThr + NumMMAThreads); + if (epi_load_active) { + clc_pipeline_params.consumer_arv_count += cluster_size * NumEpilogueLoadThreads; + } + if constexpr (kPeerMmaIdle) { + clc_pipeline_params.consumer_arv_count -= uint32_t(cluster_size / 2) * NumMMAThreads; + } + clc_pipeline_params.transaction_bytes = CLCResponseSize; + clc_pipeline_params.initializing_warp = 4; + CLCPipeline clc_pipeline(shared_storage.pipelines.clc, clc_pipeline_params, cluster_shape); + + typename AccumulatorPipeline::Params accumulator_pipeline_params; + if (WarpCategory::MMA == warp_category) { + accumulator_pipeline_params.role = AccumulatorPipeline::ThreadCategory::Producer; + } + if (WarpCategory::Epilogue == warp_category) { + accumulator_pipeline_params.role = AccumulatorPipeline::ThreadCategory::Consumer; + } + accumulator_pipeline_params.producer_arv_count = 1; + accumulator_pipeline_params.consumer_arv_count = CustomEpi ? size(AtomThrShapeMNK{}) * (NumEpiThr / 32) + : size(AtomThrShapeMNK{}) * NumEpiThr; + accumulator_pipeline_params.initializing_warp = 5; + AccumulatorPipeline accumulator_pipeline(shared_storage.pipelines.accumulator, + accumulator_pipeline_params, + cluster_shape, + cute::true_type{}, // Perform barrier init + cute::false_type{}); // Delay mask calculation + + typename CLCThrottlePipeline::Params clc_throttle_pipeline_params; + if (WarpCategory::MainloopLoad == warp_category) { + clc_throttle_pipeline_params.role = CLCThrottlePipeline::ThreadCategory::Producer; + } + if (WarpCategory::Sched == warp_category) { + clc_throttle_pipeline_params.role = CLCThrottlePipeline::ThreadCategory::Consumer; + } + clc_throttle_pipeline_params.producer_arv_count = NumMainloopLoadThreads; + clc_throttle_pipeline_params.consumer_arv_count = NumSchedThreads; + clc_throttle_pipeline_params.dst_blockid = 0; + clc_throttle_pipeline_params.initializing_warp = 3; + CLCThrottlePipeline clc_throttle_pipeline(shared_storage.pipelines.clc_throttle, clc_throttle_pipeline_params); + CLCThrottlePipelineState clc_pipe_throttle_consumer_state; + CLCThrottlePipelineState clc_pipe_throttle_producer_state = cutlass::make_producer_start_state(); + + TmemAllocator tmem_allocator{}; + + arch::NamedBarrier tmem_allocation_result_barrier(NumMMAThreads + NumEpiThr, cutlass::arch::ReservedNamedBarriers::TmemAllocBarrier); + arch::ClusterBarrier& tmem_deallocation_result_barrier = shared_storage.pipelines.tmem_dealloc; + [[maybe_unused]] uint32_t dealloc_barrier_phase = 0; + if (WarpCategory::MMA == warp_category) { + if constexpr(!IsOverlappingAccum) { + if (has_mma_peer_cta && lane_predicate) { + tmem_deallocation_result_barrier.init(NumMMAThreads); + } + } + else { + if (has_mma_peer_cta && lane_predicate) { + tmem_deallocation_result_barrier.init(NumEpilogueThreads*2); + } + else if (lane_predicate) { + tmem_deallocation_result_barrier.init(NumEpilogueThreads); + } + } + } + + pipeline_init_arrive_relaxed(cluster_size); + + auto load_inputs = collective_mainloop.load_init( + problem_shape_MNKL, shared_storage.tensors.mainloop); + + MainloopPipelineState mainloop_pipe_consumer_state; + MainloopPipelineState mainloop_pipe_producer_state = cutlass::make_producer_start_state(); + + EpiLoadPipelineState epi_load_pipe_consumer_state; + EpiLoadPipelineState epi_load_pipe_producer_state = cutlass::make_producer_start_state(); + + EpiStorePipelineState epi_store_pipe_producer_state = cutlass::make_producer_start_state(); + + CLCPipelineState clc_pipe_consumer_state; + CLCPipelineState clc_pipe_producer_state = cutlass::make_producer_start_state(); + + AccumulatorPipelineState accumulator_pipe_consumer_state; + AccumulatorPipelineState accumulator_pipe_producer_state = cutlass::make_producer_start_state(); + + dim3 block_id_in_cluster = cute::block_id_in_cluster(); + + mainloop_pipeline.init_masks(cluster_shape, block_id_in_cluster); + accumulator_pipeline.init_masks(cluster_shape, block_id_in_cluster); + + TileScheduler scheduler(&shared_storage.clc_response[0], params.scheduler, block_id_in_cluster); + constexpr bool kNoClc = (CustomEpi && EpiWG == 2 && !WPrefFirst && !WeightIsA && + int(size<1>(CtaShape_MNK{})) == 128) || (RawW && WeightIsA); + auto fetch_nw = [&](auto const& wti, auto& pipe, auto const& st) { + if constexpr (kNoClc) { + auto w = wti; + w.is_valid_tile = false; + return cute::make_tuple(w, false); + } else { + return scheduler.fetch_next_work(wti, pipe, st); + } + }; + typename TileScheduler::WorkTileInfo work_tile_info = scheduler.initial_work_tile_info(cluster_shape); + auto cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + auto tmem_storage = collective_mainloop.template init_tmem_tensors(EpilogueTile{}); + + pipeline_init_wait(cluster_size); + + cutlass::arch::launch_dependent_grids(); + + if (is_participant.main_load) { + // RawW: raw weight-SF source + the weight-SF (MMA-A SF) smem buffer + const RawWsf raw_w{kp.raw_wsf, params.raw_rows, params.raw_ksf, + cute::cast_smem_ptr_to_uint(shared_storage.tensors.mainloop.smem_SFA.begin()), + cute::cast_smem_ptr_to_uint(&shared_storage.pipelines.mainloop.empty_barrier_[0])}; + bool pref_tile = true; // WPrefFirst: true only while loading the first work tile + auto load_main = [&](MainloopPipelineState st, auto kit, int cnt) { + if constexpr (RawW) { + return collective_mainloop.load_raw(mainloop_pipeline, st, load_inputs, cta_coord_mnkl, kit, cnt, raw_w); + } else { + if constexpr (WPref) { + if (!WPrefFirst || pref_tile) + return collective_mainloop.load_std(mainloop_pipeline, st, load_inputs, cta_coord_mnkl, kit, cnt); + return collective_mainloop.load_hint(mainloop_pipeline, st, load_inputs, cta_coord_mnkl, kit, cnt); + } else { + return collective_mainloop.load_hint(mainloop_pipeline, st, load_inputs, cta_coord_mnkl, kit, cnt); + } + } + }; + // [PDL weight-first] Before griddepcontrol.wait: acquire the first n_pre stages of the + // FIRST work tile and issue only the weight-operand TMA loads (the FP4 weight is a + // read-only kernel input -- no producer kernel writes it). Activation / SF loads of the + // same stages are issued after the wait (SFB = swizzled weight SF comes from kernel 1). + constexpr int kCNp = int(size<1>(CtaShape_MNK{})); + constexpr bool kPrefDedup = CustomEpi && EpiWG == 2 && WPref && !WPrefFirst && !WeightIsA && + (kCNp == 224 || kCNp == 176); + constexpr bool kPrefM0 = CustomEpi && EpiWG == 2 && WPref && WPrefFirst && !WeightIsA; + auto set_pref_tile = [&]() { + if constexpr (kPrefM0) + collective_mainloop.pref_on_ = + (int(get<0>(cta_coord_mnkl)) / int(size(typename TiledMma::AtomThrID{}))) == 0; + if constexpr (kPrefDedup) + collective_mainloop.pref_on_ = (kCNp == 176) + ? (int(get<0>(cta_coord_mnkl)) / int(size(typename TiledMma::AtomThrID{}))) == 0 + : ((int(get<0>(cta_coord_mnkl)) / int(size(typename TiledMma::AtomThrID{}))) & 1) == 0; + }; + int n_pre = 0; + auto pre_k_tile_iter = scheduler.get_k_tile_iterator(work_tile_info, problem_shape_MNKL, CtaShape_MNK{}, load_inputs.k_tiles); + MainloopPipelineState pre_state = mainloop_pipe_producer_state; + if (work_tile_info.is_valid()) { + auto k_tile_count0 = TileScheduler::get_work_k_tile_count(work_tile_info, problem_shape_MNKL, CtaShape_MNK{}); + // pre-issue the weight TMA for only Stages-2 stages; the last 2 stage + // slots of the first tile are loaded in full (weight + act + SFB) after the PDL wait. + constexpr int kPreStages = RawW ? (MainloopPipeline::Stages > 2 ? MainloopPipeline::Stages - 2 : 1) + : MainloopPipeline::Stages; + n_pre = min(kPreStages, k_tile_count0); + set_pref_tile(); + if constexpr (CustomEpi && EpiWG == 2 && WPref && !WPrefFirst && !WeightIsA && kCNp == 224) { + const int nN = int(size<1>(load_inputs.tBgB_nkl)); + const int mt = int(get<0>(cta_coord_mnkl)) / int(size(typename TiledMma::AtomThrID{})); + const int nt = int(get<1>(cta_coord_mnkl)); + collective_mainloop.mirror_n_ = (mt == 0 && nt >= 3 && nt + 18 < nN && nt <= 18) ? nt + 18 : -1; + } + if constexpr (CustomEpi && EpiWG == 2 && WPref && !WPrefFirst && !WeightIsA && kCNp == 128) { + const int nN = int(size<1>(load_inputs.tBgB_nkl)); + const int mt = int(get<0>(cta_coord_mnkl)) / int(size(typename TiledMma::AtomThrID{})); + const int nt = int(get<1>(cta_coord_mnkl)); + collective_mainloop.mirror_n_ = (mt == 0 && nt < 16 && nt + 48 < nN) ? nt + 48 : -1; + } + if constexpr (CustomEpi && EpiWG == 2 && WPref && !WPrefFirst && !WeightIsA && kCNp == 176) { + const int nN = int(size<1>(load_inputs.tBgB_nkl)); + const int nM = (int(get<0>(problem_shape_MNKL)) + 255) / 256; + const int mt = int(get<0>(cta_coord_mnkl)) / int(size(typename TiledMma::AtomThrID{})); + const int nt = int(get<1>(cta_coord_mnkl)); + const int c = nt * nM + mt; + const int tg = 9 + (2 * c) / 3; + collective_mainloop.mirror_n_ = (c < 24 && tg < nN) ? tg : -1; + } + collective_mainloop.load_weight_pre(mainloop_pipeline, mainloop_pipe_producer_state, + load_inputs, cta_coord_mnkl, pre_k_tile_iter, n_pre, raw_w); + } + + // Ensure that the prefetched kernel does not touch + // unflushed global memory prior to this instruction + cutlass::arch::wait_on_dependent_grids(); + + bool do_load_order_arrive = is_epi_load_needed; + bool requires_clc_query = true; + bool first_tile = true; + int clc_thr_fresh = int(CLCThrottlePipeline::Stages); + + do { + auto k_tile_iter = scheduler.get_k_tile_iterator(work_tile_info, problem_shape_MNKL, CtaShape_MNK{}, load_inputs.k_tiles); + auto k_tile_count = TileScheduler::get_work_k_tile_count(work_tile_info, problem_shape_MNKL, CtaShape_MNK{}); + auto k_tile_prologue = min(MainloopPipeline::Stages, k_tile_count); + if (first_tile && n_pre > 0) k_tile_prologue = n_pre; // pre-acquired stages only + set_pref_tile(); + + if constexpr (IsSchedDynamicPersistent) { + if (!kNoClc && is_first_cta_in_cluster && requires_clc_query) { + if (clc_thr_fresh > 0) { + --clc_thr_fresh; + clc_throttle_pipeline.producer_acquire(clc_pipe_throttle_producer_state, + decltype(clc_throttle_pipeline.producer_try_acquire(clc_pipe_throttle_producer_state)){cutlass::BarrierStatus::WaitDone}); + } else { + clc_throttle_pipeline.producer_acquire(clc_pipe_throttle_producer_state); + } + clc_throttle_pipeline.producer_commit(clc_pipe_throttle_producer_state); + ++clc_pipe_throttle_producer_state; + } + } + + // Start mainloop prologue loads, arrive on the epilogue residual load barrier, resume mainloop loads + // [PDL weight-first] first tile: its prologue stages are already acquired and carry the + // weight loads -> issue only the remaining operands (n_pre == k_tile_prologue here). + auto [mainloop_producer_state_next, k_tile_iter_next] = (first_tile && n_pre > 0) + ? collective_mainloop.load_rest_post( + mainloop_pipeline, + pre_state, + load_inputs, + cta_coord_mnkl, + k_tile_iter, k_tile_prologue) + : load_main(mainloop_pipe_producer_state, k_tile_iter, k_tile_prologue); + first_tile = false; + mainloop_pipe_producer_state = mainloop_producer_state_next; + + if (do_load_order_arrive) { + load_order_barrier.arrive(); + do_load_order_arrive = false; + } + + auto [mainloop_producer_state_next_, unused_] = load_main( + mainloop_pipe_producer_state, k_tile_iter_next, k_tile_count - k_tile_prologue); + mainloop_pipe_producer_state = mainloop_producer_state_next_; + pref_tile = false; + + __syncwarp(); + auto [next_work_tile_info, increment_pipe] = fetch_nw( + work_tile_info, + clc_pipeline, + clc_pipe_consumer_state + ); + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + requires_clc_query = increment_pipe; + if (increment_pipe) { + ++clc_pipe_consumer_state; + } + } while (work_tile_info.is_valid()); + collective_mainloop.load_tail(mainloop_pipeline, mainloop_pipe_producer_state); + + } + + else if (is_participant.sched) { + if constexpr (IsSchedDynamicPersistent && !kNoClc) { + bool requires_clc_query = true; + + constexpr int kCN_ = int(size<1>(CtaShape_MNK{})); + constexpr bool kSchedNoWait = CustomEpi && EpiWG == 2 && (kCN_ > 0); + if constexpr (!kSchedNoWait) cutlass::arch::wait_on_dependent_grids(); + + do { + if (requires_clc_query) { + clc_throttle_pipeline.consumer_wait(clc_pipe_throttle_consumer_state); + clc_throttle_pipeline.consumer_release(clc_pipe_throttle_consumer_state); + ++clc_pipe_throttle_consumer_state; + + clc_pipe_producer_state = scheduler.advance_to_next_work(clc_pipeline, clc_pipe_producer_state); + } + + auto [next_work_tile_info, increment_pipe] = fetch_nw( + work_tile_info, + clc_pipeline, + clc_pipe_consumer_state + ); + + requires_clc_query = increment_pipe; + if (increment_pipe) { + ++clc_pipe_consumer_state; + } + + work_tile_info = next_work_tile_info; + } while (work_tile_info.is_valid()); + clc_pipeline.producer_tail(clc_pipe_producer_state); + } + } + + else if (is_participant.mma) { + tmem_allocator.allocate(TmemAllocator::Sm100TmemCapacityColumns, &shared_storage.tmem_base_ptr); + __syncwarp(); + tmem_allocation_result_barrier.arrive(); + uint32_t tmem_base_ptr = shared_storage.tmem_base_ptr; + collective_mainloop.set_tmem_offsets(tmem_storage, tmem_base_ptr); + + auto mma_inputs = collective_mainloop.mma_init( + tmem_storage, + shared_storage.tensors.mainloop); + + const bool peer_skip = kPeerMmaIdle && !is_mma_leader_cta; + int acc_uses = 0; + const int mma_elect = cute::elect_one_sync() ? 1 : 0; + if (!peer_skip) do { + auto k_tile_count = TileScheduler::get_work_k_tile_count(work_tile_info, problem_shape_MNKL, CtaShape_MNK{}); + + auto [next_work_tile_info, increment_pipe] = fetch_nw( + work_tile_info, + clc_pipeline, + clc_pipe_consumer_state + ); + + if (increment_pipe) { + ++clc_pipe_consumer_state; + } + + int acc_stage = [&] () { + if constexpr (IsOverlappingAccum) { + return accumulator_pipe_producer_state.phase() ^ 1; + } + else { + return accumulator_pipe_producer_state.index(); + } + }(); + + if (is_mma_leader_cta) { + if constexpr (HasAccFirstSkip::value) { + const bool acc_first_use = acc_uses < int(AccumulatorPipeline::Stages); + mainloop_pipe_consumer_state = collective_mainloop.mma( + cute::make_tuple(mainloop_pipeline, accumulator_pipeline), + cute::make_tuple(mainloop_pipe_consumer_state, accumulator_pipe_producer_state), + collective_mainloop.slice_accumulator(tmem_storage, acc_stage), + mma_inputs, + cta_coord_mnkl, + k_tile_count, + acc_first_use, + mma_elect, + cute::cast_smem_ptr_to_uint(&shared_storage.pipelines.mainloop.empty_barrier_[0]) + ); + } else { + mainloop_pipe_consumer_state = collective_mainloop.mma( + cute::make_tuple(mainloop_pipeline, accumulator_pipeline), + cute::make_tuple(mainloop_pipe_consumer_state, accumulator_pipe_producer_state), + collective_mainloop.slice_accumulator(tmem_storage, acc_stage), + mma_inputs, + cta_coord_mnkl, + k_tile_count + ); + } + accumulator_pipeline.producer_commit(accumulator_pipe_producer_state); + } + ++accumulator_pipe_producer_state; + ++acc_uses; + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + } while (work_tile_info.is_valid()); + + tmem_allocator.release_allocation_lock(); + + if constexpr (!IsOverlappingAccum) { + if (is_mma_leader_cta) { + accumulator_pipeline.producer_tail(accumulator_pipe_producer_state); + } + if constexpr (has_mma_peer_cta) { + tmem_deallocation_result_barrier.arrive(mma_peer_cta_rank, not is_mma_leader_cta); + tmem_deallocation_result_barrier.wait(dealloc_barrier_phase); + tmem_deallocation_result_barrier.arrive(mma_peer_cta_rank, is_mma_leader_cta); + } + } + else { + tmem_deallocation_result_barrier.wait(dealloc_barrier_phase); + } + + tmem_allocator.free(tmem_base_ptr, TmemAllocator::Sm100TmemCapacityColumns); + } + + else if (is_participant.epi_load) { + if constexpr (CustomEpi) { + // [CustomEpi] residual L2 prefetch only: first tile (before the PDL wait; read-only input), + // then every next tile as soon as the CLC response is known (~one tile ahead). + const int epi_lane = int(threadIdx.x & 31); + if (!kNextResPref && work_tile_info.is_valid()) prefetch_residual(params, kp.resid, cta_coord_mnkl, epi_lane); + do { + auto [next_work_tile_info, increment_pipe] = fetch_nw( + work_tile_info, clc_pipeline, clc_pipe_consumer_state); + work_tile_info = next_work_tile_info; + if (work_tile_info.is_valid()) { + const auto nco = scheduler.work_tile_to_cta_coord(work_tile_info); + prefetch_residual(params, kp.resid, nco, epi_lane); + if constexpr (kNextResPref && (WPrefDist == 4 || WPrefDist == 16)) { + if (epi_lane == 0 && (int(get<0>(nco)) / int(size(typename TiledMma::AtomThrID{}))) == 0) + collective_mainloop.prefetch_w_head(load_inputs, nco, 2 * int(MainloopPipeline::Stages)); + } + } + if (increment_pipe) { + ++clc_pipe_consumer_state; + } + } while (work_tile_info.is_valid()); + } else { + // [Residual L2 prefetch] first work tile's residual rows, before the PDL wait. + const int epi_lane = int(threadIdx.x & 31); + if (work_tile_info.is_valid()) prefetch_residual(params, kp.resid, cta_coord_mnkl, epi_lane); + + bool do_load_order_wait = true; + bool do_tail_load = false; + int current_wave = 0; + bool first_loaded = false; + if constexpr (RawW) { + if (work_tile_info.is_valid() && TileScheduler::compute_epilogue(work_tile_info, params.scheduler)) { + epi_load_pipe_producer_state = collective_epilogue.template load( + epi_load_pipeline, epi_load_pipe_producer_state, problem_shape_MNKL, CtaShape_MNK{}, + cta_coord_mnkl, TileShape{}, TiledMma{}, shared_storage.tensors.epilogue, + IsOverlappingAccum); + first_loaded = true; + do_tail_load = true; + do_load_order_wait = false; + } + } + // Ensure that the prefetched kernel does not touch + // unflushed global memory prior to this instruction + cutlass::arch::wait_on_dependent_grids(); + + do { + bool compute_epilogue = TileScheduler::compute_epilogue(work_tile_info, params.scheduler); + if (first_loaded) { compute_epilogue = false; first_loaded = false; } + + auto [next_work_tile_info, increment_pipe] = fetch_nw( + work_tile_info, + clc_pipeline, + clc_pipe_consumer_state + ); + work_tile_info = next_work_tile_info; + // [Residual L2 prefetch] next tile (persistent CTAs), during this tile's mainloop. + if (work_tile_info.is_valid()) + prefetch_residual(params, kp.resid, scheduler.work_tile_to_cta_coord(work_tile_info), epi_lane); + + if (increment_pipe) { + ++clc_pipe_consumer_state; + } + + if (compute_epilogue) { + if (do_load_order_wait) { + load_order_barrier.wait(); + do_load_order_wait = false; + } + + bool reverse_epi_n = IsOverlappingAccum && (current_wave % 2 == 0); + epi_load_pipe_producer_state = collective_epilogue.template load( + epi_load_pipeline, + epi_load_pipe_producer_state, + problem_shape_MNKL, + CtaShape_MNK{}, + cta_coord_mnkl, + TileShape{}, + TiledMma{}, + shared_storage.tensors.epilogue, + reverse_epi_n + ); + + do_tail_load = true; + } + current_wave++; + + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + } while (work_tile_info.is_valid()); + + if (do_tail_load) { + collective_epilogue.load_tail( + epi_load_pipeline, epi_load_pipe_producer_state, + epi_store_pipeline, epi_store_pipe_producer_state); + } + } + } + + else if (is_participant.epilogue) { + if constexpr (CustomEpi && (EpiWG == 2 || EpiPre)) { + static_assert(!IsOverlappingAccum && !WeightIsA && !RawW, "CustomEpi: normal orientation, 2 acc stages"); + constexpr int CN = int(size<1>(CtaShape_MNK{})); + // Column split: warpgroup 0 owns cols [0, CW), warpgroup 1 owns [CW, CN), CW = CN/2 rounded + // up to 16 (keeps every 32 B chunk 32 B aligned, e.g. CN = 176 -> 96 + 80; CN = 224 -> 112 + 112). + static_assert(CN % 16 == 0, "CustomEpi2: CN % 16"); + constexpr int CW = (EpiWG == 1) ? CN : (CN == 224) ? 128 : ((CN / 2 + 15) / 16) * 16; // cols of warpgroup 0 + static_assert(int(size<0>(CtaShape_MNK{})) == 128 && CW % 16 == 0, "CustomEpi2: 128 x (16k) tile"); + constexpr int NCH = CW / 16; // max 16-col chunks per warpgroup (TMEM x16 load / 32 B global) + const int lane = int(threadIdx.x & 31); + const int q = warp_idx & 3; + const int h = (warp_idx - static_cast(WarpCategory::Epilogue)) >> 2; // warpgroup 0/1 + const int nch = (h == 0) ? NCH : (CN - CW) / 16; // chunks of this warpgroup + constexpr bool kQuad = (CN == 176) || (CN == 224) || (CN == 128); + constexpr int kGrp = kQuad ? 4 : 2; + constexpr bool kOneWait = (CN == 176) && (NCH == 6); + const int ls = kOneWait ? 0 : (nch - 1) & ~(kGrp - 1); + tmem_allocation_result_barrier.arrive_and_wait(); + collective_mainloop.set_tmem_offsets(tmem_storage, shared_storage.tmem_base_ptr); + const int ncols = params.res_cols; + const bool vec_ok = (ncols % 16 == 0) && + (((reinterpret_cast(kp.resid) | reinterpret_cast(kp.out)) & 31) == 0); + // TmaSt: per-warp 2 x 1 KB staging slots (32 rows x 32 B, row-major = the TMA box layout) + bool use_tma = false; + uint32_t st_base = 0; + uint32_t st_cnt = 0; // chunks issued by this warp (slot = st_slot) + uint32_t st_slot = 0; // st_cnt % kTmaStBufs + if constexpr (TmaSt) { + uint32_t dsz; + asm volatile("mov.u32 %0, %%dynamic_smem_size;" : "=r"(dsz)); + use_tma = vec_ok && params.tma_st != 0 && dsz >= kSmemTotal; + const int ew = warp_idx - static_cast(WarpCategory::Epilogue); // 0 .. 4*EpiWG-1 + st_base = cute::cast_smem_ptr_to_uint(smem_buf) + kTmaStSmemOff + uint32_t(ew) * (kTmaStBufs * 1024u); + } + bool waited = false; + float alpha = 0.f; + uint64_t alpha2 = 0ull; + const uint64_t st_pol = make_ef_policy(); + uint64_t out_pol = st_pol; + if ((CN == 176 || WPrefFirst) && params.res_tokens <= 1024) + asm volatile("createpolicy.fractional.L2::evict_normal.b64 %0, 1.0;" : "=l"(out_pol)); + uint32_t r[NCH][8]; // residual chunks of the current tile (persist across tiles: next-tile preload) + bool pre = false; // r[0..nch-2] already hold this tile's residual (issued during the previous tile) + bool rs_on = false; + uint32_t rs_slot = 0, rs_bar = 0, rs_ph = 0; + if constexpr (kRs) { + uint32_t dsz; + asm volatile("mov.u32 %0, %%dynamic_smem_size;" : "=r"(dsz)); + rs_on = vec_ok && dsz >= kRsSmemTotal && h == 0; + const int ew = (warp_idx - static_cast(WarpCategory::Epilogue)) & 3; + const uint32_t base = cute::cast_smem_ptr_to_uint(smem_buf) + kRsSmemOff; + rs_slot = base + uint32_t(ew) * 1024u + uint32_t(lane) * 32u; + rs_bar = base + 4u * 1024u + uint32_t(ew) * 8u; + if (rs_on && lane == 0) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], 1;" :: "r"(rs_bar) : "memory"); + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + } + __syncwarp(); + } + // issue this warp's chunk-0 copies (lane: 32 B of its row if ok) on the warp's mbarrier. + // Warp-uniform call. fence.proxy.async orders this lane's earlier LDS of the slot (generic + // proxy) before the async-proxy overwrite. + auto rs_issue = [&](const uint8_t* src, bool ok) { + const uint32_t nb = __reduce_add_sync(0xffffffffu, ok ? 32u : 0u); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + if (lane == 0) + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" :: "r"(rs_bar), "r"(nb) : "memory"); + __syncwarp(); + if (ok) + asm volatile("cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1], 32, [%2], %3;" + :: "r"(rs_slot), "l"(src), "r"(rs_bar), "l"(st_pol) : "memory"); + }; + auto rs_read = [&](uint32_t (&w)[8]) { + uint32_t done = 0; + do { + asm volatile("{\n\t.reg .pred p;\n\t" + "mbarrier.try_wait.parity.shared::cta.b64 p, [%1], %2;\n\t" + "selp.u32 %0, 1, 0, p;\n\t}" + : "=r"(done) : "r"(rs_bar), "r"(rs_ph) : "memory"); + } while (!done); + rs_ph ^= 1u; + asm volatile("ld.shared.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(w[0]), "=r"(w[1]), "=r"(w[2]), "=r"(w[3]) : "r"(rs_slot) : "memory"); + asm volatile("ld.shared.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(w[4]), "=r"(w[5]), "=r"(w[6]), "=r"(w[7]) : "r"(rs_slot + 16u) : "memory"); + }; + do { + auto [next_work_tile_info, increment_pipe] = fetch_nw( + work_tile_info, clc_pipeline, clc_pipe_consumer_state); + if (increment_pipe) { + ++clc_pipe_consumer_state; + } + const int row = int(get<0>(cta_coord_mnkl)) * 128 + q * 32 + lane; + const int col0 = int(get<1>(cta_coord_mnkl)) * CN + h * CW; + const bool row_ok = row < params.res_tokens; + const size_t off = ((size_t)(row_ok ? row : 0) * ncols + col0) * 2; + const uint8_t* rp = kp.resid + off; + uint8_t* op = kp.out + off; + const bool full = row_ok && vec_ok && col0 + nch * 16 <= ncols; + // (1) residual -> registers (full in-range chunks only; tails use the scalar path) + constexpr bool kDeferRes = !WPrefFirst && !kNoClc; + if (kDeferRes && !waited) { + cutlass::arch::wait_on_dependent_grids(); + alpha = __ldcg(kp.alpha); + alpha2 = pack_alpha2(alpha); + waited = true; + } + if constexpr (kNoClc) { + if (!waited) { + if (lane == 0) { + const unsigned int* ab = reinterpret_cast(kp.alpha) - 2; + const unsigned int nq = unsigned((int(K) / 128) * ((params.res_tokens + 127) / 128) / 4); + uint64_t t0; + asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t0)); + while (true) { + const unsigned int c0 = ld_relaxed_gpu(ab + 33), c1 = ld_relaxed_gpu(ab + 65); + if (c0 >= nq || c1 >= nq) break; + uint64_t t1; + asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t1)); + if (t1 - t0 > 4000ull) break; + __nanosleep(128); + } + } + __syncwarp(); + } + } + if (rs_on && !pre) rs_issue(rp, row_ok && col0 + 16 <= ncols); + CUTLASS_PRAGMA_UNROLL + for (int ch = 0; ch < NCH; ++ch) { + if (rs_on && ch == 0) continue; + if (!pre && ch < nch && (full || (row_ok && vec_ok && col0 + ch * 16 + 16 <= ncols))) + ldg256_na(rp + ch * 32, r[ch]); + } + pre = false; + if (!waited) { // alpha (written by act_quant) / D stores after the prerequisite grids + cutlass::arch::wait_on_dependent_grids(); + alpha = __ldcg(kp.alpha); + alpha2 = pack_alpha2(alpha); + waited = true; + } + const int acc_stage = accumulator_pipe_consumer_state.index(); + const uint32_t tmem_acc = + uint32_t(get<0>(collective_mainloop.slice_accumulator(tmem_storage, acc_stage)).data().get()) + + (uint32_t(q * 32) << 16) + uint32_t(h * CW); + { + const uint32_t afb = cute::cast_smem_ptr_to_uint(&shared_storage.pipelines.accumulator.full_barrier_[acc_stage]); + const uint32_t aph = accumulator_pipe_consumer_state.phase(); + if (WPrefFirst && !next_work_tile_info.is_valid() && params.res_tokens >= 1024) { + asm volatile("{\n\t.reg .pred p;\n\t" + "LAB_WAIT_T:\n\t" + "mbarrier.test_wait.parity.shared::cta.b64 p, [%0], %1;\n\t" + "@!p bra LAB_WAIT_T;\n\t}" + :: "r"(afb), "r"(aph) : "memory"); + } else { + mbar_wait_sleep(afb, aph); + } + } + constexpr bool ALL_LD = (CN == 224) && !WPrefFirst && (NCH == 7); + uint32_t f32[kOneWait ? NCH * 16 : kGrp * 16]; // TMEM data (ALL_LD: the pair in flight; else current load group) + uint32_t pka[ALL_LD ? NCH * 8 : 1]; + const uint8_t* nrp_s = nullptr; + bool nok_s = false; + int ncol0_s = 0; // ALL_LD: packed bf16(acc) of the row segment + auto nc_s = cta_coord_mnkl; + bool have_nc = false; + CUTLASS_PRAGMA_UNROLL + for (int ch = 0; ch < NCH; ++ch) { + if (ch >= nch) break; // warp-uniform (h is per warp) + if constexpr (ALL_LD) { + if ((ch & 1) == 0) { + if (ch == 0) tmem_ld_32x32b_x32(tmem_acc, f32); + asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); + const int np = (ch + 1 < nch) ? 16 : 8; // packed words of this pair + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 16; ++i) + if (i < np && ch * 8 + i < NCH * 8) pka[ch * 8 + i] = pack_bf16x2_rn(__uint_as_float(f32[2 * i]), __uint_as_float(f32[2 * i + 1])); + if (ch + 2 < nch) { // next pair in flight during this pair's combine / stores + if (ch + 3 < nch) tmem_ld_32x32b_x32(tmem_acc + uint32_t((ch + 2) * 16), f32); + else tmem_ld_32x32b_x16p(tmem_acc + uint32_t((ch + 2) * 16), f32); + } + } + } else if (kOneWait) { + if (ch == 0) { + tmem_ld_32x32b_x64p(tmem_acc, f32); + if (nch >= 6) tmem_ld_32x32b_x32(tmem_acc + 64u, *reinterpret_cast(f32 + 64)); + else tmem_ld_32x32b_x16p(tmem_acc + 64u, f32 + 64); + asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); + } + } else if ((ch % kGrp) == 0) { // load group of kGrp chunks (pairs: x32, trailing odd: x16), one wait + if (kGrp == 4 && ch + 3 < nch) { + tmem_ld_32x32b_x64p(tmem_acc + uint32_t(ch * 16), f32); + } else + CUTLASS_PRAGMA_UNROLL + for (int pr = 0; pr < kGrp; pr += 2) { + const int c2 = ch + pr; + if (c2 + 1 < nch) { + tmem_ld_32x32b_x32(tmem_acc + uint32_t(c2 * 16), *reinterpret_cast(f32 + pr * 16)); + } else if (c2 < nch) { + tmem_ld_32x32b_x16p(tmem_acc + uint32_t(c2 * 16), f32 + pr * 16); + } + } + asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); + } + const uint32_t* f = f32 + (kOneWait ? ch : (ch % kGrp)) * 16; + if (kRs && ch == 0 && rs_on) rs_read(r[0]); + if (ch == ls) { + cutlass::arch::fence_view_async_tmem_load(); + __syncwarp(); + if ((threadIdx.x & 31) == 0) accumulator_pipeline.consumer_release(accumulator_pipe_consumer_state); + if (next_work_tile_info.is_valid()) { + auto nc = scheduler.work_tile_to_cta_coord(next_work_tile_info); + nc_s = nc; have_nc = true; + const int nrow = int(get<0>(nc)) * 128 + q * 32 + lane; + const int ncol0 = int(get<1>(nc)) * CN + h * CW; + const bool nrow_ok = nrow < params.res_tokens; + const uint8_t* nrp = kp.resid + ((size_t)(nrow_ok ? nrow : 0) * ncols + ncol0) * 2; + if (rs_on) rs_issue(nrp, nrow_ok && ncol0 + 16 <= ncols); + CUTLASS_PRAGMA_UNROLL + for (int j = 0; j < NCH; ++j) { + if (rs_on && j == 0) continue; + if (j < ls && nrow_ok && vec_ok && ncol0 + j * 16 + 16 <= ncols) ldg256_na(nrp + j * 32, r[j]); + } + pre = true; + nrp_s = nrp; nok_s = nrow_ok; ncol0_s = ncol0; + } + } + uint32_t pk[8]; // pk[i] = {bf16(acc[2i]) lo, bf16(acc[2i+1]) hi} of this chunk + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 8; ++i) + pk[i] = ALL_LD ? pka[ALL_LD ? ch * 8 + i : 0] + : pack_bf16x2_rn(__uint_as_float(f[2 * i]), __uint_as_float(f[2 * i + 1])); + if (TmaSt && use_tma) { + // warp-uniform: chunk inside the output columns and warp's first row inside M + const int cc = col0 + ch * 16; + const int wrow0 = row - lane; + if (cc < ncols && wrow0 < params.res_tokens) { + uint32_t o[8]; + CUTLASS_PRAGMA_UNROLL + for (int e = 0; e < 8; ++e) o[e] = epi_combine_x2a(pk[e], r[ch][e], alpha2); + const uint32_t slot = st_base + st_slot * 1024u; + // slot reuse: the bulk store issued from it kTmaStBufs chunks ago (the oldest group) + // must have read its smem; the newer kTmaStBufs-1 groups may stay in flight + if (lane == 0) asm volatile("cp.async.bulk.wait_group.read %0;" :: "n"(int(kTmaStBufs) - 1) : "memory"); + __syncwarp(); + const uint32_t a = slot + uint32_t(lane) * 32u; + asm volatile("st.shared.v4.b32 [%0], {%1,%2,%3,%4};" :: "r"(a), "r"(o[0]), "r"(o[1]), "r"(o[2]), "r"(o[3]) : "memory"); + asm volatile("st.shared.v4.b32 [%0], {%1,%2,%3,%4};" :: "r"(a + 16u), "r"(o[4]), "r"(o[5]), "r"(o[6]), "r"(o[7]) : "memory"); + asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); + __syncwarp(); + if (lane == 0) { + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group [%0, {%2, %3}], [%1];" + :: "l"(reinterpret_cast(¶ms.out_tmap)), "r"(slot), "r"(cc), "r"(wrow0) + : "memory"); + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + } + ++st_cnt; + st_slot = (st_slot + 1u == kTmaStBufs) ? 0u : st_slot + 1u; + } + } else if (full) { + uint32_t o[8]; + CUTLASS_PRAGMA_UNROLL + for (int e = 0; e < 8; ++e) + o[e] = (!ALL_LD) ? epi_combine_acc2f(f[2 * e], f[2 * e + 1], r[ch][e], uint32_t(alpha2)) + : epi_combine_x2a(pk[e], r[ch][e], alpha2); + stg256p(op + ch * 32, o, out_pol); + } else if (row_ok) { + const int cc = col0 + ch * 16; + if (vec_ok && cc + 16 <= ncols) { + uint32_t o[8]; + CUTLASS_PRAGMA_UNROLL + for (int e = 0; e < 8; ++e) o[e] = epi_combine_x2a(pk[e], r[ch][e], alpha2); + stg256p(op + ch * 32, o, out_pol); + } else if (cc < ncols) { // scalar tail / unaligned fallback + const uint16_t* r16 = reinterpret_cast(rp) + ch * 16; + uint16_t* o16 = reinterpret_cast(op) + ch * 16; + for (int e = 0; e < 16 && cc + e < ncols; ++e) { + const uint32_t pw = pk[e >> 1]; + const uint32_t a = (e & 1) ? (pw >> 16) : (pw & 0xffffu); + o16[e] = uint16_t(epi_combine(a, uint32_t(r16[e]), alpha) & 0xffffu); + } + } + } + if (pre && ch >= ls && nok_s && vec_ok && ncol0_s + ch * 16 + 16 <= ncols) ldg256_na(nrp_s + ch * 32, r[ch]); + } + ++accumulator_pipe_consumer_state; // (stage released inside the chunk loop, ) + work_tile_info = next_work_tile_info; + cta_coord_mnkl = have_nc ? nc_s : scheduler.work_tile_to_cta_coord(work_tile_info); + } while (work_tile_info.is_valid()); + if constexpr (TmaSt) { // all bulk stores of this thread complete before exit + if (use_tma && lane == 0) asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); + __syncwarp(); + } + } else if constexpr (CustomEpi) { + static_assert(!IsOverlappingAccum && !WeightIsA && !RawW, "CustomEpi: normal orientation, 2 acc stages"); + constexpr int CN = int(size<1>(CtaShape_MNK{})); + static_assert(int(size<0>(CtaShape_MNK{})) == 128 && CN % 32 == 0 && CN <= 256, + "CustomEpi: per-CTA tile 128 x (32k)"); + constexpr int NCH32 = CN / 32; // 32-col TMEM load chunks + constexpr int NCH16 = CN / 16; // 16-col (32 B) global chunks + constexpr int GRP = NCH16 / 2; // residual loads in flight per group + static_assert(NCH16 % GRP == 0, "groups"); + const int lane = int(threadIdx.x & 31); + const int q = warp_idx & 3; // TMEM lane quarter this warp may access (warp_id % 4) + if (q == 0 && work_tile_info.is_valid()) prefetch_residual(params, kp.resid, cta_coord_mnkl, lane); + tmem_allocation_result_barrier.arrive_and_wait(); + collective_mainloop.set_tmem_offsets(tmem_storage, shared_storage.tmem_base_ptr); + // alpha (written by act_quant) and the D stores: after the prerequisite grids completed. + cutlass::arch::wait_on_dependent_grids(); + const float alpha = __ldcg(kp.alpha); + const int ncols = params.res_cols; + const bool vec_ok = (ncols % 16 == 0) && + (((reinterpret_cast(kp.resid) | reinterpret_cast(kp.out)) & 31) == 0); + const uint64_t st_pol = make_ef_policy(); + do { + auto [next_work_tile_info, increment_pipe] = fetch_nw( + work_tile_info, clc_pipeline, clc_pipe_consumer_state); + if (increment_pipe) { + ++clc_pipe_consumer_state; + } + if (q == 0 && next_work_tile_info.is_valid()) + prefetch_residual(params, kp.resid, scheduler.work_tile_to_cta_coord(next_work_tile_info), lane); + const int acc_stage = accumulator_pipe_consumer_state.index(); + const uint32_t tmem_acc = + uint32_t(get<0>(collective_mainloop.slice_accumulator(tmem_storage, acc_stage)).data().get()) + + (uint32_t(q * 32) << 16); + accumulator_pipeline.consumer_wait(accumulator_pipe_consumer_state); + uint32_t pk[CN / 2]; // pk[k] = {bf16(acc[2k]) lo, bf16(acc[2k+1]) hi} + CUTLASS_PRAGMA_UNROLL + for (int c = 0; c < NCH32; ++c) { + uint32_t f[32]; + tmem_ld_32x32b_x32(tmem_acc + uint32_t(c * 32), f); + asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < 16; ++i) + pk[c * 16 + i] = pack_bf16x2_rn(__uint_as_float(f[2 * i]), __uint_as_float(f[2 * i + 1])); + } + cutlass::arch::fence_view_async_tmem_load(); + __syncwarp(); + if ((threadIdx.x & 31) == 0) accumulator_pipeline.consumer_release(accumulator_pipe_consumer_state); + ++accumulator_pipe_consumer_state; + + // (4) D = bf16(bf16(t1 * alpha) + residual), overlapped with the next tile's mainloop. + // Thread = one output row (TMEM lane), CN contiguous cols in NCH16 chunks of 32 B. + const int row = int(get<0>(cta_coord_mnkl)) * 128 + q * 32 + lane; + const int col0 = int(get<1>(cta_coord_mnkl)) * CN; + if (row < params.res_tokens) { + const size_t off = ((size_t)row * ncols + col0) * 2; + const uint8_t* rp = kp.resid + off; + uint8_t* op = kp.out + off; + CUTLASS_PRAGMA_UNROLL + for (int b = 0; b < NCH16 / GRP; ++b) { + uint32_t r[GRP][8]; + CUTLASS_PRAGMA_UNROLL + for (int j = 0; j < GRP; ++j) { + const int ch = b * GRP + j; + if (vec_ok && col0 + ch * 16 + 16 <= ncols) ldg256_na(rp + ch * 32, r[j]); + } + CUTLASS_PRAGMA_UNROLL + for (int j = 0; j < GRP; ++j) { + const int ch = b * GRP + j; + const int cc = col0 + ch * 16; + if (vec_ok && cc + 16 <= ncols) { + uint32_t o[8]; + CUTLASS_PRAGMA_UNROLL + for (int e = 0; e < 8; ++e) o[e] = epi_combine_x2(pk[ch * 8 + e], r[j][e], alpha); // packed f32x2 (bit-exact) + stg256p(op + ch * 32, o, st_pol); + } else if (cc < ncols) { // scalar tail / unaligned fallback + const uint16_t* r16 = reinterpret_cast(rp) + ch * 16; + uint16_t* o16 = reinterpret_cast(op) + ch * 16; + for (int e = 0; e < 16 && cc + e < ncols; ++e) { + const uint32_t pw = pk[ch * 8 + (e >> 1)]; + const uint32_t a = (e & 1) ? (pw >> 16) : (pw & 0xffffu); + o16[e] = uint16_t(epi_combine(a, uint32_t(r16[e]), alpha) & 0xffffu); + } + } + } + } + } + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + } while (work_tile_info.is_valid()); + // (non-overlapping accumulators: TMEM dealloc handshake is done by the MMA warps after + // accumulator producer_tail, as in CUTLASS) + } else { + // RawW: the epilogue warps gather the raw weight SF of every k-tile of the tile they will + // write (tile 0 here, before the PDL-independent TMEM wait; tile i+1 inside the loop before + // tile i's epilogue). Stage ring tracked with an own producer state: wait the stage's + // EMPTY barrier (same phase the load warp waits on), store the prefetched SF row, arrive on FULL. + MainloopPipelineState gather_state = cutlass::make_producer_start_state(); + int gather_fresh = MainloopPipeline::Stages; + const int epi_w = warp_idx - static_cast(WarpCategory::Epilogue), epi_l = int(threadIdx.x & 31); + const int epi_tid = (epi_l & 7) + 8 * epi_w + 32 * (epi_l >> 3); + const RawWsf raw_w{kp.raw_wsf, params.raw_rows, params.raw_ksf, + cute::cast_smem_ptr_to_uint(shared_storage.tensors.mainloop.smem_SFA.begin())}; + auto gather_tile = [&](auto const& wti) { + if constexpr (RawW) { + auto coord = scheduler.work_tile_to_cta_coord(wti); + auto kit = scheduler.get_k_tile_iterator(wti, problem_shape_MNKL, CtaShape_MNK{}, load_inputs.k_tiles); + int cnt = TileScheduler::get_work_k_tile_count(wti, problem_shape_MNKL, CtaShape_MNK{}); + const int row0 = int(get<0>(coord)) * 128; + constexpr int D = PdlMainloop::kGatherD; + const int kt0 = int(cute::get<0>(cute::wrap(*kit))); + const int r = row0 + epi_tid; + constexpr int kKsf = 512, kKt = kKsf / 16; + const bool k8 = raw_w.ksf == kKsf && r < raw_w.rows && (kt0 & 1) == 0 && + (reinterpret_cast(raw_w.src) & 31) == 0; + const uint8_t* rowp = raw_w.src + (size_t)(r < raw_w.rows ? r : 0) * kKsf; + auto ld2 = [&](int kt, uint4& a, uint4& b) { + if (k8 && kt + 1 < kKt) { + asm volatile("ld.global.nc.v8.u32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];" + : "=r"(a.x), "=r"(a.y), "=r"(a.z), "=r"(a.w), + "=r"(b.x), "=r"(b.y), "=r"(b.z), "=r"(b.w) : "l"(rowp + kt * 16)); + } else { + PdlMainloop::raw_wsf_load2(raw_w, r, kt, a, b); + } + }; + uint4 vc[D], vn[D]; + CUTLASS_PRAGMA_UNROLL + for (int j = 0; j < D; j += 2) { // pairs of k-tiles; entries beyond cnt are never stored + if (j < cnt) ld2(kt0 + j, vc[j], vc[j + 1]); + else { vc[j] = make_uint4(0u, 0u, 0u, 0u); vc[j + 1] = vc[j]; } + } + auto gather_chunk = [&](int base, uint4 (&cur)[D], uint4 (&nxt)[D]) { + CUTLASS_PRAGMA_UNROLL + for (int j = 0; j < D; ++j) { + if (j == 1) { // chunk c's first stage written -> prefetch chunk c+1 + CUTLASS_PRAGMA_UNROLL + for (int jj = 0; jj < D; jj += 2) { + if (base + D + jj < cnt) ld2(kt0 + base + D + jj, nxt[jj], nxt[jj + 1]); + else { nxt[jj] = make_uint4(0u, 0u, 0u, 0u); nxt[jj + 1] = nxt[jj]; } + } + } + if (base + j < cnt) { + const int stg = gather_state.index(); + if (gather_fresh > 0) --gather_fresh; + else shared_storage.pipelines.mainloop.empty_barrier_[stg].wait(gather_state.phase()); + PdlMainloop::raw_wsf_store_arrive(raw_w, cur[j], epi_tid, stg, + reinterpret_cast(&shared_storage.pipelines.mainloop.full_barrier_[stg])); + ++gather_state; + } + } + }; + CUTLASS_PRAGMA_NO_UNROLL + for (int base = 0; base < cnt; base += 2 * D) { + gather_chunk(base, vc, vn); + if (base + D >= cnt) break; + gather_chunk(base + D, vn, vc); + } + } + }; + if (work_tile_info.is_valid()) gather_tile(work_tile_info); + tmem_allocation_result_barrier.arrive_and_wait(); + uint32_t tmem_base_ptr = shared_storage.tmem_base_ptr; + collective_mainloop.set_tmem_offsets(tmem_storage, tmem_base_ptr); + + bool do_tail_store = false; + do { + auto [next_work_tile_info, increment_pipe] = fetch_nw( + work_tile_info, + clc_pipeline, + clc_pipe_consumer_state + ); + + if (increment_pipe) { + ++clc_pipe_consumer_state; + } + if (next_work_tile_info.is_valid()) gather_tile(next_work_tile_info); + + int acc_stage = [&] () { + if constexpr (IsOverlappingAccum) { + return accumulator_pipe_consumer_state.phase(); + } + else { + return accumulator_pipe_consumer_state.index(); + } + }(); + + if constexpr (RawW && !IsOverlappingAccum) { + mbar_wait_sleep(cute::cast_smem_ptr_to_uint(&shared_storage.pipelines.accumulator.full_barrier_[acc_stage]), + accumulator_pipe_consumer_state.phase()); + } + auto accumulator = get<0>(collective_mainloop.slice_accumulator(tmem_storage, acc_stage)); + accumulator_pipe_consumer_state = scheduler.template fixup( + TiledMma{}, + work_tile_info, + accumulator, + accumulator_pipeline, + accumulator_pipe_consumer_state, + typename CollectiveEpilogue::CopyOpT2R{} + ); + + if (scheduler.compute_epilogue(work_tile_info)) { + auto [load_state_next, store_state_next, acc_state_next] = collective_epilogue.template store( + epi_load_pipeline, + epi_load_pipe_consumer_state, + epi_store_pipeline, + epi_store_pipe_producer_state, + accumulator_pipeline, + accumulator_pipe_consumer_state, + problem_shape_MNKL, + CtaShape_MNK{}, + cta_coord_mnkl, + TileShape{}, + TiledMma{}, + accumulator, + shared_storage.tensors.epilogue + ); + epi_load_pipe_consumer_state = load_state_next; + epi_store_pipe_producer_state = store_state_next; + accumulator_pipe_consumer_state = acc_state_next; + do_tail_store = true; + } + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + + } while (work_tile_info.is_valid()); + + if constexpr (IsOverlappingAccum) { + if constexpr (has_mma_peer_cta) { + tmem_deallocation_result_barrier.arrive(mma_peer_cta_rank); + } + tmem_deallocation_result_barrier.arrive(); + } + + if (do_tail_store) { + collective_epilogue.store_tail( + epi_load_pipeline, epi_load_pipe_consumer_state, + epi_store_pipeline, epi_store_pipe_producer_state, + CtaShape_MNK{}); + } + } + } + + else { + } + } + + CUTLASS_DEVICE void operator() (Params const& params, char* smem_buf) { impl(params, params, smem_buf); } +}; + +} // namespace cutlass::gemm::kernel + +unsigned long long g_const_uploads = 0; +template +__constant__ __align__(128) unsigned char c_gemm_params_raw[sizeof(typename GK::Params)]; +template struct SplitCl { + static constexpr unsigned x = unsigned(decltype(cute::size<0>(typename GK::ClusterShape{}))::value); + static constexpr unsigned y = unsigned(decltype(cute::size<1>(typename GK::ClusterShape{}))::value); + static constexpr unsigned z = unsigned(decltype(cute::size<2>(typename GK::ClusterShape{}))::value); +}; +template +__global__ void __cluster_dims__(SplitCl::x, SplitCl::y, SplitCl::z) +__launch_bounds__(GK::MaxThreadsPerBlock, GK::MinBlocksPerMultiprocessor) +gemm_split_kernel(const __grid_constant__ typename GK::CallParams kp) { + extern __shared__ char smem[]; + GK op; + if ((threadIdx.x >> 5) == 4) { + constexpr unsigned kNB = unsigned(sizeof(typename GK::Params)); + uint32_t acc = 0u; + #pragma unroll + for (unsigned off = (threadIdx.x & 31u) * 64u; off < kNB; off += 2048u) + acc ^= *reinterpret_cast(c_gemm_params_raw + (off & ~3u)); + asm volatile("" :: "r"(acc)); + } + op.impl(*reinterpret_cast(c_gemm_params_raw), kp, smem); +} + +// ---------------- 3. CUTLASS SM100 NVFP4 GEMM (templated on tile config + orientation) ------- +using ElementA = cutlass::nv_float4_t; +using LayoutA = cutlass::layout::RowMajor; // MMA-A (rows x K), K contiguous +constexpr int AlignA = 32; +using ElementB = cutlass::nv_float4_t; +using LayoutB = cutlass::layout::ColumnMajor; // MMA-B (cols x K), K contiguous +constexpr int AlignB = 32; +using ElementC = cutlass::bfloat16_t; // residual +constexpr int AlignC = 128 / cutlass::sizeof_bits::value; +using ElementD = cutlass::bfloat16_t; +constexpr int AlignD = 128 / cutlass::sizeof_bits::value; +using ElementAcc = float; +using ArchTag = cutlass::arch::Sm100; +using OpClass = cutlass::arch::OpClassBlockScaledTensorOp; + +namespace fus = cutlass::epilogue::fusion; +constexpr auto RN = cutlass::FloatRoundStyle::round_to_nearest; +using EvtRound = fus::Sm90EVT, + fus::Sm90AccFetch>; +using EvtScale = fus::Sm90EVT, + EvtRound, fus::Sm90ScalarBroadcast>; +using EvtOut = fus::Sm90EVT, + EvtScale, fus::Sm90SrcFetch>; + +// Children: AccFetch (fp32 acc), ScalarBroadcast (alpha), SrcFetch (bf16 residual C). Per pair: +// cvt.rn.bf16x2.f32 (t1 = bf16(acc)) -> unpack (shl / and) -> mul.rn.f32x2 alpha -> +// cvt.rn.bf16x2.f32 (t2) -> add.rn.bf16x2 with C (D). Same rounding chain as the 3-node EVT +// (bit-exact, see epi_combine_x2), no per-element fp32<->bf16 array conversions between nodes. +// Inherits all Params / Arguments / SharedStorage / producer callbacks from Sm90Compute (empty); +// only the consumer-store visit is replaced. CUTLASS's C-load / D-store structure is untouched. +struct Sm90FusedResidEpi : fus::Sm90Compute { + using Base = fus::Sm90Compute; + using Base::Base; + struct ConsumerStoreCallbacks : fus::EmptyConsumerStoreCallbacks { + template + CUTLASS_DEVICE cutlass::Array + visit(cutlass::Array const& frg_acc, int, int, int, + cutlass::Array const& frg_acc_in, + cutlass::Array const& frg_alpha, + cutlass::Array const& frg_c) { + static_assert(FragmentSize % 2 == 0, "fused epi: even fragment"); + cutlass::Array out; + const uint32_t* cw = reinterpret_cast(&frg_c); + uint32_t* ow = reinterpret_cast(&out); + const float alpha = frg_alpha[0]; + const uint64_t alpha2 = pack_alpha2(alpha); + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < FragmentSize / 2; ++i) { + const uint32_t d = epi_combine_acc2(__float_as_uint(float(frg_acc_in[2 * i])), + __float_as_uint(float(frg_acc_in[2 * i + 1])), cw[i], alpha2); + ow[i] = d; + } + return out; + } + }; + template + CUTLASS_DEVICE auto get_consumer_store_callbacks(fus::ConsumerStoreArgs const&) { + return ConsumerStoreCallbacks(); + } +}; +using EvtFusedOut = fus::Sm90EVT, + fus::Sm90SrcFetch>; +template struct IsFusedEvt : std::false_type {}; +template <> struct IsFusedEvt : std::true_type {}; + +// Swap=false: MMA computes C[M,N] = act * W^T, C/D row-major (ld N). +// Swap=true : MMA computes C^T[N,M] = W * act^T, C/D column-major with ld N -- the same +// bytes as the row-major [M,N] output / residual. +// Raster: persistent scheduler raster order (0 = heuristic, 1 = AlongM, 2 = AlongN; swizzle 1). +// EpiTile: epilogue subtile (per CTA); default EpilogueTileAuto. +template +struct EpiNoStorage : E { + struct TensorStorage {}; + CUTLASS_DEVICE EpiNoStorage(typename E::Params const& p, TensorStorage& t) + : E(p, *reinterpret_cast(&t)) {} +}; + +template +struct GemmCfg { + static_assert(!CE || WF, "CustomEpi requires the derived (WF) kernel"); + // RawW (requires WF): the weight SF is read by the GEMM straight from the raw row-major + // weight_scale (no W-SF swizzle pass needed for this config). + static_assert(!RawW || WF, "RawW requires the derived (WF) kernel"); + static constexpr bool kRawW = RawW; + using LayoutC = std::conditional_t; + using LayoutD = LayoutC; + using CollectiveEpilogueBuilt = typename cutlass::epilogue::collective::CollectiveBuilder< + ArchTag, OpClass, MmaTileShape, ClusterShape, + EpiTile, + ElementAcc, float, + ElementC, LayoutC, AlignC, + ElementD, LayoutD, AlignD, + EpiSched, Evt>::CollectiveOp; + static_assert(!EpiNoSt || CE, "EpiNoSt requires CustomEpi"); + using CollectiveEpilogue = std::conditional_t, CollectiveEpilogueBuilt>; + static constexpr int kEpiCarve = EpiNoSt ? 0 : static_cast(sizeof(typename CollectiveEpilogueBuilt::SharedStorage)); + + using CollectiveMainloopBuilt = typename cutlass::gemm::collective::CollectiveBuilder< + ArchTag, OpClass, + ElementA, LayoutA, AlignA, + ElementB, LayoutB, AlignB, + ElementAcc, MmaTileShape, ClusterShape, + cutlass::gemm::collective::StageCountAutoCarveout, + MainSched>::CollectiveOp; + // MMA N = 224 (2SM 256x224): same collective with the CTA-N check widened (collective_anyn.hpp). + // The SFB (weight SF, MMA-B) tile is 256 rows: the weight SF MUST be in the padded-tile layout. + static constexpr int kTileN = int(cute::size<1>(MmaTileShape{})); + static constexpr bool kPadSfb = (kTileN == 224 || kTileN == 176 || kTileN == 112); + static constexpr int kPadRows = kTileN <= 128 ? 128 : 256; // SFB rows per N tile (padded) + static_assert(!kPadSfb || !Swap, "N=224/176 tile: weight must be MMA-B (padded SFB layout)"); + // CollectiveMmaAnyN: verbatim CUTLASS collective + the k-loop reorder (landed stage's SF + // tcgen05.cp + MMAs + release issued before the suspending try_wait peek of the next stage). + // Same instructions, same tensor-pipe order -> bit-exact. + static constexpr bool kReorderMma = kPadSfb || (WF && RawW) || (CE && kTileN == 128); + using CollectiveMainloop = std::conditional_t< + kReorderMma, typename cutlass::gemm::collective::RebindAnyN::type, + CollectiveMainloopBuilt>; + + using GemmKernelBase = cutlass::gemm::kernel::GemmUniversal< + Shape, CollectiveMainloop, CollectiveEpilogue, void>; + // WF: weight operand (MMA-A when swapped, MMA-B otherwise) TMA issued before the PDL wait. + using GemmKernel = std::conditional_t< + WF, cutlass::gemm::kernel::PdlWeightFirstKernel, GemmKernelBase>; + using Gemm = cutlass::gemm::device::GemmUniversalAdapter; + + using StrideA = typename GemmKernel::StrideA; + using StrideB = typename GemmKernel::StrideB; + using StrideC = typename GemmKernel::StrideC; + using StrideD = typename GemmKernel::StrideD; + using Sm1xxBlkScaledConfig = typename GemmKernel::CollectiveMainloop::Sm1xxBlkScaledConfig; + + static typename Gemm::Arguments make_args(int M, int N, int K, const void* act, const void* w, + const void* act_sf, const void* w_sf, const void* C, + void* D, const float* alpha_ptr, + int raster_rt = 0, int swz_rt = 1) { + const int Mm = Swap ? N : M, Nm = Swap ? M : N; + const void* A = Swap ? w : act; + const void* B = Swap ? act : w; + const void* SFA = Swap ? w_sf : act_sf; + const void* SFB = Swap ? act_sf : w_sf; + StrideA sA{}; get<0>(sA) = K; get<2>(sA) = (int64_t)Mm * K; + StrideB sB{}; get<0>(sB) = K; get<2>(sB) = (int64_t)Nm * K; + StrideC sC{}; + StrideD sD{}; + if constexpr (Swap) { + get<1>(sC) = Mm; get<2>(sC) = (int64_t)Mm * Nm; + get<1>(sD) = Mm; get<2>(sD) = (int64_t)Mm * Nm; + } else { + get<0>(sC) = Nm; get<2>(sC) = (int64_t)Mm * Nm; + get<0>(sD) = Nm; get<2>(sD) = (int64_t)Mm * Nm; + } + auto lSFA = Sm1xxBlkScaledConfig::tile_atom_to_shape_SFA(make_shape(Mm, Nm, K, 1)); + // padded-tile SFB (kPadSfb): ceil(N/224) tiles x 256 SF rows (see wsf_src_row) + const int NmSf = kPadSfb ? ((Nm + kTileN - 1) / kTileN) * kPadRows : Nm; + auto lSFB = Sm1xxBlkScaledConfig::tile_atom_to_shape_SFB(make_shape(Mm, NmSf, K, 1)); + typename GemmKernelBase::Arguments bargs{ + cutlass::gemm::GemmUniversalMode::kGemm, + {Mm, Nm, K, 1}, + {reinterpret_cast(A), sA, + reinterpret_cast(B), sB, + reinterpret_cast(SFA), lSFA, + reinterpret_cast(SFB), lSFB}, + {{}, + reinterpret_cast(C), sC, + reinterpret_cast(D), sD}}; + using ThreadArgs = std::remove_reference_t; + if constexpr (IsFusedEvt::value) { + // fused node: {AccFetch, ScalarBroadcast(alpha), SrcFetch, node} + bargs.epilogue.thread = ThreadArgs{{}, {{1.0f}, {alpha_ptr}}, {}, {}}; + } else { + bargs.epilogue.thread = ThreadArgs{ + { + {{}, {}}, + {{1.0f}, {alpha_ptr}}, + {}}, + {}, + {}}; + } + typename Gemm::Arguments args; + static_cast(args) = bargs; + if constexpr (RawW) args.raw_wsf = reinterpret_cast(w_sf); // raw [N][K/16] + if constexpr (WF && (Pref || CE)) args.resid = reinterpret_cast(C); // residual (L2 prefetch / CE epilogue) + if constexpr (CE) { + args.out = reinterpret_cast(D); + args.alpha = alpha_ptr; + } + if constexpr (Raster != 0) { + args.scheduler.max_swizzle_size = 1; + using RO = decltype(args.scheduler.raster_order); + args.scheduler.raster_order = (Raster == 2) ? RO::AlongN : RO::AlongM; + } + if (raster_rt > 0) { // per-M runtime raster/swizzle override (see sched_for) + using RO = decltype(args.scheduler.raster_order); + args.scheduler.raster_order = (raster_rt == 2) ? RO::AlongN : RO::AlongM; + args.scheduler.max_swizzle_size = swz_rt; + } + return args; + } + + static size_t workspace(int M, int N, int K) { + auto args = make_args(M, N, K, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); + return Gemm::get_workspace_size(args); + } + + // Cached adapter (heap, never destroyed); later calls only update() params. + static void run(int M, int N, int K, const void* act, const void* w, const void* act_sf, + const void* w_sf, const void* C, void* D, const float* alpha, void* ws, + size_t ws_size, cudaStream_t stream, int raster_rt = 0, int swz_rt = 1) { + static Gemm& gemm = *new Gemm(); + static bool inited = false; + // (1) the kernel Params (incl. the TMA descriptors encoded on the host) depend only on the shape, + // the buffer pointers and the scheduler knobs: when all equal the previous call's and no + // workspace is used, the stored Params are reused (no make_args / update / descriptor encode). + struct Key { + int M, N, K, raster, swz, pad; // pad: no implicit padding (memcmp) + const void *act, *w, *act_sf, *w_sf, *alpha, *ws; + }; + static Key last{}; + static const void* lastC = nullptr; + static void* lastD = nullptr; + static auto& P = *new typename GemmKernel::Params(); // heap, never freed (POD-like, no CUDA tensors) + static unsigned p_gen = 1; + static bool lc_valid = false; + static bool c_dirty = true; + const Key key{M, N, K, raster_rt, swz_rt, 0, act, w, act_sf, w_sf, alpha, ws}; + bool same = inited && ws_size == 0 && std::memcmp(&key, &last, sizeof(Key)) == 0; + bool p_stale = false; // P differs from the adapter's internal params (only C / D patched) + static bool p_patched = false; + static bool p_wpatched = false; + struct EpiEnt { const void* C; void* D; typename GemmKernel::Params* P; }; + constexpr int kEpiEnts = 8; + static EpiEnt* ents = [] { + EpiEnt* e = new EpiEnt[kEpiEnts]; + for (int i = 0; i < kEpiEnts; ++i) e[i] = EpiEnt{nullptr, nullptr, new typename GemmKernel::Params()}; + return e; + }(); + static int n_ents = 0, next_ent = 0; + static const void* baseC = nullptr; // C / D of the adapter's internal (full-build) params + static void* baseD = nullptr; + auto put_ent = [&](const void* c, void* d) { + EpiEnt& e = ents[next_ent]; + e.C = c; e.D = d; *e.P = P; + next_ent = (next_ent + 1) % kEpiEnts; + if (n_ents < kEpiEnts) ++n_ents; + }; + if (!same && inited && ws_size == 0) { + using ReplFn = CUresult (*)(CUtensorMap*, void*); + static ReplFn repl = [] { + void* f = nullptr; + cudaDriverEntryPointQueryResult q{}; + if (cudaGetDriverEntryPointByVersion("cuTensorMapReplaceAddress", &f, 12000, cudaEnableDefault, &q) != cudaSuccess || + q != cudaDriverEntryPointSuccess) { + (void)cudaGetLastError(); + f = nullptr; + } + return reinterpret_cast(f); + }(); + Key kw = key; + kw.w = last.w; + if (RawW) kw.w_sf = last.w_sf; + if (repl != nullptr && std::memcmp(&kw, &last, sizeof(Key)) == 0) { + static auto& Pn = *new typename GemmKernel::Params(); // heap scratch, never freed + Pn = P; + auto rp = [&](auto const& atom, const void* addr) { + return repl(const_cast(reinterpret_cast(atom.get_tma_descriptor())), + const_cast(addr)) == CUDA_SUCCESS; + }; + bool ok = true; + constexpr bool kDynCl = GemmKernel::CollectiveMainloop::IsDynamicCluster; + if constexpr (Swap) { // weight = MMA-A + ok = rp(Pn.mainloop.tma_load_a, w) && (!kDynCl || rp(Pn.mainloop.tma_load_a_fallback, w)); + if (RawW && ok) ok = rp(Pn.mainloop.tma_load_sfa, w_sf) && (!kDynCl || rp(Pn.mainloop.tma_load_sfa_fallback, w_sf)); + } else { // weight = MMA-B + ok = rp(Pn.mainloop.tma_load_b, w) && (!kDynCl || rp(Pn.mainloop.tma_load_b_fallback, w)); + } + if (ok) { + if constexpr (RawW) Pn.raw_wsf = reinterpret_cast(w_sf); + P = Pn; + ++p_gen; + last = key; + same = true; + p_wpatched = true; + n_ents = 0; next_ent = 0; // (C, D) entries belonged to the previous weight pointer + put_ent(lastC, lastD); // P is now valid for (key, lastC, lastD) + } + } + } + if (!same) { + auto args = make_args(M, N, K, act, w, act_sf, w_sf, C, D, alpha, raster_rt, swz_rt); + if (!inited || ws_size != 0) { + gemm.initialize(args, ws, stream); + inited = true; + } else { + gemm.update(args, ws); + } + P = gemm.params(); + c_dirty = true; + ++p_gen; + last = key; + lastC = C; lastD = D; + baseC = C; baseD = D; + lc_valid = false; + p_wpatched = false; + n_ents = 0; next_ent = 0; // entries belong to the previous key + put_ent(C, D); + } else if (C != lastC || D != lastD) { + int hit = -1; + for (int i = 0; i < n_ents; ++i) + if (ents[i].C == C && ents[i].D == D) { hit = i; break; } + if (hit >= 0) { + P = *ents[hit].P; + ++p_gen; + } else { + auto args = make_args(M, N, K, act, w, act_sf, w_sf, C, D, alpha, raster_rt, swz_rt); + P.epilogue = GemmKernel::CollectiveEpilogue::to_underlying_arguments(args.problem_shape, args.epilogue, nullptr); + if constexpr (WF) GemmKernel::patch_epi(P, args); + ++p_gen; + put_ent(C, D); + } + lastC = C; lastD = D; + } + p_patched = (C != baseC || D != baseD); + p_stale = p_patched; + if (ws_size == 0) { + using GK = GemmKernel; + static dim3 grid, block; + static int smem = 0; + static unsigned lc_gen = 1; + if (!lc_valid) { + grid = GK::get_grid_shape(gemm.params()); + block = GK::get_block_shape(); + smem = int(GK::SharedStorageSize); + if constexpr (WF && TST) { // + TMA-store staging slots (if the device allows that much smem) + static int tst_ok = -1; + if (tst_ok < 0) { + tst_ok = cudaFuncSetAttribute(cutlass::device_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, + int(GK::kSmemTotal)) == cudaSuccess ? 1 : 0; + (void)cudaGetLastError(); + } + if (tst_ok) smem = int(GK::kSmemTotal); + } + if constexpr (WF && !TST) { if constexpr (GK::kRs) { + static int rs_ok = -1; + if (rs_ok < 0) { + rs_ok = cudaFuncSetAttribute(gemm_split_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, + int(GK::kRsSmemTotal)) == cudaSuccess ? 1 : 0; + (void)cudaGetLastError(); + if (rs_ok) { + (void)cudaFuncSetAttribute(cutlass::device_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, + int(GK::kRsSmemTotal)); + (void)cudaGetLastError(); + } + } + if (rs_ok) smem = int(GK::kRsSmemTotal); + } } + lc_valid = true; + ++lc_gen; + } + cudaLaunchConfig_t lc = {}; + lc.gridDim = grid; + lc.blockDim = block; + lc.dynamicSmemBytes = smem; + lc.stream = stream; + cudaLaunchAttribute at[2]; + at[0].id = cudaLaunchAttributeClusterDimension; + at[0].val.clusterDim.x = cute::size<0>(typename GK::ClusterShape{}); + at[0].val.clusterDim.y = cute::size<1>(typename GK::ClusterShape{}); + at[0].val.clusterDim.z = cute::size<2>(typename GK::ClusterShape{}); + at[1].id = cudaLaunchAttributeProgrammaticStreamSerialization; + at[1].val.programmaticStreamSerializationAllowed = 1; + lc.attrs = at; + lc.numAttrs = 2; + if constexpr (WF && !TST) { + static int split_ok = -1; + if (split_ok < 0) { + split_ok = cudaFuncSetAttribute(gemm_split_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem) == cudaSuccess ? 1 : 0; + (void)cudaGetLastError(); + } + if (split_ok == 1) { + bool up = true; + if (c_dirty) { + up = cudaMemcpyToSymbolAsync(c_gemm_params_raw, &P, sizeof(P), 0, cudaMemcpyHostToDevice, stream) == cudaSuccess; + if (up) { c_dirty = false; ++g_const_uploads; } else (void)cudaGetLastError(); + } + if (up) { + static auto& kp = *new typename GK::CallParams(); + static unsigned kp_gen = 0; + if (kp_gen != p_gen) { GK::make_call(kp, P); kp_gen = p_gen; } + using DrvLaunchFn = CUresult (*)(const CUlaunchConfig*, CUfunction, void**, void**); + static DrvLaunchFn drv_launch = [] { + void* f = nullptr; + cudaDriverEntryPointQueryResult q{}; + if (cudaGetDriverEntryPointByVersion("cuLaunchKernelEx", &f, 12000, cudaEnableDefault, &q) != cudaSuccess || + q != cudaDriverEntryPointSuccess) { (void)cudaGetLastError(); f = nullptr; } + return reinterpret_cast(f); + }(); + static CUfunction drv_fn = [] { + cudaFunction_t fn = nullptr; + if (cudaGetFuncBySymbol(&fn, reinterpret_cast(gemm_split_kernel)) != cudaSuccess) { + (void)cudaGetLastError(); fn = nullptr; + } + return reinterpret_cast(fn); + }(); + if (drv_launch != nullptr && drv_fn != nullptr) { + static CUlaunchAttribute da[2]; + static CUlaunchConfig dc = {}; + static unsigned dc_gen = 0; + if (dc_gen != lc_gen) { + da[0].id = CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION; + da[0].value.clusterDim.x = at[0].val.clusterDim.x; + da[0].value.clusterDim.y = at[0].val.clusterDim.y; + da[0].value.clusterDim.z = at[0].val.clusterDim.z; + da[1].id = CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_STREAM_SERIALIZATION; + da[1].value.programmaticStreamSerializationAllowed = 1; + dc = CUlaunchConfig{}; + dc.gridDimX = grid.x; dc.gridDimY = grid.y; dc.gridDimZ = grid.z; + dc.blockDimX = block.x; dc.blockDimY = block.y; dc.blockDimZ = block.z; + dc.sharedMemBytes = (unsigned)smem; + dc.attrs = da + 1; + dc.numAttrs = 1; + dc_gen = lc_gen; + } + dc.hStream = reinterpret_cast(stream); + void* kargs[1] = {const_cast(reinterpret_cast(&kp))}; + if (drv_launch(&dc, drv_fn, kargs, nullptr) == CUDA_SUCCESS) return; + drv_launch = nullptr; // fall back to the runtime launch from now on + } + lc.attrs = at + 1; lc.numAttrs = 1; + if (cudaLaunchKernelEx(&lc, gemm_split_kernel, kp) == cudaSuccess) return; + (void)cudaGetLastError(); + lc.attrs = at; lc.numAttrs = 2; + split_ok = 0; + } + } + } + if (cudaLaunchKernelEx(&lc, cutlass::device_kernel, P) == cudaSuccess) return; + (void)cudaGetLastError(); // launch-config error (not sticky): use the adapter's own launch + } + if (p_stale || p_wpatched) { // adapter params lack the C / D (or weight) patch: full update before its own launch + auto args = make_args(M, N, K, act, w, act_sf, w_sf, C, D, alpha, raster_rt, swz_rt); + gemm.update(args, ws); + P = gemm.params(); + ++p_gen; + p_patched = false; + p_wpatched = false; + baseC = C; baseD = D; + n_ents = 0; next_ent = 0; + put_ent(C, D); + } + gemm.run(stream, nullptr, /*launch_with_pdl=*/true); + } +}; + +using Sch1 = cutlass::gemm::KernelTmaWarpSpecialized1SmNvf4Sm100; +using Sch2 = cutlass::gemm::KernelTmaWarpSpecialized2SmNvf4Sm100; +using Epi1 = cutlass::epilogue::TmaWarpSpecialized1Sm; +using Epi2 = cutlass::epilogue::TmaWarpSpecialized2Sm; +using Cfg1 = GemmCfg, Shape<_2, _1, _1>, Epi2, Sch2, false, 2, + Shape<_128, _32>, /*WF=*/true, /*RawW=*/false, /*Pref=*/false, /*WPref=*/true>; +using Cfg2 = GemmCfg, Shape<_1, _2, _1>, Epi1, Sch1, true, 0, + cutlass::epilogue::collective::EpilogueTileAuto, /*WF=*/true, /*RawW=*/true, /*Pref=*/true, /*WPref=*/true, + /*WPrefFirst=*/false, /*WPrefDist=*/7, /*CE=*/false, /*EWG=*/1, /*EPRE=*/false, /*TST=*/false, + EvtFusedOut>; // fused 1-node EVT epilogue; Cfg2 weight L2 prefetch distance 6 -> 7 +// 4: Cfg1 + PDL weight-first (M == 256) +// epilogue subtile 128x16 -> 128x32 (as Cfg1 in ) +// + weight TMA L2 prefetch kWPrefDist k-tiles ahead (WPref; see PdlWeightFirstMainloop). +using Cfg4 = GemmCfg, Shape<_2, _1, _1>, Epi2, Sch2, false, 2, + Shape<_128, _32>, /*WF=*/true, /*RawW=*/false, /*Pref=*/true, /*WPref=*/true>; +using Cfg3 = GemmCfg, Shape<_2, _1, _1>, Epi2, Sch2, false, 2, + Shape<_128, _16>, /*WF=*/true, /*RawW=*/false, /*Pref=*/false>; +using Cfg5 = GemmCfg, Shape<_2, _1, _1>, Epi2, Sch2, true, 0>; +// 6: normal 2SM 256x224 (cluster 2x1, MMA 256x224x64 per CTA pair: each CTA 128 rows of A and +// 112 rows of B, 2 TMEM accumulator stages x 224 cols + SFA 16 + SFB 32 cols = 496 <= 512). +// 37 N tiles over N = 8192 -> (M/256)*37 clusters = exact full waves of 74 clusters at +// M = 512*k. Last N tile (cols 8064..8287) bounds-checked by TMA (B / C loads zero/clip, +// D store clipped). Weight SF in the padded-tile layout (wtn = 224). Same derived kernel as +// Cfg3 (PDL weight-first, no residual prefetch), raster AlongN swizzle 1. +// epilogue subtile 128x16 -> 128x32 (224 = 7 x 32). (Cfg7: 176 is not a multiple of 32 -> stays 128x16.) +using Cfg6 = GemmCfg, Shape<_2, _1, _1>, Epi2, Sch2, false, 2, + Shape<_128, _32>, /*WF=*/true, /*RawW=*/false, /*Pref=*/false>; +// 7: Cfg6 with MMA N = 176 (2SM 256x176x256; per CTA 128 A rows / 88 B rows; TMEM +// 2 x 176 + 16 + 32 = 400 cols). 47 N tiles over N = 8192 -> at M = 768: 141 clusters +// = 2 waves of 74 x N=176 (wave cost 352) vs Cfg3 2 waves x 192 (384) / Cfg6 2 x 224. +// Weight SF in the padded-tile layout with wtn = 176 (N tile n at padded rows 256n..). +// Cfg7 (M=768) also issues the weight TMA L2 prefetch (WPref, dist 6): first-wave cold weight. +// Cfg7 prefetches the weight only while loading each CTA's first work tile (WPrefFirst). +using Cfg7 = GemmCfg, Shape<_2, _1, _1>, Epi2, Sch2, false, 2, + Shape<_128, _16>, /*WF=*/true, /*RawW=*/false, /*Pref=*/false, /*WPref=*/true, + /*WPrefFirst=*/true, /*WPrefDist=*/6>; +using Cfg9 = GemmCfg, Shape<_2, _1, _1>, Epi2, Sch2, false, 2, + Shape<_128, _32>, /*WF=*/true, /*RawW=*/false, /*Pref=*/true, /*WPref=*/true, + /*WPrefFirst=*/false, /*WPrefDist=*/4>; +// 8: Cfg6 + weight TMA L2 prefetch (WPref), used instead of Cfg6 for M <= 1536 only +// (mid M: few tiles per cluster, cold-weight latency matters; large M is MMA-bound -> plain Cfg6). +// Cfg8 (M 1024/1536, 2-3 waves) prefetches the weight only on each CTA's first work tile. +using Cfg8 = GemmCfg, Shape<_2, _1, _1>, Epi2, Sch2, false, 2, + Shape<_128, _32>, /*WF=*/true, /*RawW=*/false, /*Pref=*/false, /*WPref=*/true, + /*WPrefFirst=*/true, /*WPrefDist=*/4>; + +// 10: Cfg6 + weight TMA L2 prefetch on each CTA's FIRST work tile only (WPrefFirst). +// Replaces Cfg6 (M >= 3072, previously no prefetch) and Cfg8 (M = 2048 bucket, all-tile +// prefetch): only the first wave reads the weight cold from DRAM. +// Cfg10 first-tile weight prefetch distance 6 -> 12 k-tiles (more cold-weight DRAM +// requests in flight during the first wave; K=8192 has 32 k-tiles). +using Cfg10 = GemmCfg, Shape<_2, _1, _1>, Epi2, Sch2, false, 2, + Shape<_128, _32>, /*WF=*/true, /*RawW=*/false, /*Pref=*/false, /*WPref=*/true, + /*WPrefFirst=*/true, /*WPrefDist=*/12>; + +// M3072: cur(Cfg10 M s4 rev) 96.28 | Cfg11 N s2 fwd 96.27 (tie, keep) | Cfg3 M s1 100.86 +// M4096: cur(Cfg10 M s4 rev) 130.18 (best) | Cfg11 N s1 130.71 | Cfg6 N s1 132.90 +using Cfg11 = GemmCfg, Shape<_2, _1, _1>, Epi2, Sch2, false, 2, + Shape<_128, _32>, /*WF=*/true, /*RawW=*/false, /*Pref=*/false, /*WPref=*/true, + /*WPrefFirst=*/true, /*WPrefDist=*/6>; + +// 12: Cfg10 tile (2SM 256x224, first-tile weight prefetch dist 12) with the CustomEpi +// register epilogue (NoSmem epilogue type -> no C/D smem -> more mainloop stages). +using Cfg12 = GemmCfg, Shape<_2, _1, _1>, + cutlass::epilogue::NoSmemWarpSpecialized2Sm, Sch2, false, 2, + Shape<_128, _32> /*unused by CE*/, /*WF=*/true, /*RawW=*/false, + /*Pref=*/false, /*WPref=*/true, /*WPrefFirst=*/true, /*WPrefDist=*/12, /*CE=*/true>; + +// 15: Cfg9 (M in [512,768): residual L2 prefetch, all-tile weight prefetch dist 4) with the +// CustomEpi register epilogue on TWO epilogue warpgroups (CTA 384 threads, each warpgroup 112 +// of the 224 accumulator columns; residual preloaded into registers before the accumulator wait). +using Cfg15 = GemmCfg, Shape<_2, _1, _1>, + cutlass::epilogue::NoSmemWarpSpecialized2Sm, Sch2, false, 2, + Shape<_128, _32> /*unused by CE*/, /*WF=*/true, /*RawW=*/false, + /*Pref=*/true, /*WPref=*/true, /*WPrefFirst=*/false, /*WPrefDist=*/4, /*CE=*/true, /*EWG=*/2, /*EPRE=*/false, /*TST=*/false>; // + TMA bulk-store output path + +using Cfg14 = GemmCfg, Shape<_2, _1, _1>, + cutlass::epilogue::NoSmemWarpSpecialized2Sm, Sch2, false, 2, + Shape<_128, _32> /*unused by CE*/, /*WF=*/true, /*RawW=*/false, + /*Pref=*/false, /*WPref=*/true, /*WPrefFirst=*/true, /*WPrefDist=*/4, /*CE=*/true, /*EWG=*/2, /*EPRE=*/false, /*TST=*/false, EvtOut, /*EpiNoSt=*/true>; + +// Confirm: M2048 def 69.06 | CE2d6AM1r 66.29 | CE2d12AM1r 66.41 | CE2d6AM4f 66.65 | CE1d12AM1r 67.37 +// M3072 def 92.17 | CE2d6AM1r 91.56 | CE2d12AM1r 91.59 | CE2d6AM4f 91.57 | CE1d12AM1r 92.17 +using Cfg16 = GemmCfg, Shape<_2, _1, _1>, + cutlass::epilogue::NoSmemWarpSpecialized2Sm, Sch2, false, 2, + Shape<_128, _32> /*unused by CE*/, /*WF=*/true, /*RawW=*/false, + /*Pref=*/false, /*WPref=*/true, /*WPrefFirst=*/true, /*WPrefDist=*/4, /*CE=*/true, /*EWG=*/2, /*EPRE=*/false, /*TST=*/false, EvtOut, /*EpiNoSt=*/true>; // Cfg16 first-tile weight L2 prefetch distance 12 -> 4 + +using Cfg23 = GemmCfg, Shape<_2, _1, _1>, + cutlass::epilogue::NoSmemWarpSpecialized2Sm, Sch2, false, 2, + Shape<_128, _32> /*unused by CE*/, /*WF=*/true, /*RawW=*/false, + /*Pref=*/false, /*WPref=*/true, /*WPrefFirst=*/true, /*WPrefDist=*/6, /*CE=*/true, /*EWG=*/2, /*EPRE=*/false, /*TST=*/false, EvtOut, /*EpiNoSt=*/true>; + +// 24: Cfg12 (2SM 256x224, first-tile weight prefetch dist 12, NoSmem) with the CustomEpi +// register epilogue on TWO warpgroups (128 + 96 cols, x64 TMEM quads) and activation TMA loads +// L2 EVICT_LAST (ActLast, automatic for CE2 + WPrefFirst) -- M >= 8192 only, AlongN s8. +using Cfg24 = GemmCfg, Shape<_2, _1, _1>, + cutlass::epilogue::NoSmemWarpSpecialized2Sm, Sch2, false, 2, + Shape<_128, _32> /*unused by CE*/, /*WF=*/true, /*RawW=*/false, + /*Pref=*/false, /*WPref=*/true, /*WPrefFirst=*/true, /*WPrefDist=*/12, /*CE=*/true, /*EWG=*/2, /*EPRE=*/false, /*TST=*/false, EvtOut, /*EpiNoSt=*/true>; +using Cfg26 = GemmCfg, Shape<_2, _1, _1>, + cutlass::epilogue::NoSmemWarpSpecialized2Sm, Sch2, false, 2, + Shape<_128, _32> /*unused by CE*/, /*WF=*/true, /*RawW=*/false, + /*Pref=*/false, /*WPref=*/true, /*WPrefFirst=*/true, /*WPrefDist=*/16, /*CE=*/true, /*EWG=*/2, /*EPRE=*/false, /*TST=*/false, EvtOut, /*EpiNoSt=*/true>; + +using Cfg17 = GemmCfg, Shape<_2, _1, _1>, + cutlass::epilogue::NoSmemWarpSpecialized2Sm, Sch2, false, 2, + Shape<_128, _16> /*unused by CE*/, /*WF=*/true, /*RawW=*/false, + /*Pref=*/false, /*WPref=*/true, /*WPrefFirst=*/false, /*WPrefDist=*/6, /*CE=*/true, /*EWG=*/2, /*EPRE=*/false, /*TST=*/false, EvtOut, /*EpiNoSt=*/true>; // weight L2 prefetch on ALL tiles + +// M256: Cfg4 29.96 | Cfg4 cluster 2x2 (act multicast) 29.91 | Cfg4+CE2WG 27.23 <- | 2SM 256x112 (74 cl) 30.12 +// M512: Cfg15 d4 33.38 | Cfg15 cluster 4x1 (weight multicast) 41.10 | d2 33.32 | d8 33.42 | d12 33.38 -> keep Cfg15 +using Cfg20 = GemmCfg, Shape<_2, _1, _1>, + cutlass::epilogue::NoSmemWarpSpecialized2Sm, Sch2, false, 2, + Shape<_128, _32> /*unused by CE*/, /*WF=*/true, /*RawW=*/false, + /*Pref=*/true, /*WPref=*/true, /*WPrefFirst=*/false, /*WPrefDist=*/6, /*CE=*/true, /*EWG=*/2>; + +// Wave cost of a 2SM data-parallel config with N tile tn: (#cluster waves) x tn. +static long long wave_cost(int M, int N, int tn) { + static int cpw = 0; // clusters (2 SMs) per wave + if (cpw == 0) { + int dev = 0, nsm = 148; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&nsm, cudaDevAttrMultiProcessorCount, dev); + cpw = std::max(nsm / 2, 1); + } + const long long cl = (long long)((M + 255) / 256) * ((N + tn - 1) / tn); + return ((cl + cpw - 1) / cpw) * tn; +} + +static int pick_cfg_base(int M); +static int pick_cfg(int M, int N) { + const int c = pick_cfg_base(M); + if (c == 1 && M >= 512 && M < 768 && N >= 224 && wave_cost(M, N, 224) < wave_cost(M, N, 128)) return 15; // Cfg9 + 2-warpgroup CustomEpi // Cfg8 + residual prefetch + if (c == 3 && M >= 3072 && N >= 224 && wave_cost(M, N, 224) <= wave_cost(M, N, 192)) return M < 4096 ? 23 : (M >= 8192 ? 26 : 24); + if ((c == 1 || c == 3) && M >= 768 && M < 4096 && N >= 224) { + long long best = wave_cost(M, N, c == 1 ? 128 : 192); + int pick = c; + const long long c224 = wave_cost(M, N, 224), c176 = wave_cost(M, N, 176); + if (c224 < best) { best = c224; pick = (M <= 1536) ? 14 : (M >= 2048 && M < 3072) ? 16 : 6; } // 2048 bucket -> Cfg16 (was Cfg11) // 2048 bucket -> Cfg10 // WPref also for the M=2048 bucket + if (c176 < best) { best = c176; pick = 17; } // Cfg7 -> Cfg17 (Cfg7 + 2-WG CustomEpi) + return pick; + } + if (c == 4) return 20; // M in (128,256] -> Cfg4 tile + 2-WG CustomEpi + return c; +} + +static int pick_cfg_base(int M) { + if (M <= 128) return 2; + const int rem = M % 256; + if (rem != 0 && rem <= 128) return 5; + if (M >= 1024 && M < 1280) return 1; + if (M >= 768) return 3; + if (M <= 256) return 4; + return 1; +} + +static void sched_for(int cfg, int M, int& raster, int& swz) { + raster = 0; swz = 1; + if (cfg == 14 || cfg == 15 || cfg == 16 || cfg == 17 || cfg == 23) { raster = 1; swz = 1; return; } + if (cfg == 6 || cfg == 8 || cfg == 9 || cfg == 10 || cfg == 11 || cfg == 12 || cfg == 15 || cfg == 24 || cfg == 26) { + if (cfg == 26) { raster = 1; swz = 1; } + else if (M >= 8192) { raster = 2; swz = 8; } // AlongN s8; AlongN s1 + else if (cfg == 24 && M >= 4096) { raster = 1; swz = 1; } + else if (cfg == 12 && M >= 4096) { raster = 1; swz = 2; } + else if (M >= 3072) { raster = 1; swz = 4; } // AlongM s4 (M in [3072,8192)) + else if (cfg == 10 && M >= 2048) { raster = 2; swz = 1; } // Cfg10 M=2048 bucket AlongN s1 (was s2) + else { raster = 2; swz = 2; } + return; + } + if (cfg != 3) return; + if (M >= 2048 && M < 3072) { raster = 1; swz = 1; } + else if (M >= 4096 && M < 8192) { raster = 1; swz = 4; } +} + +#define CFG_DISPATCH(id, CALL) \ + switch (id) { \ + case 1: CALL(Cfg1); break; \ + case 2: CALL(Cfg2); break; \ + case 3: CALL(Cfg3); break; \ + case 4: CALL(Cfg4); break; \ + case 6: CALL(Cfg6); break; \ + case 7: CALL(Cfg7); break; \ + case 8: CALL(Cfg8); break; \ + case 9: CALL(Cfg9); break; \ + case 10: CALL(Cfg10); break; \ + case 11: CALL(Cfg11); break; \ + case 12: CALL(Cfg12); break; \ + case 14: CALL(Cfg14); break; \ + case 15: CALL(Cfg15); break; \ + case 16: CALL(Cfg16); break; \ + case 17: CALL(Cfg17); break; \ + case 20: CALL(Cfg20); break; \ + case 23: CALL(Cfg23); break; \ + case 24: CALL(Cfg24); break; \ + case 26: CALL(Cfg26); break; \ + default: CALL(Cfg5); break; \ + } + +size_t nvfp4_gemm_workspace_size(int M, int N, int K, int cfg) { + size_t r = 0; + if (cfg < 0) cfg = pick_cfg(M, N); +#define WS_CALL(C) r = C::workspace(M, N, K) + CFG_DISPATCH(cfg, WS_CALL) +#undef WS_CALL + return r; +} + +// Does GEMM config `cfg` read the raw row-major weight SF (no swizzle pass needed)? +static bool cfg_raw_wsf(int cfg) { + bool r = false; +#define RAW_CALL(C) r = C::kRawW + CFG_DISPATCH(cfg, RAW_CALL) +#undef RAW_CALL + return r; +} + +static void run_gemm(int cfg, int M, int N, int K, const void* act, const void* w, + const void* act_sf, const void* w_sf, const void* C, void* D, + const float* alpha, void* ws, size_t ws_size, cudaStream_t stream) { + int raster, swz; + sched_for(cfg, M, raster, swz); +#define RUN_CALL(Cf) Cf::run(M, N, K, act, w, act_sf, w_sf, C, D, alpha, ws, ws_size, stream, raster, swz) + CFG_DISPATCH(cfg, RUN_CALL) +#undef RUN_CALL +} + +// Launch helper: regular <<<>>> semantics + the PDL stream-serialization attribute. +// mode bit 0: PDL attribute; bit 1: cooperative launch (driver GUARANTEES all CTAs are +// co-resident or rejects the launch with an error -> used by the fused grid barrier); +// bit 2: 2-CTA cluster along x (grid.x must be even) -> cluster ranks 2k/2k+1 share a +// TPC, so early-exiting CTAs free whole TPCs for the PDL-launched 2SM GEMM CTA pairs. The +// kernels use no cluster feature (pure placement hint). +template +static cudaError_t fast_launch(const cudaLaunchConfig_t& lc, void (*kern)(KArgs...), Args... args) { + using DrvLaunchFn = CUresult (*)(const CUlaunchConfig*, CUfunction, void**, void**); + static DrvLaunchFn drv = [] { + void* f = nullptr; + cudaDriverEntryPointQueryResult q{}; + if (cudaGetDriverEntryPointByVersion("cuLaunchKernelEx", &f, 12000, cudaEnableDefault, &q) != cudaSuccess || + q != cudaDriverEntryPointSuccess) { (void)cudaGetLastError(); f = nullptr; } + return reinterpret_cast(f); + }(); + // per-instantiation cache (one kernel signature may map to a few instances: linear search) + struct Ent { const void* k; CUfunction f; }; + static Ent ents[8]; + static int n_ent = 0; + CUfunction fn = nullptr; + const void* kp = reinterpret_cast(kern); + for (int i = 0; i < n_ent; ++i) if (ents[i].k == kp) { fn = ents[i].f; break; } + if (fn == nullptr && drv != nullptr && n_ent < 8) { + cudaFunction_t rf = nullptr; + if (cudaGetFuncBySymbol(&rf, kp) == cudaSuccess && rf != nullptr) { + fn = reinterpret_cast(rf); + ents[n_ent++] = Ent{kp, fn}; + } else { + (void)cudaGetLastError(); + } + } + if (drv != nullptr && fn != nullptr && lc.numAttrs <= 4) { + CUlaunchAttribute da[4]; + unsigned nda = 0; + bool ok = true; + for (unsigned i = 0; i < lc.numAttrs; ++i) { + const cudaLaunchAttribute& a = lc.attrs[i]; + if (a.id == cudaLaunchAttributeClusterDimension) { + da[nda].id = CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION; + da[nda].value.clusterDim.x = a.val.clusterDim.x; + da[nda].value.clusterDim.y = a.val.clusterDim.y; + da[nda].value.clusterDim.z = a.val.clusterDim.z; + } else if (a.id == cudaLaunchAttributeProgrammaticStreamSerialization) { + da[nda].id = CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_STREAM_SERIALIZATION; + da[nda].value.programmaticStreamSerializationAllowed = a.val.programmaticStreamSerializationAllowed; + } else if (a.id == cudaLaunchAttributePriority) { + da[nda].id = CU_LAUNCH_ATTRIBUTE_PRIORITY; + da[nda].value.priority = a.val.priority; + } else if (a.id == cudaLaunchAttributeCooperative) { + da[nda].id = CU_LAUNCH_ATTRIBUTE_COOPERATIVE; + da[nda].value.cooperative = a.val.cooperative; + } else { ok = false; break; } + ++nda; + } + if (ok) { + CUlaunchConfig dc = {}; + dc.gridDimX = lc.gridDim.x; dc.gridDimY = lc.gridDim.y; dc.gridDimZ = lc.gridDim.z; + dc.blockDimX = lc.blockDim.x; dc.blockDimY = lc.blockDim.y; dc.blockDimZ = lc.blockDim.z; + dc.sharedMemBytes = (unsigned)lc.dynamicSmemBytes; + dc.hStream = reinterpret_cast(lc.stream); + dc.attrs = da; + dc.numAttrs = nda; + std::tuple tv(static_cast(args)...); + void* kargs[sizeof...(KArgs) > 0 ? sizeof...(KArgs) : 1]; + std::apply([&](auto&... e) { int i = 0; ((kargs[i++] = reinterpret_cast(&e)), ...); }, tv); + const CUresult r = drv(&dc, fn, kargs, nullptr); + if (r == CUDA_SUCCESS) return cudaSuccess; + if (r == CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE) return cudaErrorCooperativeLaunchTooLarge; + } + } + return cudaLaunchKernelEx(&lc, kern, static_cast(args)...); +} + +static size_t g_launch_dsmem = 0; +template +static cudaError_t launch_ex(int mode, void (*kern)(KArgs...), dim3 grid, dim3 block, + cudaStream_t stream, Args... args) { + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = grid; + cfg.blockDim = block; + cfg.dynamicSmemBytes = g_launch_dsmem; + cfg.stream = stream; + cudaLaunchAttribute attr[3]; + int na = 0; + if (mode & 4) { + attr[na].id = cudaLaunchAttributeClusterDimension; + attr[na].val.clusterDim.x = 2; attr[na].val.clusterDim.y = 1; attr[na].val.clusterDim.z = 1; + ++na; + } + if (mode & 1) { + attr[na].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attr[na].val.programmaticStreamSerializationAllowed = 1; + ++na; + } + if (mode & 2) { + attr[na].id = cudaLaunchAttributeCooperative; + attr[na].val.cooperative = 1; + ++na; + } + cfg.attrs = attr; + cfg.numAttrs = na; + return fast_launch(cfg, kern, args...); +} +static int g_cl2_ok = 1; +template +static cudaError_t launch_ex_cl2(int mode, void (*kern)(KArgs...), dim3 grid, dim3 block, + cudaStream_t stream, Args... args) { + if (g_cl2_ok && (grid.x & 1) == 0) { + cudaError_t e = launch_ex(mode | 4, kern, grid, block, stream, args...); + if (e == cudaSuccess) return e; + (void)cudaGetLastError(); + if (e != cudaErrorCooperativeLaunchTooLarge) g_cl2_ok = 0; + } + return launch_ex(mode, kern, grid, block, stream, args...); +} +template +static void launch_pdl(void (*kern)(KArgs...), dim3 grid, dim3 block, cudaStream_t stream, + Args... args) { + launch_ex(1, kern, grid, block, stream, args...); +} + +void launch_pipeline(const void* attn_bf16, const void* residual_bf16, + const void* w_fp4, const void* w_sf_rowmajor, + float w_global_decode, void* out_bf16, + void* act_fp4, void* act_sf, void* w_sf_swz, + unsigned int* amax_bufs, int parity, float* alpha_buf, + void* gemm_ws, size_t gemm_ws_size, + int M, int N, int K, cudaStream_t stream, int cfg) { + size_t n_vec = (size_t)M * K / 8; + const int g4 = K / 64; + static int pl_M = -1, pl_N = -1, pl_req = -2, pl_cfg = 0; + static bool pl_raw = false; + if (M != pl_M || N != pl_N || cfg != pl_req) { + pl_M = M; pl_N = N; pl_req = cfg; + pl_cfg = cfg < 0 ? pick_cfg(M, N) : cfg; + pl_raw = cfg_raw_wsf(pl_cfg); + } + cfg = pl_cfg; + // Raw-W-SF GEMM configs consume weight_scale directly -> no swizzle tiles at all. + const bool raw_w = pl_raw; + // Cfg6 (256x224 tile) reads the weight SF in the padded-tile layout (wtn = 224): N tile n's SFs + // at padded rows [256n, 256n+224), zero rows up to 256n+256 -> wsf_rows = ceil(N/224)*256. + const int wtn = (cfg == 6 || cfg == 8 || cfg == 14 || cfg == 9 || cfg == 10 || cfg == 11 || cfg == 12 || cfg == 15 || cfg == 16 || cfg == 23 || cfg == 24 || cfg == 26) ? 224 : (cfg == 7 || cfg == 17) ? 176 : 0; + const int wsf_rows = wtn ? ((N + wtn - 1) / wtn) * (wtn <= 128 ? 128 : 256) : N; + int wsf_real_end = wsf_rows; + if (wtn) { + const int stride = wtn <= 128 ? 128 : 256; + const int ntn = (N + wtn - 1) / wtn; + wsf_real_end = (ntn - 1) * stride + (N - (ntn - 1) * wtn); + } + const int nWt = raw_w ? 0 : ((wsf_real_end + 127) / 128) * ((g4 + 31) / 32); // W-SF swizzle tiles + // M >= 2048: the swizzle moves into act_quant (pure-DRAM amax); else it stays in kernel 1. + const bool wsf_in_quant = (M >= 1024) && !raw_w; + // 1. amax CTAs (|| weight SF swizzle CTAs for small M), grid capped to one resident wave. + const int nW = wsf_in_quant ? 0 : nWt; + const int mblk_ = (M + 127) / 128; + // reverse quant row order for M >= 2048; also for the Cfg14 bucket (A/B above). + const int rev_q = (M >= 2048 || (cfg == 14 && M >= 1536)) ? 1 : 0; + // FUSED single-pass amax+quant (CA=2) when all quant CTAs fit co-resident on the GPU. + bool fused = false; + if (K % 128 == 0) { + static int n_sm = 0, occ_w = 0, occ_n = 0; + if (n_sm == 0) { + int dev = 0; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&n_sm, cudaDevAttrMultiProcessorCount, dev); + cudaOccupancyMaxActiveBlocksPerMultiprocessor(&occ_w, act_quant_tile_kernel<2, true, true>, 256, 0); + cudaOccupancyMaxActiveBlocksPerMultiprocessor(&occ_n, act_quant_tile_kernel<2, false, true>, 256, 0); + } + const long long nq = (long long)(K / 128) * mblk_; + const int occ = (nWt > 0) ? occ_w : occ_n; + fused = nq <= (long long)occ * n_sm; + } + // M <= 128 (raw W-SF Cfg2, no swizzle tiles): single-cluster front (act_quant_cluster_kernel). + const bool kc8k = (K == 8192 && N == 8192); + auto clk = (kc8k && M == 128) ? act_quant_cluster_kernel<8192, 128> + : kc8k ? act_quant_cluster_kernel<8192, 0> : act_quant_cluster_kernel<0, 0>; + auto f1k = !kc8k ? act_quant_fused1k_kernel<0, 0, 0> + : M == 256 ? act_quant_fused1k_kernel<8192, 8192, 256> + : M == 512 ? act_quant_fused1k_kernel<8192, 8192, 512> + : M == 768 ? act_quant_fused1k_kernel<8192, 8192, 768> + : act_quant_fused1k_kernel<8192, 8192, 0>; + auto fpk = !kc8k ? act_quant_persist_kernel + : M == 1024 ? act_quant_persist_kernel + : M == 1536 ? act_quant_persist_kernel + : M == 2048 ? act_quant_persist_kernel + : M == 3072 ? act_quant_persist_kernel + : M == 4096 ? act_quant_persist_kernel + : M == 8192 ? act_quant_persist_kernel + : act_quant_persist_kernel; + auto ppk = !kc8k ? act_quant_persist_kernel + : M == 8192 ? act_quant_persist_kernel + : act_quant_persist_kernel; + if (M <= 128 && nWt == 0 && K % 512 == 0 && K / 512 >= 1 && K / 512 <= 16) { + static int cl_mode = -1; // -1 untried, 1 works, 0 disabled + if (cl_mode != 0) { + if (cl_mode < 0) { + cudaFuncSetAttribute(act_quant_cluster_kernel<8192, 128>, cudaFuncAttributeNonPortableClusterSizeAllowed, 1); + cudaFuncSetAttribute(act_quant_cluster_kernel<8192, 0>, cudaFuncAttributeNonPortableClusterSizeAllowed, 1); + cudaFuncSetAttribute(act_quant_cluster_kernel<0, 0>, cudaFuncAttributeNonPortableClusterSizeAllowed, 1); + (void)cudaGetLastError(); + } + const int nc = K / 512; + cudaLaunchConfig_t lc = {}; + lc.gridDim = dim3((unsigned)nc); + lc.blockDim = dim3(1024); + lc.dynamicSmemBytes = 0; + lc.stream = stream; + cudaLaunchAttribute at[2]; + at[0].id = cudaLaunchAttributeClusterDimension; + at[0].val.clusterDim.x = (unsigned)nc; at[0].val.clusterDim.y = 1; at[0].val.clusterDim.z = 1; + at[1].id = cudaLaunchAttributeProgrammaticStreamSerialization; + at[1].val.programmaticStreamSerializationAllowed = 1; + lc.attrs = at; + lc.numAttrs = 2; + // (CTA scheduling / launch overlaps the previous GEMM's tail; no early input reads) + cudaError_t e = fast_launch(lc, clk, + reinterpret_cast(attn_bf16), M, K, amax_bufs, parity, + w_global_decode, alpha_buf, reinterpret_cast(act_fp4), + reinterpret_cast(act_sf)); + if (e == cudaSuccess) { + cl_mode = 1; + run_gemm(cfg, M, N, K, act_fp4, w_fp4, act_sf, w_sf_rowmajor, + residual_bf16, out_bf16, alpha_buf, gemm_ws, gemm_ws_size, stream); + return; + } + (void)cudaGetLastError(); + cl_mode = 0; + } + } + if (fused && M > 128 && M < 1024 && K % 512 == 0) { + static int f1k_mode = -1; // -1 untried, 1 ok, 0 disabled + if (f1k_mode != 0) { + if (f1k_mode < 0) { + cudaFuncSetAttribute(act_quant_fused1k_kernel<8192, 8192, 256>, cudaFuncAttributeMaxDynamicSharedMemorySize, kFused1kSmem); + cudaFuncSetAttribute(act_quant_fused1k_kernel<8192, 8192, 512>, cudaFuncAttributeMaxDynamicSharedMemorySize, kFused1kSmem); + cudaFuncSetAttribute(act_quant_fused1k_kernel<8192, 8192, 768>, cudaFuncAttributeMaxDynamicSharedMemorySize, kFused1kSmem); + cudaFuncSetAttribute(act_quant_fused1k_kernel<8192, 8192, 0>, cudaFuncAttributeMaxDynamicSharedMemorySize, kFused1kSmem); + cudaFuncSetAttribute(act_quant_fused1k_kernel<0, 0, 0>, cudaFuncAttributeMaxDynamicSharedMemorySize, kFused1kSmem); + (void)cudaGetLastError(); + } + const int nqc = (K / 128) * mblk_ / 4; + // W-SF swizzle tiles per CTA: 4 (one per group) if the whole grid fits one + // co-resident wave, else 8 (two per group) so the cooperative launch still fits + // (M = 768: 96 quant + 94 -> 47 swizzle CTAs = 143 <= 148 SMs). + static int f1k_cap = 0; + if (f1k_cap == 0) { + int dev = 0, nsm = 148, occ = 1; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&nsm, cudaDevAttrMultiProcessorCount, dev); + if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&occ, f1k, 1024, kFused1kSmem) != cudaSuccess || occ < 1) { + (void)cudaGetLastError(); + occ = 1; + } + f1k_cap = occ * nsm; + } + int wpg = 1; + if ((nWt + 3) / 4 + nqc > f1k_cap) wpg = 2; + const int nWc0 = (nWt + 4 * wpg - 1) / (4 * wpg); + static int cl2_mode = 1; // 1 try cluster-2 launch, 0 disabled + const int pad = ((nWc0 + nqc) & 1) && cl2_mode ? 1 : 0; + cudaError_t e = cudaErrorUnknown; + for (int attempt = 0; attempt < 2; ++attempt) { + const bool use_cl = attempt == 0; + if (use_cl && !cl2_mode) continue; + const int nWc = nWc0 + (use_cl ? pad : 0); + cudaLaunchConfig_t lc = {}; + lc.gridDim = dim3((unsigned)(nWc + nqc)); + lc.blockDim = dim3(1024); + lc.dynamicSmemBytes = kFused1kSmem; + lc.stream = stream; + cudaLaunchAttribute at[4]; + at[0].id = cudaLaunchAttributeCooperative; + at[0].val.cooperative = 1; + at[1].id = cudaLaunchAttributeProgrammaticStreamSerialization; + at[1].val.programmaticStreamSerializationAllowed = 1; + at[2].id = cudaLaunchAttributeClusterDimension; + at[2].val.clusterDim.x = 2; at[2].val.clusterDim.y = 1; at[2].val.clusterDim.z = 1; + lc.attrs = at; + static int f1k_prio = INT_MAX; + if (f1k_prio == INT_MAX) { + int lo = 0, hi = 0; + if (cudaDeviceGetStreamPriorityRange(&lo, &hi) != cudaSuccess) { (void)cudaGetLastError(); hi = 0; } + f1k_prio = hi; + } + at[use_cl ? 3 : 2].id = cudaLaunchAttributePriority; + at[use_cl ? 3 : 2].val.priority = f1k_prio; + lc.numAttrs = use_cl ? 4 : 3; + e = fast_launch(lc, f1k, + reinterpret_cast(attn_bf16), M, K, amax_bufs, parity, + w_global_decode, alpha_buf, reinterpret_cast(act_fp4), + reinterpret_cast(act_sf), nWc, nWt, wpg, + reinterpret_cast(w_sf_rowmajor), reinterpret_cast(w_sf_swz), N, wtn, + (M >= 512 && M < 1024) ? 1 : 0); + if (e == cudaSuccess) break; + (void)cudaGetLastError(); + if (use_cl && e != cudaErrorCooperativeLaunchTooLarge) cl2_mode = 0; + } + if (e == cudaSuccess) { + if (f1k_mode < 0) f1k_mode = 1; + run_gemm(cfg, M, N, K, act_fp4, w_fp4, act_sf, raw_w ? w_sf_rowmajor : (const void*)w_sf_swz, + residual_bf16, out_bf16, alpha_buf, gemm_ws, gemm_ws_size, stream); + return; + } + (void)cudaGetLastError(); + if (e != cudaErrorCooperativeLaunchTooLarge) f1k_mode = 0; // TooLarge: only this M + } + } + if (M >= 1024 && M <= 8192 && K % 128 == 0) { + static int fp_mode = 3; // 3 = coop + PDL, 2 = coop only, 0 = disabled + static int fp_occ = 0, fp_nsm = 0; + constexpr int kFpDsm = 65536; + static int fp_dsm_ok = 1; + if (fp_occ == 0) { + int dev = 0; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&fp_nsm, cudaDevAttrMultiProcessorCount, dev); + void (*fps[])(const __nv_bfloat16*, int, int, unsigned int*, int, float, float*, uint8_t*, uint8_t*, + int, const uint8_t*, uint8_t*, int, int, int) = { + act_quant_persist_kernel, act_quant_persist_kernel, + act_quant_persist_kernel, act_quant_persist_kernel, + act_quant_persist_kernel, act_quant_persist_kernel, + act_quant_persist_kernel, act_quant_persist_kernel}; + fp_occ = INT_MAX; + for (auto fn : fps) { + if (cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, kFpDsm) != cudaSuccess) { + (void)cudaGetLastError(); fp_dsm_ok = 0; + } + int o = 0; + if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&o, fn, 256, kFpDsm) != cudaSuccess) { (void)cudaGetLastError(); o = 1; } + fp_occ = std::min(fp_occ, o); + } + if (fp_occ < 1) fp_occ = 1; + } + const int ntiles = (K / 128) * mblk_; + const int nWq = wsf_in_quant ? nWt : 0; + int G = std::min(ntiles, fp_occ * fp_nsm); + G = std::max(G, nWq); + if ((G & 1) && G + 1 <= fp_occ * fp_nsm) ++G; + cudaError_t e = cudaErrorUnknown; + while (fp_mode != 0 && G <= fp_occ * fp_nsm) { + g_launch_dsmem = !fp_dsm_ok ? 0 : (ntiles > 3 * G) ? (size_t)kFpDsm : (ntiles > 2 * G) ? (size_t)32768 : 0; + e = launch_ex_cl2(fp_mode, fpk, dim3((unsigned)G), dim3(256), stream, + reinterpret_cast(attn_bf16), M, K, amax_bufs, parity, + w_global_decode, alpha_buf, reinterpret_cast(act_fp4), + reinterpret_cast(act_sf), nWq, + reinterpret_cast(w_sf_rowmajor), + reinterpret_cast(w_sf_swz), N, rev_q, wtn); + g_launch_dsmem = 0; + if (e == cudaSuccess) break; + (void)cudaGetLastError(); + if (e == cudaErrorCooperativeLaunchTooLarge) break; + fp_mode = (fp_mode == 3) ? 2 : 0; + } + if (e == cudaSuccess) { + run_gemm(cfg, M, N, K, act_fp4, w_fp4, act_sf, raw_w ? w_sf_rowmajor : (const void*)w_sf_swz, + residual_bf16, out_bf16, alpha_buf, gemm_ws, gemm_ws_size, stream); + return; + } + } + if (fused) { + const int gx = K / 128; + const int wy = nWt > 0 ? (nWt + gx - 1) / gx : 0; + auto kern = (nWt > 0) ? act_quant_tile_kernel<2, true, true> : act_quant_tile_kernel<2, false, true>; + static int coop_mode = 2; // [race fix] 2 = coop only (no PDL: first kernel of the chain), 0 = fused disabled + cudaError_t e = cudaErrorUnknown; + while (coop_mode != 0) { + e = launch_ex_cl2(coop_mode, kern, dim3((unsigned)gx, (unsigned)(mblk_ + wy)), dim3(256), stream, + reinterpret_cast(attn_bf16), M, K, amax_bufs, parity, + w_global_decode, alpha_buf, reinterpret_cast(act_fp4), + reinterpret_cast(act_sf), wy, nWt, + reinterpret_cast(w_sf_rowmajor), + reinterpret_cast(w_sf_swz), N, rev_q, wtn); + if (e == cudaSuccess) break; + (void)cudaGetLastError(); // launch-config errors are not sticky; clear it + if (e == cudaErrorCooperativeLaunchTooLarge) break; // this M too big: 2-launch path + coop_mode = 0; + } + if (e == cudaSuccess) { + run_gemm(cfg, M, N, K, act_fp4, w_fp4, act_sf, raw_w ? w_sf_rowmajor : (const void*)w_sf_swz, + residual_bf16, out_bf16, alpha_buf, gemm_ws, gemm_ws_size, stream); + return; + } + } + const int wave = 148 * 8; + const int cap = std::max(wave - nW, 148); + int nA = (int)std::min((n_vec + 255) / 256, (size_t)cap); + nA = std::max(nA, 1); + // even grid for the 2-CTA cluster launch (one more amax CTA: the grid-stride max is + // order-free / idempotent -> bit-exact) + if ((nW + nA) & 1) ++nA; + launch_ex_cl2(1, amax_wsf_kernel, dim3(nW + nA), dim3(256), stream, + reinterpret_cast(attn_bf16), n_vec, amax_bufs + parity, nW, nA, + reinterpret_cast(w_sf_rowmajor), reinterpret_cast(w_sf_swz), + N, K, wtn); + // 2. activation quant: 128-row x 64*CA-col tiles. CA=2 (4 blocks/thread) when that still + // gives >= 2 CTAs per SM, else CA=1 (more CTAs for small M). Needs K % 128 == 0 for CA=2. + // With wsf_in_quant, wy leading grid rows hold the nWt swizzle CTAs. + const int mblk = (M + 127) / 128; + auto qa = [&](auto kern, int CA, bool wsf) { + const int gx = K / (64 * CA); + const int wy = wsf ? (nWt + gx - 1) / gx : 0; + launch_pdl(kern, dim3((unsigned)gx, (unsigned)(mblk + wy)), dim3(256), stream, + reinterpret_cast(attn_bf16), M, K, amax_bufs, parity, + w_global_decode, alpha_buf, reinterpret_cast(act_fp4), + reinterpret_cast(act_sf), wy, wsf ? nWt : 0, + reinterpret_cast(w_sf_rowmajor), + reinterpret_cast(w_sf_swz), N, rev_q, wtn); + }; + const bool ca2 = K % 128 == 0 && (long long)(K / 128) * mblk >= 2LL * 148; + if (M >= 1024 && K % 128 == 0) { + // persistent, register-pipelined quant (+ W-SF swizzle items when wsf_in_quant) + static int pq_occ = 0, pq_nsm = 0; + if (pq_occ == 0) { + int dev = 0; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&pq_nsm, cudaDevAttrMultiProcessorCount, dev); + void (*pps[])(const __nv_bfloat16*, int, int, unsigned int*, int, float, float*, uint8_t*, uint8_t*, + int, const uint8_t*, uint8_t*, int, int, int) = { + act_quant_persist_kernel, act_quant_persist_kernel, + act_quant_persist_kernel}; + pq_occ = INT_MAX; + for (auto fn : pps) { + int o = 0; + if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&o, fn, 256, 0) != cudaSuccess) { (void)cudaGetLastError(); o = 1; } + pq_occ = std::min(pq_occ, o); + } + if (pq_occ < 1) pq_occ = 1; + } + const int ntiles = (K / 128) * mblk; + const int nWq = wsf_in_quant ? nWt : 0; + int G = std::min(ntiles, pq_occ * pq_nsm); + G = std::max(G, nWq); + if (G & 1) ++G; // even grid for the 2-CTA cluster launch (extra CTA: idle if t >= ntiles) + launch_ex_cl2(1, ppk, dim3((unsigned)G), dim3(256), stream, + reinterpret_cast(attn_bf16), M, K, amax_bufs, parity, + w_global_decode, alpha_buf, reinterpret_cast(act_fp4), + reinterpret_cast(act_sf), nWq, + reinterpret_cast(w_sf_rowmajor), + reinterpret_cast(w_sf_swz), N, rev_q, wtn); + } else if (wsf_in_quant) { + if (ca2) qa(act_quant_tile_kernel<2, true>, 2, true); + else qa(act_quant_tile_kernel<1, true>, 1, true); + } else { + if (ca2) qa(act_quant_tile_kernel<2, false>, 2, false); + else qa(act_quant_tile_kernel<1, false>, 1, false); + } + // 3. GEMM (tile config / orientation chosen per M), PDL-launched + run_gemm(cfg, M, N, K, act_fp4, w_fp4, act_sf, raw_w ? w_sf_rowmajor : (const void*)w_sf_swz, + residual_bf16, out_bf16, + alpha_buf, gemm_ws, gemm_ws_size, stream); +} diff --git a/kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/kernel.h b/kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..08bd2e052d10e673288523915922b37235242b63 --- /dev/null +++ b/kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/kernel.h @@ -0,0 +1,28 @@ +// kernel.h -- interface between main.cpp (torch binding) and kernel.cu +#pragma once +#include +#include +#include + +// Bytes of the swizzled (128x4 blocked) SF buffer for a rows x (K/16) scale matrix. +inline size_t sf_swizzled_bytes(int rows, int K) { + size_t rb = (size_t)((rows + 127) / 128); + size_t kb = (size_t)((K / 16 + 3) / 4); + return rb * kb * 512; +} + +// cfg < 0: automatic per-M choice (pick_cfg); otherwise a fixed GEMM config id (probing). +size_t nvfp4_gemm_workspace_size(int M, int N, int K, int cfg = -1); + +// amax_bufs: [0],[1] amax slots, [2] alpha, [4],[5] fused-barrier counters, [32+32p],[33+32p] fused {amax,counter} pairs (96 uint32 total, 128 B line per parity); +// slots used alternately (parity); the quant kernel zeroes the +// slot the NEXT call will use, so no memset launch is needed in the hot path. +void launch_pipeline(const void* attn_bf16, const void* residual_bf16, + const void* w_fp4, const void* w_sf_rowmajor, + float w_global_decode, void* out_bf16, + void* act_fp4, void* act_sf, void* w_sf_swz, + unsigned int* amax_bufs, int parity, float* alpha_buf, + void* gemm_ws, size_t gemm_ws_size, + int M, int N, int K, cudaStream_t stream, int cfg = -1); + +extern unsigned long long g_const_uploads; diff --git a/kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/main.cpp b/kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e599a4d035c4793200d3635683f402844c8e7415 --- /dev/null +++ b/kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/main.cpp @@ -0,0 +1,329 @@ +// main.cpp -- torch binding for NVFP4 o_proj + residual. +// Hot path = torch::empty(output) + 3 kernel launches (amax[/w-SF swizzle], act quant +// [/w-SF swizzle], GEMM), chained with Programmatic Dependent Launch (see kernel.cu). +// All scratch buffers (fp4 activations, SFs, amax/alpha, GEMM workspace) are cached in a +// HEAP-allocated, never-freed struct (grown on demand) -> no per-call allocations and no +// static CUDA-tensor destructor at teardown. +#include +#include +#include +#include +#include +#include +#include +#include +#include "kernel.h" + +namespace { +struct Scratch { + void* act_fp4 = nullptr; size_t act_fp4_cap = 0; + void* act_sf = nullptr; size_t act_sf_cap = 0; + void* w_sf = nullptr; size_t w_sf_cap = 0; + void* gws = nullptr; size_t gws_cap = 0; + unsigned int* small = nullptr; // [0],[1]: amax slots, [2]: alpha (float bits), [4],[5]: fused-barrier counters, [32+32p],[33+32p]: fused barrier {amax,counter} pairs (own 128 B line per parity) + int parity = 0; +}; +Scratch& scratch() { static Scratch& s = *new Scratch(); return s; } + +void ensure(void*& p, size_t& cap, size_t need) { + if (need <= cap) return; + if (p) { cudaDeviceSynchronize(); cudaFree(p); } + size_t c = need + need / 4 + 256; + cudaMalloc(&p, c); + cap = c; +} + +void ensure_programmatic_edges(cudaGraph_t g) { + size_t n = 0; +#if CUDART_VERSION >= 13000 + if (cudaGraphGetEdges(g, nullptr, nullptr, nullptr, &n) != cudaSuccess || n == 0) { (void)cudaGetLastError(); return; } +#else + if (cudaGraphGetEdges_v2(g, nullptr, nullptr, nullptr, &n) != cudaSuccess || n == 0) { (void)cudaGetLastError(); return; } +#endif + std::vector from(n), to(n); + std::vector ed(n); +#if CUDART_VERSION >= 13000 + if (cudaGraphGetEdges(g, from.data(), to.data(), ed.data(), &n) != cudaSuccess) { (void)cudaGetLastError(); return; } +#else + if (cudaGraphGetEdges_v2(g, from.data(), to.data(), ed.data(), &n) != cudaSuccess) { (void)cudaGetLastError(); return; } +#endif + for (size_t i = 0; i < n; ++i) { + if (ed[i].type == cudaGraphDependencyTypeProgrammatic) continue; + cudaGraphNodeType ta, tb; + if (cudaGraphNodeGetType(from[i], &ta) != cudaSuccess || cudaGraphNodeGetType(to[i], &tb) != cudaSuccess) { + (void)cudaGetLastError(); continue; + } + if (ta != cudaGraphNodeTypeKernel || tb != cudaGraphNodeTypeKernel) continue; + cudaGraphEdgeData pe = {}; + pe.from_port = cudaGraphKernelNodePortProgrammatic; + pe.to_port = 0; + pe.type = cudaGraphDependencyTypeProgrammatic; +#if CUDART_VERSION >= 13000 + if (cudaGraphRemoveDependencies(g, &from[i], &to[i], &ed[i], 1) != cudaSuccess) { (void)cudaGetLastError(); continue; } + if (cudaGraphAddDependencies(g, &from[i], &to[i], &pe, 1) != cudaSuccess) { + (void)cudaGetLastError(); + (void)cudaGraphAddDependencies(g, &from[i], &to[i], &ed[i], 1); // restore the full edge + (void)cudaGetLastError(); + } +#else + if (cudaGraphRemoveDependencies_v2(g, &from[i], &to[i], &ed[i], 1) != cudaSuccess) { (void)cudaGetLastError(); continue; } + if (cudaGraphAddDependencies_v2(g, &from[i], &to[i], &pe, 1) != cudaSuccess) { + (void)cudaGetLastError(); + (void)cudaGraphAddDependencies_v2(g, &from[i], &to[i], &ed[i], 1); + (void)cudaGetLastError(); + } +#endif + } +} + +void pipeline(Scratch& s, const void* attn, const void* res, const void* wq, const void* ws, + float wgd, void* out, int M, int N, int K, cudaStream_t stream, int cfg) { + if (!s.small) { + cudaMalloc(&s.small, 96 * sizeof(unsigned int)); + cudaMemsetAsync(s.small, 0, 96 * sizeof(unsigned int), stream); // one-time init + } + static int wM = -1, wN = -1, wK = -1, wC = -2; + static size_t wsz_c = 0; + if (M != wM || N != wN || K != wK || cfg != wC) { + ensure(s.act_fp4, s.act_fp4_cap, (size_t)M * K / 2); + ensure(s.act_sf, s.act_sf_cap, sf_swizzled_bytes(M, K)); + // weight SF: sized for the padded-tile layouts of the 256x224/176 configs (ceil(N/176)*256 rows >= N) + { + const size_t cap0 = s.w_sf_cap; + ensure(s.w_sf, s.w_sf_cap, sf_swizzled_bytes(((N + 175) / 176) * 256, K)); + if (s.w_sf_cap != cap0) cudaMemsetAsync(s.w_sf, 0, s.w_sf_cap, stream); + } + wsz_c = nvfp4_gemm_workspace_size(M, N, K, cfg); + ensure(s.gws, s.gws_cap, wsz_c + 16); + wM = M; wN = N; wK = K; wC = cfg; + } + const size_t wsz = wsz_c; + auto direct = [&](cudaStream_t st) { + launch_pipeline(attn, res, wq, ws, wgd, out, s.act_fp4, s.act_sf, s.w_sf, s.small, s.parity, + reinterpret_cast(s.small + 2), s.gws, wsz, M, N, K, st, cfg); + }; + struct GKey { + const void *attn, *res, *wq, *ws, *out, *a4, *asf, *wsf, *gws, *small; + uint32_t wgd_bits; int32_t M, N, K, parity, cfg; + }; + static_assert(sizeof(GKey) == 10 * 8 + 6 * 4, "GKey: no padding (memcmp)"); + struct StabKey { const void *wq, *ws, *a4, *asf, *wsf, *gws, *small; int32_t M, N, K, cfg; }; + struct GEnt { GKey k; cudaGraphExec_t ex; unsigned long long gen; bool used; }; + constexpr int kGEnts = 32; + static GEnt* gents = new GEnt[kGEnts](); // heap, never freed + static int g_next = 0; + static bool g_ok = true; + static cudaStream_t cap_stream = nullptr; + static StabKey last_stab; + static bool have_stab = false; + GKey gk; + std::memset(&gk, 0, sizeof(gk)); + gk.attn = attn; gk.res = res; gk.wq = wq; gk.ws = ws; gk.out = out; + gk.a4 = s.act_fp4; gk.asf = s.act_sf; gk.wsf = s.w_sf; gk.gws = s.gws; gk.small = s.small; + std::memcpy(&gk.wgd_bits, &wgd, 4); + gk.M = M; gk.N = N; gk.K = K; gk.parity = s.parity; gk.cfg = cfg; + StabKey sk; + std::memset(&sk, 0, sizeof(sk)); + sk.wq = wq; sk.ws = ws; sk.a4 = s.act_fp4; sk.asf = s.act_sf; sk.wsf = s.w_sf; sk.gws = s.gws; + sk.small = s.small; sk.M = M; sk.N = N; sk.K = K; sk.cfg = cfg; + const bool stable = have_stab && std::memcmp(&sk, &last_stab, sizeof(sk)) == 0; + last_stab = sk; have_stab = true; + bool done = false; + if (g_ok && wsz == 0) { + cudaStreamCaptureStatus cst = cudaStreamCaptureStatusNone; + if (cudaStreamIsCapturing(stream, &cst) != cudaSuccess) { (void)cudaGetLastError(); cst = cudaStreamCaptureStatusActive; } + if (cst == cudaStreamCaptureStatusNone) { + for (int i = 0; i < kGEnts; ++i) { + GEnt& e = gents[i]; + if (!e.used || std::memcmp(&e.k, &gk, sizeof(gk)) != 0) continue; + if (e.gen != g_const_uploads) { // stale (__constant__ Params changed): drop + cudaStreamSynchronize(stream); + cudaGraphExecDestroy(e.ex); + e.used = false; + break; + } + if (cudaGraphLaunch(e.ex, stream) == cudaSuccess) done = true; + else { (void)cudaGetLastError(); g_ok = false; } + break; + } + if (!done && g_ok && stable) { + if (cap_stream == nullptr && + cudaStreamCreateWithFlags(&cap_stream, cudaStreamNonBlocking) != cudaSuccess) { + (void)cudaGetLastError(); cap_stream = nullptr; g_ok = false; + } + if (cap_stream != nullptr) { + const unsigned long long up0 = g_const_uploads; + cudaGraph_t g = nullptr; + cudaGraphExec_t ex = nullptr; + bool ok = cudaStreamBeginCapture(cap_stream, cudaStreamCaptureModeThreadLocal) == cudaSuccess; + if (ok) { + direct(cap_stream); + ok = cudaStreamEndCapture(cap_stream, &g) == cudaSuccess && g != nullptr; + } + if (ok) ensure_programmatic_edges(g); + GEnt& e = gents[g_next]; + bool updated = false; + if (ok && e.used) { + cudaGraphExecUpdateResultInfo info{}; + if (cudaGraphExecUpdate(e.ex, g, &info) == cudaSuccess) { ex = e.ex; updated = true; } + else (void)cudaGetLastError(); + } + if (ok && !updated) ok = cudaGraphInstantiate(&ex, g, 0) == cudaSuccess; + if (g) cudaGraphDestroy(g); + if (ok) ok = cudaGraphLaunch(ex, stream) == cudaSuccess; + if (ok) { + done = true; + if (e.used && !updated) { cudaStreamSynchronize(stream); cudaGraphExecDestroy(e.ex); } + e.k = gk; e.ex = ex; e.gen = up0; e.used = true; // gen != current if an upload was captured + g_next = (g_next + 1) % kGEnts; + } else { + (void)cudaGetLastError(); + if (updated) { cudaStreamSynchronize(stream); cudaGraphExecDestroy(e.ex); e.used = false; } + else if (ex) cudaGraphExecDestroy(ex); + g_ok = false; // graphs unusable here: direct launches from now on + } + } + } + } + } + if (!done) direct(stream); + s.parity ^= 1; +} +} // namespace + +// * the full validation (TORCH_CHECKs, dtype / shape / numel checks) runs only when the +// (sizes, strides-contiguity, dtypes, device) signature differs from the last validated call; +// the fast path compares a small POD key (no dispatcher calls), +// * no .contiguous() dispatcher round trips when inputs are already contiguous (checked inline), +// * the output is allocated with at::detail::empty_cuda (direct caching-allocator call, no +// dispatcher / TensorOptions construction) -- a fresh tensor every call, +// * the current stream is read once per call (thread-local lookup). +// Device work and numerics are unchanged (bit-exact). +namespace { +struct RunKey { + int64_t as[3], rs[3], wq_numel, ws_numel, wq_last, ws_last; + int32_t adim, rdim, dev_ok, dev, at_dt, res_dt, wq_es, ws_es; +}; +static_assert(sizeof(RunKey) == 10 * 8 + 8 * 4, "RunKey: no padding (memcmp)"); + +constexpr int kOutPool = 2; +struct OutPool { at::Tensor t[kOutPool]; int next = 0; int last = 0; }; +OutPool& out_pool() { static OutPool& p = *new OutPool(); return p; } +} // namespace + +torch::Tensor run(const torch::Tensor& attn_output, const torch::Tensor& residual, + const torch::Tensor& weight_fp4, const torch::Tensor& weight_scale, + double weight_global_decode) { + // contiguous() only when needed (inline is_contiguous check; normally no copy, no dispatch) + torch::Tensor attn_c, res_c, wq_c, ws_c; + const torch::Tensor* pa = &attn_output; + const torch::Tensor* pr = &residual; + const torch::Tensor* pw = &weight_fp4; + const torch::Tensor* ps = &weight_scale; + if (!attn_output.is_contiguous()) { attn_c = attn_output.contiguous(); pa = &attn_c; } + if (!residual.is_contiguous()) { res_c = residual.contiguous(); pr = &res_c; } + if (!weight_fp4.is_contiguous()) { wq_c = weight_fp4.contiguous(); pw = &wq_c; } + if (!weight_scale.is_contiguous()) { ws_c = weight_scale.contiguous(); ps = &ws_c; } + const torch::Tensor& a = *pa; const torch::Tensor& r = *pr; + const torch::Tensor& wq = *pw; const torch::Tensor& ws = *ps; + + RunKey key; + const auto asz = a.sizes(), rsz = r.sizes(); + key.adim = (int32_t)asz.size(); key.rdim = (int32_t)rsz.size(); + if (key.adim == 3) { key.as[0] = asz[0]; key.as[1] = asz[1]; key.as[2] = asz[2]; } + else { key.as[0] = key.as[1] = key.as[2] = 0; } + if (key.rdim == 3) { key.rs[0] = rsz[0]; key.rs[1] = rsz[1]; key.rs[2] = rsz[2]; } + else { key.rs[0] = key.rs[1] = key.rs[2] = 0; } + const auto wsz = wq.sizes(), ssz = ws.sizes(); + key.wq_numel = wq.numel(); key.ws_numel = ws.numel(); + key.wq_last = wsz.empty() ? -1 : wsz.back(); + key.ws_last = ssz.empty() ? -1 : ssz.back(); + const c10::Device da = a.device(); + key.dev_ok = (da.is_cuda() && r.device() == da && wq.device() == da && ws.device() == da) ? 1 : 0; + key.dev = (int32_t)da.index(); + key.at_dt = (int32_t)a.scalar_type(); key.res_dt = (int32_t)r.scalar_type(); + key.wq_es = (int32_t)wq.element_size(); key.ws_es = (int32_t)ws.element_size(); + + static RunKey last{}; + static bool last_ok = false; + if (!last_ok || std::memcmp(&key, &last, sizeof(RunKey)) != 0) { + // full validation (slow path; the kernels' assumptions, see kernel.cu): bf16 activations / + // residual, packed FP4 weight [*, N, K/2], e4m3 SF [*, N, K/16], K % 64 == 0, N % 8 == 0. + TORCH_CHECK(key.dev_ok == 1 && key.dev >= 0, "inputs must be CUDA tensors on one device"); + TORCH_CHECK(key.adim == 3 && key.rdim == 3, "attn_output / residual must be 3-D"); + TORCH_CHECK(a.scalar_type() == at::kBFloat16 && r.scalar_type() == at::kBFloat16, + "attn_output / residual must be bfloat16"); + TORCH_CHECK(key.wq_es == 1 && key.ws_es == 1, "weight_fp4 / weight_scale must be 1-byte types"); + TORCH_CHECK(key.rs[0] == key.as[0] && key.rs[1] == key.as[1], "residual batch/seq must match attn_output"); + const int64_t K = key.as[2], N = key.rs[2]; + TORCH_CHECK(K % 64 == 0 && K > 0 && K <= INT32_MAX, "proj_dim must be a positive multiple of 64"); + TORCH_CHECK(N % 8 == 0 && N > 0 && N <= INT32_MAX, "hidden_size must be a positive multiple of 8"); + TORCH_CHECK(key.wq_numel == N * (K / 2) && key.wq_last == K / 2, "weight_fp4 must be [1, N, K/2]"); + TORCH_CHECK(key.ws_numel == N * (K / 16) && key.ws_last == K / 16, "weight_scale must be [1, N, K/16]"); + TORCH_CHECK(key.as[0] * key.as[1] <= INT32_MAX, "too many tokens"); + last = key; + last_ok = true; + } + const int K = (int)key.as[2], N = (int)key.rs[2]; + const int M = (int)(key.as[0] * key.as[1]); + // output: reuse a uniquely-owned pooled tensor of the same shape / device, else allocate + OutPool& op = out_pool(); + at::Tensor out; + const int64_t osz[3] = {key.as[0], key.as[1], key.rs[2]}; + const c10::IntArrayRef oszr(osz, 3); + for (int k = 1; k <= kOutPool; ++k) { + const int i = (op.last + k) % kOutPool; + at::Tensor& t = op.t[i]; + if (t.use_count() == 1 && t.storage().use_count() == 1 && t.sizes().equals(oszr) && + t.device() == da) { + out = t; + op.last = i; + break; + } + } + if (!out.defined()) { + out = at::detail::empty_cuda(oszr, at::kBFloat16, da, c10::nullopt); + op.t[op.next] = out; + op.last = op.next; + op.next = (op.next + 1) % kOutPool; + } + if (M == 0) return out; + cudaStream_t stream = c10::cuda::getCurrentCUDAStream(key.dev).stream(); + pipeline(scratch(), a.data_ptr(), r.data_ptr(), wq.data_ptr(), ws.data_ptr(), + (float)weight_global_decode, out.data_ptr(), M, N, K, stream, -1); + return out; +} + +namespace { +PyObject* g_run_pb = nullptr; // pybind11 function object (strong ref, never released) +PyObject* run_fast(PyObject* /*self*/, PyObject* const* args, Py_ssize_t nargs, PyObject* kwnames) { + if (kwnames == nullptr && nargs == 5 && THPVariable_Check(args[0]) && THPVariable_Check(args[1]) && + THPVariable_Check(args[2]) && THPVariable_Check(args[3]) && + (PyFloat_CheckExact(args[4]) || PyLong_CheckExact(args[4]))) { + const double wgd = PyFloat_CheckExact(args[4]) ? PyFloat_AS_DOUBLE(args[4]) : PyLong_AsDouble(args[4]); + if (!(wgd == -1.0 && PyErr_Occurred())) { + try { + torch::Tensor out = run(THPVariable_Unpack(args[0]), THPVariable_Unpack(args[1]), + THPVariable_Unpack(args[2]), THPVariable_Unpack(args[3]), wgd); + return THPVariable_Wrap(std::move(out)); + } catch (...) { + // fall through: the pybind11 path re-runs and translates the exception + } + } else { + PyErr_Clear(); + } + } + return PyObject_Vectorcall(g_run_pb, args, (size_t)nargs, kwnames); +} +PyMethodDef g_run_def = {"run", reinterpret_cast(reinterpret_cast(run_fast)), + METH_FASTCALL | METH_KEYWORDS, "NVFP4 attention o_proj + residual"}; +} // namespace + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("run_pb", &run, "NVFP4 attention o_proj + residual (pybind11 path)"); + g_run_pb = m.attr("run_pb").ptr(); + Py_INCREF(g_run_pb); + PyObject* f = PyCFunction_NewEx(&g_run_def, nullptr, nullptr); + if (f == nullptr) throw pybind11::error_already_set(); + m.add_object("run", pybind11::reinterpret_steal(f)); +} diff --git a/kernels/Quant/019_nvfp4_grouped_query_attention/README.md b/kernels/Quant/019_nvfp4_grouped_query_attention/README.md new file mode 100644 index 0000000000000000000000000000000000000000..37224f8318d932ad80e19112b0a8ee78920ce309 --- /dev/null +++ b/kernels/Quant/019_nvfp4_grouped_query_attention/README.md @@ -0,0 +1,11 @@ +# NVFP4 grouped query attention (Quant 019) + +An NVFP4 GQA attention block: hidden states quantized to NVFP4, Q/K/V projections as NVFP4 GEMMs, RoPE, causal attention, then the result quantized again for the NVFP4 output projection. + +- Language: CUDA C++. Entry point: `main.cpp::run`. Files: 7 (15,311 lines). +- Idea: CUTLASS block-scaled NVFP4 tcgen05 GEMMs (Q/K/V as one grouped GEMM), custom amax and FP4 quant kernels, persistent warp-specialized tcgen05 causal attention; PDL between launches. +- Result: SOL score 0.956; speedup 13.35x over the benchmark's baseline (geometric mean). Public SOL-ExecBench results as of 2026-11-11. +- Origin: search agent (Claude). +- Comments edited; unused test helpers removed; the code that runs is identical to the scored submission. +- Re-checked on a B200 after the edit: it builds and passes every workload of the SOL-ExecBench correctness check. +- Generated by Claude via Amazon Bedrock. Verified on the SOL-ExecBench site; not production-ready. diff --git a/kernels/Quant/019_nvfp4_grouped_query_attention/kernel.json b/kernels/Quant/019_nvfp4_grouped_query_attention/kernel.json new file mode 100644 index 0000000000000000000000000000000000000000..761fa33c278930fd840196ae19768c08fc89c7ee --- /dev/null +++ b/kernels/Quant/019_nvfp4_grouped_query_attention/kernel.json @@ -0,0 +1,97 @@ +{ + "board": "Quant", + "id": "019_nvfp4_grouped_query_attention", + "name": "NVFP4 grouped query attention", + "language": "CUDA C++", + "files": [ + { + "path": "src/array_pre.hpp", + "lines": 1598, + "bytes": 73332 + }, + { + "path": "src/cutlass/gemm/collective/builders/sm100_common.inl", + "lines": 1010, + "bytes": 46550 + }, + { + "path": "src/cutlass/gemm/collective/sm100_blockscaled_mma_array_warpspecialized.hpp", + "lines": 1372, + "bytes": 64902 + }, + { + "path": "src/cutlass/gemm/collective/sm100_blockscaled_mma_warpspecialized.hpp", + "lines": 1125, + "bytes": 52635 + }, + { + "path": "src/kernel.cu", + "lines": 9777, + "bytes": 599675 + }, + { + "path": "src/kernel.h", + "lines": 123, + "bytes": 8664 + }, + { + "path": "src/main.cpp", + "lines": 306, + "bytes": 17218 + } + ], + "origin": "search agent (Claude)", + "result": { + "public": true, + "sol_score": 0.956118, + "speedup": 13.3457, + "board_row": true, + "note": "the row the public SOL-ExecBench board shows for this problem, as of 2026-11-11" + }, + "idea": "CUTLASS block-scaled NVFP4 tcgen05 GEMMs (Q/K/V as one grouped GEMM), custom amax and FP4 quant kernels, persistent warp-specialized tcgen05 causal attention; PDL between launches.", + "spec": { + "languages": [ + "cuda_cpp" + ], + "target_hardware": [ + "B200", + "LOCAL" + ], + "entry_point": "main.cpp::run", + "binding": "torch", + "destination_passing_style": false, + "dependencies": [], + "compile_options": { + "cuda_cflags": [ + "-std=c++17", + "-O3", + "-gencode=arch=compute_100a,code=sm_100a", + "--expt-relaxed-constexpr", + "-DCUTLASS_ENABLE_GDC_FOR_SM100=1", + "-DNDEBUG", + "-Xptxas=-O3", + "--fmad=true", + "-Xptxas=--allow-expensive-optimizations=true", + "--extra-device-vectorization", + "-Xcompiler=-O3,-DNDEBUG,-fno-plt,-fvisibility=hidden", + "-Xptxas=--warn-on-spills,--warn-on-local-memory-usage,--warning-as-error" + ], + "ld_flags": [], + "cflags": [ + "-O3", + "-DNDEBUG", + "-fno-plt", + "-fvisibility=hidden" + ] + }, + "sources": [ + "kernel.h", + "array_pre.hpp", + "kernel.cu", + "main.cpp", + "cutlass/gemm/collective/sm100_blockscaled_mma_warpspecialized.hpp", + "cutlass/gemm/collective/builders/sm100_common.inl", + "cutlass/gemm/collective/sm100_blockscaled_mma_array_warpspecialized.hpp" + ] + } +} diff --git a/kernels/Quant/019_nvfp4_grouped_query_attention/src/array_pre.hpp b/kernels/Quant/019_nvfp4_grouped_query_attention/src/array_pre.hpp new file mode 100644 index 0000000000000000000000000000000000000000..eb6e1e11b4861957ca21161a597f16d574bb9e0e --- /dev/null +++ b/kernels/Quant/019_nvfp4_grouped_query_attention/src/array_pre.hpp @@ -0,0 +1,1598 @@ +/*************************************************************************************************** + * Copyright (c) 2024 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + **************************************************************************************************/ + +#pragma once +// ===================================================================================== +// PATCHED COPY of CUTLASS 4.4.1 cutlass/gemm/kernel/sm100_gemm_array_tma_warpspecialized.hpp +// (ptr-array / batched sm100 tcgen05 GEMM kernel) as a standalone class template GemmArrayPre. +// Change vs upstream (batched kArray mode with the dynamic-persistent CLC scheduler only): +// ===================================================================================== +#ifndef DKS +#define DKS(i) do {} while (0) +#endif + +#include "cutlass/cutlass.h" +#include "cutlass/workspace.h" +#include "cutlass/kernel_hardware_info.hpp" +#include "cutlass/detail/cluster.hpp" +#include "cutlass/arch/grid_dependency_control.h" +#include "cutlass/fast_math.h" +#include "cute/arch/cluster_sm90.hpp" +#include "cutlass/arch/arch.h" +#include "cutlass/arch/barrier.h" +#include "cutlass/arch/reg_reconfig.h" +#include "cutlass/gemm/gemm.h" +#include "cutlass/gemm/dispatch_policy.hpp" +#include "cutlass/detail/mainloop_fusion_helper_scale_factor.hpp" +#include "cutlass/gemm/group_array_problem_shape.hpp" +#include "cutlass/gemm/kernel/sm100_tile_scheduler.hpp" +#include "cutlass/gemm/kernel/sm100_tile_scheduler_group.hpp" +#include "cutlass/pipeline/pipeline.hpp" +#include "cutlass/detail/sm100_tmem_helper.hpp" + +#include "cute/tensor.hpp" +#include "cute/arch/tmem_allocator_sm100.hpp" +#include "cute/atom/mma_atom.hpp" + +/////////////////////////////////////////////////////////////////////////////// + +namespace cutlass::gemm::kernel { + +/////////////////////////////////////////////////////////////////////////////// + +// Host-built TMA descriptors of every batch (A / SFA shared by all batches). +// NAD = number of distinct A / SFA descriptors (batch g uses index g / (NB / NAD)); NAD = 2: split-K halves. +template +struct alignas(64) PreDescTable { + cute::TmaDescriptor a[NAD], sfa[NAD]; + cute::TmaDescriptor b[NB], sfb[NB], d[NB]; +}; + +template < + class ProblemShape_, + class CollectiveMainloop_, + class CollectiveEpilogue_, + class TileSchedulerTag_, + int NB_, + int NAD_ = 1 +> +class GemmArrayPre +{ +public: + // + // Type Aliases + // + using ProblemShape = ProblemShape_; + static_assert(rank(typename ProblemShape::UnderlyingProblemShape{}) == 3 or rank(typename ProblemShape::UnderlyingProblemShape{}) == 4, + "ProblemShape{} should be or "); + + // Mainloop derived types + using CollectiveMainloop = CollectiveMainloop_; + using TileShape = typename CollectiveMainloop::TileShape; + using TiledMma = typename CollectiveMainloop::TiledMma; + using ArchTag = typename CollectiveMainloop::ArchTag; + using ElementA = typename CollectiveMainloop::ElementA; + using StrideA = typename CollectiveMainloop::StrideA; + using InternalStrideA = typename CollectiveMainloop::InternalStrideA; + using ElementB = typename CollectiveMainloop::ElementB; + using StrideB = typename CollectiveMainloop::StrideB; + using InternalStrideB = typename CollectiveMainloop::InternalStrideB; + using LayoutSFA = typename cutlass::detail::LayoutSFAType::type; + using LayoutSFB = typename cutlass::detail::LayoutSFBType::type; + using ElementSF = typename cutlass::detail::ElementSFType::type; + using DispatchPolicy = typename CollectiveMainloop::DispatchPolicy; + using Schedule = typename DispatchPolicy::Schedule; + using ElementAccumulator = typename CollectiveMainloop::ElementAccumulator; + using ClusterShape = typename DispatchPolicy::ClusterShape; + using MainloopArguments = typename CollectiveMainloop::Arguments; + using MainloopParams = typename CollectiveMainloop::Params; + static_assert(ArchTag::kMinComputeCapability >= 100); + static constexpr bool IsGdcEnabled = cutlass::arch::IsGdcGloballyEnabled; + + // Epilogue derived types + using CollectiveEpilogue = CollectiveEpilogue_; + using EpilogueTile = typename CollectiveEpilogue::EpilogueTile; + using ElementC = typename CollectiveEpilogue::ElementC; + using StrideC = typename CollectiveEpilogue::StrideC; + using InternalStrideC = typename CollectiveEpilogue::InternalStrideC; + using ElementD = typename CollectiveEpilogue::ElementD; + using StrideD = typename CollectiveEpilogue::StrideD; + using InternalStrideD = typename CollectiveEpilogue::InternalStrideD; + using EpilogueArguments = typename CollectiveEpilogue::Arguments; + using EpilogueParams = typename CollectiveEpilogue::Params; + + // CLC pipeline depth + // determines how many waves (stages-1) a warp can race ahead + static constexpr uint32_t SchedulerPipelineStageCount = DispatchPolicy::Schedule::SchedulerPipelineStageCount; + static constexpr uint32_t AccumulatorPipelineStageCount = DispatchPolicy::Schedule::AccumulatorPipelineStageCount; + static constexpr bool IsOverlappingAccum = DispatchPolicy::IsOverlappingAccum; + + // TileID scheduler + // Get Blk and Scheduling tile shapes + using AtomThrShapeMNK = typename CollectiveMainloop::AtomThrShapeMNK; + using CtaShape_MNK = typename CollectiveMainloop::CtaShape_MNK; + + + //For the case of RCGroupedGemm we are still GroupedGemm but our StrideA will not match with InternalStrideA + // Hence it's better to take this decision based upon StrideB + static constexpr bool IsGroupedGemmKernel = !(cute::is_same_v); + using TileSchedulerTag = cute::conditional_t; + + using TileScheduler = typename detail::TileSchedulerSelector< + TileSchedulerTag, ArchTag, CtaShape_MNK, ClusterShape, SchedulerPipelineStageCount, ProblemShape>::Scheduler; + using TileSchedulerArguments = typename TileScheduler::Arguments; + using TileSchedulerParams = typename TileScheduler::Params; + + static constexpr bool IsSchedDynamicPersistent = TileScheduler::IsDynamicPersistent; + static constexpr bool IsTensorMapUpdateAsync = not IsSchedDynamicPersistent; + static_assert(!IsGroupedGemmKernel && !IsTensorMapUpdateAsync, + "GemmArrayPre: precomputed descriptors implemented for the batched (kArray) CLC path only"); + static constexpr bool IsDynamicCluster = not cute::is_static_v; + static constexpr uint32_t MinTensorMapWorkspaceAlignment = 64; + + // Warp specialization thread count per threadblock + static constexpr uint32_t NumSchedThreads = NumThreadsPerWarp; // 1 warp + static constexpr uint32_t NumTensorMapUpdaterThreads = IsTensorMapUpdateAsync ? NumThreadsPerWarp * 4 : 0; // Four warps to update tensor maps and plumb updated tileId. + static constexpr uint32_t NumMMAThreads = NumThreadsPerWarp; // 1 warp + static constexpr uint32_t NumMainloopLoadThreads = NumThreadsPerWarp; // 1 warp + static constexpr uint32_t NumEpilogueLoadThreads = NumThreadsPerWarp; // 1 warp + static constexpr uint32_t NumEpilogueThreads = CollectiveEpilogue::ThreadCount; + static constexpr uint32_t NumEpilogueWarps = NumEpilogueThreads / NumThreadsPerWarp; + + static_assert( + SchedulerPipelineStageCount % (IsTensorMapUpdateAsync ? NumTensorMapUpdaterThreads / NumThreadsPerWarp : 1) == 0, + "SchedulerPipelineStageCount for async tensor map update kernels must be divisible by the number of asynchronous tensor map updater warps." + ); + + static_assert( + (!IsTensorMapUpdateAsync) + || CollectiveEpilogue::NumMaxSchedulerPipelineStageCount >= SchedulerPipelineStageCount, + "The epilog collective expected a less scheduler stage count. Consider relaxing its NumMaxSchedulerPipelineStageCount parameter." + ); + + static constexpr uint32_t MaxThreadsPerBlock = NumSchedThreads + NumTensorMapUpdaterThreads + + NumMainloopLoadThreads + NumMMAThreads + + NumEpilogueLoadThreads + NumEpilogueThreads; + static constexpr uint32_t MinBlocksPerMultiprocessor = 1; + static constexpr uint32_t NumFixupBarriers = 1; + static constexpr uint32_t CLCResponseSize = sizeof(typename TileScheduler::CLCResponse); + + static constexpr uint32_t GenericRegisterRequirement = 136; + static constexpr uint32_t AccumRegisterRequirement = 232; + + // Pipeline and pipeline state types + using MainloopPipeline = typename CollectiveMainloop::MainloopPipeline; + using MainloopPipelineState = typename CollectiveMainloop::MainloopPipelineState; + + using EpiLoadPipeline = typename CollectiveEpilogue::LoadPipeline; + using EpiLoadPipelineState = typename CollectiveEpilogue::LoadPipelineState; + + using EpiStorePipeline = typename CollectiveEpilogue::StorePipeline; + using EpiStorePipelineState = typename CollectiveEpilogue::StorePipelineState; + + using LoadOrderBarrier = cutlass::OrderedSequenceBarrier<1,2>; + + using AccumulatorPipeline = cutlass::PipelineUmmaAsync; + using AccumulatorPipelineState = typename AccumulatorPipeline::PipelineState; + + using CLCPipeline = cute::conditional_t, + cutlass::PipelineAsync>; + using CLCPipelineState = typename CLCPipeline::PipelineState; + using TensorMapReadyPipeline = cute::conditional_t, + CLCPipeline + >; + using TensorMapReadyPipelineState = typename TensorMapReadyPipeline::PipelineState; + using CLCThrottlePipeline = cute::conditional_t, + cutlass::PipelineEmpty>; + using CLCThrottlePipelineState = typename CLCThrottlePipeline::PipelineState; + + template + struct WithTensorMapUpdateInfo : public BaseResponse { + uint16_t batch_changed = 0; + uint16_t TMA_stage = 0; + WithTensorMapUpdateInfo() = default; + CUTLASS_DEVICE WithTensorMapUpdateInfo(BaseResponse const& response) : BaseResponse(response) {} + }; + + using CLCResponseWithAdditionalInformation = cute::conditional_t< + IsTensorMapUpdateAsync, + WithTensorMapUpdateInfo, + typename TileScheduler::CLCResponse + >; + + using TmemAllocator = cute::conditional_t(typename TiledMma::ThrLayoutVMNK{})) == 1, + cute::TMEM::Allocator1Sm, cute::TMEM::Allocator2Sm>; + + // Kernel level shared memory storage + struct SharedStorage { + // The PipelineStorageImplWithoutAsyncUpdate and PipelineStorageImplWithAsyncUpdate only differ in the + // presence of the TensorMapReadyPipelineStorage. + // We could use some other technique to avoid duplication for the common members, but any technique + // we tried would break the MSVC build. + // As a workaround, we just copied the code. + + struct PipelineStorageImplWithoutAsyncUpdate : cute::aligned_struct<16, _1> { + using MainloopPipelineStorage = typename CollectiveMainloop::PipelineStorage; + using EpiLoadPipelineStorage = typename CollectiveEpilogue::PipelineStorage; + using LoadOrderBarrierStorage = typename LoadOrderBarrier::SharedStorage; + using CLCPipelineStorage = typename CLCPipeline::SharedStorage; + using AccumulatorPipelineStorage = typename AccumulatorPipeline::SharedStorage; + using CLCThrottlePipelineStorage = typename CLCThrottlePipeline::SharedStorage; + + alignas(16) MainloopPipelineStorage mainloop; + alignas(16) EpiLoadPipelineStorage epi_load; + alignas(16) LoadOrderBarrierStorage load_order; + alignas(16) CLCPipelineStorage clc; + alignas(16) AccumulatorPipelineStorage accumulator; + alignas(16) CLCThrottlePipelineStorage clc_throttle; + alignas(16) arch::ClusterBarrier tmem_dealloc; + }; + + struct PipelineStorageImplWithAsyncUpdate : cute::aligned_struct<16, _1> { + using MainloopPipelineStorage = typename CollectiveMainloop::PipelineStorage; + using EpiLoadPipelineStorage = typename CollectiveEpilogue::PipelineStorage; + using LoadOrderBarrierStorage = typename LoadOrderBarrier::SharedStorage; + using CLCPipelineStorage = typename CLCPipeline::SharedStorage; + using AccumulatorPipelineStorage = typename AccumulatorPipeline::SharedStorage; + using CLCThrottlePipelineStorage = typename CLCThrottlePipeline::SharedStorage; + + alignas(16) MainloopPipelineStorage mainloop; + alignas(16) EpiLoadPipelineStorage epi_load; + alignas(16) LoadOrderBarrierStorage load_order; + alignas(16) CLCPipelineStorage clc; + alignas(16) AccumulatorPipelineStorage accumulator; + alignas(16) CLCThrottlePipelineStorage clc_throttle; + alignas(16) arch::ClusterBarrier tmem_dealloc; + + // Below is the only difference between PipelineStorageImpl and PipelineStorageImpl + using TensorMapReadyPipelineStorage = typename TensorMapReadyPipeline::SharedStorage; + alignas(16) TensorMapReadyPipelineStorage tensor_map_ready; + }; + + using PipelineStorage = cute::conditional_t; + + PipelineStorage pipelines; + + alignas(16) CLCResponseWithAdditionalInformation clc_response[IsTensorMapUpdateAsync ? 2 : 1][SchedulerPipelineStageCount]; + uint32_t tmem_base_ptr; + + struct TensorMapStorage : cute::aligned_struct<128, _1> { + using EpilogueTensorMapStorage = typename CollectiveEpilogue::TensorMapStorage; + using MainloopTensorMapStorage = typename CollectiveMainloop::TensorMapStorage; + alignas(128) EpilogueTensorMapStorage epilogue; + alignas(128) MainloopTensorMapStorage mainloop; + } tensormaps[(NumTensorMapUpdaterThreads/NumThreadsPerWarp)+1]; + + struct TensorStorage : cute::aligned_struct<128, _1> { + using EpilogueTensorStorage = typename CollectiveEpilogue::TensorStorage; + using MainloopTensorStorage = typename CollectiveMainloop::TensorStorage; + + EpilogueTensorStorage epilogue; + MainloopTensorStorage mainloop; + } tensors; + }; + + static constexpr int SharedStorageSize = sizeof(SharedStorage); + + // Host facing host arguments + struct Arguments { + GemmUniversalMode mode{}; + ProblemShape problem_shape{}; + MainloopArguments mainloop{}; + EpilogueArguments epilogue{}; + KernelHardwareInfo hw_info{}; + TileSchedulerArguments scheduler{}; + }; + + // Kernel device entry point API + struct Params { + GemmUniversalMode mode{}; + ProblemShape problem_shape{}; + MainloopParams mainloop{}; + EpilogueParams epilogue{}; + TileSchedulerParams scheduler{}; + KernelHardwareInfo hw_info{}; + PreDescTable pre{}; // filled on the host before every launch (see header comment) + int trig_first = 0; + }; + + enum class WarpCategory : int32_t { + MMA = 0, + Sched = 1, + MainloopLoad = 2, + EpilogueLoad = 3, + Epilogue = 4, + // TensorMapUpdater starts at 256 thread alignment + TensorMapUpdater = 8 + }; + + struct IsParticipant { + uint32_t mma = false; + uint32_t sched = false; + uint32_t main_load = false; + uint32_t epi_load = false; + uint32_t epilogue = false; + uint32_t tensor_map_updater = false; + }; + + // + // Methods + // + + // Convert to underlying arguments. + static + Params + to_underlying_arguments(Arguments const& args, void* workspace) { + constexpr uint32_t NumEpilogueSubTiles = 1; + CUTLASS_TRACE_HOST("to_underlying_arguments():"); + ProblemShape problem_shapes = args.problem_shape; + // Get SM count if needed, otherwise use user supplied SM count + int sm_count = args.hw_info.sm_count; + if (IsGroupedGemmKernel && sm_count <= 0) { + CUTLASS_TRACE_HOST(" WARNING: Arguments do not include a valid SM count.\n" + " For optimal performance, populate the arguments KernelHardwareInfo struct with the SM count."); + sm_count = KernelHardwareInfo::query_device_multiprocessor_count(args.hw_info.device_id); + } + else if (!IsGroupedGemmKernel && sm_count != 0) { + CUTLASS_TRACE_HOST(" WARNING: SM100 tile scheduler does not allow for user specified SM counts.\n" + " To restrict a kernel's resource usage, consider using CUDA driver APIs instead (green contexts)."); + } + CUTLASS_TRACE_HOST("to_underlying_arguments(): Setting persistent grid SM count to " << sm_count); + + // Calculate workspace pointers + uint8_t* workspace_ptr = reinterpret_cast(workspace); + size_t workspace_offset = 0; + + // Epilogue + void* epilogue_workspace = workspace_ptr + workspace_offset; + workspace_offset += CollectiveEpilogue::get_workspace_size(problem_shapes, args.epilogue, args.hw_info.sm_count); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + + void* mainloop_workspace = workspace_ptr + workspace_offset; + workspace_offset += CollectiveMainloop::get_workspace_size(problem_shapes, args.mainloop, args.hw_info.sm_count); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + + // Tile scheduler + void* scheduler_workspace = workspace_ptr + workspace_offset; + workspace_offset += TileScheduler::template get_workspace_size( + args.scheduler, problem_shapes.get_host_problem_shape(0), args.hw_info, NumFixupBarriers, NumEpilogueSubTiles, CollectiveEpilogue::NumAccumulatorMtxs); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + + TileSchedulerParams scheduler; + if constexpr (IsGroupedGemmKernel) { + scheduler = TileScheduler::to_underlying_arguments( + problem_shapes, TileShape{}, AtomThrShapeMNK{}, ClusterShape{}, + args.hw_info, args.scheduler, scheduler_workspace); + } + else { + scheduler = TileScheduler::to_underlying_arguments( + problem_shapes.get_host_problem_shape(), TileShape{}, AtomThrShapeMNK{}, ClusterShape{}, + args.hw_info, args.scheduler, scheduler_workspace + ); + } + + return { + args.mode, + problem_shapes, + CollectiveMainloop::to_underlying_arguments(problem_shapes, args.mainloop, mainloop_workspace, args.hw_info), + CollectiveEpilogue::to_underlying_arguments(problem_shapes, args.epilogue, epilogue_workspace), + scheduler, + args.hw_info + }; + } + + static bool + can_implement(Arguments const& args) { + bool implementable = true; + if constexpr (IsGroupedGemmKernel) { + // Group GEMM currently only supports rank-3 problem shapes + implementable &= (args.mode == GemmUniversalMode::kGrouped && rank(typename ProblemShape::UnderlyingProblemShape{}) == 3); + } + else { + implementable &= (args.mode == GemmUniversalMode::kArray && rank(typename ProblemShape::UnderlyingProblemShape{}) == 4); + } + if (!implementable) { + CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Arguments or Problem Shape don't meet the requirements for Ptr Array Gemm or Grouped Gemm.\n"); + return implementable; + } + implementable &= CollectiveMainloop::can_implement(args.problem_shape, args.mainloop); + implementable &= CollectiveEpilogue::can_implement(args.problem_shape, args.epilogue); + implementable &= TileScheduler::can_implement(args.scheduler); + if (!implementable) { + CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Mainloop, Epilogue or Scheduler don't meet the requirements for Ptr Array Gemm or Grouped Gemm.\n"); + return implementable; + } + + if constexpr (IsDynamicCluster) { + static constexpr int MaxClusterSize = 16; + implementable &= size(args.hw_info.cluster_shape) <= MaxClusterSize; + implementable &= size(args.hw_info.cluster_shape_fallback) <= MaxClusterSize; + implementable &= cutlass::detail::preferred_cluster_can_implement(args.hw_info.cluster_shape, args.hw_info.cluster_shape_fallback); + } + if (!implementable) { + CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Dynamic Cluster or Preferred Cluster don't meet the requirements for Ptr Array Gemm or Grouped Gemm.\n"); + return implementable; + } + + constexpr bool IsBlockscaled = !cute::is_void_v; + if constexpr (IsBlockscaled) { + if constexpr (IsDynamicCluster) { + implementable &= cutlass::detail::preferred_cluster_can_implement(args.hw_info.cluster_shape, args.hw_info.cluster_shape_fallback); + // Special cluster check for scale factor multicasts. Due to limited size of scale factors, we can't multicast among + // more than 4 CTAs + implementable &= (args.hw_info.cluster_shape.x <= 4 && args.hw_info.cluster_shape.y <= 4 && + args.hw_info.cluster_shape_fallback.x <= 4 && args.hw_info.cluster_shape_fallback.y <= 4); + } + else { + // Special cluster check for scale factor multicasts. Due to limited size of scale factors, we can't multicast among + // more than 4 CTAs + implementable &= ((size<0>(ClusterShape{}) <= 4) && (size<1>(ClusterShape{}) <= 4)); + } + } + + return implementable; + } + + static size_t + get_workspace_size(Arguments const& args) { + constexpr uint32_t NumEpilogueSubTiles = 1; + size_t workspace_size = 0; + + // Epilogue + workspace_size += CollectiveEpilogue::get_workspace_size(args.problem_shape, args.epilogue, args.hw_info.sm_count); + workspace_size = round_nearest(workspace_size, MinTensorMapWorkspaceAlignment); + + // Mainloop + workspace_size += CollectiveMainloop::get_workspace_size(args.problem_shape, args.mainloop, args.hw_info.sm_count); + workspace_size = round_nearest(workspace_size, MinTensorMapWorkspaceAlignment); + + // Tile scheduler + workspace_size += TileScheduler::template get_workspace_size( + args.scheduler, args.problem_shape.get_host_problem_shape(0), args.hw_info, NumFixupBarriers, NumEpilogueSubTiles, CollectiveEpilogue::NumAccumulatorMtxs); + workspace_size = round_nearest(workspace_size, MinTensorMapWorkspaceAlignment); + + return workspace_size; + } + + static cutlass::Status + initialize_workspace(Arguments const& args, void* workspace = nullptr, cudaStream_t stream = nullptr, + CudaHostAdapter* cuda_adapter = nullptr) { + constexpr uint32_t NumEpilogueSubTiles = 1; + Status status = Status::kSuccess; + uint8_t* workspace_ptr = reinterpret_cast(workspace); + size_t workspace_offset = 0; + + // Epilogue + status = CollectiveEpilogue::initialize_workspace(args.problem_shape, args.epilogue, workspace_ptr + workspace_offset, stream, cuda_adapter); + workspace_offset += CollectiveEpilogue::get_workspace_size(args.problem_shape, args.epilogue, args.hw_info.sm_count); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + if (status != Status::kSuccess) { + return status; + } + + // Mainloop + status = CollectiveMainloop::initialize_workspace(args.problem_shape, args.mainloop, workspace_ptr + workspace_offset, stream, cuda_adapter); + workspace_offset += CollectiveMainloop::get_workspace_size(args.problem_shape, args.mainloop, args.hw_info.sm_count); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + if (status != Status::kSuccess) { + return status; + } + + // Tile scheduler + status = TileScheduler::template initialize_workspace( + args.scheduler, workspace_ptr + workspace_offset, stream, args.problem_shape.get_host_problem_shape(0), args.hw_info, NumFixupBarriers, NumEpilogueSubTiles, CollectiveEpilogue::NumAccumulatorMtxs, cuda_adapter); + workspace_offset += TileScheduler::template get_workspace_size( + args.scheduler, args.problem_shape.get_host_problem_shape(0), args.hw_info, NumFixupBarriers, NumEpilogueSubTiles, CollectiveEpilogue::NumAccumulatorMtxs); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + if (status != Status::kSuccess) { + return status; + } + + return status; + } + + // Computes the kernel launch grid shape based on runtime parameters + static dim3 + get_grid_shape(Params const& params) { + // NOTE: cluster_shape here is the major cluster shape, not fallback one + auto cluster_shape = cutlass::detail::select_cluster_shape(ClusterShape{}, params.hw_info.cluster_shape); + + dim3 grid_shape; + if constexpr (IsGroupedGemmKernel) { + grid_shape = TileScheduler::get_grid_shape( + params.scheduler, + params.problem_shape, + TileShape{}, + AtomThrShapeMNK{}, + cluster_shape, + params.hw_info); + } + else { + grid_shape = TileScheduler::get_grid_shape( + params.scheduler, + params.problem_shape.get_host_problem_shape(), + TileShape{}, + AtomThrShapeMNK{}, + cluster_shape, + params.hw_info); + } + return grid_shape; + } + + static dim3 + get_block_shape() { + return dim3(MaxThreadsPerBlock, 1, 1); + } + + CUTLASS_DEVICE + void + operator() (Params const& params, char* smem_buf) { + + using namespace cute; + using X = Underscore; + if (threadIdx.x == 0) DKS(0); + + static_assert(SharedStorageSize <= cutlass::arch::sm100_smem_capacity_bytes, "SMEM usage exceeded capacity."); + auto problem_shape = params.problem_shape; + + // Account for more than one epilogue warp + int warp_idx = canonical_warp_idx_sync(); + WarpCategory warp_category = warp_idx < static_cast(WarpCategory::Epilogue) ? WarpCategory(warp_idx) + : warp_idx < static_cast(WarpCategory::TensorMapUpdater) ? WarpCategory::Epilogue + : WarpCategory::TensorMapUpdater; + + uint32_t lane_predicate = cute::elect_one_sync(); + auto cluster_shape = cutlass::detail::select_cluster_shape(ClusterShape{}); + int cluster_size = size(cluster_shape); + uint32_t cta_rank_in_cluster = cute::block_rank_in_cluster(); + bool is_first_cta_in_cluster = cta_rank_in_cluster == 0; + int cta_coord_v = cta_rank_in_cluster % size<0>(typename TiledMma::AtomThrID{}); + bool is_mma_leader_cta = cta_coord_v == 0; + constexpr bool has_mma_peer_cta = size(AtomThrShapeMNK{}) == 2; + [[maybe_unused]] uint32_t mma_peer_cta_rank = has_mma_peer_cta ? cta_rank_in_cluster ^ 1 : cta_rank_in_cluster; + + // Kernel level shared memory storage + SharedStorage& shared_storage = *reinterpret_cast(smem_buf); + + // In a warp specialized kernel, collectives expose data movement and compute operations separately + CollectiveMainloop collective_mainloop(params.mainloop, cluster_shape, cta_rank_in_cluster); + CollectiveEpilogue collective_epilogue(params.epilogue, shared_storage.tensors.epilogue); + + // Do we load source tensor C or other aux inputs + bool is_epi_load_needed = collective_epilogue.is_producer_load_needed(); + IsParticipant is_participant = { + (warp_category == WarpCategory::MMA), // mma + (warp_category == WarpCategory::Sched) && (IsSchedDynamicPersistent ? is_first_cta_in_cluster : true), // sched + (warp_category == WarpCategory::MainloopLoad), // main_load + (warp_category == WarpCategory::EpilogueLoad) && is_epi_load_needed, // epi_load + (warp_category == WarpCategory::Epilogue), // epilogue + (warp_category == WarpCategory::TensorMapUpdater) && IsTensorMapUpdateAsync // tensor_map_updater + }; + + int32_t sm_id = static_cast(cutlass::arch::SmId()); + if constexpr (IsGroupedGemmKernel) { + // In case user wants to engage less SMs than available on device + sm_id = blockIdx.x + (blockIdx.y * gridDim.x); + } + auto tensormaps_init_main_load = [&] () { + if constexpr (IsTensorMapUpdateAsync) { + return collective_mainloop.template tensormaps_init( + params.mainloop, + shared_storage.tensormaps[0].mainloop, + params.hw_info.sm_count, + sm_id + ); + } + else { + return nullptr; + } + }; + + auto tensormaps_init_epi_load = [&] () { + if constexpr (IsTensorMapUpdateAsync) { + return collective_epilogue.template tensormaps_init( + params.epilogue, + shared_storage.tensormaps[0].epilogue, + params.hw_info.sm_count, + sm_id + ); + } + else { + return nullptr; + } + }; + + decltype(tensormaps_init_main_load()) pre_init_main_load_tensormaps; + decltype(tensormaps_init_epi_load()) pre_init_epi_load_tensormaps; + + + if (is_participant.main_load) { + pre_init_main_load_tensormaps = tensormaps_init_main_load(); + } + if (is_participant.epi_load) { + pre_init_epi_load_tensormaps = tensormaps_init_epi_load(); + } + + // Mainloop Load pipeline + typename MainloopPipeline::Params mainloop_pipeline_params; + if (WarpCategory::MainloopLoad == warp_category) { + mainloop_pipeline_params.role = MainloopPipeline::ThreadCategory::Producer; + } + if (WarpCategory::MMA == warp_category) { + mainloop_pipeline_params.role = MainloopPipeline::ThreadCategory::Consumer; + } + mainloop_pipeline_params.is_leader = lane_predicate && is_mma_leader_cta && is_participant.main_load; + mainloop_pipeline_params.transaction_bytes = CollectiveMainloop::TmaTransactionBytes; + mainloop_pipeline_params.initializing_warp = 0; + MainloopPipeline mainloop_pipeline(shared_storage.pipelines.mainloop, + mainloop_pipeline_params, + cluster_shape, + cute::true_type{}, // Perform barrier init + cute::false_type{}); // Delay mask calculation + + // Epilogue Load pipeline + typename EpiLoadPipeline::Params epi_load_pipeline_params; + if (WarpCategory::EpilogueLoad == warp_category) { + epi_load_pipeline_params.role = EpiLoadPipeline::ThreadCategory::Producer; + } + if (WarpCategory::Epilogue == warp_category) { + epi_load_pipeline_params.role = EpiLoadPipeline::ThreadCategory::Consumer; + } + epi_load_pipeline_params.dst_blockid = cta_rank_in_cluster; + epi_load_pipeline_params.producer_arv_count = NumEpilogueLoadThreads; + epi_load_pipeline_params.consumer_arv_count = NumEpilogueThreads; + epi_load_pipeline_params.transaction_bytes = CollectiveEpilogue::TmaTransactionBytes; + epi_load_pipeline_params.initializing_warp = 1; + EpiLoadPipeline epi_load_pipeline(shared_storage.pipelines.epi_load, epi_load_pipeline_params); + + // Epilogue Store pipeline + typename EpiStorePipeline::Params epi_store_pipeline_params; + epi_store_pipeline_params.always_wait = true; + EpiStorePipeline epi_store_pipeline(epi_store_pipeline_params); + + // Load order barrier + typename LoadOrderBarrier::Params load_order_barrier_params; + load_order_barrier_params.group_id = (warp_category == WarpCategory::MainloopLoad) ? 0 : 1; + load_order_barrier_params.group_size = NumMainloopLoadThreads; + load_order_barrier_params.initializing_warp = 3; + LoadOrderBarrier load_order_barrier(shared_storage.pipelines.load_order, load_order_barrier_params); + + // CLC pipeline + typename CLCPipeline::Params clc_pipeline_params; + if (WarpCategory::Sched == warp_category) { + clc_pipeline_params.role = IsSchedDynamicPersistent ? + CLCPipeline::ThreadCategory::ProducerConsumer : + CLCPipeline::ThreadCategory::Producer; + } + else { + clc_pipeline_params.role = CLCPipeline::ThreadCategory::Consumer; + } + clc_pipeline_params.initializing_warp = 4; + clc_pipeline_params.producer_arv_count = 1; + + if constexpr (IsSchedDynamicPersistent) { + clc_pipeline_params.producer_blockid = 0; + clc_pipeline_params.consumer_arv_count = NumSchedThreads + cluster_size * + (NumMainloopLoadThreads + NumEpilogueThreads + NumMMAThreads); + if (is_epi_load_needed) { + clc_pipeline_params.consumer_arv_count += cluster_size * NumEpilogueLoadThreads; + } + clc_pipeline_params.transaction_bytes = CLCResponseSize; + } + else { + if constexpr (IsTensorMapUpdateAsync) { + clc_pipeline_params.consumer_arv_count = NumThreadsPerWarp; + } + else { + clc_pipeline_params.consumer_arv_count = NumMainloopLoadThreads + NumEpilogueThreads + NumMMAThreads; + if (is_epi_load_needed) { + clc_pipeline_params.consumer_arv_count += NumEpilogueLoadThreads; + } + } + } + // Now declare the pipeline outside the if constexpr + CLCPipeline clc_pipeline = [&]() { + if constexpr (IsSchedDynamicPersistent) { + return CLCPipeline(shared_storage.pipelines.clc, clc_pipeline_params, cluster_shape); + } + else { + return CLCPipeline(shared_storage.pipelines.clc, clc_pipeline_params); + } + }(); + + auto tensor_map_ready_pipeline = [&] () { + if constexpr (IsGroupedGemmKernel) { + // TMA update ready pipeline + typename TensorMapReadyPipeline::Params tensor_map_ready_pipeline_params; + + if (WarpCategory::TensorMapUpdater == warp_category) { + tensor_map_ready_pipeline_params.role = TensorMapReadyPipeline::ThreadCategory::Producer; + } + else { + tensor_map_ready_pipeline_params.role = TensorMapReadyPipeline::ThreadCategory::Consumer; + } + + tensor_map_ready_pipeline_params.initializing_warp = 8; + tensor_map_ready_pipeline_params.producer_arv_count = NumThreadsPerWarp; + + tensor_map_ready_pipeline_params.consumer_arv_count = NumMainloopLoadThreads + NumEpilogueThreads + NumMMAThreads; + if (is_epi_load_needed) { + tensor_map_ready_pipeline_params.consumer_arv_count += NumEpilogueLoadThreads; + } + return TensorMapReadyPipeline(shared_storage.pipelines.tensor_map_ready, tensor_map_ready_pipeline_params); + } + else { + return clc_pipeline; + } + }(); + + // Mainloop-Epilogue pipeline + typename AccumulatorPipeline::Params accumulator_pipeline_params; + if (WarpCategory::MMA == warp_category) { + accumulator_pipeline_params.role = AccumulatorPipeline::ThreadCategory::Producer; + } + if (WarpCategory::Epilogue == warp_category) { + accumulator_pipeline_params.role = AccumulatorPipeline::ThreadCategory::Consumer; + } + // Only one producer thread arrives on this barrier. + accumulator_pipeline_params.producer_arv_count = 1; + accumulator_pipeline_params.consumer_arv_count = size(AtomThrShapeMNK{}) * NumEpilogueThreads; + accumulator_pipeline_params.initializing_warp = 5; + AccumulatorPipeline accumulator_pipeline(shared_storage.pipelines.accumulator, + accumulator_pipeline_params, + cluster_shape, + cute::true_type{}, // Perform barrier init + cute::false_type{}); // Delay mask calculation + + // CLC throttle pipeline + typename CLCThrottlePipeline::Params clc_throttle_pipeline_params; + if constexpr (IsSchedDynamicPersistent) { + if (WarpCategory::MainloopLoad == warp_category) { + clc_throttle_pipeline_params.role = CLCThrottlePipeline::ThreadCategory::Producer; + } + if (WarpCategory::Sched == warp_category) { + clc_throttle_pipeline_params.role = CLCThrottlePipeline::ThreadCategory::Consumer; + } + clc_throttle_pipeline_params.producer_arv_count = NumMainloopLoadThreads; + clc_throttle_pipeline_params.consumer_arv_count = NumSchedThreads; + clc_throttle_pipeline_params.dst_blockid = 0; + clc_throttle_pipeline_params.initializing_warp = 3; + } + CLCThrottlePipeline clc_throttle_pipeline(shared_storage.pipelines.clc_throttle, clc_throttle_pipeline_params); + CLCThrottlePipelineState clc_pipe_throttle_consumer_state; + CLCThrottlePipelineState clc_pipe_throttle_producer_state = cutlass::make_producer_start_state(); + + // Tmem allocator + TmemAllocator tmem_allocator{}; + + // Sync allocation status between MMA and epilogue warps within CTA + arch::NamedBarrier tmem_allocation_result_barrier(NumMMAThreads + NumEpilogueThreads, cutlass::arch::ReservedNamedBarriers::TmemAllocBarrier); + // Sync deallocation status between MMA warps of peer CTAs + arch::ClusterBarrier& tmem_deallocation_result_barrier = shared_storage.pipelines.tmem_dealloc; + [[maybe_unused]] uint32_t dealloc_barrier_phase = 0; + if (WarpCategory::MMA == warp_category) { + if constexpr(!IsOverlappingAccum) { + if (has_mma_peer_cta && lane_predicate) { + tmem_deallocation_result_barrier.init(NumMMAThreads); + } + } + else { + if (has_mma_peer_cta && lane_predicate) { + tmem_deallocation_result_barrier.init(NumEpilogueThreads*2); + } + else if (lane_predicate) { + tmem_deallocation_result_barrier.init(NumEpilogueThreads); + } + } + } + + // We need this to guarantee that the Pipeline init is visible + // To all producers and consumer threadblocks in the cluster + pipeline_init_arrive_relaxed(cluster_size); + + MainloopPipelineState mainloop_pipe_consumer_state; + MainloopPipelineState mainloop_pipe_producer_state = cutlass::make_producer_start_state(); + + EpiLoadPipelineState epi_load_pipe_consumer_state; + EpiLoadPipelineState epi_load_pipe_producer_state = cutlass::make_producer_start_state(); + + // epilogue store pipe is producer-only (consumer is TMA unit, waits via scoreboarding) + EpiStorePipelineState epi_store_pipe_producer_state = cutlass::make_producer_start_state(); + + CLCPipelineState clc_pipe_consumer_state; + CLCPipelineState clc_pipe_producer_state = cutlass::make_producer_start_state(); + + TensorMapReadyPipelineState tensor_map_ready_pipe_consumer_state; + TensorMapReadyPipelineState tensor_map_ready_pipe_producer_state = cutlass::make_producer_start_state(); + + AccumulatorPipelineState accumulator_pipe_consumer_state; + AccumulatorPipelineState accumulator_pipe_producer_state = cutlass::make_producer_start_state(); + + dim3 block_id_in_cluster = cute::block_id_in_cluster(); + + // Calculate mask after cluster barrier arrival + mainloop_pipeline.init_masks(cluster_shape, block_id_in_cluster); + accumulator_pipeline.init_masks(cluster_shape, block_id_in_cluster); + + // PATCH: prefetch every precomputed descriptor (kernel-parameter space, host-written) before the PDL wait. + if (warp_category == WarpCategory::MainloopLoad && lane_predicate) { + for (int i = 0; i < NAD_; ++i) { + cute::prefetch_tma_descriptor(¶ms.pre.a[i]); + cute::prefetch_tma_descriptor(¶ms.pre.sfa[i]); + } + CUTLASS_PRAGMA_NO_UNROLL + for (int i = 0; i < NB_; ++i) { + cute::prefetch_tma_descriptor(¶ms.pre.b[i]); + cute::prefetch_tma_descriptor(¶ms.pre.sfb[i]); + cute::prefetch_tma_descriptor(¶ms.pre.d[i]); + } + } + + // Ensure that the prefetched kernel does not touch + // unflushed global memory prior to this instruction. + // For the static grouped scheduler, the problem shapes + // might be produced by a previous kernel in global memory. + // PATCH (PDL prologue overlap): NO kernel-wide griddepcontrol.wait here. Scheduler construction (blockIdx only), + // TMEM allocation, mma_init and the cluster pipeline_init_wait touch only params / smem / TMEM and now run before + // the dependency wait, overlapping the predecessor's tail. Every role that reads global memory waits itself first: + // main_load / sched / epi_load (their own waits below), MMA (after its TMEM alloc, before its first tile) and the + // epilogue warps (at branch entry). Sync-only -> bit-identical. + if (threadIdx.x == 0) DKS(1); + + // TileID scheduler + TileScheduler scheduler( + (!IsTensorMapUpdateAsync || is_participant.sched || is_participant.tensor_map_updater) + ? &shared_storage.clc_response[0][0] + : &shared_storage.clc_response[1][0], + params.scheduler, + block_id_in_cluster + ); + + auto work_tile_info = [&] () { + if constexpr (IsTensorMapUpdateAsync) { + return scheduler.initial_work_tile_info(cluster_shape, [] (typename TileScheduler::CLCResponse response) { + CLCResponseWithAdditionalInformation response_with_additional_info = response; + response_with_additional_info.TMA_stage = 0; + response_with_additional_info.batch_changed = 1; + return response_with_additional_info; + }); + } + else { + return scheduler.initial_work_tile_info(cluster_shape); + } + } (); + + auto get_tma_desc_offset = [] ([[maybe_unused]] const auto& tile_info) { + if constexpr (IsTensorMapUpdateAsync) { + return tile_info.TMA_stage; + } + else { + return 0; + } + }; + + auto get_tensormap = [] (auto& tensormaps, [[maybe_unused]] auto tma_desc_offset) { + if constexpr (IsTensorMapUpdateAsync) { + return tensormaps[tma_desc_offset]; + } + else { + return tensormaps; + } + }; + + auto cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + + // + // TMEM "Allocation" + // + auto tmem_storage = collective_mainloop.template init_tmem_tensors(EpilogueTile{}); + pipeline_init_wait(cluster_size); + if (threadIdx.x == 0) DKS(2); + + if constexpr (IsGroupedGemmKernel) { + if (not work_tile_info.is_valid()) { + // When problem shapes are only on device, the grid launched may be larger than the total number of blocks across groups + return; + } + } + // Optionally append 1s until problem shape is rank-4 in case it is only rank-3 (MNK) + auto problem_shape_MNKL = append<4>(problem_shape.get_problem_shape(work_tile_info.L_idx), 1); + + if (is_participant.main_load) { + // Ensure that the prefetched kernel does not touch + // unflushed global memory prior to this instruction + cutlass::arch::wait_on_dependent_grids(); + + auto load_inputs = collective_mainloop.load_init( + problem_shape_MNKL, params.mainloop, + shared_storage.tensors.mainloop, + shared_storage.tensormaps[0].mainloop, + params.hw_info.sm_count, sm_id, problem_shape.groups(), work_tile_info.L_idx); + + bool do_load_order_arrive = is_epi_load_needed; + Tensor gA_mkl = get<0>(load_inputs); + + // Fetch a copy of tensormaps for the CTA from Params + auto input_tensormaps = [&] ([[maybe_unused]] auto inputs) { + if constexpr (IsTensorMapUpdateAsync) { + return pre_init_main_load_tensormaps; + } + else { + static constexpr size_t idx = rank(inputs) - 1; + return get(inputs); + } + } (load_inputs); + + if constexpr (IsTensorMapUpdateAsync) { + // Register reconfiguration + arch::warpgroup_reg_dealloc(); + } + + auto pad_inputs = [] (auto& inputs, [[maybe_unused]] auto tensormaps) { + if constexpr (IsTensorMapUpdateAsync) { + return cute::tuple_cat(inputs, cute::make_tuple(tensormaps)); + } + else { + return inputs; + } + }; + + // Initial batch's tensor address update + // Even the first tile for a CTA can be from any of the batches. + // And during initialization of the first TMA descriptor on host, we don't initialize to the first batch due to that args value being device-only. + bool is_first_iteration = true; + bool did_batch_change = true; + bool requires_clc_query = true; + + do { + auto tma_desc_offset = get_tma_desc_offset(work_tile_info); + int32_t curr_batch = idx2crd(work_tile_info.L_idx, shape<4>(gA_mkl)); // Usually just returns work_tile_info.L_idx; + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(problem_shape.get_problem_shape(curr_batch), 1); + } + // PATCH: no in-kernel descriptor update -- this batch's host-built descriptors (param space). + auto pre_inputs = cute::tuple_cat(cute::take<0, 14>(load_inputs), + cute::make_tuple(cute::make_tuple(const_cast(¶ms.pre.a[curr_batch / (NB_ / NAD_)]), + const_cast(¶ms.pre.b[curr_batch]), + const_cast(¶ms.pre.sfa[curr_batch / (NB_ / NAD_)]), + const_cast(¶ms.pre.sfb[curr_batch])))); + if (is_first_iteration && cute::elect_one_sync()) DKS(3); + + // Get the number of K tiles to compute for this work as well as the starting K tile offset of the work. + auto k_tile_iter = scheduler.get_k_tile_iterator(work_tile_info, problem_shape_MNKL, CtaShape_MNK{}, shape<3>(gA_mkl)); + auto k_tile_count = TileScheduler::get_work_k_tile_count(work_tile_info, problem_shape_MNKL, CtaShape_MNK{}); + auto k_tile_prologue = min(MainloopPipeline::Stages, k_tile_count); + + // Problem Shape and therefore strides that we construct are [M,N,K,L], but since here for the TMA loads + // we are managing TMA descriptors to change batches, we need to neglect the L mode + auto cta_coord_mnk = append<4>(make_coord(get<0>(cta_coord_mnkl), get<1>(cta_coord_mnkl), get<2>(cta_coord_mnkl)), Int<0>{}); + + if constexpr (IsSchedDynamicPersistent) { + if (is_first_cta_in_cluster && requires_clc_query) { + clc_throttle_pipeline.producer_acquire(clc_pipe_throttle_producer_state); + clc_throttle_pipeline.producer_commit(clc_pipe_throttle_producer_state); + ++clc_pipe_throttle_producer_state; + } + } + + // Start mainloop prologue loads, arrive on the epilogue residual load barrier, resume mainloop loads + auto [mainloop_producer_state_next, k_tile_iter_next] = collective_mainloop.load( + params.mainloop, + mainloop_pipeline, + mainloop_pipe_producer_state, + pre_inputs, + cta_coord_mnk, + k_tile_iter, k_tile_prologue, + false, // PATCH: param-space descriptors, never modified -> no tensormap acquire fence + curr_batch + ); + mainloop_pipe_producer_state = mainloop_producer_state_next; + + if (is_first_iteration && cute::elect_one_sync()) DKS(4); + if (do_load_order_arrive) { + load_order_barrier.arrive(); + do_load_order_arrive = false; + } + + auto [mainloop_producer_state_next_, unused_] = collective_mainloop.load( + params.mainloop, + mainloop_pipeline, + mainloop_pipe_producer_state, + pre_inputs, + cta_coord_mnk, + k_tile_iter_next, k_tile_count - k_tile_prologue, + false, /* did_batch_change - prologue loads handle tensormap acquire */ + curr_batch + ); + mainloop_pipe_producer_state = mainloop_producer_state_next_; + + // Sync warp to prevent non-participating threads entering next wave early + __syncwarp(); + + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work( + work_tile_info, + tensor_map_ready_pipeline, + tensor_map_ready_pipe_consumer_state + ); + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + requires_clc_query = increment_pipe; + if (increment_pipe) { + ++tensor_map_ready_pipe_consumer_state; + } + // For subsequent tiles, check if batch changes and therefore, we need tensormap updates + is_first_iteration = false; + did_batch_change = curr_batch != idx2crd(work_tile_info.L_idx, shape<4>(gA_mkl)); + } while (work_tile_info.is_valid()); + if (cute::elect_one_sync()) DKS(5); + collective_mainloop.load_tail(mainloop_pipeline, mainloop_pipe_producer_state); + + } + + else if (is_participant.sched) { + + if constexpr (IsTensorMapUpdateAsync) { + // Register reconfiguration + arch::warpgroup_reg_dealloc(); + } + + // Grouped GEMM uses static tile scheduler + if constexpr (IsSchedDynamicPersistent) { + // Whether a new CLC query must be performed. + // See comment below where this variable is updated for a description of + // why this variable is needed. + bool requires_clc_query = true; + + if (params.trig_first) cutlass::arch::launch_dependent_grids(); // TRIG-FIRST (see Params::trig_first) + cutlass::arch::wait_on_dependent_grids(); + + do { + if (requires_clc_query) { + clc_throttle_pipeline.consumer_wait(clc_pipe_throttle_consumer_state); + clc_throttle_pipeline.consumer_release(clc_pipe_throttle_consumer_state); + ++clc_pipe_throttle_consumer_state; + + // Query next clcID and update producer state + clc_pipe_producer_state = scheduler.advance_to_next_work(clc_pipeline, clc_pipe_producer_state); + } + + // Fetch next work tile + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work( + work_tile_info, + clc_pipeline, + clc_pipe_consumer_state + ); + + // Only perform a new CLC query if we consumed a new CLC query result in + // `fetch_next_work`. An example of a case in which CLC `fetch_next_work` does + // not consume a new CLC query response is when processing stream-K units. + // The current stream-K scheduler uses single WorkTileInfo to track multiple + // (potentially-partial) tiles to be computed via stream-K. In this case, + // `fetch_next_work` simply performs in-place updates on the existing WorkTileInfo, + // rather than consuming a CLC query response. + requires_clc_query = increment_pipe; + if (increment_pipe) { + ++clc_pipe_consumer_state; + } + + work_tile_info = next_work_tile_info; + } while (work_tile_info.is_valid()); + clc_pipeline.producer_tail(clc_pipe_producer_state); + } + else { + + static_assert(IsTensorMapUpdateAsync || IsSchedDynamicPersistent, "We only support async tensor map update with static persistent scheduler"); + + auto update_tensor_map_stages = [&] (typename TileScheduler::CLCResponse next_work_tile_info_from_scheduler) { + if constexpr (IsTensorMapUpdateAsync) { + CLCResponseWithAdditionalInformation next_work_tile_info = next_work_tile_info_from_scheduler; + auto tensor_map_buffer_stage = work_tile_info.TMA_stage; + next_work_tile_info.batch_changed = work_tile_info.L_idx != next_work_tile_info.L_idx; + if (next_work_tile_info.batch_changed) { + ++tensor_map_buffer_stage; + } + next_work_tile_info.TMA_stage = tensor_map_buffer_stage; + return next_work_tile_info; + } + }; + + do { + auto [next_work_tile_info, increment_pipe] = scheduler.advance_to_next_work(clc_pipeline, clc_pipe_producer_state, 1, update_tensor_map_stages); + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++clc_pipe_producer_state; + } + } while (work_tile_info.is_valid()); + + // Push additional invalid work items for all tensormap updater threads + for (int i = 0; i < NumTensorMapUpdaterThreads / NumThreadsPerWarp;) { + auto [next_work_tile_info, increment_pipe] = scheduler.advance_to_next_work(clc_pipeline, clc_pipe_producer_state, 1, update_tensor_map_stages); + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++clc_pipe_producer_state; + ++i; + } + } + } + } + + else if (is_participant.tensor_map_updater) { + if constexpr (IsTensorMapUpdateAsync) { + // Register reconfiguration + arch::warpgroup_reg_dealloc(); + } + + // Ensure that the prefetched kernel does not touch + // unflushed global memory prior to this instruction + cutlass::arch::wait_on_dependent_grids(); + + if constexpr (IsTensorMapUpdateAsync) { + auto updater_id = canonical_warp_idx_sync() - static_cast(WarpCategory::TensorMapUpdater); + + clc_pipe_consumer_state += updater_id; + tensor_map_ready_pipe_producer_state += updater_id; + + auto tensormaps_mainloop = collective_mainloop.tensormaps_init( + params.mainloop,shared_storage.tensormaps[updater_id+1].mainloop, params.hw_info.sm_count, sm_id); + auto tensormaps_epilogue_load = collective_epilogue.template tensormaps_init( + params.epilogue, shared_storage.tensormaps[updater_id+1].epilogue, params.hw_info.sm_count, sm_id); + auto tensormaps_epilogue_store = collective_epilogue.template tensormaps_init( + params.epilogue, shared_storage.tensormaps[updater_id+1].epilogue, params.hw_info.sm_count, sm_id); + + auto update_tensor_map_and_increment_pipe_if_needed = [&] (auto &next_work_tile_info, auto &increment_pipe) { + auto next_batch = next_work_tile_info.L_idx; + auto did_batch_change = next_work_tile_info.batch_changed; + + if (increment_pipe) { + tensor_map_ready_pipeline.producer_acquire(tensor_map_ready_pipe_producer_state); + if (next_work_tile_info.is_valid() && did_batch_change) { + auto tma_desc_offset = get_tma_desc_offset(next_work_tile_info); + collective_mainloop.template tensormaps_perform_update( + shared_storage.tensormaps[updater_id+1].mainloop, + params.mainloop, + tensormaps_mainloop[tma_desc_offset], + problem_shape, + next_batch + ); + + if (collective_epilogue.is_producer_load_needed()) { + collective_epilogue.template tensormaps_perform_update( + shared_storage.tensormaps[updater_id+1].epilogue, + params.epilogue, + tensormaps_epilogue_load[tma_desc_offset], + problem_shape, + next_batch + ); + } + + collective_epilogue.template tensormaps_perform_update( + shared_storage.tensormaps[updater_id+1].epilogue, + params.epilogue, + tensormaps_epilogue_store[tma_desc_offset], + problem_shape, + next_batch + ); + + collective_mainloop.tensormaps_fence_acquire(tensormaps_mainloop[tma_desc_offset]); + + if (collective_epilogue.is_producer_load_needed()) { + collective_epilogue.template tensormaps_fence_acquire(tensormaps_epilogue_load[tma_desc_offset]); + } + collective_epilogue.template tensormaps_fence_acquire(tensormaps_epilogue_store[tma_desc_offset]); + } + if (cute::elect_one_sync()) { + cute::tma_desc_commit_group(); + shared_storage.clc_response[1][tensor_map_ready_pipe_producer_state.index()] = next_work_tile_info; + cutlass::arch::fence_view_async_shared(); + cute::tma_desc_wait_group(); + } + + // Signal the other warps that the TMA update is complete + tensor_map_ready_pipeline.producer_commit(tensor_map_ready_pipe_producer_state); + tensor_map_ready_pipe_producer_state += (NumTensorMapUpdaterThreads / NumThreadsPerWarp); + clc_pipe_consumer_state += (NumTensorMapUpdaterThreads / NumThreadsPerWarp); + } + }; + + do { + + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work( + work_tile_info, + clc_pipeline, + clc_pipe_consumer_state + ); + update_tensor_map_and_increment_pipe_if_needed(next_work_tile_info, increment_pipe); + work_tile_info = next_work_tile_info; + + } while (work_tile_info.is_valid()); + } + } + + else if (is_participant.mma) { + + // Tmem allocation sequence + tmem_allocator.allocate(TmemAllocator::Sm100TmemCapacityColumns, &shared_storage.tmem_base_ptr); + __syncwarp(); + tmem_allocation_result_barrier.arrive(); + uint32_t tmem_base_ptr = shared_storage.tmem_base_ptr; + collective_mainloop.set_tmem_offsets(tmem_storage, tmem_base_ptr); + auto mma_inputs = collective_mainloop.mma_init(tmem_storage, shared_storage.tensors.mainloop); + cutlass::arch::wait_on_dependent_grids(); // PATCH: deferred kernel-wide wait (after TMEM alloc / mma_init) + if (cute::elect_one_sync()) DKS(6); + [[maybe_unused]] bool dks_first = true; + + if constexpr (IsTensorMapUpdateAsync) { + // Register reconfiguration + arch::warpgroup_reg_dealloc(); + } + + do { + + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(problem_shape.get_problem_shape(work_tile_info.L_idx), 1); + } + auto k_tile_count = TileScheduler::get_work_k_tile_count(work_tile_info, problem_shape_MNKL, CtaShape_MNK{}); + // Accumulator stage slice + int acc_stage = [&] () { + if constexpr (IsOverlappingAccum) { + return accumulator_pipe_producer_state.phase() ^ 1; + } + else { + return accumulator_pipe_producer_state.index(); + } + }(); + auto accumulator = collective_mainloop.slice_accumulator(tmem_storage, acc_stage); + if (is_mma_leader_cta && k_tile_count > 0) { + mainloop_pipe_consumer_state = collective_mainloop.mma( + cute::make_tuple(mainloop_pipeline, accumulator_pipeline), + cute::make_tuple(mainloop_pipe_consumer_state, accumulator_pipe_producer_state), + accumulator, + mma_inputs, + cta_coord_mnkl, + k_tile_count + ); + accumulator_pipeline.producer_commit(accumulator_pipe_producer_state); + } + if (dks_first && cute::elect_one_sync()) DKS(7); + dks_first = false; + if (k_tile_count > 0) { + ++accumulator_pipe_producer_state; + } + + // Fetch next work tile + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work( + work_tile_info, + tensor_map_ready_pipeline, + tensor_map_ready_pipe_consumer_state + ); + + if (increment_pipe) { + ++tensor_map_ready_pipe_consumer_state; + } + + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + } while (work_tile_info.is_valid()); + + // Hint on an early release of global memory resources. + // The timing of calling this function only influences performance, + // not functional correctness. + cutlass::arch::launch_dependent_grids(); + + // Release the right to allocate before deallocations so that the next CTA can rasterize + tmem_allocator.release_allocation_lock(); + + if constexpr (!IsOverlappingAccum) { + // Leader MMA waits for leader + peer epilogues to release accumulator stage + if (is_mma_leader_cta) { + accumulator_pipeline.producer_tail(accumulator_pipe_producer_state); + } + // Signal to peer MMA that entire tmem allocation can be deallocated + if constexpr (has_mma_peer_cta) { + // Leader does wait + arrive, follower does arrive + wait + tmem_deallocation_result_barrier.arrive(mma_peer_cta_rank, not is_mma_leader_cta); + tmem_deallocation_result_barrier.wait(dealloc_barrier_phase); + tmem_deallocation_result_barrier.arrive(mma_peer_cta_rank, is_mma_leader_cta); + } + } + else { + tmem_deallocation_result_barrier.wait(dealloc_barrier_phase); + } + + // Free entire tmem allocation + tmem_allocator.free(tmem_base_ptr, TmemAllocator::Sm100TmemCapacityColumns); + if (cute::elect_one_sync()) DKS(8); + } + + else if (is_participant.epi_load) { + + if constexpr (IsTensorMapUpdateAsync) { + // Register reconfiguration + arch::warpgroup_reg_dealloc(); + } + + // Ensure that the prefetched kernel does not touch + // unflushed global memory prior to this instruction + cutlass::arch::wait_on_dependent_grids(); + + bool do_load_order_wait = true; + bool do_tail_load = false; + int current_wave = 0; + + // Fetch a copy of tensormaps for the CTA from Params + auto epi_load_tensormap = [&] () { + if constexpr (IsTensorMapUpdateAsync) { + collective_epilogue.template load_init( + params.epilogue, + shared_storage.tensormaps[0].epilogue, + params.hw_info.sm_count, + sm_id + ); + return pre_init_epi_load_tensormaps; + } + else { + return get<0>(collective_epilogue.template load_init( + params.epilogue, shared_storage.tensormaps[0].epilogue, params.hw_info.sm_count, sm_id)); + } + } (); + + // Initial batch's tensor address update + // Even the first tile for a CTA can be from any of the batches. + // And during initialization of the first TMA descriptor on host, we don't initialize to the first batch due to that args value being device-only. + bool is_first_iteration = true; + bool did_batch_change = true; + constexpr bool IsEpiLoad = true; + + do { + int32_t curr_batch = work_tile_info.L_idx; + auto tma_desc_offset = get_tma_desc_offset(work_tile_info); + if (IsTensorMapUpdateAsync ? is_first_iteration : did_batch_change) { + collective_epilogue.template tensormaps_perform_update( + shared_storage.tensormaps[0].epilogue, + params.epilogue, + get_tensormap(epi_load_tensormap, tma_desc_offset), + problem_shape, + curr_batch + ); + } + bool compute_epilogue = TileScheduler::compute_epilogue(work_tile_info, params.scheduler); + + if (compute_epilogue) { + if (do_load_order_wait) { + load_order_barrier.wait(); + do_load_order_wait = false; + } + + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(problem_shape.get_problem_shape(curr_batch), 1); + } + bool reverse_epi_n = IsOverlappingAccum && (current_wave % 2 == 0); + epi_load_pipe_producer_state = collective_epilogue.template load( + epi_load_pipeline, + epi_load_pipe_producer_state, + problem_shape_MNKL, + CtaShape_MNK{}, + cta_coord_mnkl, + TileShape{}, + TiledMma{}, + shared_storage.tensors.epilogue, + cute::make_tuple(get_tensormap(epi_load_tensormap, tma_desc_offset), IsTensorMapUpdateAsync ? is_first_iteration : did_batch_change), + reverse_epi_n + ); + + do_tail_load = true; + } + // Relevant only for OverlappingAccum cases. + // Only increment the wave if the problem shape K dimension is not 0, otherwise accumulator will be skipped. + if constexpr (IsOverlappingAccum) { + if (size<2>(problem_shape_MNKL) > 0) { + current_wave++; + } + } + + // Fetch the next work tile + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work( + work_tile_info, + tensor_map_ready_pipeline, + tensor_map_ready_pipe_consumer_state + ); + work_tile_info = next_work_tile_info; + + if (increment_pipe) { + ++tensor_map_ready_pipe_consumer_state; + } + // Calculate the cta coordinates of the next work tile + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + // For subsequent tiles, check if batch changes and therefore, we need tensormap updates + is_first_iteration = false; + did_batch_change = curr_batch != work_tile_info.L_idx; + } while (work_tile_info.is_valid()); + + // Only perform a tail load if one of the work units processed performed + // an epilogue load. An example of a case in which a tail load should not be + // performed is in split-K if a cluster is only assigned non-final splits (for which + // the cluster does not compute the epilogue). + if (do_tail_load) { + collective_epilogue.load_tail( + epi_load_pipeline, epi_load_pipe_producer_state, + epi_store_pipeline, epi_store_pipe_producer_state); + } + } + + else if (is_participant.epilogue) { + if constexpr (IsTensorMapUpdateAsync) { + // Register reconfiguration + arch::warpgroup_reg_alloc(); + } + + // Wait for tmem allocate here + cutlass::arch::wait_on_dependent_grids(); // PATCH: deferred kernel-wide wait (epilogue warps) + tmem_allocation_result_barrier.arrive_and_wait(); + if (threadIdx.x % 128 == 0) DKS(9); + uint32_t tmem_base_ptr = shared_storage.tmem_base_ptr; + collective_mainloop.set_tmem_offsets(tmem_storage, tmem_base_ptr); + + auto warp_idx_in_epi = canonical_warp_idx_sync() - static_cast(WarpCategory::Epilogue); + bool do_tail_store = false; + // Fetch a copy of tensormaps for the CTA from Params + auto epi_store_tensormap = [&] () { + if constexpr (IsTensorMapUpdateAsync) { + collective_epilogue.template store_init( + params.epilogue, + shared_storage.tensormaps[0].epilogue, + params.hw_info.sm_count, + sm_id + ); + + return collective_epilogue.template tensormaps_init( + params.epilogue, + shared_storage.tensormaps[0].epilogue, + params.hw_info.sm_count, + sm_id, + warp_idx_in_epi == 0 + ); + } + else { + return get<0>(collective_epilogue.template store_init( + params.epilogue, shared_storage.tensormaps[0].epilogue, params.hw_info.sm_count, sm_id)); + } + } (); + + // Initial batch's tensor address update + // Even the first tile for a CTA can be from any of the batches. + // And during initialization of the first TMA descriptor on host, we don't initialize to the first batch due to that args value being device-only. + bool is_first_iteration = true; + bool did_batch_change = true; + constexpr bool IsEpiLoad = false; + do { + int32_t curr_batch = work_tile_info.L_idx; + auto tma_desc_offset = get_tma_desc_offset(work_tile_info); + // PATCH: no in-kernel D descriptor update (host-built per-batch descriptor, see store() below) + if (is_first_iteration && threadIdx.x % 128 == 0) DKS(10); + // Fetch next work tile + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work( + work_tile_info, + tensor_map_ready_pipeline, + tensor_map_ready_pipe_consumer_state + ); + + if (increment_pipe) { + ++tensor_map_ready_pipe_consumer_state; + } + + // Accumulator stage slice + int acc_stage = [&] () { + if constexpr (IsOverlappingAccum) { + return accumulator_pipe_consumer_state.phase(); + } + else { + return accumulator_pipe_consumer_state.index(); + } + }(); + auto accumulator = collective_mainloop.slice_accumulator(tmem_storage, acc_stage); + + // Fusions may need problem shape for the current group + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(problem_shape.get_problem_shape(curr_batch), 1); + } + // + // Epilogue and write to gD + // + auto [ + load_state_next, + store_state_next, + acc_state_next + ] = collective_epilogue.template store( + epi_load_pipeline, + epi_load_pipe_consumer_state, + epi_store_pipeline, + epi_store_pipe_producer_state, + accumulator_pipeline, + accumulator_pipe_consumer_state, + problem_shape_MNKL, + CtaShape_MNK{}, + cta_coord_mnkl, + TileShape{}, + TiledMma{}, + accumulator, + shared_storage.tensors.epilogue, + cute::make_tuple(const_cast(¶ms.pre.d[curr_batch]), false) + ); + epi_load_pipe_consumer_state = load_state_next; + epi_store_pipe_producer_state = store_state_next; + accumulator_pipe_consumer_state = acc_state_next; + if (is_first_iteration && threadIdx.x % 128 == 0) DKS(11); + + do_tail_store |= TileScheduler::compute_epilogue(work_tile_info, params.scheduler); + work_tile_info = next_work_tile_info; + cta_coord_mnkl = scheduler.work_tile_to_cta_coord(work_tile_info); + // For subsequent tiles, check if batch changes and therefore, we need tensormap updates + is_first_iteration = false; + did_batch_change = curr_batch != work_tile_info.L_idx; + } while (work_tile_info.is_valid()); + + if constexpr (IsOverlappingAccum) { + // Signal to peer MMA that Full TMEM alloc can be deallocated + if constexpr (has_mma_peer_cta) { + tmem_deallocation_result_barrier.arrive(mma_peer_cta_rank); + } + tmem_deallocation_result_barrier.arrive(); + } + + // Only perform a tail store if one of the work units processed performed + // an epilogue. An example of a case in which a tail load should not be + // performed is in split-K if a cluster is only assigned non-final splits (for which + // the cluster does not compute the epilogue). + if (do_tail_store) { + collective_epilogue.store_tail( + epi_load_pipeline, epi_load_pipe_consumer_state, + epi_store_pipeline, epi_store_pipe_producer_state, + CtaShape_MNK{}); + } + if (threadIdx.x % 128 == 0) DKS(12); + } + + else { + if constexpr (IsTensorMapUpdateAsync) { + // Register reconfiguration + arch::warpgroup_reg_dealloc(); + } + + } + } +}; + +/////////////////////////////////////////////////////////////////////////////// + +} // namespace cutlass::gemm::kernel diff --git a/kernels/Quant/019_nvfp4_grouped_query_attention/src/cutlass/gemm/collective/builders/sm100_common.inl b/kernels/Quant/019_nvfp4_grouped_query_attention/src/cutlass/gemm/collective/builders/sm100_common.inl new file mode 100644 index 0000000000000000000000000000000000000000..7982df4b5597079db0c36e5ab9a3edc96db70fc1 --- /dev/null +++ b/kernels/Quant/019_nvfp4_grouped_query_attention/src/cutlass/gemm/collective/builders/sm100_common.inl @@ -0,0 +1,1010 @@ +/*************************************************************************************************** + * Copyright (c) 2023 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + **************************************************************************************************/ + +// SHADOW of CUTLASS 4.4.1 builders/sm100_common.inl: identical except the 2SM block-scaled tiled-MMA builder +// also accepts TileShape_N = 224 (see the shadowed sm100_blockscaled_mma_warpspecialized.hpp). +#define NVFP4_SHADOW_N224_BUILDER 1 +#pragma once + +#include "cutlass/gemm/gemm.h" +#include "cutlass/gemm/kernel/sm100_tile_scheduler.hpp" +#include "cutlass/gemm/dispatch_policy.hpp" // KernelSchedule1Sm, KernelSchedule2Sm +#include "cutlass/gemm/collective/builders/sm90_common.inl" // detail::sm90_cluster_shape_to_tma_atom() +#include "cutlass/numeric_types.h" // all numeric types +#include "cutlass/detail/dependent_false.hpp" // detail::dependent_false +#include "cutlass/pipeline/pipeline.hpp" +#include "cutlass/detail/layout.hpp" // cutlass::detail::get_input_alignment_bits() +#include "cutlass/layout/matrix.h" // cutlass::layout::RowMajor, cutlass::layout::ColumnMajor +#include "cutlass/fast_math.h" // cutlass::round_up, cutlass::const_max +#include "cutlass/arch/arch.h" +#include "cutlass/gemm/collective/builders/sm1xx_common.inl" + +#include "cute/atom/mma_traits_sm100.hpp" // UMMA::Layout_MN_SW* +#include "cute/atom/copy_traits_sm100_tma.hpp" // SM100_TMA_*SM_LOAD_* +#include "cute/arch/tmem_allocator_sm100.hpp" +#include "cute/arch/mma_sm100_desc.hpp" // cute::UMMA::Major +#include "cute/arch/mma_sm100_umma.hpp" // SM100_*MMA_SS_* +#include "cute/numeric/integral_constant.hpp" // is_static_v, cute::integral_constant +#include "cute/util/type_traits.hpp" // cute::alignment_of_v + +///////////////////////////////////////////////////////////////////////////////////////////////// + +namespace cutlass::gemm::collective { + +// Forward Declaration +struct KernelScheduleAuto; + +///////////////////////////////////////////////////////////////////////////////////////////////// + +namespace detail { + +// +// Some named constants +// +constexpr int sm100_smem_capacity_bytes = cutlass::arch::sm100_smem_capacity_bytes; +constexpr int CLCResponseSize = + sizeof(typename cutlass::gemm::kernel::detail::PersistentTileSchedulerSm100,1>::CLCResponse{}); + + +// Helper for SS UMMA smem selection that considers a tensor TileShape: +// (BLK_MN, BLK_K) +// or hierarchically +// ((BLK_MN0,BLK_MN1,...),(BLK_K0,BLK_K1,...)) +// and returns the largest UMMA::Layout that fits BLK_MN0 and BLK_K0 +template +CUTE_HOST_DEVICE constexpr +auto +sm100_smem_selector() { + auto BLK_MN0 = size<0>(BLK_MN{}); + auto BLK_K0 = size<0>(BLK_K{}); + + static_assert(BLK_MN0 % 8 == 0, "BLK_MN0 must be a multiple of 8."); + static_assert(BLK_K0 % 8 == 0, "BLK_K0 must be a multiple of 8."); + + if constexpr (major == cute::UMMA::Major::MN) { + // Handle the special case for F32 NT kernels + if constexpr ((sizeof(ElementType) == 4)) { + static_assert(BLK_MN0 % size<0>(UMMA::Layout_MN_SW128_32B_Atom{}) == 0, "for mn-major tf32 operands, SW128_32B is the only available smem layout"); + return UMMA::Layout_MN_SW128_32B_Atom{}; + } + else { + // All other data types are handled as SM90 + if constexpr (BLK_MN0 % size<0>(UMMA::Layout_MN_SW128_Atom{}) == 0) { + return UMMA::Layout_MN_SW128_Atom{}; + } + else if constexpr (BLK_MN0 % size<0>(UMMA::Layout_MN_SW64_Atom{}) == 0) { + return UMMA::Layout_MN_SW64_Atom{}; + } + else if constexpr (BLK_MN0 % size<0>(UMMA::Layout_MN_SW32_Atom{}) == 0) { + return UMMA::Layout_MN_SW32_Atom{}; + } + else if constexpr (BLK_MN0 % size<0>(UMMA::Layout_MN_INTER_Atom{}) == 0) { + return UMMA::Layout_MN_INTER_Atom{}; + } + else { + static_assert(BLK_MN0 % size<0>(UMMA::Layout_MN_INTER_Atom{}) == 0, + "BLK_MN0 must be a multiple of size<0>(UMMA::Layout_MN_INTER_Atom{})"); + } + } + } + else if constexpr (major == cute::UMMA::Major::K) { + if constexpr (BLK_K0 % size<1>(UMMA::Layout_K_SW128_Atom{}) == 0) { + return UMMA::Layout_K_SW128_Atom{}; + } + else if constexpr (BLK_K0 % size<1>(UMMA::Layout_K_SW64_Atom{}) == 0) { + return UMMA::Layout_K_SW64_Atom{}; + } + else if constexpr (BLK_K0 % size<1>(UMMA::Layout_K_SW32_Atom{}) == 0) { + return UMMA::Layout_K_SW32_Atom{}; + } + else if constexpr (BLK_K0 % size<1>(UMMA::Layout_K_INTER_Atom{}) == 0) { + return UMMA::Layout_K_INTER_Atom{}; + } + else { + static_assert(BLK_K0 % size<1>(UMMA::Layout_K_INTER_Atom{}) == 0, + "BLK_K0 must be a multiple of size<1>(UMMA::Layout_K_INTER_Atom{})"); + } + } +} + +// Helper for SS UMMA smem selection that considers a tensor TileShape: +// (BLK_MN, BLK_K) +// or hierarchically +// ((BLK_MN0,BLK_MN1,...),(BLK_K0,BLK_K1,...)) +// and returns the largest UMMA::Layout that fits BLK_MN0 and BLK_K0 +template +CUTE_HOST_DEVICE constexpr +auto +sm100_smem_selector_sparse() +{ + auto BLK_MN0 = size<0>(BLK_MN{}); + auto BLK_K0 = size<0>(BLK_K{}); + + static_assert(BLK_MN0 % 8 == 0, "BLK_MN0 must be a multiple of 8."); + static_assert(BLK_K0 % 8 == 0, "BLK_K0 must be a multiple of 8."); + + if constexpr (major == cute::UMMA::Major::MN) { + + // Handle the special case for F32 NT kernels + if constexpr ((sizeof(ElementType) == 4 && (BLK_MN0 % size<0>(UMMA::Layout_MN_SW128_32B_SpAtom{}) == 0))) { + return UMMA::Layout_MN_SW128_32B_SpAtom{}; + } + else { + // All other data types are handled as SM90 + if constexpr (BLK_MN0 % size<0>(UMMA::Layout_MN_SW128_SpAtom{}) == 0) { + return UMMA::Layout_MN_SW128_SpAtom{}; + } + else if constexpr (BLK_MN0 % size<0>(UMMA::Layout_MN_SW64_SpAtom{}) == 0) { + return UMMA::Layout_MN_SW64_SpAtom{}; + } + else if constexpr (BLK_MN0 % size<0>(UMMA::Layout_MN_SW32_SpAtom{}) == 0) { + return UMMA::Layout_MN_SW32_SpAtom{}; + } + else if constexpr (BLK_MN0 % size<0>(UMMA::Layout_MN_INTER_SpAtom{}) == 0) { + return UMMA::Layout_MN_INTER_SpAtom{}; + } + else { + static_assert(BLK_MN0 % size<0>(UMMA::Layout_MN_INTER_SpAtom{}) == 0, + "BLK_MN0 must be a multiple of size<0>(UMMA::Layout_MN_INTER_SpAtom{})"); + } + } + } + else if constexpr (major == cute::UMMA::Major::K) { + if constexpr (BLK_K0 % size<1>(UMMA::Layout_K_SW128_SpAtom{}) == 0) { + return UMMA::Layout_K_SW128_SpAtom{}; + } + else if constexpr (BLK_K0 % size<1>(UMMA::Layout_K_SW64_SpAtom{}) == 0) { + return UMMA::Layout_K_SW64_SpAtom{}; + } + else if constexpr (BLK_K0 % size<1>(UMMA::Layout_K_SW32_SpAtom{}) == 0) { + return UMMA::Layout_K_SW32_SpAtom{}; + } + else if constexpr (BLK_K0 % size<1>(UMMA::Layout_K_INTER_SpAtom{}) == 0) { + return UMMA::Layout_K_INTER_SpAtom{}; + } + else { + static_assert(BLK_K0 % size<1>(UMMA::Layout_K_INTER_SpAtom{}) == 0, + "BLK_K0 must be a multiple of size<1>(UMMA::Layout_K_INTER_SpAtom{})"); + } + } +} + +template +constexpr auto +sm100_cluster_shape_to_tma_atom_A(ClusterShapeMNK cluster_shape_mnk, AtomThrId atom_thr_id) { + static_assert(cute::rank(cluster_shape_mnk) == 3); + constexpr bool IsDynamicCluster = not cute::is_static_v; + + if constexpr (cute::size(atom_thr_id) == 2) { + if constexpr (!IsDynamicCluster) { + static_assert(cute::size<0>(cluster_shape_mnk) % 2 == 0, "Cluster shape not divisible by MMA size"); + if constexpr (cute::size<1>(cluster_shape_mnk) == 1) { + return cute::SM100_TMA_2SM_LOAD{}; + } + else { + return cute::SM100_TMA_2SM_LOAD_MULTICAST{}; + } + } + else { + return cute::SM100_TMA_2SM_LOAD_MULTICAST{}; + } + } + else if constexpr (size(atom_thr_id) == 1) { + if constexpr (!IsDynamicCluster) { + return detail::sm90_cluster_shape_to_tma_atom(cute::size<1>(cluster_shape_mnk)); + } + else { + // In the case of dynamic cluster, multicast decision is not known at compile time. + // A multicast instruction is forced by passing a cute::Int<2>{} to this helper. + return detail::sm90_cluster_shape_to_tma_atom(cute::Int<2>{}); + } + } + else { + static_assert(cutlass::detail::dependent_false, + "Unsupported Configuration for SM100 TMA"); + } +} + +template +constexpr auto +sm100_cluster_shape_to_tma_atom_B(ClusterShapeMNK cluster_shape_mnk, AtomThrId atom_thr_id) { + static_assert(cute::rank(cluster_shape_mnk) == 3); + constexpr bool IsDynamicCluster = not cute::is_static_v; + + if constexpr (cute::size(atom_thr_id) == 2) { + if constexpr (!IsDynamicCluster) { + static_assert(cute::size<0>(cluster_shape_mnk) % 2 == 0, "Cluster shape not divisible by MMA size"); + if constexpr (cute::size<0>(cluster_shape_mnk) == 2) { + return cute::SM100_TMA_2SM_LOAD{}; + } + else { + return cute::SM100_TMA_2SM_LOAD_MULTICAST{}; + } + } + else { + return cute::SM100_TMA_2SM_LOAD_MULTICAST{}; + } + } else if constexpr (size(atom_thr_id) == 1) { + if constexpr (!IsDynamicCluster) { + return detail::sm90_cluster_shape_to_tma_atom(cute::size<0>(cluster_shape_mnk)); + } + else { + // In the case of dynamic cluster, multicast decision is not known at compile time. + // A multicast instruction is forced by passing a cute::Int<2>{} to this helper. + return detail::sm90_cluster_shape_to_tma_atom(cute::Int<2>{}); + } + } + else { + static_assert(cutlass::detail::dependent_false, + "Unsupported Configuration for SM100 TMA"); + } +} + + +template +constexpr auto +sm100_cluster_shape_to_tma_atom_SFB(ClusterShapeMNK cluster_shape_mnk, AtomThrId atom_thr_id) { + static_assert(cute::rank(cluster_shape_mnk) == 3); + if constexpr (cute::size(atom_thr_id) == 2) { + // Always could use multicast feature for SFB with 2cta MMA. + return cute::SM100_TMA_2SM_LOAD_MULTICAST{}; + } + else if constexpr (size(atom_thr_id) == 1) { + constexpr bool IsDynamicCluster = not cute::is_static_v; + if constexpr (!IsDynamicCluster) { + return detail::sm90_cluster_shape_to_tma_atom(cute::size<0>(cluster_shape_mnk)); + } + else { + // In the case of dynamic cluster, multicast decision is not known at compile time. + // A multicast instruction is forced by passing a cute::Int<2>{} to this helper. + return detail::sm90_cluster_shape_to_tma_atom(cute::Int<2>{}); + } + } + else { + static_assert(cutlass::detail::dependent_false, + "Unsupported Configuration for SM100 TMA"); + } +} + +template< + class ElementAMma, + class ElementBMma, + class ElementAMmaccumulator, + class TileShape_MNK, + class ClusterShape_MNK, + UMMA::Major UmmaMajorA, + UMMA::Major UmmaMajorB, + UMMA::ScaleIn ANeg = UMMA::ScaleIn::One, + UMMA::ScaleIn BNeg = UMMA::ScaleIn::One +> +constexpr auto +sm100_make_1sm_trivial_tiled_mma() { + + constexpr int M = cute::size<0>(TileShape_MNK{}); + static_assert(M == 64 || M == 128, "Invalid TileShape_M."); + + // Do not allow a tiled MMA N mode > 1, as that is not reasonable. + constexpr int N = cute::size<1>(TileShape_MNK{}); + static_assert(N % 8 == 0 && N <= 256, "Invalid TileShape_N."); + + if constexpr (cute::is_same_v) { + static_assert(cute::is_same_v, "ElementAMma and ElementBMma must match."); + return make_tiled_mma(cute::SM100_MMA_TF32_SS{}); + } + else if constexpr (cute::is_same_v || + cute::is_same_v) { + static_assert(cute::is_same_v, "ElementAMma and ElementBMma must match."); + return make_tiled_mma(cute::SM100_MMA_F16BF16_SS{}); + } + else if constexpr (cute::is_same_v || + cute::is_same_v) { + return make_tiled_mma(cute::SM100_MMA_S8_SS{}); + } + else if constexpr (cute::is_same_v + || cute::is_same_v + || cute::is_same_v + || cute::is_same_v + || cute::is_same_v + || cute::is_same_v + || cute::is_same_v + || cute::is_same_v + ) { + + return make_tiled_mma( + cute::MMA_Traits< + cute::SM100_MMA_F8F6F4_SS, + ElementAMma, + ElementBMma, + ElementAMmaccumulator, + cute::C, + cute::C, + cute::integral_constant, + cute::integral_constant, + cute::integral_constant, + cute::integral_constant + >{} + ); + } + else { + static_assert(cutlass::detail::dependent_false, + "Unsupported configuration for SM100 collective builder."); + } +} + +template< + class ElementAMma, + class ElementBMma, + class ElementAMmaccumulator, + class TileShape_MNK, + class ClusterShape_MNK, + UMMA::Major UmmaMajorA, + UMMA::Major UmmaMajorB, + UMMA::ScaleIn ANeg = UMMA::ScaleIn::One, + UMMA::ScaleIn BNeg = UMMA::ScaleIn::One +> +constexpr auto +sm100_make_2sm_trivial_tiled_mma() { + + constexpr int M = cute::size<0>(TileShape_MNK{}); + static_assert(M == 128 || M == 256, "Invalid TileShape_M."); + + // Do not allow a tiled MMA N mode > 1, as that is not reasonable. + constexpr int N = cute::size<1>(TileShape_MNK{}); + static_assert(N % 8 == 0 && N <= 256, "Invalid TileShape_N."); + + if constexpr (cute::is_same_v) { + static_assert(cute::is_same_v, "ElementAMma and ElementBMma must match."); + return make_tiled_mma(cute::SM100_MMA_TF32_2x1SM_SS{}); + } + else if constexpr (cute::is_same_v || + cute::is_same_v) { + static_assert(cute::is_same_v, "ElementAMma and ElementBMma must match."); + return make_tiled_mma(cute::SM100_MMA_F16BF16_2x1SM_SS{}); + } + else if constexpr (cute::is_same_v || + cute::is_same_v) { + return make_tiled_mma(cute::SM100_MMA_S8_2x1SM_SS{}); + } + else if constexpr (cute::is_same_v + || cute::is_same_v + || cute::is_same_v + || cute::is_same_v + || cute::is_same_v + || cute::is_same_v + || cute::is_same_v + || cute::is_same_v + ) { + + return make_tiled_mma( + cute::MMA_Traits< + cute::SM100_MMA_F8F6F4_2x1SM_SS, + ElementAMma, + ElementBMma, + ElementAMmaccumulator, + cute::C, + cute::C, + cute::integral_constant, + cute::integral_constant, + cute::integral_constant, + cute::integral_constant + >{} + ); + + } + else { + static_assert(cutlass::detail::dependent_false, + "Unsupported configuration for SM100 collective builder."); + } +} + +// For new MMA construction and partitioning that supports both dynamic and static cluster shape. +// Used in conjunction with make_tma_atom_(A|B)_sm100 +// TileShape_MNK is always static and has shape (MmaAtomShapeM, MmaAtomShapeN, TileK) +// ClusterShape_MNK can be dynamic or static. +template< + class ElementAMma, + class ElementBMma, + class ElementAccumulator, + class TileShape_MNK, + class ClusterShape_MNK, + UMMA::Major UmmaMajorA, + UMMA::Major UmmaMajorB, + class BuilderScheduleTag, + UMMA::ScaleIn ANeg = UMMA::ScaleIn::One, + UMMA::ScaleIn BNeg = UMMA::ScaleIn::One +> +constexpr auto +sm100_make_trivial_tiled_mma() { + // MMA_2SM requested + if constexpr (cute::is_base_of_v ) { + return sm100_make_2sm_trivial_tiled_mma(); + } + // MMA_1SM requested + else if constexpr (cute::is_base_of_v ) { + return sm100_make_1sm_trivial_tiled_mma(); + } + // Auto scheduling requested + else if constexpr (cute::is_same_v) { + // Static cluster + if constexpr (cute::is_static_v) { + // For MMA_2SM we need a cluster shape that is multiple of 2x1 + // and only M=128 and M=256 are supported, otherwise, fall back to MMA_1SM + if constexpr (cute::size<0>(ClusterShape_MNK{}) % 2 == 0 && + cute::size<0>(TileShape_MNK{}) % 128 == 0) { + return sm100_make_2sm_trivial_tiled_mma(); + } + else { + return sm100_make_1sm_trivial_tiled_mma(); + } + // Dynamic cluster shape means we cannot assume we can use 2SM MMA + } + else { + return sm100_make_1sm_trivial_tiled_mma(); + } + } +} + +template< + class ElementAMma, + class ElementBMma, + class ElementAccumulator, + class ClusterTileShape_MNK, + class ClusterShape_MNK, + UMMA::Major UmmaMajorA, + UMMA::Major UmmaMajorB, + UMMA::ScaleIn ANeg = UMMA::ScaleIn::One, + UMMA::ScaleIn BNeg = UMMA::ScaleIn::One +> +constexpr auto +sm100_make_1sm_ts_trivial_tiled_mma() { + + constexpr int M = cute::size<0>(ClusterTileShape_MNK{}); + static_assert(M == 64 || M == 128, "Invalid TileShape_M."); + + // Do not allow a tiled MMA N mode > 1, as that is not reasonable. + constexpr int N = cute::size<1>(ClusterTileShape_MNK{}); + static_assert(N % 8 == 0 && N <= 256, "Invalid TileShape_N."); + + if constexpr (cute::is_same_v) { + static_assert(cute::is_same_v, "ElementA and ElementB must match."); + return make_tiled_mma(cute::SM100_MMA_TF32_TS{}); + } + else if constexpr (cute::is_same_v || + cute::is_same_v) { + static_assert(cute::is_same_v, "ElementA and ElementB must match."); + return make_tiled_mma(cute::SM100_MMA_F16BF16_TS{}); + } + else if constexpr (cute::is_same_v || + cute::is_same_v) { + return make_tiled_mma(cute::SM100_MMA_S8_TS{}); + } + else { + static_assert(cutlass::detail::dependent_false, + "Unsupported configuration for SM100 collective builder."); + } +} + +template< + class ElementAMma, + class ElementBMma, + class ElementAccumulator, + class ClusterTileShape_MNK, + class ClusterShape_MNK, + UMMA::Major UmmaMajorA, + UMMA::Major UmmaMajorB, + UMMA::ScaleIn ANeg = UMMA::ScaleIn::One, + UMMA::ScaleIn BNeg = UMMA::ScaleIn::One +> +constexpr auto +sm100_make_2sm_ts_trivial_tiled_mma() { + + constexpr int M = cute::size<0>(ClusterTileShape_MNK{}); + static_assert(M == 128 || M == 256, "Invalid TileShape_M."); + + // Do not allow a tiled MMA N mode > 1, as that is not reasonable. + constexpr int N = cute::size<1>(ClusterTileShape_MNK{}); + static_assert(N % 8 == 0 && N <= 256, "Invalid TileShape_N."); + + if constexpr (cute::is_same_v) { + static_assert(cute::is_same_v, "For SM100 TF32 MMA, ElementA and ElementB must match."); + return make_tiled_mma(cute::SM100_MMA_TF32_2x1SM_TS{}); + } + else if constexpr (cute::is_same_v || + cute::is_same_v) { + static_assert(cute::is_same_v, "For SM100 F16F32 MMA, ElementA and ElementB must match."); + return make_tiled_mma(cute::SM100_MMA_F16BF16_2x1SM_TS{}); + } + else if constexpr (cute::is_same_v || + cute::is_same_v) { + return make_tiled_mma(cute::SM100_MMA_S8_2x1SM_TS{}); + } + else { + static_assert(cutlass::detail::dependent_false, + "Unsupported configuration for SM100 collective builder."); + } +} + +template< + class ElementAMma, + class ElementBMma, + class ElementAccumulator, + class TileShape_MNK, + class ClusterShape_MNK, + UMMA::Major UmmaMajorA, + UMMA::Major UmmaMajorB, + int Scale, + class BuilderScheduleTag +> +constexpr auto +sm100_make_trivial_fastFP32_tiled_mma() { + constexpr bool TagHasUmmaSs = ( + cute::is_base_of_v + ); + + // MMA_2SM requested + if constexpr (cute::is_base_of_v ) { + using AtomLayout_MNK = decltype(make_layout(shape_div(ClusterShape_MNK{}, Shape<_2,_1,_1>{}))); + constexpr int M = cute::size<0>(TileShape_MNK{}); + constexpr int N = cute::size<1>(TileShape_MNK{}); + if constexpr (UmmaMajorA == cute::UMMA::Major::K && !TagHasUmmaSs) { + return make_tiled_mma(cute::SM100_MMA_F16BF16_2x1SM_TS_SCALED{}); + } + else { // If A needs to be transposed by MMA, fall back to SMEM from A MMA instructions + return make_tiled_mma(cute::SM100_MMA_F16BF16_2x1SM_SS_SCALED{}); + } + } + // MMA_1SM requested + else if constexpr (cute::is_base_of_v ) { + // using AtomLayout_MNK = Layout; + constexpr int M = cute::size<0>(TileShape_MNK{}); + constexpr int N = cute::size<1>(TileShape_MNK{}); + if constexpr (UmmaMajorA == cute::UMMA::Major::K && !TagHasUmmaSs) { + return make_tiled_mma(cute::SM100_MMA_F16BF16_TS_SCALED{}); + } + else { // If A needs to be transposed by MMA, fall back to SMEM from A MMA instructions + return make_tiled_mma(cute::SM100_MMA_F16BF16_SS_SCALED{}); + } + } + else if constexpr (cute::is_same_v || + cute::is_same_v || + cute::is_same_v || + cute::is_same_v) { + // Static cluster + if constexpr (cute::is_static_v) { + // For MMA_2SM we need a cluster shape that is multiple of 2x1 + // and only M=128 and M=256 are supported, otherwise, fall back to MMA_1SM + if constexpr (cute::get<0>(ClusterShape_MNK{}) % 2 == 0 && + (cute::get<0>(TileShape_MNK{}) / cute::get<0>(ClusterShape_MNK{})) % 64 == 0) { + if constexpr (!TagHasUmmaSs) { + return sm100_make_trivial_fastFP32_tiled_mma(); + } + else { + return sm100_make_trivial_fastFP32_tiled_mma(); + } + } + else { + if constexpr (!TagHasUmmaSs) { + return sm100_make_trivial_fastFP32_tiled_mma(); + } + else { + return sm100_make_trivial_fastFP32_tiled_mma(); + } + } + } + // Dynamic cluster shape means we cannot assume we can use 2SM MMA + else { + if constexpr (!TagHasUmmaSs) { + return sm100_make_trivial_fastFP32_tiled_mma(); + } + else { + return sm100_make_trivial_fastFP32_tiled_mma(); + } + } + } + else { + static_assert(cutlass::detail::dependent_false == 0, + "Unsupported policy for SM100 collective builder."); + } +} + +template< + class TileShape_MNK, + class ClusterShape_MNK, + class BuilderScheduleTag +> +constexpr auto +sm100_make_trivial_interleaved_complex_tf32_tiled_mma() { + // MMA_2SM requested + if constexpr (cute::is_base_of_v ) { + constexpr int M = cute::size<0>(TileShape_MNK{}); + static_assert(M == 128 || M == 256, "Invalid TileShape_M."); + + // Do not allow a tiled MMA N mode > 1, as that is not reasonable. + constexpr int N = cute::size<1>(TileShape_MNK{}); + static_assert(N % 8 == 0 && N <= 256, "Invalid TileShape_N."); + return make_tiled_mma(cute::SM100_MMA_TF32_2x1SM_TS_INTERLEAVED_CF32CTF32CTF32CF32_TN{}); + } + // MMA_1SM requested + else if constexpr (cute::is_base_of_v ) { + constexpr int M = cute::size<0>(TileShape_MNK{}); + static_assert(M == 64 || M == 128, "Invalid TileShape_M."); + // Do not allow a tiled MMA N mode > 1, as that is not reasonable. + constexpr int N = cute::size<1>(TileShape_MNK{}); + static_assert(N % 8 == 0 && N <= 256, "Invalid TileShape_N."); + return make_tiled_mma(cute::SM100_MMA_TF32_TS_INTERLEAVED_CF32CTF32CTF32CF32_TN{}); + } + else if constexpr (cute::is_same_v) { + // Static cluster + if constexpr (cute::is_static_v) { + // For MMA_2SM we need a cluster shape that is multiple of 2x1 + // and only M=128 and M=256 are supported, otherwise, fall back to MMA_1SM + if constexpr (cute::get<0>(ClusterShape_MNK{}) % 2 == 0 && + cute::size<0>(TileShape_MNK{}) % 128 == 0) { + return sm100_make_trivial_interleaved_complex_tf32_tiled_mma(); + } + else { + return sm100_make_trivial_interleaved_complex_tf32_tiled_mma(); + } + } + // Dynamic cluster shape means we cannot assume we can use 2SM MMA + else { + return sm100_make_trivial_interleaved_complex_tf32_tiled_mma(); + } + } +} + +//Setting mma for Mixed input gemm. Here, ElementAMma should be TACompute +template< + class ElementAMma, + class ElementBMma, + class ElementAccumulator, + class TileShape_MNK, + class ClusterShape_MNK, + UMMA::Major UmmaMajorA, + UMMA::Major UmmaMajorB, + class KernelScheduleType +> +constexpr auto +sm100_make_trivial_mixed_input_tiled_mma() { + constexpr int M = cute::size<0>(TileShape_MNK{}); + constexpr int N = cute::size<1>(TileShape_MNK{}); + //MMA 1Sm requested + if constexpr (cute::is_base_of_v ) { + if constexpr (UmmaMajorA == cute::UMMA::Major::K && !cute::is_base_of_v) { + if constexpr (cute::is_same_v || cute::is_same_v) { + return make_tiled_mma(cute::SM100_MMA_F16BF16_TS{}); + } + if constexpr (cute::is_same_v) { + return make_tiled_mma(cute::SM100_MMA_F8F6F4_TS{}); + } + } + else { // If A needs to be transposed by MMA, fall back to SMEM from A MMA instructions + if constexpr (cute::is_same_v || cute::is_same_v) { + return make_tiled_mma(cute::SM100_MMA_F16BF16_SS{}); + } + if constexpr (cute::is_same_v) { + return make_tiled_mma( + cute::MMA_Traits< + cute::SM100_MMA_F8F6F4_SS, + ElementAMma, + ElementBMma, + ElementAccumulator, + cute::C, + cute::C, + cute::integral_constant, + cute::integral_constant, + cute::integral_constant, + cute::integral_constant>{}); + } + } + } + //MMA 2Sm requested + else if constexpr (cute::is_base_of_v) { + if constexpr (UmmaMajorA == cute::UMMA::Major::K && !cute::is_base_of_v) { + if constexpr (cute::is_same_v || cute::is_same_v) { + return make_tiled_mma(cute::SM100_MMA_F16BF16_2x1SM_TS{}); + } + if constexpr (cute::is_same_v) { + return make_tiled_mma(cute::SM100_MMA_F8F6F4_2x1SM_TS{}); + } + } + } + else { + static_assert(cutlass::detail::dependent_false == 0, + "Unsupported policy for SM100 collective builder."); + } +} + +template< + class CtaShape_MNK +> +constexpr auto +sm100_simt_f32_warp_shape_mnk_selector() { + using namespace cute; + + constexpr int CtaShape_M = cute::size<0>(CtaShape_MNK{}); + constexpr int CtaShape_N = cute::size<1>(CtaShape_MNK{}); + constexpr int CtaShape_K = cute::size<2>(CtaShape_MNK{}); + + // CTA tile shape M and N are supposed to be divisible by 32. + static_assert(CtaShape_M % 32 == 0, "CtaShape_M needs to be divisible by 32."); + static_assert(CtaShape_N % 32 == 0, "CtaShape_N needs to be divisible by 32."); + + // WarpShape_MNK configuration + // We assume WarpShape_K is always 1 in our SM100 SIMT SGEMM implementation. + if constexpr (CtaShape_M >= CtaShape_N) { + if constexpr (CtaShape_M == 256 && CtaShape_N == 128) { + return cute::Shape<_4, _2, _1>{}; + } + else if constexpr ((CtaShape_M == 64 || CtaShape_M == 32) && CtaShape_N == 32) { + return cute::Shape<_1, _2, _1>{}; + } + else { + return cute::Shape<_2, _2, _1>{}; + } + } + else { + if constexpr (CtaShape_M == 128 && CtaShape_N == 256) { + return cute::Shape<_2, _4, _1>{}; + } + else if constexpr (CtaShape_M == 32 && CtaShape_N == 64) { + return cute::Shape<_1, _2, _1>{}; + } + else { + return cute::Shape<_1, _4, _1>{}; + } + } +} + + +template < + class ElementPairA, + class ElementPairB, + class ElementAccumulator, + class TileShape_MNK, + class ClusterShape_MNK, + UMMA::Major UmmaMajorA, + UMMA::Major UmmaMajorB, + detail::blockscaled::BlockScaledInstr Instr, + class BuilderScheduleTag +> +constexpr auto +sm100_make_blockscaled_1sm_trivial_tiled_mma() { + // For MMA_1sm atoms, the MMA's AtomLayout is same as the ClusterShape + using AtomLayout_MNK = Layout; + constexpr int M = cute::size<0>(TileShape_MNK{}); + static_assert(M == 128, "Invalid TileShape_M."); + + // Do not allow a tiled MMA N mode > 1, as that is not reasonable. + constexpr int N = cute::size<1>(TileShape_MNK{}); + static_assert(N == 64 || N == 128 || N == 192 || N == 256, "Invalid TileShape_N."); + + using ElementSFA = typename detail::blockscaled::blockscaled_type::sf_type; + using ElementSFB = typename detail::blockscaled::blockscaled_type::sf_type; + using ElementA = typename detail::blockscaled::blockscaled_type::data_type; + using ElementB = typename detail::blockscaled::blockscaled_type::data_type; + constexpr uint32_t SfVectorSizeA = detail::blockscaled::blockscaled_type::SfVectorSize; + [[maybe_unused]] constexpr uint32_t SfVectorSizeB = detail::blockscaled::blockscaled_type::SfVectorSize; + + using ElementAMma = decltype(cutlass::gemm::collective::detail::sm1xx_kernel_input_element_to_mma_input_element()); + using ElementBMma = decltype(cutlass::gemm::collective::detail::sm1xx_kernel_input_element_to_mma_input_element()); + + using ElementSF = ElementSFA; + + if constexpr (Instr == detail::blockscaled::BlockScaledInstr::MXF4F6F8) { + if constexpr (cute::is_base_of_v ) { + return make_tiled_mma(cute::SM100_MMA_MXF8F6F4_SS_SPARSE{}); + } + else { + return make_tiled_mma(cute::SM100_MMA_MXF8F6F4_SS{}); + } + } + else if constexpr (Instr == detail::blockscaled::BlockScaledInstr::MXF4_NVF4) { + constexpr int SfVectorSize = SfVectorSizeA; + if constexpr (cute::is_base_of_v ) { + return make_tiled_mma(cute::SM100_MMA_MXF4NVF4_SS_SPARSE{}); + } + else { + return make_tiled_mma(cute::SM100_MMA_MXF4_SS{}); + } + } + else { + static_assert(cutlass::detail::dependent_false, + "Unsupported configuration for SM100 collective builder."); + } +} + +template < + class ElementPairA, + class ElementPairB, + class ElementAccumulator, + class TileShape_MNK, + class ClusterShape_MNK, + UMMA::Major UmmaMajorA, + UMMA::Major UmmaMajorB, + detail::blockscaled::BlockScaledInstr Instr, + class BuilderScheduleTag +> +constexpr auto +sm100_make_blockscaled_2sm_trivial_tiled_mma() { + + constexpr int M = cute::size<0>(TileShape_MNK{}); + static_assert(M == 256, "Invalid TileShape_M."); + + // Do not allow a tiled MMA N mode > 1, as that is not reasonable. + constexpr int N = cute::size<1>(TileShape_MNK{}); + static_assert(N == 64 || N == 128 || N == 160 || N == 192 || N == 224 || N == 256, "Invalid TileShape_N."); + + using ElementSFA = typename detail::blockscaled::blockscaled_type::sf_type; + using ElementSFB = typename detail::blockscaled::blockscaled_type::sf_type; + using ElementA = typename detail::blockscaled::blockscaled_type::data_type; + using ElementB = typename detail::blockscaled::blockscaled_type::data_type; + constexpr uint32_t SfVectorSizeA = detail::blockscaled::blockscaled_type::SfVectorSize; + [[maybe_unused]] constexpr uint32_t SfVectorSizeB = detail::blockscaled::blockscaled_type::SfVectorSize; + using ElementAMma = decltype(cutlass::gemm::collective::detail::sm1xx_kernel_input_element_to_mma_input_element()); + using ElementBMma = decltype(cutlass::gemm::collective::detail::sm1xx_kernel_input_element_to_mma_input_element()); + + using ElementSF = ElementSFA; + + if constexpr (Instr == detail::blockscaled::BlockScaledInstr::MXF4F6F8) { + if constexpr (cute::is_base_of_v ) { + return make_tiled_mma(cute::SM100_MMA_MXF8F6F4_2x1SM_SS_SPARSE{}); + } + else { + return make_tiled_mma(cute::SM100_MMA_MXF8F6F4_2x1SM_SS{}); + } + } + else if constexpr (Instr == detail::blockscaled::BlockScaledInstr::MXF4_NVF4) { + constexpr int SfVectorSize = SfVectorSizeA > SfVectorSizeB ? SfVectorSizeA : SfVectorSizeB; + if constexpr (cute::is_base_of_v ) { + return make_tiled_mma(cute::SM100_MMA_MXF4NVF4_2x1SM_SS_SPARSE{}); + } + else { + return make_tiled_mma(cute::SM100_MMA_MXF4_2x1SM_SS{}); + } + } + else { + static_assert(cutlass::detail::dependent_false, + "Unsupported configuration for SM100 collective builder."); + } +} + +template < + class ElementPairA, + class ElementPairB, + class ElementAccumulator, + class TileShape_MNK, + class ClusterShape_MNK, + UMMA::Major UmmaMajorA, + UMMA::Major UmmaMajorB, + detail::blockscaled::BlockScaledInstr Instr, + class BuilderScheduleTag, + bool Is2SM +> +struct TrivialBlockscaledMma {}; + +template < + class ElementPairA, + class ElementPairB, + class ElementAccumulator, + class TileShape_MNK, + class ClusterShape_MNK, + UMMA::Major UmmaMajorA, + UMMA::Major UmmaMajorB, + detail::blockscaled::BlockScaledInstr Instr, + class BuilderScheduleTag +> +struct TrivialBlockscaledMma < + ElementPairA, + ElementPairB, + ElementAccumulator, + TileShape_MNK, + ClusterShape_MNK, + UmmaMajorA, + UmmaMajorB, + Instr, + BuilderScheduleTag, + true /*Is2SM*/> { + using type = decltype(sm100_make_blockscaled_2sm_trivial_tiled_mma()); + }; + +template < + class ElementPairA, + class ElementPairB, + class ElementAccumulator, + class TileShape_MNK, + class ClusterShape_MNK, + UMMA::Major UmmaMajorA, + UMMA::Major UmmaMajorB, + detail::blockscaled::BlockScaledInstr Instr, + class BuilderScheduleTag +> +struct TrivialBlockscaledMma< + ElementPairA, + ElementPairB, + ElementAccumulator, + TileShape_MNK, + ClusterShape_MNK, + UmmaMajorA, + UmmaMajorB, + Instr, + BuilderScheduleTag, + false /*Is2SM*/> { + using type = decltype(sm100_make_blockscaled_1sm_trivial_tiled_mma()); +}; + +} // namespace detail + +///////////////////////////////////////////////////////////////////////////////////////////////// + +} // namespace cutlass::gemm::collective diff --git a/kernels/Quant/019_nvfp4_grouped_query_attention/src/cutlass/gemm/collective/sm100_blockscaled_mma_array_warpspecialized.hpp b/kernels/Quant/019_nvfp4_grouped_query_attention/src/cutlass/gemm/collective/sm100_blockscaled_mma_array_warpspecialized.hpp new file mode 100644 index 0000000000000000000000000000000000000000..7392a7427d4d8f24f5c3818a067e7cb08085463a --- /dev/null +++ b/kernels/Quant/019_nvfp4_grouped_query_attention/src/cutlass/gemm/collective/sm100_blockscaled_mma_array_warpspecialized.hpp @@ -0,0 +1,1372 @@ +/*************************************************************************************************** + * Copyright (c) 2023 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + **************************************************************************************************/ +// SHADOW of CUTLASS 4.4.1 cutlass/gemm/collective/sm100_blockscaled_mma_array_warpspecialized.hpp (picked up via the +// solution's source root, which precedes the CUTLASS include path). Identical except: CTA tile N = 160 is accepted +// (batched small-M QKV GEMM B2SM160). For N = 160 the SFB operand must be in a PADDED blocked layout: N-tile t's 160 +// scale rows at virtual rows [256t, 256t+160) (TileShape_SF N = 256, plain SFB path, no TMEM shift). +#define NVFP4_SHADOW_ARRAY_N160 1 +#pragma once + +#include "cutlass/cutlass.h" +#include "cutlass/detail/collective.hpp" +#include "cutlass/detail/cluster.hpp" +#include "cutlass/gemm/dispatch_policy.hpp" +#include "cutlass/numeric_types.h" +#include "cutlass/pipeline/pipeline.hpp" +#include "cutlass/gemm/gemm.h" +#include "cutlass/detail/sm100_blockscaled_layout.hpp" +#include "cutlass/trace.h" +#include "cutlass/kernel_hardware_info.hpp" +#include "cutlass/detail/collective.hpp" +#include "cutlass/detail/sm100_tmem_helper.hpp" + +#include "cute/algorithm/functional.hpp" +#include "cute/arch/cluster_sm90.hpp" +#include "cute/atom/mma_atom.hpp" +#include "cute/algorithm/gemm.hpp" +#include "cute/numeric/arithmetic_tuple.hpp" + +///////////////////////////////////////////////////////////////////////////////////////////////// + +namespace cutlass::gemm::collective { +using namespace cute; + +///////////////////////////////////////////////////////////////////////////////////////////////// + +// WarpSpecialized Mainloop +// Both DMA Load and MMA methods of this class must be run by a single thread that's picked by elect_one +template < + int Stages, + int SchedulerPipelineStageCount, + int AccumulatorPipelineStageCount, + class ClusterShape, // Static cluster shape or dynamic (int, int, _1) + class TileShape_, // (MmaAtomShapeM, MmaAtomShapeN, TileK) + class ElementPairA_, + class StridePairA_, + class ElementPairB_, + class StridePairB_, + class TiledMma_, + class GmemTiledCopyPairA_, + class SmemLayoutAtomPairA_, + class SmemCopyAtomA_, + class TransformA_, + class GmemTiledCopyPairB_, + class SmemLayoutAtomPairB_, + class SmemCopyAtomB_, + class TransformB_> +struct CollectiveMma< + MainloopSm100ArrayTmaUmmaWarpSpecializedBlockScaled< + Stages, + SchedulerPipelineStageCount, + AccumulatorPipelineStageCount, + ClusterShape>, + TileShape_, + ElementPairA_, + StridePairA_, + ElementPairB_, + StridePairB_, + TiledMma_, + GmemTiledCopyPairA_, + SmemLayoutAtomPairA_, + SmemCopyAtomA_, + TransformA_, + GmemTiledCopyPairB_, + SmemLayoutAtomPairB_, + SmemCopyAtomB_, + TransformB_> +{ + // + // Type Aliases + // + using TiledMma = TiledMma_; + using AtomThrShapeMNK = Shape(typename TiledMma::ThrLayoutVMNK{})), _1, _1>; + + using DispatchPolicy = MainloopSm100ArrayTmaUmmaWarpSpecializedBlockScaled< + Stages, + SchedulerPipelineStageCount, + AccumulatorPipelineStageCount, + ClusterShape>; + using TileShape = TileShape_; + // Due to an MSVC bug, we can't use decltype(make_tiled_mma()) interface. + using TiledMMA_SF = TiledMMA, + Layout>, + Tile>; + + static constexpr bool IsDynamicCluster = not cute::is_static_v; + static constexpr int SFVecSize = TiledMma::SFVecSize; + static constexpr bool IsOverlappingAccum = DispatchPolicy::IsOverlappingAccum; + + CUTE_STATIC_ASSERT_V(evenly_divides(TileShape{}, tile_shape(TiledMma{})), + "Static cluster shape used: TileShape should be evenly divided by TiledMma"); + + using CtaShape_MNK = decltype(shape_div(TileShape{}, AtomThrShapeMNK{})); + static_assert(shape<1>(CtaShape_MNK{}) == 192 or shape<1>(CtaShape_MNK{}) == 160 or shape<1>(CtaShape_MNK{}) == 64 or + shape<1>(CtaShape_MNK{}) == 128 or shape<1>(CtaShape_MNK{}) == 256, + "Cta N should be one of 64/128/160/192/256"); + + using ClusterTileShape = decltype(make_shape(get<0>(TileShape{})*get<0>(ClusterShape{}),get<1>(TileShape{})*get<1>(ClusterShape{}),get<2>(TileShape{})*get<2>(ClusterShape{}))); + using Sm1xxBlkScaledConfig = cutlass::detail::Sm1xxBlockScaledConfig; + using Blk_MN = typename Sm1xxBlkScaledConfig::Blk_MN; + static constexpr int IsCtaN192 = shape<1>(CtaShape_MNK{}) == 192; + static constexpr int IsCtaN64 = shape<1>(CtaShape_MNK{}) == 64; + static int constexpr CTA_N_SF = cutlass::ceil_div(size<1>(CtaShape_MNK{}), Blk_MN{}) * Blk_MN{}; + // Tile shape used for partitioning Scale Factor B. + // The M-dim does not affect the SFB, so just set it as the original TileShape; + using TileShape_SF = decltype(make_shape(get<0>(CtaShape_MNK{}), + Int{} * shape<2>(typename TiledMma::ThrLayoutVMNK()), + get<2>(TileShape{}))); + + // Define A and B block shapes for reduced size TMA_LOADs + using MmaShapeA_MK = decltype(partition_shape_A(TiledMma{}, make_shape(size<0>(TileShape{}), size<2>(TileShape{})))); + using MmaShapeB_NK = decltype(partition_shape_B(TiledMma{}, make_shape(size<1>(TileShape{}), size<2>(TileShape{})))); + + // Multiple buffer the TMA descriptors for each SM so that we can update them asynchronously. + // This should be larger than the total number of TMA requests inflight (from update to issued to returned). + // This can be calculated by SchedulerStages + max(TmaStages) + 2 (for consumer and producer in-flight accessies). + constexpr static uint32_t NumTmaDescriptorsPerSm = SchedulerPipelineStageCount + Stages + 2; + + using ElementPairA = ElementPairA_; + using ElementPairB = ElementPairB_; + using ElementAMma = typename TiledMma::ValTypeA; + using ElementBMma = typename TiledMma::ValTypeB; + using StridePairA = StridePairA_; + using StridePairB = StridePairB_; + using SmemLayoutAtomPairA = SmemLayoutAtomPairA_; + using SmemLayoutAtomPairB = SmemLayoutAtomPairB_; + static_assert(cute::is_same_v(ElementPairA{}))>, + remove_cvref_t(ElementPairB{}))>>, "SFA and SFB data types should be the same"); + + // A and B matrices + using ElementA = remove_cvref_t(ElementPairA{}))>; + using StrideA = remove_cvref_t(StridePairA{}))>; + using InternalStrideA = cute::remove_pointer_t; + + using ElementB = remove_cvref_t(ElementPairB{}))>; + using StrideB = remove_cvref_t(StridePairB{}))>; + using InternalStrideB = cute::remove_pointer_t; + + static constexpr bool IsRuntimeDataTypeA = cutlass::gemm::collective::detail::is_sm10x_runtime_f8f6f4(); + static constexpr bool IsRuntimeDataTypeB = cutlass::gemm::collective::detail::is_sm10x_runtime_f8f6f4(); + + static_assert((IsRuntimeDataTypeA && IsRuntimeDataTypeB) || + (!IsRuntimeDataTypeA && !IsRuntimeDataTypeB), + "ElementA and ElementB should be both runtime or both static."); + + static constexpr bool IsRuntimeDataType = IsRuntimeDataTypeA && IsRuntimeDataTypeB; + + // SFA and SFB + using ElementSF = remove_cvref_t(ElementPairA{}))>; + using LayoutSFA = remove_cvref_t(StridePairA{}))>; + using InternalLayoutSFA = cute::remove_pointer_t; + using LayoutSFB = remove_cvref_t(StridePairB{}))>; + using InternalLayoutSFB = cute::remove_pointer_t; + + using ElementAccumulator = typename TiledMma::ValTypeC; + using GmemTiledCopyPairA = GmemTiledCopyPairA_; + using GmemTiledCopyPairB = GmemTiledCopyPairB_; + using GmemTiledCopyA = remove_cvref_t(GmemTiledCopyPairA{}))>; + using GmemTiledCopySFA = remove_cvref_t(GmemTiledCopyPairA{}))>; + using GmemTiledCopyB = remove_cvref_t(GmemTiledCopyPairB{}))>; + using GmemTiledCopySFB = remove_cvref_t(GmemTiledCopyPairB{}))>; + + using SmemLayoutAtomA = remove_cvref_t(SmemLayoutAtomPairA{}))>; + using SmemLayoutAtomSFA = remove_cvref_t(SmemLayoutAtomPairA{}))>; + using SmemLayoutAtomB = remove_cvref_t(SmemLayoutAtomPairB{}))>; + using SmemLayoutAtomSFB = remove_cvref_t(SmemLayoutAtomPairB{}))>; + + using SmemCopyAtomA = SmemCopyAtomA_; + using SmemCopyAtomB = SmemCopyAtomB_; + using TransformA = TransformA_; + using TransformB = TransformB_; + using ArchTag = typename DispatchPolicy::ArchTag; + + using MainloopPipeline = cutlass::PipelineTmaUmmaAsync< + DispatchPolicy::Stages, + ClusterShape, + AtomThrShapeMNK>; + using MainloopPipelineState = typename MainloopPipeline::PipelineState; + + static_assert(rank(SmemLayoutAtomA{}) == 2, "SmemLayoutAtom must be rank 2 (M/N, K)"); + static_assert((size<0>(TileShape{}) % size<0>(SmemLayoutAtomA{})) == 0, "SmemLayoutAtomA must evenly divide the tile shape."); + static_assert((size<2>(TileShape{}) % size<1>(SmemLayoutAtomA{})) == 0, "SmemLayoutAtomA must evenly divide the tile shape."); + static_assert(cute::is_void_v, + "SM100 UMMA cannot have a non-void copy atom for smem sourced instructions."); + + static_assert(rank(SmemLayoutAtomB{}) == 2, "SmemLayoutAtom must be rank 2 (M/N, K)"); + static_assert((size<1>(TileShape{}) % size<0>(SmemLayoutAtomB{})) == 0, "SmemLayoutAtomB must evenly divide the tile shape."); + static_assert((size<2>(TileShape{}) % size<1>(SmemLayoutAtomB{})) == 0, "SmemLayoutAtomB must evenly divide the tile shape."); + static_assert(cute::is_void_v, + "SM100 UMMA cannot have a non-void copy atom for smem sourced instructions."); + + // Tile along K mode first before tiling over MN. PIPE mode last as usual. + // This maximizes TMA boxes due to better smem-K vectorization, reducing total issued TMAs. + // (MMA_TILE_M,MMA_TILE_K),MMA_M,MMA_K,PIPE) + using SmemLayoutA = decltype(UMMA::tile_to_mma_shape( + SmemLayoutAtomA{}, + append(MmaShapeA_MK{}, Int{}), + cute::conditional_t(), Step<_2,_1,_3>, Step<_1,_2,_3>>{})); + // (MMA_TILE_N,MMA_TILE_K),MMA_N,MMA_K,PIPE) + using SmemLayoutB = decltype(UMMA::tile_to_mma_shape( + SmemLayoutAtomB{}, + append(MmaShapeB_NK{}, Int{}), + cute::conditional_t(), Step<_2,_1,_3>, Step<_1,_2,_3>>{})); + + // SmemLayoutAtomSFA and SmemLayoutAtomSFB are for whole CTA tiles. We add the number of pipeline stages here. + // The number of pipeline stages is the same as the number of pipeline stages from AB Load <-> MainLoop + using SmemLayoutSFA = decltype(make_layout( + append(shape(SmemLayoutAtomSFA{}), Int{}), + append(stride(SmemLayoutAtomSFA{}), size(filter_zeros(SmemLayoutAtomSFA{}))) + )); + using SmemLayoutSFB = decltype(make_layout( + append(shape(SmemLayoutAtomSFB{}), Int{}), + append(stride(SmemLayoutAtomSFB{}), size(filter_zeros(SmemLayoutAtomSFB{}))) + )); + + static_assert(cute::is_base_of::value && + cute::is_base_of::value, + "MMA atom must source both A and B operand from smem_desc for this mainloop."); + static_assert( + (size(AtomThrShapeMNK{}) == 1 && + (cute::is_same_v || cute::is_same_v)) || + (size(AtomThrShapeMNK{}) == 2 && + (cute::is_same_v || cute::is_same_v)), + "GmemTiledCopy - invalid TMA copy atom specified."); + static_assert( + (size(AtomThrShapeMNK{}) == 1 && + (cute::is_same_v || cute::is_same_v)) || + (size(AtomThrShapeMNK{}) == 2 && + (cute::is_same_v || cute::is_same_v)), + "GmemTiledCopy - invalid TMA copy atom specified."); + + static constexpr bool IsF8F6F4 = detail::is_sm100_mma_f8f6f4(); + static constexpr bool IsGroupedGemmKernel = !cute::is_same_v; + + using TmaInternalElementA = cute::conditional_t; + using TmaInternalElementB = cute::conditional_t; + + using SmemAllocTypeA = cute::conditional_t < 8, uint8_t, ElementAMma>; + using SmemAllocTypeB = cute::conditional_t < 8, uint8_t, ElementBMma>; + + using BitTypeElementA = cute::uint_bit_t>; + using BitTypeElementB = cute::uint_bit_t>; + + using ArrayElementA = cute::conditional_t; + using ArrayElementB = cute::conditional_t; + + using RuntimeDataTypeA = typename detail::sm10x_block_scale_runtime_input_t::Type; + using RuntimeDataTypeB = typename detail::sm10x_block_scale_runtime_input_t::Type; + + struct SharedStorage { + struct TensorStorage : cute::aligned_struct<128, _0> { + cute::ArrayEngine> smem_A; + cute::ArrayEngine> smem_B; + cute::ArrayEngine> smem_SFA; + cute::ArrayEngine> smem_SFB; + } tensors; + + struct TensorMapStorage : cute::aligned_struct<128, _0> { + cute::TmaDescriptor smem_tensormap_A; + cute::TmaDescriptor smem_tensormap_B; + cute::TmaDescriptor smem_tensormap_SFA; + cute::TmaDescriptor smem_tensormap_SFB; + } tensormaps; + + using PipelineStorage = typename MainloopPipeline::SharedStorage; + PipelineStorage pipeline; + }; + + // Expose shared storage for tensors/pipelines separately to allow kernel layer to reorder them. + using TensorStorage = typename SharedStorage::TensorStorage; + using TensorMapStorage = typename SharedStorage::TensorMapStorage; + using PipelineStorage = typename SharedStorage::PipelineStorage; + + // Only one thread issues the TMA and updates the barriers in a 2SM MMA, adjust bytes accordingly + static constexpr uint32_t SFTransactionBytes = + cutlass::bits_to_bytes(size(AtomThrShapeMNK{}) * cosize(take<0,3>(SmemLayoutSFA{})) * cute::sizeof_bits_v) + + cutlass::bits_to_bytes(size(AtomThrShapeMNK{}) * cosize(take<0,3>(SmemLayoutSFB{})) * cute::sizeof_bits_v); + static constexpr uint32_t ABTmaTransactionBytes = + cutlass::bits_to_bytes(size(AtomThrShapeMNK{}) * cosize(take<0,3>(SmemLayoutA{})) * cute::sizeof_bits_v) + + cutlass::bits_to_bytes(size(AtomThrShapeMNK{}) * cosize(take<0,3>(SmemLayoutB{})) * cute::sizeof_bits_v); + static constexpr uint32_t TmaTransactionBytes = ABTmaTransactionBytes + SFTransactionBytes; + + template + struct TmemStorage { + AccTensor accumulators; + SfaTensor tCtSFA; + SfbTensor tCtSFB; + }; + + // Host side kernel arguments + struct Arguments { + ArrayElementA const** ptr_A{nullptr}; + StrideA dA{}; + ArrayElementB const** ptr_B{nullptr}; + StrideB dB{}; + ElementSF const** ptr_SFA{nullptr}; + LayoutSFA layout_SFA{}; + ElementSF const** ptr_SFB{nullptr}; + LayoutSFB layout_SFB{}; + RuntimeDataTypeA runtime_data_type_a{}; + RuntimeDataTypeB runtime_data_type_b{}; + }; + + // Device side kernel params + struct Params { + using ClusterLayout_VMNK = + decltype(tiled_divide(make_layout(conditional_return(make_shape(uint32_t(0), uint32_t(0), Int<1>{}), + ClusterShape{})), make_tile(typename TiledMma::AtomThrID{}))); + using ClusterLayoutSfb_VMNK = + decltype(tiled_divide(make_layout(conditional_return(make_shape(uint32_t(0), uint32_t(0), Int<1>{}), + ClusterShape{})), make_tile(typename TiledMMA_SF::AtomThrID{}))); + + using TMA_A = decltype(make_tma_atom_A_sm100( + GmemTiledCopyA{}, + make_tensor(recast_ptr(nullptr), repeat_like(InternalStrideA{}, int32_t(0)), InternalStrideA{}), + SmemLayoutA{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + ClusterLayout_VMNK{}) + ); + + using TMA_B = decltype(make_tma_atom_B_sm100( + GmemTiledCopyB{}, + make_tensor(recast_ptr(nullptr), repeat_like(InternalStrideB{}, int32_t(0)), InternalStrideB{}), + SmemLayoutB{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + ClusterLayout_VMNK{}) + ); + + using TMA_SFA = decltype(make_tma_atom_A_sm100( + GmemTiledCopySFA{}, + make_tensor(static_cast(nullptr), InternalLayoutSFA{}), + SmemLayoutSFA{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + ClusterLayout_VMNK{}) + ); + + using TMA_SFB = decltype(make_tma_atom_B_sm100( + GmemTiledCopySFB{}, + make_tensor(static_cast(nullptr), InternalLayoutSFB{}), + SmemLayoutSFB{}(_,_,_,cute::Int<0>{}), + TileShape_SF{}, + TiledMMA_SF{}, + ClusterLayoutSfb_VMNK{}) + ); + + TMA_A tma_load_a; + TMA_B tma_load_b; + TMA_SFA tma_load_sfa; + TMA_SFB tma_load_sfb; + TMA_A tma_load_a_fallback; + TMA_B tma_load_b_fallback; + TMA_SFA tma_load_sfa_fallback; + TMA_SFB tma_load_sfb_fallback; + dim3 cluster_shape_fallback; + RuntimeDataTypeA runtime_data_type_a; + RuntimeDataTypeB runtime_data_type_b; + cute::TmaDescriptor* tensormaps; + ArrayElementA const** ptr_A; + StrideA dA; + ArrayElementB const** ptr_B; + StrideB dB; + ElementSF const** ptr_SFA; + LayoutSFA layout_SFA; + ElementSF const** ptr_SFB; + LayoutSFB layout_SFB; + }; + + CUTLASS_DEVICE + CollectiveMma(Params const& params, ClusterShape cluster_shape, uint32_t block_rank_in_cluster) + : cluster_shape_(cluster_shape) + , block_rank_in_cluster_(block_rank_in_cluster) + , layout_SFA_(params.layout_SFA) + , layout_SFB_(params.layout_SFB) + , runtime_data_type_a_(params.runtime_data_type_a) + , runtime_data_type_b_(params.runtime_data_type_b) { + if constexpr (IsDynamicCluster) { + const bool is_fallback_cluster = (cute::size<0>(cluster_shape_) == params.cluster_shape_fallback.x && + cute::size<1>(cluster_shape_) == params.cluster_shape_fallback.y); + observed_tma_load_a_ = is_fallback_cluster ? ¶ms.tma_load_a_fallback : ¶ms.tma_load_a; + observed_tma_load_b_ = is_fallback_cluster ? ¶ms.tma_load_b_fallback : ¶ms.tma_load_b; + observed_tma_load_sfa_ = is_fallback_cluster ? ¶ms.tma_load_sfa_fallback : ¶ms.tma_load_sfa; + observed_tma_load_sfb_ = is_fallback_cluster ? ¶ms.tma_load_sfb_fallback : ¶ms.tma_load_sfb; + } + else { + observed_tma_load_a_ = ¶ms.tma_load_a; + observed_tma_load_b_ = ¶ms.tma_load_b; + observed_tma_load_sfa_ = ¶ms.tma_load_sfa; + observed_tma_load_sfb_ = ¶ms.tma_load_sfb; + } + } + + template + static constexpr Params + to_underlying_arguments( + ProblemShape problem_shapes, + Arguments const& args, + void* workspace, + cutlass::KernelHardwareInfo const& hw_info = cutlass::KernelHardwareInfo{}) { + // These tensor shapes (only applicable for grouped gemm) and pointers are only used to create tensormap/tma desc. + // These will be replaced with correct values before the initial tma load. + auto init_M = int32_t(size<0>(TileShape{})); + auto init_N = int32_t(size<1>(TileShape{})); + auto init_K = int32_t(size<2>(TileShape{})); + auto init_L = 1; + + // Tensor pointers will be fixed before the first access + TmaInternalElementA const* ptr_A_first_batch = nullptr; + TmaInternalElementB const* ptr_B_first_batch = nullptr; + + InternalStrideA stride_a; + InternalStrideB stride_b; + InternalLayoutSFA layout_SFA; + InternalLayoutSFB layout_SFB; + + if constexpr (IsGroupedGemmKernel) { + // Strides for Grouped Gemm will be replaced prior to the first access regardless. + stride_a = InternalStrideA{}; + stride_b = InternalStrideB{}; + layout_SFA = Sm1xxBlkScaledConfig::tile_atom_to_shape_SFA(cute::make_shape(init_M, init_N, init_K, 1)); + layout_SFB = Sm1xxBlkScaledConfig::tile_atom_to_shape_SFA(cute::make_shape(init_M, init_N, init_K, 1)); + } + else { + // Tensor shapes for Ptr-Array are initialized correctly only here. + auto problem_shape_MNK = problem_shapes.get_host_problem_shape(0); + init_M = get<0>(problem_shape_MNK); + init_N = get<1>(problem_shape_MNK); + init_K = get<2>(problem_shape_MNK); + + stride_a = args.dA; + stride_b = args.dB; + layout_SFA = args.layout_SFA; + layout_SFB = args.layout_SFB; + } + + // Batches/Groups are managed by using appropriate pointers to input matrices. + Tensor tensor_a = make_tensor(ptr_A_first_batch, make_layout(make_shape(init_M,init_K,init_L), stride_a)); + Tensor tensor_b = make_tensor(ptr_B_first_batch, make_layout(make_shape(init_N,init_K,init_L), stride_b)); + + auto cluster_shape = cutlass::detail::select_cluster_shape(ClusterShape{}, hw_info.cluster_shape); + // Cluster layout for TMA construction + auto cluster_layout_vmnk = tiled_divide(make_layout(cluster_shape), make_tile(typename TiledMma::AtomThrID{})); + auto cluster_shape_fallback = cutlass::detail::select_cluster_shape(ClusterShape{}, hw_info.cluster_shape_fallback); + auto cluster_layout_vmnk_fallback = tiled_divide(make_layout(cluster_shape_fallback), make_tile(typename TiledMma::AtomThrID{})); + + // Tensor pointers will be fixed before the first access + ElementSF const* ptr_SFA_first_batch = nullptr; + ElementSF const* ptr_SFB_first_batch = nullptr; + + Tensor tensor_sfa = make_tensor(ptr_SFA_first_batch, layout_SFA); + Tensor tensor_sfb = make_tensor(ptr_SFB_first_batch, layout_SFB); + + // Cluster layout for TMA construction of SFB + auto cluster_layout_sfb_vmnk = tiled_divide(make_layout(cluster_shape), make_tile(typename TiledMMA_SF::AtomThrID{})); + auto cluster_layout_sfb_vmnk_fallback = tiled_divide(make_layout(cluster_shape_fallback), make_tile(typename TiledMMA_SF::AtomThrID{})); + + typename Params::TMA_A tma_load_a = make_tma_atom_A_sm100( + GmemTiledCopyA{}, + tensor_a, + SmemLayoutA{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + cluster_layout_vmnk); + + typename Params::TMA_B tma_load_b = make_tma_atom_B_sm100( + GmemTiledCopyB{}, + tensor_b, + SmemLayoutB{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + cluster_layout_vmnk); + + typename Params::TMA_A tma_load_a_fallback = make_tma_atom_A_sm100( + GmemTiledCopyA{}, + tensor_a, + SmemLayoutA{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + cluster_layout_vmnk_fallback); + + typename Params::TMA_B tma_load_b_fallback = make_tma_atom_B_sm100( + GmemTiledCopyB{}, + tensor_b, + SmemLayoutB{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + cluster_layout_vmnk_fallback); + + typename Params::TMA_SFA tma_load_sfa = make_tma_atom_A_sm100( + GmemTiledCopySFA{}, + tensor_sfa, + SmemLayoutSFA{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + cluster_layout_vmnk); + + typename Params::TMA_SFB tma_load_sfb = make_tma_atom_B_sm100( + GmemTiledCopySFB{}, + tensor_sfb, + SmemLayoutSFB{}(_,_,_,cute::Int<0>{}), + TileShape_SF{}, + TiledMMA_SF{}, + cluster_layout_sfb_vmnk); + + typename Params::TMA_SFA tma_load_sfa_fallback = make_tma_atom_A_sm100( + GmemTiledCopySFA{}, + tensor_sfa, + SmemLayoutSFA{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + cluster_layout_vmnk_fallback); + + typename Params::TMA_SFB tma_load_sfb_fallback = make_tma_atom_B_sm100( + GmemTiledCopySFB{}, + tensor_sfb, + SmemLayoutSFB{}(_,_,_,cute::Int<0>{}), + TileShape_SF{}, + TiledMMA_SF{}, + cluster_layout_sfb_vmnk_fallback); + + return { + tma_load_a, + tma_load_b, + tma_load_sfa, + tma_load_sfb, + tma_load_a_fallback, + tma_load_b_fallback, + tma_load_sfa_fallback, + tma_load_sfb_fallback, + hw_info.cluster_shape_fallback, + args.runtime_data_type_a, + args.runtime_data_type_b, + reinterpret_cast(workspace), + reinterpret_cast(args.ptr_A), + args.dA, + reinterpret_cast(args.ptr_B), + args.dB, + reinterpret_cast(args.ptr_SFA), + args.layout_SFA, + reinterpret_cast(args.ptr_SFB), + args.layout_SFB, + }; + } + + struct TensorMaps : cute::aligned_struct<256, _0> { + cute::TmaDescriptor tma_desc_a; + cute::TmaDescriptor tma_desc_b; + cute::TmaDescriptor tma_desc_sfa; + cute::TmaDescriptor tma_desc_sfb; + }; + + template + static size_t + get_workspace_size(ProblemShape const& problem_shape, Arguments const& args, int sm_count) { + // Allocate gmem space for input tensormaps per each SM. + return (sm_count * sizeof(TensorMaps) * NumTmaDescriptorsPerSm); + } + + template + static cutlass::Status + initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { + return cutlass::Status::kSuccess; + } + + template + static bool + can_implement( + ProblemShape problem_shapes, + [[maybe_unused]] Arguments const& args) { + constexpr int tma_alignment_bits_A = cutlass::detail::get_input_alignment_bits(); + constexpr int tma_alignment_bits_B = cutlass::detail::get_input_alignment_bits(); + constexpr int min_tma_aligned_elements_A = tma_alignment_bits_A / cute::sizeof_bits::value; + constexpr int min_tma_aligned_elements_B = tma_alignment_bits_B / cute::sizeof_bits::value; + + bool implementable = true; + if (problem_shapes.is_host_problem_shape_available()) { + // Check alignment for all problem sizes + for (int i = 0; i < problem_shapes.groups(); i++) { + auto problem_shape_MNKL = append<4>(problem_shapes.get_host_problem_shape(i), 1); + auto [M,N,K,L] = problem_shape_MNKL; + implementable = implementable && cutlass::detail::check_alignment(cute::make_shape(M,K,L), InternalStrideA{}); + implementable = implementable && cutlass::detail::check_alignment(cute::make_shape(N,K,L), InternalStrideB{}); + } + } + + if (!implementable) { + CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Problem Size doesn't meet the minimum alignment requirements for TMA.\n"); + } + return implementable; + } + + /// Construct A Single Stage's Accumulator Shape + CUTLASS_DEVICE static + auto + partition_accumulator_shape() { + auto acc_shape = partition_shape_C(TiledMma{}, take<0,2>(TileShape{})); // ((MMA_TILE_M,MMA_TILE_N),MMA_M,MMA_N) + + return acc_shape; + } + + template + CUTLASS_DEVICE static + auto + slice_accumulator(TmemStorage tmem_storage, int stage) { + return tmem_storage.accumulators(_,_,_,stage); + } + + template + CUTLASS_DEVICE static + auto + init_tmem_tensors(EpilogueTile epi_tile) { + TiledMma tiled_mma; + auto acc_shape = partition_accumulator_shape(); + // ((MMA_TILE_M,MMA_TILE_N),MMA_M,MMA_N,ACC_PIPE) where ACC_PIPE=2 so we can double buffer our accumulators for mainloop and epilogue. + Tensor accumulators = cutlass::detail::make_sm100_accumulator( + tiled_mma, acc_shape, EpilogueTile{}); + Tensor tCtSFA = make_tensor(shape(SmemLayoutAtomSFA{})); + Tensor tCtSFB = make_tensor(shape(SmemLayoutAtomSFB{})); + + TmemStorage tmem_storage; + tmem_storage.accumulators = accumulators; + tmem_storage.tCtSFA = tCtSFA; + tmem_storage.tCtSFB = tCtSFB; + + return tmem_storage; + } + + template + CUTLASS_DEVICE static + void + set_tmem_offsets(TmemStorage& tmem_storage, uint32_t tmem_base_addr) { + tmem_storage.accumulators.data() = tmem_base_addr; + tmem_storage.tCtSFA.data() = tmem_storage.accumulators.data().get() + cutlass::detail::find_tmem_tensor_col_offset(tmem_storage.accumulators); + tmem_storage.tCtSFB.data() = tmem_storage.tCtSFA.data().get() + cutlass::detail::find_tmem_tensor_col_offset(tmem_storage.tCtSFA); + } + + /// Set up the data needed by this collective for load. + /// Return tuple element contain + /// gA_mkl - The tiled tma tensor for input A + /// gB_nkl - The tiled tma tensor for input B + /// tAgA_mkl - partitioned gmem tensor for A + /// tBgB_nkl - partitioned gmem tensor for B + /// tAsA - partitioned smem tensor for A + /// tBsB - partitioned smem tensor for B + /// tAgSFA_mkl - partitioned gmem tensor for SFA + /// tBgSFB_nkl - partitioned gmem tensor for SFB + /// tAsSFA - partitioned tmem tensor for SFA + /// tAsSFB - partitioned tmem tensor for SFB + /// mcast_mask_a - tma multicast mask for A + /// mcast_mask_b - tma multicast mask for B + /// mcast_mask_sfa - tma multicast mask for SFA + /// mcast_mask_sfb - tma multicast mask for SFB + template + CUTLASS_DEVICE auto + load_init( + ProblemShape_MNKL const& problem_shape_MNKL, + Params const& params, + TensorStorage& shared_tensors, + TensorMapStorage& shared_tensormaps, + int32_t const sm_count, int32_t const sm_idx, + [[maybe_unused]] int32_t num_groups, + int32_t init_group) const { + using X = Underscore; + + // Separate out problem shape for convenience + auto [M,N,K,L] = problem_shape_MNKL; + // Problem Shape and therefore strides that we construct are [M,N,K,L], but since here for the TMA loads + // we are managing TMA descriptors to change batches, we need to neglect the L mode + const int32_t mock_L = 1; + + // Represent the full tensors -- get these from TMA + Tensor mA_mkl = observed_tma_load_a_->get_tma_tensor(make_shape(M,K,mock_L)); + Tensor mB_nkl = observed_tma_load_b_->get_tma_tensor(make_shape(N,K,mock_L)); + + // Tile the tensors and defer the slice + Tensor gA_mkl = local_tile(mA_mkl, TileShape{}, make_coord(_,_,_), Step<_1, X,_1>{}); // (BLK_M, BLK_K, m, k, l) + Tensor gB_nkl = local_tile(mB_nkl, TileShape{}, make_coord(_,_,_), Step< X,_1,_1>{}); // (BLK_N, BLK_K, n, k, l) + + // Represent the full tensor of Scale factors + InternalLayoutSFA layout_SFA{}; + InternalLayoutSFB layout_SFB{}; + if constexpr (IsGroupedGemmKernel) { + layout_SFA = params.layout_SFA[init_group]; + layout_SFB = params.layout_SFB[init_group]; + } + else { + layout_SFA = params.layout_SFA; + layout_SFB = params.layout_SFB; + } + Tensor mSFA_mkl = observed_tma_load_sfa_->get_tma_tensor(shape(layout_SFA)); + auto mSFB_nkl = [=](){ + if constexpr (IsCtaN192) { + Tensor mSFB_tmp = observed_tma_load_sfb_->get_tma_tensor(shape(layout_SFB)); + auto x = stride<0,1>(mSFB_tmp); + auto y = ceil_div(shape<0,1>(mSFB_tmp), 4); + auto new_shape = make_shape (make_shape( shape<0,0>(mSFB_tmp), + make_shape( make_shape(_2{}, _2{}), y)), shape<1>(mSFB_tmp), shape<2>(mSFB_tmp)); + auto new_stride = make_stride(make_stride(stride<0,0>(mSFB_tmp), + make_stride(make_stride( x, x), x*3)), stride<1>(mSFB_tmp), stride<2>(mSFB_tmp)); + return make_tensor(mSFB_tmp.data(), make_layout(new_shape, new_stride)); + } + else if constexpr (IsCtaN64) { + Tensor mSFB_tmp = observed_tma_load_sfb_->get_tma_tensor(shape(layout_SFB)); + auto new_shape = make_shape(make_shape(shape<0,0>(mSFB_tmp), + make_shape(_2{} , shape<0,1>(mSFB_tmp))), shape<1>(mSFB_tmp), shape<2>(mSFB_tmp)); + auto new_stride = make_stride(make_stride(stride<0,0>(mSFB_tmp), + make_stride(_0{}, stride<0,1>(mSFB_tmp))), stride<1>(mSFB_tmp), stride<2>(mSFB_tmp)); + return make_tensor(mSFB_tmp.data(), make_layout(new_shape, new_stride)); + } + else { + return observed_tma_load_sfb_->get_tma_tensor(shape(layout_SFB)); + } + }(); + + Tensor gSFA_mkl = local_tile(mSFA_mkl, TileShape{}, make_coord(_,_,_), Step<_1, X,_1>{}); // (TILE_M,TILE_K,m,k,l) + Tensor gSFB_nkl = local_tile(mSFB_nkl, TileShape_SF{}, make_coord(_,_,_), Step< X,_1,_1>{}); // (TILE_N,TILE_K,n,k,l) + + // Partition for this CTA + ThrMMA cta_mma = TiledMma{}.get_slice(blockIdx.x % size(typename TiledMma::AtomThrID{})); + + Tensor tCgA_mkl = cta_mma.partition_A(gA_mkl); // (MMA, MMA_M, MMA_K, m, k, l) + Tensor tCgB_nkl = cta_mma.partition_B(gB_nkl); // (MMA, MMA_N, MMA_K, n, k, l) + + Tensor sA = make_tensor(make_smem_ptr(shared_tensors.smem_A.begin()), SmemLayoutA{}); // (MMA,MMA_M,MMA_K,PIPE) + Tensor sB = make_tensor(make_smem_ptr(shared_tensors.smem_B.begin()), SmemLayoutB{}); // (MMA,MMA_N,MMA_K,PIPE) + + ThrMMA cta_mma_sfb = TiledMMA_SF{}.get_slice(blockIdx.x % size(typename TiledMMA_SF::AtomThrID{})); + Tensor tCgSFA_mkl = cta_mma.partition_A(gSFA_mkl); // (MMA, MMA_M, MMA_K, m, k, l) + Tensor tCgSFB_nkl = cta_mma_sfb.partition_B(gSFB_nkl); // (MMA, MMA_N, MMA_K, n, k, l) + + Tensor sSFA = make_tensor(make_smem_ptr(shared_tensors.smem_SFA.begin()), SmemLayoutSFA{}); + Tensor sSFB = make_tensor(make_smem_ptr(shared_tensors.smem_SFB.begin()), SmemLayoutSFB{}); + + // Define the CTA-in-Cluster Layout and Coord + Layout cta_layout_mnk = make_layout(cluster_shape_); + Layout cta_layout_vmnk = tiled_divide(cta_layout_mnk, make_tile(typename TiledMma::AtomThrID{})); + auto cta_coord_vmnk = cta_layout_vmnk.get_flat_coord(block_rank_in_cluster_); + + Layout cta_layout_sfb_vmnk = tiled_divide(cta_layout_mnk, make_tile(typename TiledMMA_SF::AtomThrID{})); + auto cta_coord_sfb_vmnk = cta_layout_sfb_vmnk.get_flat_coord(block_rank_in_cluster_); + + // Project the cta_layout for tma_a along the n-modes + auto [tAgA_mkl, tAsA] = tma_partition(*observed_tma_load_a_, + get<2>(cta_coord_vmnk), make_layout(size<2>(cta_layout_vmnk)), + group_modes<0,3>(sA), group_modes<0,3>(tCgA_mkl)); + + // Project the cta_layout for tma_b along the m-modes + auto [tBgB_nkl, tBsB] = tma_partition(*observed_tma_load_b_, + get<1>(cta_coord_vmnk), make_layout(size<1>(cta_layout_vmnk)), + group_modes<0,3>(sB), group_modes<0,3>(tCgB_nkl)); + + // Project the cta_layout for tma_a along the n-modes + auto [tAgSFA_mkl, tAsSFA] = tma_partition(*observed_tma_load_sfa_, + get<2>(cta_coord_vmnk), make_layout(size<2>(cta_layout_vmnk)), + group_modes<0,3>(sSFA), group_modes<0,3>(tCgSFA_mkl)); + + // Project the cta_layout for tma_b along the m-modes + auto [tBgSFB_nkl, tBsSFB] = tma_partition(*observed_tma_load_sfb_, + get<1>(cta_coord_sfb_vmnk), make_layout(size<1>(cta_layout_sfb_vmnk)), + group_modes<0,3>(sSFB), group_modes<0,3>(tCgSFB_nkl)); + + // TMA Multicast Masks + uint16_t mcast_mask_a = create_tma_multicast_mask<2>(cta_layout_vmnk, cta_coord_vmnk); + uint16_t mcast_mask_b = create_tma_multicast_mask<1>(cta_layout_vmnk, cta_coord_vmnk); + uint16_t mcast_mask_sfa = create_tma_multicast_mask<2>(cta_layout_vmnk, cta_coord_vmnk); + uint16_t mcast_mask_sfb = create_tma_multicast_mask<1>(cta_layout_sfb_vmnk, cta_coord_sfb_vmnk); + + auto ret = cute::make_tuple( + gA_mkl, gB_nkl, // for scheduler + tAgA_mkl, tBgB_nkl, tAsA, tBsB, // for input tensor values + tAgSFA_mkl, tBgSFB_nkl, tAsSFA, tBsSFB, // for input scale factor tensor values + mcast_mask_a, mcast_mask_b, mcast_mask_sfa, mcast_mask_sfb); // multicast masks + + if constexpr (IsTensorMapUpdateAsync) { + return ret; + } else { + // Fetch a copy of tensormaps for the CTA from Params + auto input_tensormaps = tensormaps_init(params, shared_tensormaps, sm_count, sm_idx); + return cute::tuple_cat(ret, cute::make_tuple(input_tensormaps)); + } + } + + /// Set up the data needed by this collective for mma compute. + template + CUTLASS_DEVICE auto + mma_init( + TmemStorage tmem_storage, + TensorStorage& shared_tensors) const { + + // Allocate "fragments/descriptors" for A and B matrices + Tensor sA = make_tensor(make_smem_ptr(shared_tensors.smem_A.begin()), SmemLayoutA{}); // (BLK_M,BLK_K,PIPE) + Tensor sB = make_tensor(make_smem_ptr(shared_tensors.smem_B.begin()), SmemLayoutB{}); // (BLK_N,BLK_K,PIPE) + + // Allocate "fragments/descriptors" for A and B matrices + Tensor tCrA = TiledMma::make_fragment_A(sA); // (MMA,MMA_M,MMA_K,PIPE) + Tensor tCrB = TiledMma::make_fragment_B(sB); // (MMA,MMA_N,MMA_K,PIPE) + + CUTE_STATIC_ASSERT_V(Int{} == size<3>(sA)); // PIPE + CUTE_STATIC_ASSERT_V(Int{} == size<3>(sB)); // PIPE + + // + // Scale Factor + // + Tensor tCtSFA = tmem_storage.tCtSFA; + Tensor tCtSFB = tmem_storage.tCtSFB; + // Setup smem descriptors for UTCCP + Tensor tCsSFA = make_tensor(make_smem_ptr(shared_tensors.smem_SFA.begin()), SmemLayoutSFA{}); + Tensor tCsSFB = make_tensor(make_smem_ptr(shared_tensors.smem_SFB.begin()), SmemLayoutSFB{}); + + // Make SMEM and TMEM tensors compact removing the zero strides to eliminate unnecessary copy instructions. + auto tCsSFA_compact = make_tensor(tCsSFA.data(), filter_zeros(tCsSFA.layout())); + auto tCtSFA_compact = make_tensor(tCtSFA.data(), filter_zeros(tCtSFA.layout())); + auto tCsSFB_compact = make_tensor(tCsSFB.data(), filter_zeros(tCsSFB.layout())); + auto tCtSFB_compact = make_tensor(tCtSFB.data(), filter_zeros(tCtSFB.layout())); + + // Create the SMEM to TMEM copy operations based on the MMA atom used (1CTA vs 2CTA) + using AtomThrID = typename TiledMma::AtomThrID; + using UtccpOp = cute::conditional_t<(decltype(cute::size(AtomThrID{}) == Int<2>{})::value), + SM100_UTCCP_4x32dp128bit_2cta, SM100_UTCCP_4x32dp128bit_1cta>; + auto tiled_copy_s2t_SFA = make_utccp_copy(UtccpOp{}, tCtSFA_compact); + auto tiled_copy_s2t_SFB = make_utccp_copy(UtccpOp{}, tCtSFB_compact); + + auto thr_copy_s2t_SFA = tiled_copy_s2t_SFA.get_slice(0); + auto thr_tCsSFA_compact_s2t_ = thr_copy_s2t_SFA.partition_S(tCsSFA_compact); + // SMEM to TMEM copy operation requires source SMEM operand to be an SMEM descriptor + auto thr_tCsSFA_compact_s2t = get_utccp_smem_desc_tensor(thr_tCsSFA_compact_s2t_); + auto thr_tCtSFA_compact_s2t = thr_copy_s2t_SFA.partition_D(tCtSFA_compact); + + auto thr_copy_s2t_SFB = tiled_copy_s2t_SFB.get_slice(0); + auto thr_tCsSFB_compact_s2t_ = thr_copy_s2t_SFB.partition_S(tCsSFB_compact); + // SMEM to TMEM copy operation requires source SMEM operand to be an SMEM descriptor + auto thr_tCsSFB_compact_s2t = get_utccp_smem_desc_tensor(thr_tCsSFB_compact_s2t_); + auto thr_tCtSFB_compact_s2t = thr_copy_s2t_SFB.partition_D(tCtSFB_compact); + + TiledMma tiled_mma; + + if constexpr (IsRuntimeDataType) { + // Update instruction descriptor according to runtime argument. + // Applying bitmask (0b111) to help compiler deduce that the conversion and assignment are safe. + tiled_mma.idesc_.a_format_ = uint8_t(runtime_data_type_a_) & 0b111; + tiled_mma.idesc_.b_format_ = uint8_t(runtime_data_type_b_) & 0b111; + } + + return cute::make_tuple( + tiled_mma, + tCrA, tCrB, tCtSFA, tCtSFB, + tiled_copy_s2t_SFA, thr_tCsSFA_compact_s2t, thr_tCtSFA_compact_s2t, + tiled_copy_s2t_SFB, thr_tCsSFB_compact_s2t, thr_tCtSFB_compact_s2t); + } + + /// Perform a collective-scoped matrix multiply-accumulate + /// Producer Perspective + template < + class GTensorA, class GTensorB, + class GTensorPartitionedA, class GTensorPartitionedB, + class STensorA, class STensorB, + class GTensorPartitionedSFA, class GTensorPartitionedSFB, + class STensorSFA, class STensorSFB, + class TensorMapA, class TensorMapB, + class TensorMapSFA, class TensorMapSFB, + class TileCoordMNKL, + class KTileIterator + > + CUTLASS_DEVICE auto + load( + Params const& params, + MainloopPipeline mainloop_pipeline, + MainloopPipelineState mainloop_pipe_producer_state, + cute::tuple> const& load_inputs, + TileCoordMNKL const& cta_coord_mnkl, + KTileIterator k_tile_iter, int k_tile_count, + bool did_batch_change, + [[maybe_unused]] int curr_batch) { + + auto [unused_gA, unused_gB, + tAgA_mkl, tBgB_nkl, tAsA, tBsB, + tAgSFA_mkl, tBgSFB_nkl, tAsSFA, tBsSFB, + mcast_mask_a, mcast_mask_b, mcast_mask_sfa, mcast_mask_sfb, + input_tensormaps] = load_inputs; + + // Check to see if tensormaps have been replaced in gmem + if (did_batch_change) { + tensormaps_fence_acquire(input_tensormaps); + } + + // slice out the work coord from partitioned tensors + Tensor tAgA = tAgA_mkl(_, get<0>(cta_coord_mnkl) / size(typename TiledMma::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgB = tBgB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + Tensor tAgSFA = tAgSFA_mkl(_, get<0>(cta_coord_mnkl) / size(typename TiledMma::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgSFB = tBgSFB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + + auto barrier_token = mainloop_pipeline.producer_try_acquire(mainloop_pipe_producer_state); + + // Issue the Mainloop loads + CUTLASS_PRAGMA_NO_UNROLL + while (k_tile_count > 0) { + // LOCK mainloop_pipe_producer_state for _writing_ + mainloop_pipeline.producer_acquire(mainloop_pipe_producer_state, barrier_token); + // Note: We don't synchronize the sf_pipeline for "Buffer_Empty". We use mainloop pipeline + // to do the synchronization at once. + + using BarrierType = typename MainloopPipeline::ProducerBarrierType; + BarrierType* tma_barrier = mainloop_pipeline.producer_get_barrier(mainloop_pipe_producer_state); + + int write_stage = mainloop_pipe_producer_state.index(); + ++mainloop_pipe_producer_state; + barrier_token = mainloop_pipeline.producer_try_acquire(mainloop_pipe_producer_state); + + if (cute::elect_one_sync()) { + copy(observed_tma_load_a_->with(get<0>(input_tensormaps), *tma_barrier, mcast_mask_a), tAgA(_,*k_tile_iter), tAsA(_,write_stage)); + copy(observed_tma_load_b_->with(get<1>(input_tensormaps), *tma_barrier, mcast_mask_b), tBgB(_,*k_tile_iter), tBsB(_,write_stage)); + copy(observed_tma_load_sfa_->with(get<2>(input_tensormaps), *tma_barrier, mcast_mask_sfa), tAgSFA(_,*k_tile_iter), tAsSFA(_,write_stage)); + copy(observed_tma_load_sfb_->with(get<3>(input_tensormaps), *tma_barrier, mcast_mask_sfb), tBgSFB(_,*k_tile_iter), tBsSFB(_,write_stage)); + } + + --k_tile_count; + ++k_tile_iter; + } + + return cute::make_tuple(mainloop_pipe_producer_state, k_tile_iter); + } + + /// Perform a Producer Epilogue to prevent early exit of ctas in a Cluster + CUTLASS_DEVICE void + load_tail(MainloopPipeline mainloop_pipeline, MainloopPipelineState mainloop_pipe_producer_state) { + // Issue the epilogue waits + // This helps avoid early exit of ctas in Cluster + // Waits for all stages to either be released (all + // Consumer UNLOCKs), or if the stage was never used + // then would just be acquired since the phase was + // still inverted from make_producer_start_state + mainloop_pipeline.producer_tail(mainloop_pipe_producer_state); + } + + /// Perform a collective-scoped matrix multiply-accumulate + /// Consumer Perspective + template < + class AccumulatorPipeline, + class FrgEngine, class FrgLayout, + class FragmentA, class FragmentB, + class FragmentSFA, class FragmentSFB, + class CtaTileCoord, + class SFATiledCopy, class SmemFrgSFA, class TmemFrgSFA, + class SFBTiledCopy, class SmemFrgSFB, class TmemFrgSFB + > + CUTLASS_DEVICE auto + mma(cute::tuple pipelines, + cute::tuple pipeline_states, + cute::Tensor& accumulators, + cute::tuple const& mma_inputs, + CtaTileCoord cta_tile_coord, + int k_tile_count + ) { + static_assert(is_tmem::value, "Accumulator must be tmem resident."); + static_assert(rank(FrgLayout{}) == 3, "Accumulator must be MMA-partitioned: (MMA, MMA_M, MMA_N)"); + + auto [tiled_mma, + tCrA, tCrB, tCtSFA, tCtSFB, + tiled_copy_s2t_SFA, thr_tCsSFA_s2t, + thr_tCtSFA_s2t, tiled_copy_s2t_SFB, + thr_tCsSFB_s2t, thr_tCtSFB_s2t] = mma_inputs; + + auto [mainloop_pipeline, accumulator_pipeline] = pipelines; + auto [mainloop_pipe_consumer_state, accumulator_pipe_producer_state] = pipeline_states; + + auto tCtSFB_mma = [tCtSFB = tCtSFB, cta_tile_coord]() { + if constexpr (IsCtaN192) { + // If this is an ODD tile, shift the TMEM start address for N=192 case by two words (ignores first 64 columns of SFB) + auto tCtSFB_tmp = tCtSFB; + if (size<1>(cta_tile_coord) % 2 == 1) { + tCtSFB_tmp.data() = tCtSFB_tmp.data().get() + 2; + } + return tCtSFB_tmp; + } + else if constexpr (IsCtaN64) { + // Move in increments of 64 columns of SFB + auto tCtSFB_tmp = tCtSFB; + tCtSFB_tmp.data() = tCtSFB_tmp.data().get() + (size<1>(cta_tile_coord) % 2) * 2; + return tCtSFB_tmp; + } + else { + return tCtSFB; + } + }(); + + uint32_t skip_wait = k_tile_count <= 0; + auto barrier_token = mainloop_pipeline.consumer_try_wait(mainloop_pipe_consumer_state, skip_wait); + + // + // PIPELINED MAIN LOOP + // + tiled_mma.accumulate_ = UMMA::ScaleOut::Zero; + + if constexpr (IsOverlappingAccum) { + // first iteration manual unroll for tmem overlap kernel + if (k_tile_count > 0) { + // WAIT on mainloop_pipe_consumer_state until its data are available + // (phase bit flips from mainloop_pipe_consumer_state.phase() value) + mainloop_pipeline.consumer_wait(mainloop_pipe_consumer_state, barrier_token); + + // Compute on k_tile + int read_stage = mainloop_pipe_consumer_state.index(); + // Save current mainlop pipeline read state + auto curr_mainloop_pipe_consumer_state = mainloop_pipe_consumer_state; + + // Advance mainloop_pipe + ++mainloop_pipe_consumer_state; + --k_tile_count; + skip_wait = k_tile_count <= 0; + // Peek at next iteration + barrier_token = mainloop_pipeline.consumer_try_wait(mainloop_pipe_consumer_state, skip_wait); + + if (cute::elect_one_sync()) { + copy(tiled_copy_s2t_SFA, thr_tCsSFA_s2t(_,_,_,_,read_stage), thr_tCtSFA_s2t); + copy(tiled_copy_s2t_SFB, thr_tCsSFB_s2t(_,_,_,_,read_stage), thr_tCtSFB_s2t); + } + + // Wait for tmem accumulator buffer to become empty with a flipped phase + accumulator_pipeline.producer_acquire(accumulator_pipe_producer_state); + + // Unroll the K mode manually so we can set scale C to 1 + CUTLASS_PRAGMA_UNROLL + for (int k_block = 0; k_block < size<2>(tCrA); ++k_block) { + // (V,M) x (V,N) => (V,M,N) + cute::gemm(tiled_mma.with(tiled_mma.accumulate_, + tCtSFA(_,_,k_block), + tCtSFB_mma(_,_,k_block)), + tCrA(_,_,k_block,read_stage), + tCrB(_,_,k_block,read_stage), + accumulators); + tiled_mma.accumulate_ = UMMA::ScaleOut::One; + } + + mainloop_pipeline.consumer_release(curr_mainloop_pipe_consumer_state); + } + } + else { + if (k_tile_count > 0) { + // Wait for tmem accumulator buffer to become empty with a flipped phase + accumulator_pipeline.producer_acquire(accumulator_pipe_producer_state); + } + } + + CUTLASS_PRAGMA_NO_UNROLL + while (k_tile_count > 0) { + // WAIT on mainloop_pipe_consumer_state until its data are available + // (phase bit flips from mainloop_pipe_consumer_state.phase() value) + mainloop_pipeline.consumer_wait(mainloop_pipe_consumer_state, barrier_token); + + // Compute on k_tile + int read_stage = mainloop_pipe_consumer_state.index(); + // Save current mainlop pipeline read state + auto curr_mainloop_pipe_consumer_state = mainloop_pipe_consumer_state; + + // Advance mainloop_pipe + ++mainloop_pipe_consumer_state; + --k_tile_count; + skip_wait = k_tile_count <= 0; + // Peek at next iteration + barrier_token = mainloop_pipeline.consumer_try_wait(mainloop_pipe_consumer_state, skip_wait); + + if (cute::elect_one_sync()) { + copy(tiled_copy_s2t_SFA, thr_tCsSFA_s2t(_,_,_,_,read_stage), thr_tCtSFA_s2t); + copy(tiled_copy_s2t_SFB, thr_tCsSFB_s2t(_,_,_,_,read_stage), thr_tCtSFB_s2t); + } + + // Unroll the K mode manually so we can set scale C to 1 + CUTLASS_PRAGMA_UNROLL + for (int k_block = 0; k_block < size<2>(tCrA); ++k_block) { + // (V,M) x (V,N) => (V,M,N) + cute::gemm(tiled_mma.with(tiled_mma.accumulate_, + tCtSFA(_,_,k_block), + tCtSFB_mma(_,_,k_block)), + tCrA(_,_,k_block,read_stage), + tCrB(_,_,k_block,read_stage), + accumulators); + tiled_mma.accumulate_ = UMMA::ScaleOut::One; + } + + mainloop_pipeline.consumer_release(curr_mainloop_pipe_consumer_state); + } + + return mainloop_pipe_consumer_state; + } + + // + // Methods to perform different parts of TMA/Tensormap modifications + // + + template + CUTLASS_DEVICE auto + tensormaps_init( + Params const& mainloop_params, + TensorMapStorage& shared_tensormaps, + int32_t const sm_count, + int32_t const sm_idx) const { + + TensorMaps* gmem_tensormap = &(reinterpret_cast(mainloop_params.tensormaps)[sm_idx * NumTmaDescriptorsPerSm]); + + if (cute::elect_one_sync()) { + // Bringing tensormaps from params to smem for modification later + Tensor pA_tensormap = make_tensor(observed_tma_load_a_->get_tma_descriptor(), Int<1>{}, Int<1>{}); + Tensor sA_tensormap = make_tensor(make_smem_ptr(&shared_tensormaps.smem_tensormap_A), Int<1>{}, Int<1>{}); + Tensor pB_tensormap = make_tensor(observed_tma_load_b_->get_tma_descriptor(), Int<1>{}, Int<1>{}); + Tensor sB_tensormap = make_tensor(make_smem_ptr(&shared_tensormaps.smem_tensormap_B), Int<1>{}, Int<1>{}); + + Tensor pSFA_tensormap = make_tensor(observed_tma_load_sfa_->get_tma_descriptor(), Int<1>{}, Int<1>{}); + Tensor sSFA_tensormap = make_tensor(make_smem_ptr(&shared_tensormaps.smem_tensormap_SFA), Int<1>{}, Int<1>{}); + Tensor pSFB_tensormap = make_tensor(observed_tma_load_sfb_->get_tma_descriptor(), Int<1>{}, Int<1>{}); + Tensor sSFB_tensormap = make_tensor(make_smem_ptr(&shared_tensormaps.smem_tensormap_SFB), Int<1>{}, Int<1>{}); + + copy(recast(pA_tensormap), recast(sA_tensormap)); + copy(recast(pB_tensormap), recast(sB_tensormap)); + + copy(recast(pSFA_tensormap), recast(sSFA_tensormap)); + copy(recast(pSFB_tensormap), recast(sSFB_tensormap)); + } + + __syncwarp(); + + struct TensorMapArray { + + TensorMaps *tensor_maps; + + TensorMapArray() = default; + + CUTLASS_DEVICE + TensorMapArray(void* tensormaps) : tensor_maps(reinterpret_cast(tensormaps)) {} + + CUTLASS_DEVICE + cute::tuple + operator[](int32_t idx) { + idx = idx % NumTmaDescriptorsPerSm; + return cute::make_tuple(&tensor_maps[idx].tma_desc_a, &tensor_maps[idx].tma_desc_b, &tensor_maps[idx].tma_desc_sfa, &tensor_maps[idx].tma_desc_sfb); + } + }; + if constexpr (IsTensorMapUpdateAsync) { + return TensorMapArray(gmem_tensormap); + } else { + return cute::make_tuple(&gmem_tensormap->tma_desc_a, &gmem_tensormap->tma_desc_b, &gmem_tensormap->tma_desc_sfa, &gmem_tensormap->tma_desc_sfb); + } + } + + // Replace address for the global tensor (to be done by single thread) + CUTLASS_DEVICE + void + tensormaps_replace_global_address( + TensorMapStorage& shared_tensormaps, + Params const& mainloop_params, + int32_t next_batch) { + // Replacing global_address for the next batch + cute::tma_descriptor_replace_addr_in_shared_mem(shared_tensormaps.smem_tensormap_A, + mainloop_params.ptr_A[next_batch]); + cute::tma_descriptor_replace_addr_in_shared_mem(shared_tensormaps.smem_tensormap_B, + mainloop_params.ptr_B[next_batch]); + + cute::tma_descriptor_replace_addr_in_shared_mem(shared_tensormaps.smem_tensormap_SFA, + mainloop_params.ptr_SFA[next_batch]); + cute::tma_descriptor_replace_addr_in_shared_mem(shared_tensormaps.smem_tensormap_SFB, + mainloop_params.ptr_SFB[next_batch]); + } + + // Replace dim and strides for the global tensor - used only for Grouped GEMM (to be done by single thread) + template + CUTLASS_DEVICE + void + tensormaps_replace_global_tensor_properties( + TensorMapStorage& shared_tensormaps, + Params const& mainloop_params, + int32_t next_group, + ProblemShape_MNKL problem_shape_mnkl) { + const uint32_t M = get<0>(problem_shape_mnkl); + const uint32_t N = get<1>(problem_shape_mnkl); + const uint32_t K = get<2>(problem_shape_mnkl); + // Replace all dims for consistency + constexpr int MaxTensorRank = 5; + cute::array prob_shape_A = {1,1,1,1,1}; + cute::array prob_stride_A = {0,0,0,0,0}; + cute::array prob_shape_SFA = {1,1,1,1,1}; + cute::array prob_stride_SFA = {0,0,0,0,0}; + cute::array prob_shape_B = {1,1,1,1,1}; + cute::array prob_stride_B = {0,0,0,0,0}; + cute::array prob_shape_SFB = {1,1,1,1,1}; + cute::array prob_stride_SFB = {0,0,0,0,0}; + + TmaInternalElementA const* ptr_A = nullptr; + Tensor tensor_a = make_tensor(ptr_A, make_shape(M,K,Int<1>{}), mainloop_params.dA[next_group]); + + ElementSF const* ptr_SF = nullptr; + Tensor tensor_sfa = make_tensor(ptr_SF, mainloop_params.layout_SFA[next_group]); + + TmaInternalElementB const* ptr_B = nullptr; + Tensor tensor_b = make_tensor(ptr_B, make_shape(N,K,Int<1>{}), mainloop_params.dB[next_group]); + + Tensor tensor_sfb = make_tensor(ptr_SF, mainloop_params.layout_SFB[next_group]); + + cute::detail::fill_tma_gmem_shape_stride(*observed_tma_load_a_, tensor_a, + prob_shape_A, prob_stride_A); + cute::detail::fill_tma_gmem_shape_stride(*observed_tma_load_sfa_, tensor_sfa, + prob_shape_SFA, prob_stride_SFA); + cute::detail::fill_tma_gmem_shape_stride(*observed_tma_load_b_, tensor_b, + prob_shape_B, prob_stride_B); + cute::detail::fill_tma_gmem_shape_stride(*observed_tma_load_sfb_, tensor_sfb, + prob_shape_SFB, prob_stride_SFB); + + // Convert strides to byte strides + for (uint64_t& stride : prob_stride_A) { + stride = (stride * sizeof_bits_v) / 8; + } + for (uint64_t& stride : prob_stride_SFA) { + stride = (stride * sizeof_bits_v) / 8; + } + for (uint64_t& stride : prob_stride_B) { + stride = (stride * sizeof_bits_v) / 8; + } + for (uint64_t& stride : prob_stride_SFB) { + stride = (stride * sizeof_bits_v) / 8; + } + + cute::tma_descriptor_replace_dims_strides_in_shared_mem(shared_tensormaps.smem_tensormap_A, + prob_shape_A, + prob_stride_A); + cute::tma_descriptor_replace_dims_strides_in_shared_mem(shared_tensormaps.smem_tensormap_SFA, + prob_shape_SFA, + prob_stride_SFA); + cute::tma_descriptor_replace_dims_strides_in_shared_mem(shared_tensormaps.smem_tensormap_B, + prob_shape_B, + prob_stride_B); + cute::tma_descriptor_replace_dims_strides_in_shared_mem(shared_tensormaps.smem_tensormap_SFB, + prob_shape_SFB, + prob_stride_SFB); + } + + // The entire warp must call this function collectively (that is, the instructions are aligned) + template + CUTLASS_DEVICE + void + tensormaps_perform_update( + TensorMapStorage& shared_tensormaps, + Params const& mainloop_params, + cute::tuple const& input_tensormaps, + ProblemShape problem_shape, + int32_t next_batch + ) { + if (cute::elect_one_sync()) { + + if constexpr (IsGroupedGemmKernel) { + auto problem_shape_MNKL = append<4>(problem_shape.get_problem_shape(next_batch), 1); + // Replacing global dims and strides for the next batch + tensormaps_replace_global_tensor_properties(shared_tensormaps, + mainloop_params, next_batch, problem_shape_MNKL); + } + + // Replacing global_address for the next batch + tensormaps_replace_global_address(shared_tensormaps, mainloop_params, next_batch); + } + // Ensure warp is converged before issuing tensormap fence release + __syncwarp(); + // Entire warp must do this (ie its aligned) + tensormaps_cp_fence_release( + shared_tensormaps, + input_tensormaps + ); + } + + template + CUTLASS_DEVICE + void + tensormaps_cp_fence_release ( + TensorMapStorage& shared_tensormaps, + cute::tuple const& input_tensormaps + ) { + + if constexpr (WaitForInflightTmaRequests) { + if (cute::elect_one_sync()) { + cute::tma_desc_commit_group(); + cute::tma_desc_wait_group(); + } + } + + // Entire warp must do this (i.e. it's aligned) + tma_descriptor_cp_fence_release(get<0>(input_tensormaps), shared_tensormaps.smem_tensormap_A); + tma_descriptor_cp_fence_release(get<1>(input_tensormaps), shared_tensormaps.smem_tensormap_B); + + tma_descriptor_cp_fence_release(get<2>(input_tensormaps), shared_tensormaps.smem_tensormap_SFA); + tma_descriptor_cp_fence_release(get<3>(input_tensormaps), shared_tensormaps.smem_tensormap_SFB); + } + + // The entire warp must call this function collectively (that is, the instructions are aligned) + template + CUTLASS_DEVICE + void + tensormaps_fence_acquire(cute::tuple const& input_tensormaps) { + cute::tma_descriptor_fence_acquire(get<0>(input_tensormaps)); + cute::tma_descriptor_fence_acquire(get<1>(input_tensormaps)); + cute::tma_descriptor_fence_acquire(get<2>(input_tensormaps)); + cute::tma_descriptor_fence_acquire(get<3>(input_tensormaps)); + } + +protected: + + typename Params::TMA_A const* observed_tma_load_a_{nullptr}; + typename Params::TMA_B const* observed_tma_load_b_{nullptr}; + typename Params::TMA_SFA const* observed_tma_load_sfa_{nullptr}; + typename Params::TMA_SFB const* observed_tma_load_sfb_{nullptr}; + + LayoutSFA layout_SFA_; + LayoutSFB layout_SFB_; + RuntimeDataTypeA runtime_data_type_a_{}; + RuntimeDataTypeB runtime_data_type_b_{}; + + ClusterShape cluster_shape_; + uint32_t block_rank_in_cluster_; +}; + +///////////////////////////////////////////////////////////////////////////////////////////////// + +} // namespace cutlass::gemm::collective + +///////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/kernels/Quant/019_nvfp4_grouped_query_attention/src/cutlass/gemm/collective/sm100_blockscaled_mma_warpspecialized.hpp b/kernels/Quant/019_nvfp4_grouped_query_attention/src/cutlass/gemm/collective/sm100_blockscaled_mma_warpspecialized.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f35b8c18744890345ec450eee1498786655040fa --- /dev/null +++ b/kernels/Quant/019_nvfp4_grouped_query_attention/src/cutlass/gemm/collective/sm100_blockscaled_mma_warpspecialized.hpp @@ -0,0 +1,1125 @@ +/*************************************************************************************************** + * Copyright (c) 2023 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + **************************************************************************************************/ +// SHADOW of CUTLASS 4.4.1 cutlass/gemm/collective/sm100_blockscaled_mma_warpspecialized.hpp (picked up via the +// solution's source root, which precedes the CUTLASS include path). Identical except: CTA tile N = 224 is accepted. +// For N = 224 the SFB operand must be in a PADDED blocked layout: N-tile t's 224 weight-scale rows occupy virtual +// rows [256t, 256t+224) (virtual N = 256 * ceil(N/224)), so every tile's SF starts at a 128-row block boundary +// (TileShape_SF N = 256, no TMEM shift). can_implement checks layout_SFB against that virtual N. +#define NVFP4_SHADOW_N224 1 +#pragma once + +#include "cutlass/cutlass.h" +#include "cutlass/detail/collective.hpp" +#include "cutlass/detail/cluster.hpp" +#include "cutlass/gemm/dispatch_policy.hpp" +#include "cutlass/numeric_types.h" +#include "cutlass/pipeline/pipeline.hpp" +#include "cutlass/gemm/gemm.h" +#include "cutlass/detail/sm100_blockscaled_layout.hpp" +#include "cutlass/trace.h" +#include "cutlass/kernel_hardware_info.hpp" +#include "cutlass/detail/collective.hpp" +#include "cutlass/detail/sm100_tmem_helper.hpp" + +#include "cute/algorithm/functional.hpp" +#include "cute/arch/cluster_sm90.hpp" +#include "cute/atom/mma_atom.hpp" +#include "cute/algorithm/gemm.hpp" +#include "cute/numeric/arithmetic_tuple.hpp" + +///////////////////////////////////////////////////////////////////////////////////////////////// + +namespace cutlass::gemm::collective { +using namespace cute; + +///////////////////////////////////////////////////////////////////////////////////////////////// + +// WarpSpecialized Mainloop +// Both DMA Load and MMA methods of this class must be run by a single thread that's picked by elect_one +template < + int Stages, + int SchedulerPipelineStageCount, + int AccumulatorPipelineStageCount, + class ClusterShape, // Static cluster shape or dynamic (int, int, _1) + class TileShape_, // (MmaAtomShapeM, MmaAtomShapeN, TileK) + class ElementPairA_, + class StridePairA_, + class ElementPairB_, + class StridePairB_, + class TiledMma_, + class GmemTiledCopyPairA_, + class SmemLayoutAtomPairA_, + class SmemCopyAtomA_, + class TransformA_, + class GmemTiledCopyPairB_, + class SmemLayoutAtomPairB_, + class SmemCopyAtomB_, + class TransformB_> +struct CollectiveMma< + MainloopSm100TmaUmmaWarpSpecializedBlockScaled< + Stages, + SchedulerPipelineStageCount, + AccumulatorPipelineStageCount, + ClusterShape>, + TileShape_, + ElementPairA_, + StridePairA_, + ElementPairB_, + StridePairB_, + TiledMma_, + GmemTiledCopyPairA_, + SmemLayoutAtomPairA_, + SmemCopyAtomA_, + TransformA_, + GmemTiledCopyPairB_, + SmemLayoutAtomPairB_, + SmemCopyAtomB_, + TransformB_> +{ + // + // Type Aliases + // + using TiledMma = TiledMma_; + using AtomThrShapeMNK = Shape(typename TiledMma::ThrLayoutVMNK{})), _1, _1>; + + using DispatchPolicy = MainloopSm100TmaUmmaWarpSpecializedBlockScaled< + Stages, + SchedulerPipelineStageCount, + AccumulatorPipelineStageCount, + ClusterShape>; + using TileShape = TileShape_; + using TiledMMA_SF = TiledMMA, + Layout>, + Tile>; + + static constexpr bool IsDynamicCluster = not cute::is_static_v; + static constexpr int SFVecSize = TiledMma::SFVecSize; + static constexpr bool IsOverlappingAccum = DispatchPolicy::IsOverlappingAccum; + + CUTE_STATIC_ASSERT_V(evenly_divides(TileShape{}, tile_shape(TiledMma{})), + "Static cluster shape used: TileShape should be evenly divided by TiledMma"); + + using CtaShape_MNK = decltype(shape_div(TileShape{}, AtomThrShapeMNK{})); + static_assert(shape<1>(CtaShape_MNK{}) == 192 or shape<1>(CtaShape_MNK{}) == 64 or + shape<1>(CtaShape_MNK{}) == 128 or shape<1>(CtaShape_MNK{}) == 256 or + shape<1>(CtaShape_MNK{}) == 224 or shape<1>(CtaShape_MNK{}) == 160, + "Cta N should be one of 64/128/160/192/224/256"); + static constexpr int IsCtaN160 = shape<1>(CtaShape_MNK{}) == 160; // padded SFB layout (tile t at virtual rows 256t) + static constexpr int IsCtaN224 = shape<1>(CtaShape_MNK{}) == 224; // padded SFB layout (see header) + + using ClusterTileShape = decltype(make_shape(get<0>(TileShape{})*get<0>(ClusterShape{}),get<1>(TileShape{})*get<1>(ClusterShape{}),get<2>(TileShape{})*get<2>(ClusterShape{}))); + using Sm1xxBlkScaledConfig = cutlass::detail::Sm1xxBlockScaledConfig; + using Blk_MN = typename Sm1xxBlkScaledConfig::Blk_MN; + static constexpr int IsCtaN192 = shape<1>(CtaShape_MNK{}) == 192; + static constexpr int IsCtaN64 = shape<1>(CtaShape_MNK{}) == 64; + static int constexpr CTA_N_SF = cutlass::ceil_div(size<1>(CtaShape_MNK{}), Blk_MN{}) * Blk_MN{}; + // Tile shape used for partitioning Scale Factor B. + // The M-dim does not affect the SFB, so just set it as the original TileShape; + using TileShape_SF = decltype(make_shape(get<0>(CtaShape_MNK{}), + Int{} * shape<2>(typename TiledMma::ThrLayoutVMNK()), + get<2>(TileShape{}))); + + // Define A and B block shapes for reduced size TMA_LOADs + using MmaShapeA_MK = decltype(partition_shape_A(TiledMma{}, make_shape(size<0>(TileShape{}), size<2>(TileShape{})))); + using MmaShapeB_NK = decltype(partition_shape_B(TiledMma{}, make_shape(size<1>(TileShape{}), size<2>(TileShape{})))); + + using ElementPairA = ElementPairA_; + using ElementPairB = ElementPairB_; + using ElementAMma = typename TiledMma::ValTypeA; + using ElementBMma = typename TiledMma::ValTypeB; + using StridePairA = StridePairA_; + using StridePairB = StridePairB_; + using SmemLayoutAtomPairA = SmemLayoutAtomPairA_; + using SmemLayoutAtomPairB = SmemLayoutAtomPairB_; + static_assert(cute::is_same_v(ElementPairA{}))>, + remove_cvref_t(ElementPairB{}))>>, "SFA and SFB data types should be the same"); + + // A and B matrices + using ElementA = remove_cvref_t(ElementPairA{}))>; + using StrideA = remove_cvref_t(StridePairA{}))>; + + using ElementB = remove_cvref_t(ElementPairB{}))>; + using StrideB = remove_cvref_t(StridePairB{}))>; + + static constexpr bool IsRuntimeDataTypeA = cutlass::gemm::collective::detail::is_sm10x_runtime_f8f6f4(); + static constexpr bool IsRuntimeDataTypeB = cutlass::gemm::collective::detail::is_sm10x_runtime_f8f6f4(); + + static_assert((IsRuntimeDataTypeA && IsRuntimeDataTypeB) || + (!IsRuntimeDataTypeA && !IsRuntimeDataTypeB), + "ElementA and ElementB should be both runtime or both static."); + + static constexpr bool IsRuntimeDataType = IsRuntimeDataTypeA && IsRuntimeDataTypeB; + + // SFA and SFB + using ElementSF = remove_cvref_t(ElementPairA{}))>; + using LayoutSFA = remove_cvref_t(StridePairA{}))>; + using LayoutSFB = remove_cvref_t(StridePairB{}))>; + + using ElementAccumulator = typename TiledMma::ValTypeC; + using GmemTiledCopyPairA = GmemTiledCopyPairA_; + using GmemTiledCopyPairB = GmemTiledCopyPairB_; + using GmemTiledCopyA = remove_cvref_t(GmemTiledCopyPairA{}))>; + using GmemTiledCopySFA = remove_cvref_t(GmemTiledCopyPairA{}))>; + using GmemTiledCopyB = remove_cvref_t(GmemTiledCopyPairB{}))>; + using GmemTiledCopySFB = remove_cvref_t(GmemTiledCopyPairB{}))>; + + using SmemLayoutAtomA = remove_cvref_t(SmemLayoutAtomPairA{}))>; + using SmemLayoutAtomSFA = remove_cvref_t(SmemLayoutAtomPairA{}))>; + using SmemLayoutAtomB = remove_cvref_t(SmemLayoutAtomPairB{}))>; + using SmemLayoutAtomSFB = remove_cvref_t(SmemLayoutAtomPairB{}))>; + + using SmemCopyAtomA = SmemCopyAtomA_; + using SmemCopyAtomB = SmemCopyAtomB_; + using TransformA = TransformA_; + using TransformB = TransformB_; + using ArchTag = typename DispatchPolicy::ArchTag; + + using MainloopPipeline = cutlass::PipelineTmaUmmaAsync< + DispatchPolicy::Stages, + ClusterShape, + AtomThrShapeMNK>; + using MainloopPipelineState = typename MainloopPipeline::PipelineState; + + static_assert(rank(SmemLayoutAtomA{}) == 2, "SmemLayoutAtom must be rank 2 (M/N, K)"); + static_assert((size<0>(TileShape{}) % size<0>(SmemLayoutAtomA{})) == 0, "SmemLayoutAtomA must evenly divide the tile shape."); + static_assert((size<2>(TileShape{}) % size<1>(SmemLayoutAtomA{})) == 0, "SmemLayoutAtomA must evenly divide the tile shape."); + static_assert(cute::is_void_v, + "SM100 UMMA cannot have a non-void copy atom for smem sourced instructions."); + + static_assert(rank(SmemLayoutAtomB{}) == 2, "SmemLayoutAtom must be rank 2 (M/N, K)"); + static_assert((size<1>(TileShape{}) % size<0>(SmemLayoutAtomB{})) == 0, "SmemLayoutAtomB must evenly divide the tile shape."); + static_assert((size<2>(TileShape{}) % size<1>(SmemLayoutAtomB{})) == 0, "SmemLayoutAtomB must evenly divide the tile shape."); + static_assert(cute::is_void_v, + "SM100 UMMA cannot have a non-void copy atom for smem sourced instructions."); + + // Tile along K mode first before tiling over MN. PIPE mode last as usual. + // This maximizes TMA boxes due to better smem-K vectorization, reducing total issued TMAs. + // (MMA_TILE_M,MMA_TILE_K),MMA_M,MMA_K,PIPE) + using SmemLayoutA = decltype(UMMA::tile_to_mma_shape( + SmemLayoutAtomA{}, + append(MmaShapeA_MK{}, Int{}), + cute::conditional_t(), Step<_2,_1,_3>, Step<_1,_2,_3>>{})); + // (MMA_TILE_N,MMA_TILE_K),MMA_N,MMA_K,PIPE) + using SmemLayoutB = decltype(UMMA::tile_to_mma_shape( + SmemLayoutAtomB{}, + append(MmaShapeB_NK{}, Int{}), + cute::conditional_t(), Step<_2,_1,_3>, Step<_1,_2,_3>>{})); + + // SmemLayoutAtomSFA and SmemLayoutAtomSFB are for whole CTA tiles. We add the number of pipeline stages here. + // The number of pipeline stages is the same as the number of pipeline stages from AB Load <-> MainLoop + using SmemLayoutSFA = decltype(make_layout( + append(shape(SmemLayoutAtomSFA{}), Int{}), + append(stride(SmemLayoutAtomSFA{}), size(filter_zeros(SmemLayoutAtomSFA{}))) + )); + using SmemLayoutSFB = decltype(make_layout( + append(shape(SmemLayoutAtomSFB{}), Int{}), + append(stride(SmemLayoutAtomSFB{}), size(filter_zeros(SmemLayoutAtomSFB{}))) + )); + + static_assert(cute::is_base_of::value && + cute::is_base_of::value, + "MMA atom must source both A and B operand from smem_desc for this mainloop."); + static_assert( + (size(AtomThrShapeMNK{}) == 1 && + (cute::is_same_v || cute::is_same_v)) || + (size(AtomThrShapeMNK{}) == 2 && + (cute::is_same_v || cute::is_same_v)), + "GmemTiledCopy - invalid TMA copy atom specified."); + static_assert( + (size(AtomThrShapeMNK{}) == 1 && + (cute::is_same_v || cute::is_same_v)) || + (size(AtomThrShapeMNK{}) == 2 && + (cute::is_same_v || cute::is_same_v)), + "GmemTiledCopy - invalid TMA copy atom specified."); + + static constexpr bool IsF8F6F4 = detail::is_sm100_mma_f8f6f4(); + + using TmaInternalElementA = cute::conditional_t; + using TmaInternalElementB = cute::conditional_t; + + using SmemAllocTypeA = cute::conditional_t < 8, uint8_t, ElementAMma>; + using SmemAllocTypeB = cute::conditional_t < 8, uint8_t, ElementBMma>; + + using BitTypeElementA = cute::uint_bit_t>; + using BitTypeElementB = cute::uint_bit_t>; + + using ArrayElementA = cute::conditional_t; + using ArrayElementB = cute::conditional_t; + + using RuntimeDataTypeA = typename detail::sm10x_block_scale_runtime_input_t::Type; + using RuntimeDataTypeB = typename detail::sm10x_block_scale_runtime_input_t::Type; + + struct SharedStorage { + struct TensorStorage : cute::aligned_struct<128, _0> { + cute::ArrayEngine> smem_A; + cute::ArrayEngine> smem_B; + cute::ArrayEngine> smem_SFA; + cute::ArrayEngine> smem_SFB; + } tensors; + + using PipelineStorage = typename MainloopPipeline::SharedStorage; + PipelineStorage pipeline; + }; + + // Expose shared storage for tensors/pipelines separately to allow kernel layer to reorder them. + using TensorStorage = typename SharedStorage::TensorStorage; + using PipelineStorage = typename SharedStorage::PipelineStorage; + + // Only one thread issues the TMA and updates the barriers in a 2SM MMA, adjust bytes accordingly + static constexpr uint32_t SFTransactionBytes = + cutlass::bits_to_bytes(size(AtomThrShapeMNK{}) * cosize(take<0,3>(SmemLayoutSFA{})) * cute::sizeof_bits_v) + + cutlass::bits_to_bytes(size(AtomThrShapeMNK{}) * cosize(take<0,3>(SmemLayoutSFB{})) * cute::sizeof_bits_v); + static constexpr uint32_t ABTmaTransactionBytes = + cutlass::bits_to_bytes(size(AtomThrShapeMNK{}) * cosize(take<0,3>(SmemLayoutA{})) * cute::sizeof_bits_v) + + cutlass::bits_to_bytes(size(AtomThrShapeMNK{}) * cosize(take<0,3>(SmemLayoutB{})) * cute::sizeof_bits_v); + static constexpr uint32_t TmaTransactionBytes = ABTmaTransactionBytes + SFTransactionBytes; + + template + struct TmemStorage { + AccTensor accumulators; + SfaTensor tCtSFA; + SfbTensor tCtSFB; + }; + + template < + class KTileCount, + class GTensorPartitionedA, class GTensorPartitionedB, + class STensorA, class STensorB, + class GTensorPartitionedSFA, class GTensorPartitionedSFB, + class STensorSFA, class STensorSFB + > + struct LoadParams { + // for scheduler + KTileCount k_tiles; + // for input tensor values + GTensorPartitionedA tAgA_mkl; + GTensorPartitionedB tBgB_nkl; + STensorA tAsA; + STensorB tBsB; + // for scale factor tensor values + GTensorPartitionedSFA tAgSFA_mkl; + GTensorPartitionedSFB tBgSFB_nkl; + STensorSFA tAsSFA; + STensorSFB tBsSFB; + // the TMA multicast masks + uint16_t mcast_mask_a; + uint16_t mcast_mask_b; + uint16_t mcast_mask_sfa; + uint16_t mcast_mask_sfb; + + CUTLASS_DEVICE + LoadParams ( + KTileCount k_tiles_, + GTensorPartitionedA tAgA_mkl_, GTensorPartitionedB tBgB_nkl_, + STensorA tAsA_, STensorB tBsB_, + GTensorPartitionedSFA tAgSFA_mkl_, GTensorPartitionedSFB tBgSFB_nkl_, + STensorSFA tAsSFA_, STensorSFB tBsSFB_, + uint16_t mcast_mask_a_, uint16_t mcast_mask_b_, + uint16_t mcast_mask_sfa_, uint16_t mcast_mask_sfb_) + : k_tiles(k_tiles_) + , tAgA_mkl(tAgA_mkl_), tBgB_nkl(tBgB_nkl_) + , tAsA(tAsA_), tBsB(tBsB_) + , tAgSFA_mkl(tAgSFA_mkl_), tBgSFB_nkl(tBgSFB_nkl_) + , tAsSFA(tAsSFA_), tBsSFB(tBsSFB_) + , mcast_mask_a(mcast_mask_a_), mcast_mask_b(mcast_mask_b_) + , mcast_mask_sfa(mcast_mask_sfa_), mcast_mask_sfb(mcast_mask_sfb_) {} + }; + + template < + class TiledMma, + class FragmentA, class FragmentB, + class FragmentSFA, class FragmentSFB, + class SFATiledCopy, class SmemFrgSFA, class TmemFrgSFA, + class SFBTiledCopy, class SmemFrgSFB, class TmemFrgSFB + > + struct MmaParams { + TiledMma tiled_mma; + FragmentA tCrA; + FragmentB tCrB; + FragmentSFA tCtSFA; + FragmentSFB tCtSFB; + SFATiledCopy tiled_copy_s2t_SFA; + SmemFrgSFA thr_tCsSFA_s2t; + TmemFrgSFA thr_tCtSFA_s2t; + SFBTiledCopy tiled_copy_s2t_SFB; + SmemFrgSFB thr_tCsSFB_s2t; + TmemFrgSFB thr_tCtSFB_s2t; + + CUTLASS_DEVICE + MmaParams ( + TiledMma tiled_mma_, + FragmentA tCrA_, FragmentB tCrB_, FragmentSFA tCtSFA_, FragmentSFB tCtSFB_, + SFATiledCopy tiled_copy_s2t_SFA_, SmemFrgSFA thr_tCsSFA_s2t_, TmemFrgSFA thr_tCtSFA_s2t_, + SFBTiledCopy tiled_copy_s2t_SFB_, SmemFrgSFB thr_tCsSFB_s2t_, TmemFrgSFB thr_tCtSFB_s2t_) + : tiled_mma(tiled_mma_) + , tCrA(tCrA_), tCrB(tCrB_), tCtSFA(tCtSFA_), tCtSFB(tCtSFB_) + , tiled_copy_s2t_SFA(tiled_copy_s2t_SFA_), thr_tCsSFA_s2t(thr_tCsSFA_s2t_), thr_tCtSFA_s2t(thr_tCtSFA_s2t_) + , tiled_copy_s2t_SFB(tiled_copy_s2t_SFB_), thr_tCsSFB_s2t(thr_tCsSFB_s2t_), thr_tCtSFB_s2t(thr_tCtSFB_s2t_) {} + }; + + // Host side kernel arguments + struct Arguments { + ArrayElementA const* ptr_A{nullptr}; + StrideA dA{}; + ArrayElementB const* ptr_B{nullptr}; + StrideB dB{}; + ElementSF const* ptr_SFA{nullptr}; + LayoutSFA layout_SFA{}; + ElementSF const* ptr_SFB{nullptr}; + LayoutSFB layout_SFB{}; + RuntimeDataTypeA runtime_data_type_a{}; + RuntimeDataTypeB runtime_data_type_b{}; + }; + + // Device side kernel params + struct Params { + using ClusterLayout_VMNK = + decltype(tiled_divide(make_layout(conditional_return(make_shape(uint32_t(0), uint32_t(0), Int<1>{}), + ClusterShape{})), make_tile(typename TiledMma::AtomThrID{}))); + + using ClusterLayoutSfb_VMNK = + decltype(tiled_divide(make_layout(conditional_return(make_shape(uint32_t(0), uint32_t(0), Int<1>{}), + ClusterShape{})), make_tile(typename TiledMMA_SF::AtomThrID{}))); + + using TMA_A = decltype(make_tma_atom_A_sm100( + GmemTiledCopyA{}, + make_tensor(recast_ptr(nullptr), repeat_like(StrideA{}, int32_t(0)), StrideA{}), + SmemLayoutA{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + ClusterLayout_VMNK{}) + ); + + using TMA_B = decltype(make_tma_atom_B_sm100( + GmemTiledCopyB{}, + make_tensor(recast_ptr(nullptr), repeat_like(StrideB{}, int32_t(0)), StrideB{}), + SmemLayoutB{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + ClusterLayout_VMNK{}) + ); + + using TMA_SFA = decltype(make_tma_atom_A_sm100( + GmemTiledCopySFA{}, + make_tensor(static_cast(nullptr), LayoutSFA{}), + SmemLayoutSFA{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + ClusterLayout_VMNK{}) + ); + + using TMA_SFB = decltype(make_tma_atom_B_sm100( + GmemTiledCopySFB{}, + make_tensor(static_cast(nullptr), LayoutSFB{}), + SmemLayoutSFB{}(_,_,_,cute::Int<0>{}), + TileShape_SF{}, + TiledMMA_SF{}, + ClusterLayoutSfb_VMNK{}) + ); + + TMA_A tma_load_a; + TMA_B tma_load_b; + TMA_SFA tma_load_sfa; + TMA_SFB tma_load_sfb; + TMA_A tma_load_a_fallback; + TMA_B tma_load_b_fallback; + TMA_SFA tma_load_sfa_fallback; + TMA_SFB tma_load_sfb_fallback; + LayoutSFA layout_SFA; + LayoutSFB layout_SFB; + dim3 cluster_shape_fallback; + RuntimeDataTypeA runtime_data_type_a; + RuntimeDataTypeB runtime_data_type_b; + }; + + CUTLASS_DEVICE + CollectiveMma(Params const& params, ClusterShape cluster_shape, uint32_t block_rank_in_cluster) + : cluster_shape_(cluster_shape) + , block_rank_in_cluster_(block_rank_in_cluster) + , layout_SFA_(params.layout_SFA) + , layout_SFB_(params.layout_SFB) + , runtime_data_type_a_(params.runtime_data_type_a) + , runtime_data_type_b_(params.runtime_data_type_b) { + if constexpr (IsDynamicCluster) { + const bool is_fallback_cluster = (cute::size<0>(cluster_shape_) == params.cluster_shape_fallback.x && + cute::size<1>(cluster_shape_) == params.cluster_shape_fallback.y); + observed_tma_load_a_ = is_fallback_cluster ? ¶ms.tma_load_a_fallback : ¶ms.tma_load_a; + observed_tma_load_b_ = is_fallback_cluster ? ¶ms.tma_load_b_fallback : ¶ms.tma_load_b; + observed_tma_load_sfa_ = is_fallback_cluster ? ¶ms.tma_load_sfa_fallback : ¶ms.tma_load_sfa; + observed_tma_load_sfb_ = is_fallback_cluster ? ¶ms.tma_load_sfb_fallback : ¶ms.tma_load_sfb; + } + else { + observed_tma_load_a_ = ¶ms.tma_load_a; + observed_tma_load_b_ = ¶ms.tma_load_b; + observed_tma_load_sfa_ = ¶ms.tma_load_sfa; + observed_tma_load_sfb_ = ¶ms.tma_load_sfb; + } + } + + template + static constexpr Params + to_underlying_arguments( + ProblemShape const& problem_shape, + Arguments const& args, + [[maybe_unused]] void* workspace, + cutlass::KernelHardwareInfo const& hw_info = cutlass::KernelHardwareInfo{}) { + + // Optionally append 1s until problem shape is rank-4 (MNKL), in case it is only rank-3 (MNK) + auto problem_shape_MNKL = append<4>(problem_shape, 1); + auto [M,N,K,L] = problem_shape_MNKL; + + auto ptr_A = recast_ptr(args.ptr_A); + auto ptr_B = recast_ptr(args.ptr_B); + + Tensor tensor_a = make_tensor(ptr_A, make_layout(make_shape(M,K,L), args.dA)); + Tensor tensor_b = make_tensor(ptr_B, make_layout(make_shape(N,K,L), args.dB)); + auto cluster_shape = cutlass::detail::select_cluster_shape(ClusterShape{}, hw_info.cluster_shape); + + // Cluster layout for TMA construction + auto cluster_layout_vmnk = tiled_divide(make_layout(cluster_shape), make_tile(typename TiledMma::AtomThrID{})); + auto cluster_shape_fallback = cutlass::detail::select_cluster_shape(ClusterShape{}, hw_info.cluster_shape_fallback); + auto cluster_layout_vmnk_fallback = tiled_divide(make_layout(cluster_shape_fallback), make_tile(typename TiledMma::AtomThrID{})); + Tensor tensor_sfa = make_tensor(args.ptr_SFA, args.layout_SFA); + Tensor tensor_sfb = make_tensor(args.ptr_SFB, args.layout_SFB); + + // Cluster layout for TMA construction of SFB + auto cluster_layout_sfb_vmnk = tiled_divide(make_layout(cluster_shape), make_tile(typename TiledMMA_SF::AtomThrID{})); + auto cluster_layout_sfb_vmnk_fallback = tiled_divide(make_layout(cluster_shape_fallback), make_tile(typename TiledMMA_SF::AtomThrID{})); + + typename Params::TMA_A tma_load_a = make_tma_atom_A_sm100( + GmemTiledCopyA{}, + tensor_a, + SmemLayoutA{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + cluster_layout_vmnk); + + typename Params::TMA_B tma_load_b = make_tma_atom_B_sm100( + GmemTiledCopyB{}, + tensor_b, + SmemLayoutB{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + cluster_layout_vmnk); + + typename Params::TMA_A tma_load_a_fallback = make_tma_atom_A_sm100( + GmemTiledCopyA{}, + tensor_a, + SmemLayoutA{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + cluster_layout_vmnk_fallback); + + typename Params::TMA_B tma_load_b_fallback = make_tma_atom_B_sm100( + GmemTiledCopyB{}, + tensor_b, + SmemLayoutB{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + cluster_layout_vmnk_fallback); + + typename Params::TMA_SFA tma_load_sfa = make_tma_atom_A_sm100( + GmemTiledCopySFA{}, + tensor_sfa, + SmemLayoutSFA{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + cluster_layout_vmnk); + + typename Params::TMA_SFB tma_load_sfb = make_tma_atom_B_sm100( + GmemTiledCopySFB{}, + tensor_sfb, + SmemLayoutSFB{}(_,_,_,cute::Int<0>{}), + TileShape_SF{}, + TiledMMA_SF{}, + cluster_layout_sfb_vmnk); + + typename Params::TMA_SFA tma_load_sfa_fallback = make_tma_atom_A_sm100( + GmemTiledCopySFA{}, + tensor_sfa, + SmemLayoutSFA{}(_,_,_,cute::Int<0>{}), + TileShape{}, + TiledMma{}, + cluster_layout_vmnk_fallback); + + typename Params::TMA_SFB tma_load_sfb_fallback = make_tma_atom_B_sm100( + GmemTiledCopySFB{}, + tensor_sfb, + SmemLayoutSFB{}(_,_,_,cute::Int<0>{}), + TileShape_SF{}, + TiledMMA_SF{}, + cluster_layout_sfb_vmnk_fallback); + + return { + tma_load_a, + tma_load_b, + tma_load_sfa, + tma_load_sfb, + tma_load_a_fallback, + tma_load_b_fallback, + tma_load_sfa_fallback, + tma_load_sfb_fallback, + args.layout_SFA, + args.layout_SFB, + hw_info.cluster_shape_fallback, + args.runtime_data_type_a, + args.runtime_data_type_b + }; + } + + template + static bool + can_implement( + ProblemShape const& problem_shape, + [[maybe_unused]] Arguments const& args) { + auto problem_shape_MNKL = append<4>(problem_shape, 1); + auto [M,N,K,L] = problem_shape_MNKL; + + constexpr int tma_alignment_bits_A = cutlass::detail::get_input_alignment_bits(); + constexpr int tma_alignment_bits_B = cutlass::detail::get_input_alignment_bits(); + + bool implementable = true; + constexpr int min_tma_aligned_elements_A = tma_alignment_bits_A / cute::sizeof_bits::value; + implementable = implementable && cutlass::detail::check_alignment(cute::make_shape(M,K,L), StrideA{}); + constexpr int min_tma_aligned_elements_B = tma_alignment_bits_B / cute::sizeof_bits::value; + implementable = implementable && cutlass::detail::check_alignment(cute::make_shape(N,K,L), StrideB{}); + + // Check for SFA SFB layout requirement + const auto layout_sfa_ref = take<0,2>(Sm1xxBlkScaledConfig::tile_atom_to_shape_SFA(problem_shape_MNKL)); + // SHADOW: N = 224 tiles read SFB from the padded virtual-N layout (tile t's rows at virtual 256t..) + const auto layout_sfb_ref = [&]() { + if constexpr (IsCtaN224) { + return take<0,2>(Sm1xxBlkScaledConfig::tile_atom_to_shape_SFB( + make_shape(M, ((N + 223) / 224) * 256, K, L))); + } else if constexpr (IsCtaN160) { + return take<0,2>(Sm1xxBlkScaledConfig::tile_atom_to_shape_SFB( + make_shape(M, ((N + 159) / 160) * 256, K, L))); + } else { + return take<0,2>(Sm1xxBlkScaledConfig::tile_atom_to_shape_SFB(problem_shape_MNKL)); + } + }(); + + implementable = implementable && (layout_sfa_ref == take<0,2>(args.layout_SFA)); + if (!implementable) { + CUTLASS_TRACE_HOST(" CAN IMPLEMENT: layout_SFA mismatch, layout_SFA needs to be K-major\n"); + } + + implementable = implementable && (layout_sfb_ref == take<0,2>(args.layout_SFB)); + if (!implementable) { + CUTLASS_TRACE_HOST(" CAN IMPLEMENT: layout_SFB mismatch, layout_SFB needs to be K-major\n"); + } + + if (!implementable) { + CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Problem Size doesn't meet the minimum alignment requirements for TMA.\n"); + } + return implementable; + } + + /// Issue Tma Descriptor Prefetch -- ideally from a single thread for best performance + CUTLASS_DEVICE void + prefetch_tma_descriptors() { + cute::prefetch_tma_descriptor(observed_tma_load_a_->get_tma_descriptor()); + cute::prefetch_tma_descriptor(observed_tma_load_b_->get_tma_descriptor()); + cute::prefetch_tma_descriptor(observed_tma_load_sfa_->get_tma_descriptor()); + cute::prefetch_tma_descriptor(observed_tma_load_sfb_->get_tma_descriptor()); + } + + /// Construct A Single Stage's Accumulator Shape + CUTLASS_DEVICE static + auto + partition_accumulator_shape() { + auto acc_shape = partition_shape_C(TiledMma{}, take<0,2>(TileShape{})); // ((MMA_TILE_M,MMA_TILE_N),MMA_M,MMA_N) + + return acc_shape; + } + + template + CUTLASS_DEVICE static + auto + slice_accumulator(TmemStorage tmem_storage, int stage) { + return cute::make_tuple(tmem_storage.accumulators(_,_,_,stage)); + } + + template + CUTLASS_DEVICE static + auto + init_tmem_tensors(EpilogueTile epi_tile) { + TiledMma tiled_mma; + auto acc_shape = partition_accumulator_shape(); + // ((MMA_TILE_M,MMA_TILE_N),MMA_M,MMA_N,ACC_PIPE) where ACC_PIPE=2 so we can double buffer our accumulators for mainloop and epilogue. + Tensor accumulators = cutlass::detail::make_sm100_accumulator( + tiled_mma, acc_shape, EpilogueTile{}); + Tensor tCtSFA = make_tensor(shape(SmemLayoutAtomSFA{})); + Tensor tCtSFB = make_tensor(shape(SmemLayoutAtomSFB{})); + + TmemStorage tmem_storage; + tmem_storage.accumulators = accumulators; + tmem_storage.tCtSFA = tCtSFA; + tmem_storage.tCtSFB = tCtSFB; + + return tmem_storage; + } + + template + CUTLASS_DEVICE static + void + set_tmem_offsets(TmemStorage& tmem_storage, uint32_t tmem_base_addr) { + tmem_storage.accumulators.data() = tmem_base_addr; + tmem_storage.tCtSFA.data() = tmem_storage.accumulators.data().get() + cutlass::detail::find_tmem_tensor_col_offset(tmem_storage.accumulators); + tmem_storage.tCtSFB.data() = tmem_storage.tCtSFA.data().get() + cutlass::detail::find_tmem_tensor_col_offset(tmem_storage.tCtSFA); + } + + /// Set up the data needed by this collective for load. + /// Return tuple element contain + /// gA_mkl - The tiled tma tensor for input A + /// gB_nkl - The tiled tma tensor for input B + /// tAgA_mkl - partitioned gmem tensor for A + /// tBgB_nkl - partitioned gmem tensor for B + /// tAsA - partitioned smem tensor for A + /// tBsB - partitioned smem tensor for B + /// tAgSFA_mkl - partitioned gmem tensor for SFA + /// tBgSFB_nkl - partitioned gmem tensor for SFB + /// tAsSFA - partitioned tmem tensor for SFA + /// tAsSFB - partitioned tmem tensor for SFB + /// mcast_mask_a - tma multicast mask for A + /// mcast_mask_b - tma multicast mask for B + /// mcast_mask_sfa - tma multicast mask for SFA + /// mcast_mask_sfb - tma multicast mask for SFB + template + CUTLASS_DEVICE auto + load_init( + ProblemShape_MNKL const& problem_shape_MNKL, + TensorStorage& shared_tensors) const { + using X = Underscore; + + // Separate out problem shape for convenience + auto [M,N,K,L] = problem_shape_MNKL; + + // Represent the full tensors -- get these from TMA + Tensor mA_mkl = observed_tma_load_a_->get_tma_tensor(make_shape(M,K,L)); + Tensor mB_nkl = observed_tma_load_b_->get_tma_tensor(make_shape(N,K,L)); + + // Tile the tensors and defer the slice + Tensor gA_mkl = local_tile(mA_mkl, TileShape{}, make_coord(_,_,_), Step<_1, X,_1>{}); // (BLK_M, BLK_K, m, k, l) + Tensor gB_nkl = local_tile(mB_nkl, TileShape{}, make_coord(_,_,_), Step< X,_1,_1>{}); // (BLK_N, BLK_K, n, k, l) + + // Represent the full tensor of Scale factors + Tensor mSFA_mkl = observed_tma_load_sfa_->get_tma_tensor(shape(layout_SFA_)); + auto mSFB_nkl = [=](){ + if constexpr (IsCtaN192) { + Tensor mSFB_tmp = observed_tma_load_sfb_->get_tma_tensor(shape(layout_SFB_)); + auto x = stride<0,1>(mSFB_tmp); + auto y = ceil_div(shape<0,1>(mSFB_tmp), 4); + auto new_shape = make_shape (make_shape( shape<0,0>(mSFB_tmp), + make_shape( make_shape(_2{}, _2{}), y)), shape<1>(mSFB_tmp), shape<2>(mSFB_tmp)); + auto new_stride = make_stride(make_stride(stride<0,0>(mSFB_tmp), + make_stride(make_stride( x, x), x*3)), stride<1>(mSFB_tmp), stride<2>(mSFB_tmp)); + return make_tensor(mSFB_tmp.data(), make_layout(new_shape, new_stride)); + } + else if constexpr (IsCtaN64) { + Tensor mSFB_tmp = observed_tma_load_sfb_->get_tma_tensor(shape(layout_SFB_)); + auto new_shape = make_shape(make_shape(shape<0,0>(mSFB_tmp), + make_shape(_2{} , shape<0,1>(mSFB_tmp))), shape<1>(mSFB_tmp), shape<2>(mSFB_tmp)); + auto new_stride = make_stride(make_stride(stride<0,0>(mSFB_tmp), + make_stride(_0{}, stride<0,1>(mSFB_tmp))), stride<1>(mSFB_tmp), stride<2>(mSFB_tmp)); + return make_tensor(mSFB_tmp.data(), make_layout(new_shape, new_stride)); + } + else { + return observed_tma_load_sfb_->get_tma_tensor(shape(layout_SFB_)); + } + }(); + + Tensor gSFA_mkl = local_tile(mSFA_mkl, TileShape{}, make_coord(_,_,_), Step<_1, X,_1>{}); // (TILE_M,TILE_K,m,k,l) + Tensor gSFB_nkl = local_tile(mSFB_nkl, TileShape_SF{}, make_coord(_,_,_), Step< X,_1,_1>{}); // (TILE_N,TILE_K,n,k,l) + + // Partition for this CTA + ThrMMA cta_mma = TiledMma{}.get_slice(blockIdx.x % size(typename TiledMma::AtomThrID{})); + + Tensor tCgA_mkl = cta_mma.partition_A(gA_mkl); // (MMA, MMA_M, MMA_K, m, k, l) + Tensor tCgB_nkl = cta_mma.partition_B(gB_nkl); // (MMA, MMA_N, MMA_K, n, k, l) + + Tensor sA = make_tensor(make_smem_ptr(shared_tensors.smem_A.begin()), SmemLayoutA{}); // (MMA,MMA_M,MMA_K,PIPE) + Tensor sB = make_tensor(make_smem_ptr(shared_tensors.smem_B.begin()), SmemLayoutB{}); // (MMA,MMA_N,MMA_K,PIPE) + + ThrMMA cta_mma_sfb = TiledMMA_SF{}.get_slice(blockIdx.x % size(typename TiledMMA_SF::AtomThrID{})); + Tensor tCgSFA_mkl = cta_mma.partition_A(gSFA_mkl); // (MMA, MMA_M, MMA_K, m, k, l) + Tensor tCgSFB_nkl = cta_mma_sfb.partition_B(gSFB_nkl); // (MMA, MMA_N, MMA_K, n, k, l) + + Tensor sSFA = make_tensor(make_smem_ptr(shared_tensors.smem_SFA.begin()), SmemLayoutSFA{}); + Tensor sSFB = make_tensor(make_smem_ptr(shared_tensors.smem_SFB.begin()), SmemLayoutSFB{}); + + // Define the CTA-in-cluster Layout and Coord + Layout cta_layout_mnk = make_layout(cluster_shape_); + Layout cta_layout_vmnk = tiled_divide(cta_layout_mnk, make_tile(typename TiledMma::AtomThrID{})); + auto cta_coord_vmnk = cta_layout_vmnk.get_flat_coord(block_rank_in_cluster_); + + Layout cta_layout_sfb_vmnk = tiled_divide(cta_layout_mnk, make_tile(typename TiledMMA_SF::AtomThrID{})); + auto cta_coord_sfb_vmnk = cta_layout_sfb_vmnk.get_flat_coord(block_rank_in_cluster_); + + // Project the cta_layout for tma_a along the n-modes + auto [tAgA_mkl, tAsA] = tma_partition(*observed_tma_load_a_, + get<2>(cta_coord_vmnk), make_layout(size<2>(cta_layout_vmnk)), + group_modes<0,3>(sA), group_modes<0,3>(tCgA_mkl)); + + // Project the cta_layout for tma_b along the m-modes + auto [tBgB_nkl, tBsB] = tma_partition(*observed_tma_load_b_, + get<1>(cta_coord_vmnk), make_layout(size<1>(cta_layout_vmnk)), + group_modes<0,3>(sB), group_modes<0,3>(tCgB_nkl)); + + // Project the cta_layout for tma_a along the n-modes + auto [tAgSFA_mkl, tAsSFA] = tma_partition(*observed_tma_load_sfa_, + get<2>(cta_coord_vmnk), make_layout(size<2>(cta_layout_vmnk)), + group_modes<0,3>(sSFA), group_modes<0,3>(tCgSFA_mkl)); + + // Project the cta_layout for tma_b along the m-modes + auto [tBgSFB_nkl, tBsSFB] = tma_partition(*observed_tma_load_sfb_, + get<1>(cta_coord_sfb_vmnk), make_layout(size<1>(cta_layout_sfb_vmnk)), + group_modes<0,3>(sSFB), group_modes<0,3>(tCgSFB_nkl)); + + // TMA Multicast Masks + uint16_t mcast_mask_a = create_tma_multicast_mask<2>(cta_layout_vmnk, cta_coord_vmnk); + uint16_t mcast_mask_b = create_tma_multicast_mask<1>(cta_layout_vmnk, cta_coord_vmnk); + uint16_t mcast_mask_sfa = create_tma_multicast_mask<2>(cta_layout_vmnk, cta_coord_vmnk); + uint16_t mcast_mask_sfb = create_tma_multicast_mask<1>(cta_layout_sfb_vmnk, cta_coord_sfb_vmnk); + + return LoadParams{ + size<3>(gA_mkl), // for scheduler + tAgA_mkl, tBgB_nkl, tAsA, tBsB, // for input tensor values + tAgSFA_mkl, tBgSFB_nkl, tAsSFA, tBsSFB, // for input scale factor tensor values + mcast_mask_a, mcast_mask_b, mcast_mask_sfa, mcast_mask_sfb}; // multicast masks + } + + /// Set up the data needed by this collective for mma compute. + template + CUTLASS_DEVICE auto + mma_init( + TmemStorage tmem_storage, + TensorStorage& shared_tensors) const { + + // Allocate "fragments/descriptors" for A and B matrices + Tensor sA = make_tensor(make_smem_ptr(shared_tensors.smem_A.begin()), SmemLayoutA{}); // (BLK_M,BLK_K,PIPE) + Tensor sB = make_tensor(make_smem_ptr(shared_tensors.smem_B.begin()), SmemLayoutB{}); // (BLK_N,BLK_K,PIPE) + + // Allocate "fragments/descriptors" for A and B matrices + Tensor tCrA = TiledMma::make_fragment_A(sA); // (MMA,MMA_M,MMA_K,PIPE) + Tensor tCrB = TiledMma::make_fragment_B(sB); // (MMA,MMA_N,MMA_K,PIPE) + + CUTE_STATIC_ASSERT_V(Int{} == size<3>(sA)); // PIPE + CUTE_STATIC_ASSERT_V(Int{} == size<3>(sB)); // PIPE + + // + // Scale Factor + // + Tensor tCtSFA = tmem_storage.tCtSFA; + Tensor tCtSFB = tmem_storage.tCtSFB; + // Setup smem descriptors for UTCCP + Tensor tCsSFA = make_tensor(make_smem_ptr(shared_tensors.smem_SFA.begin()), SmemLayoutSFA{}); + Tensor tCsSFB = make_tensor(make_smem_ptr(shared_tensors.smem_SFB.begin()), SmemLayoutSFB{}); + + // Make SMEM and TMEM tensors compact removing the zero strides to eliminate unnecessary copy instructions. + auto tCsSFA_compact = make_tensor(tCsSFA.data(), filter_zeros(tCsSFA.layout())); + auto tCtSFA_compact = make_tensor(tCtSFA.data(), filter_zeros(tCtSFA.layout())); + auto tCsSFB_compact = make_tensor(tCsSFB.data(), filter_zeros(tCsSFB.layout())); + auto tCtSFB_compact = make_tensor(tCtSFB.data(), filter_zeros(tCtSFB.layout())); + + // Create the SMEM to TMEM copy operations based on the MMA atom used (1CTA vs 2CTA) + using AtomThrID = typename TiledMma::AtomThrID; + using UtccpOp = cute::conditional_t<(decltype(cute::size(AtomThrID{}) == Int<2>{})::value), + SM100_UTCCP_4x32dp128bit_2cta, SM100_UTCCP_4x32dp128bit_1cta>; + auto tiled_copy_s2t_SFA = make_utccp_copy(UtccpOp{}, tCtSFA_compact); + auto tiled_copy_s2t_SFB = make_utccp_copy(UtccpOp{}, tCtSFB_compact); + + auto thr_copy_s2t_SFA = tiled_copy_s2t_SFA.get_slice(0); + auto thr_tCsSFA_compact_s2t_ = thr_copy_s2t_SFA.partition_S(tCsSFA_compact); + // SMEM to TMEM copy operation requires source SMEM operand to be an SMEM descriptor + auto thr_tCsSFA_compact_s2t = get_utccp_smem_desc_tensor(thr_tCsSFA_compact_s2t_); + auto thr_tCtSFA_compact_s2t = thr_copy_s2t_SFA.partition_D(tCtSFA_compact); + + auto thr_copy_s2t_SFB = tiled_copy_s2t_SFB.get_slice(0); + auto thr_tCsSFB_compact_s2t_ = thr_copy_s2t_SFB.partition_S(tCsSFB_compact); + // SMEM to TMEM copy operation requires source SMEM operand to be an SMEM descriptor + auto thr_tCsSFB_compact_s2t = get_utccp_smem_desc_tensor(thr_tCsSFB_compact_s2t_); + auto thr_tCtSFB_compact_s2t = thr_copy_s2t_SFB.partition_D(tCtSFB_compact); + + TiledMma tiled_mma; + + if constexpr (IsRuntimeDataType) { + // Update instruction descriptor according to runtime argument. + // Applying bitmask (0b111) to help compiler deduce that the conversion and assignment are safe. + tiled_mma.idesc_.a_format_ = uint8_t(runtime_data_type_a_) & 0b111; + tiled_mma.idesc_.b_format_ = uint8_t(runtime_data_type_b_) & 0b111; + } + + return MmaParams{ + tiled_mma, + tCrA, tCrB, tCtSFA, tCtSFB, + tiled_copy_s2t_SFA, thr_tCsSFA_compact_s2t, thr_tCtSFA_compact_s2t, + tiled_copy_s2t_SFB, thr_tCsSFB_compact_s2t, thr_tCtSFB_compact_s2t}; + } + + /// Perform a collective-scoped matrix multiply-accumulate + /// Producer Perspective + template < + class LoadParams, + class TileCoordMNKL, + class KTileIterator + > + CUTLASS_DEVICE auto + load( + MainloopPipeline mainloop_pipeline, + MainloopPipelineState mainloop_pipe_producer_state, + LoadParams const& load_inputs, + TileCoordMNKL const& cta_coord_mnkl, + KTileIterator k_tile_iter, int k_tile_count) { + + auto [unused_k_tiles, + tAgA_mkl, tBgB_nkl, tAsA, tBsB, + tAgSFA_mkl, tBgSFB_nkl, tAsSFA, tBsSFB, + mcast_mask_a, mcast_mask_b, mcast_mask_sfa, mcast_mask_sfb] = load_inputs; + + // slice out the work coord from partitioned tensors + Tensor tAgA = tAgA_mkl(_, get<0>(cta_coord_mnkl) / size(typename TiledMma::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgB = tBgB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + Tensor tAgSFA = tAgSFA_mkl(_, get<0>(cta_coord_mnkl) / size(typename TiledMma::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgSFB = tBgSFB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + + auto barrier_token = mainloop_pipeline.producer_try_acquire(mainloop_pipe_producer_state); + + // Issue the Mainloop loads + CUTLASS_PRAGMA_NO_UNROLL + while (k_tile_count > 0) { + // LOCK mainloop_pipe_producer_state for _writing_ + mainloop_pipeline.producer_acquire(mainloop_pipe_producer_state, barrier_token); + // Note: We don't synchronize the sf_pipeline for "Buffer_Empty". We use mainloop pipeline + // to do the synchronization at once. + + using BarrierType = typename MainloopPipeline::ProducerBarrierType; + BarrierType* tma_barrier = mainloop_pipeline.producer_get_barrier(mainloop_pipe_producer_state); + + int write_stage = mainloop_pipe_producer_state.index(); + ++mainloop_pipe_producer_state; + barrier_token = mainloop_pipeline.producer_try_acquire(mainloop_pipe_producer_state); + + if (cute::elect_one_sync()) { + copy(observed_tma_load_a_->with(*tma_barrier, mcast_mask_a), tAgA(_,*k_tile_iter), tAsA(_,write_stage)); + copy(observed_tma_load_b_->with(*tma_barrier, mcast_mask_b), tBgB(_,*k_tile_iter), tBsB(_,write_stage)); + copy(observed_tma_load_sfa_->with(*tma_barrier, mcast_mask_sfa), tAgSFA(_,*k_tile_iter), tAsSFA(_,write_stage)); + copy(observed_tma_load_sfb_->with(*tma_barrier, mcast_mask_sfb), tBgSFB(_,*k_tile_iter), tBsSFB(_,write_stage)); + } + + --k_tile_count; + ++k_tile_iter; + } + + return cute::make_tuple(mainloop_pipe_producer_state, k_tile_iter); + } + + /// Perform a Producer Epilogue to prevent early exit of ctas in a Cluster + CUTLASS_DEVICE void + load_tail(MainloopPipeline mainloop_pipeline, MainloopPipelineState mainloop_pipe_producer_state) { + // Issue the epilogue waits + // This helps avoid early exit of ctas in Cluster + // Waits for all stages to either be released (all + // Consumer UNLOCKs), or if the stage was never used + // then would just be acquired since the phase was + // still inverted from make_producer_start_state + mainloop_pipeline.producer_tail(mainloop_pipe_producer_state); + } + + /// Perform a collective-scoped matrix multiply-accumulate + /// Consumer Perspective + template < + class AccumulatorPipeline, + class FrgEngine, class FrgLayout, + class MmaParams, + class CtaTileCoord + > + CUTLASS_DEVICE auto + mma(cute::tuple pipelines, + cute::tuple pipeline_states, + cute::tuple> const& accumulators_pair, + MmaParams const& mma_inputs, + CtaTileCoord cta_tile_coord, + int k_tile_count + ) { + static_assert(is_tmem::value, "Accumulator must be tmem resident."); + static_assert(rank(FrgLayout{}) == 3, "Accumulator must be MMA-partitioned: (MMA, MMA_M, MMA_N)"); + + auto accumulators = get<0>(accumulators_pair); + auto [tiled_mma, + tCrA, tCrB, tCtSFA, tCtSFB, + tiled_copy_s2t_SFA, thr_tCsSFA_s2t, + thr_tCtSFA_s2t, tiled_copy_s2t_SFB, + thr_tCsSFB_s2t, thr_tCtSFB_s2t] = mma_inputs; + + auto [mainloop_pipeline, accumulator_pipeline] = pipelines; + auto [mainloop_pipe_consumer_state, accumulator_pipe_producer_state] = pipeline_states; + + auto tCtSFB_mma = [tCtSFB = tCtSFB, cta_tile_coord]() { + if constexpr (IsCtaN192) { + // If this is an ODD tile, shift the TMEM start address for N=192 case by two words (ignores first 64 columns of SFB) + auto tCtSFB_tmp = tCtSFB; + if (size<1>(cta_tile_coord) % 2 == 1) { + tCtSFB_tmp.data() = tCtSFB_tmp.data().get() + 2; + } + return tCtSFB_tmp; + } + else if constexpr (IsCtaN64) { + // Move in increments of 64 columns of SFB + auto tCtSFB_tmp = tCtSFB; + tCtSFB_tmp.data() = tCtSFB_tmp.data().get() + (size<1>(cta_tile_coord) % 2) * 2; + return tCtSFB_tmp; + } + else { + return tCtSFB; + } + }(); + + uint32_t skip_wait = k_tile_count <= 0; + auto barrier_token = mainloop_pipeline.consumer_try_wait(mainloop_pipe_consumer_state, skip_wait); + + // + // PIPELINED MAIN LOOP + // + tiled_mma.accumulate_ = UMMA::ScaleOut::Zero; + if constexpr (IsOverlappingAccum) { + // first iteration manual unroll for tmem overlap kernel + if (k_tile_count > 0) { + // WAIT on mainloop_pipe_consumer_state until its data are available + // (phase bit flips from mainloop_pipe_consumer_state.phase() value) + mainloop_pipeline.consumer_wait(mainloop_pipe_consumer_state, barrier_token); + + // Compute on k_tile + int read_stage = mainloop_pipe_consumer_state.index(); + // Save current mainlop pipeline read state + auto curr_mainloop_pipe_consumer_state = mainloop_pipe_consumer_state; + + // Advance mainloop_pipe + ++mainloop_pipe_consumer_state; + --k_tile_count; + skip_wait = k_tile_count <= 0; + // Peek at next iteration + barrier_token = mainloop_pipeline.consumer_try_wait(mainloop_pipe_consumer_state, skip_wait); + + if (cute::elect_one_sync()) { + copy(tiled_copy_s2t_SFA, thr_tCsSFA_s2t(_,_,_,_,read_stage), thr_tCtSFA_s2t); + copy(tiled_copy_s2t_SFB, thr_tCsSFB_s2t(_,_,_,_,read_stage), thr_tCtSFB_s2t); + } + + // Wait for tmem accumulator buffer to become empty with a flipped phase + accumulator_pipeline.producer_acquire(accumulator_pipe_producer_state); + + // Unroll the K mode manually so we can set scale C to 1 + CUTLASS_PRAGMA_UNROLL + for (int k_block = 0; k_block < size<2>(tCrA); ++k_block) { + // (V,M) x (V,N) => (V,M,N) + cute::gemm(tiled_mma.with(tiled_mma.accumulate_, + tCtSFA(_,_,k_block), + tCtSFB_mma(_,_,k_block)), + tCrA(_,_,k_block,read_stage), + tCrB(_,_,k_block,read_stage), + accumulators); + tiled_mma.accumulate_ = UMMA::ScaleOut::One; + } + + mainloop_pipeline.consumer_release(curr_mainloop_pipe_consumer_state); + } + } + else { + // Wait for tmem accumulator buffer to become empty with a flipped phase + accumulator_pipeline.producer_acquire(accumulator_pipe_producer_state); + } + + CUTLASS_PRAGMA_NO_UNROLL + while (k_tile_count > 0) { + // WAIT on mainloop_pipe_consumer_state until its data are available + // (phase bit flips from mainloop_pipe_consumer_state.phase() value) + mainloop_pipeline.consumer_wait(mainloop_pipe_consumer_state, barrier_token); + + // Compute on k_tile + int read_stage = mainloop_pipe_consumer_state.index(); + // Save current mainlop pipeline read state + auto curr_mainloop_pipe_consumer_state = mainloop_pipe_consumer_state; + + // Advance mainloop_pipe + ++mainloop_pipe_consumer_state; + --k_tile_count; + skip_wait = k_tile_count <= 0; + // Peek at next iteration + barrier_token = mainloop_pipeline.consumer_try_wait(mainloop_pipe_consumer_state, skip_wait); + + if (cute::elect_one_sync()) { + copy(tiled_copy_s2t_SFA, thr_tCsSFA_s2t(_,_,_,_,read_stage), thr_tCtSFA_s2t); + copy(tiled_copy_s2t_SFB, thr_tCsSFB_s2t(_,_,_,_,read_stage), thr_tCtSFB_s2t); + } + + // Unroll the K mode manually so we can set scale C to 1 + CUTLASS_PRAGMA_UNROLL + for (int k_block = 0; k_block < size<2>(tCrA); ++k_block) { + // (V,M) x (V,N) => (V,M,N) + cute::gemm(tiled_mma.with(tiled_mma.accumulate_, + tCtSFA(_,_,k_block), + tCtSFB_mma(_,_,k_block)), + tCrA(_,_,k_block,read_stage), + tCrB(_,_,k_block,read_stage), + accumulators); + tiled_mma.accumulate_ = UMMA::ScaleOut::One; + } + + mainloop_pipeline.consumer_release(curr_mainloop_pipe_consumer_state); + } + + return mainloop_pipe_consumer_state; + } + +protected: + + typename Params::TMA_A const* observed_tma_load_a_{nullptr}; + typename Params::TMA_B const* observed_tma_load_b_{nullptr}; + typename Params::TMA_SFA const* observed_tma_load_sfa_{nullptr}; + typename Params::TMA_SFB const* observed_tma_load_sfb_{nullptr}; + + LayoutSFA layout_SFA_; + LayoutSFB layout_SFB_; + RuntimeDataTypeA runtime_data_type_a_{}; + RuntimeDataTypeB runtime_data_type_b_{}; + + ClusterShape cluster_shape_; + uint32_t block_rank_in_cluster_; +}; + +///////////////////////////////////////////////////////////////////////////////////////////////// + +} // namespace cutlass::gemm::collective + +///////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/kernels/Quant/019_nvfp4_grouped_query_attention/src/kernel.cu b/kernels/Quant/019_nvfp4_grouped_query_attention/src/kernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..2f91615752f2e8737192073f18f15422fa0863f2 --- /dev/null +++ b/kernels/Quant/019_nvfp4_grouped_query_attention/src/kernel.cu @@ -0,0 +1,9777 @@ +// B2SM160: M<=256 batched QKV GEMM 2SM 256x160 tiles (70 pair tiles vs 60 x 192) with padded per-slice SFB; shadowed array collective. Bit-identical. +constexpr int CALIB_REMEASURE_TAG = 5; +// ===================================================================================== +// NVFP4 Grouped-Query Attention forward for B200 (sm_100a). +// +// Pipeline (all custom kernels except the GEMM, which is a CUTLASS sm100 block-scaled +// tcgen05 NVFP4 kernel used as a building block): +// 1. amax_kernel : global |x| max of the bf16 hidden states (atomicMax on float bits) +// 3. weight prep : extra CTAs of the x-quant launch (quant_wprep_kernel; they skip the PDL wait and +// overlap the amax pass; no side stream / join) +// ONE launch swizzling all 4 weight scale matrices into the blocked SF layout +// (for 128 < S < 2048 the O-proj scale part runs instead in the idle warps 14-15 +// of attn_tc_kernel, overlapped with attention -> off the critical path) +// (vectorized: 16 B loads of 4 rows, transposed into 16 B atom chunks) +// (q|k|v into one buffer, O separately) + writing the grouped-GEMM device args. +// The fp4 weights are never copied: the Q/K/V projections run as ONE 3-group +// ptr-array CUTLASS GEMM reading q_w/k_w/v_w in place, writing column slices of +// the fused [M,10240] buffer (per-group alpha scalar in the EVT epilogue). +// 5. rope_kernel : RoPE in bf16 arithmetic on the K column range only (Q is rotated in smem inside +// the attention kernel right after its TMA load) +// (vectorized: 8 dims / thread, 16-byte loads + stores, coalesced head rows). +// PDL: all launches after the first use programmatic dependent launch (griddepcontrol.wait/ +// launch_dependents in the custom kernels, CUTLASS GDC in the GEMMs) to hide launch/prologue gaps. +// 6. attn_tc_kernel : persistent causal GQA attention on tcgen05 UMMA (2 CTAs/SM, atomic tile +// counter, longest tiles first); TMA reads Q/K/V strided straight from the fused +// ===================================================================================== +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "kernel.h" +#ifndef QO_RING_DEFAULT +#define QO_RING_DEFAULT 0 +#endif +#ifdef STAGE_TIMING +int g_abl = 0; +#endif +static CUtensorMapL2promotion g_gemm_l2p = (CUtensorMapL2promotion)3; // L2_256B +// PER-OPERAND L2 promotion for M > 2048 (g_l2_split): descriptors whose global address lies inside a registered +// ACTIVATION range (xq / xsf of the QKV GEMMs, aq / asf of the O GEMM) get 128 B; every other map (fp4 weights, +// blocked weight scales, D stores) gets 256 B. Classified by the encode-time address (CUTLASS make_tma_copy_desc's +// local `gmem_address`; the file-scope `gmem_address` below = nullptr is what other users of the macro see). +// Activation ranges are fixed arena slices for a given M, so cached / rebound descriptors stay consistent. +// Cache hint only -> bit-identical results. +static bool g_l2_split = false; +static const char* g_act_lo[4] = {}; +static size_t g_act_n[4] = {}; +static const void* gmem_address = nullptr; +static inline void l2_set_act(int i, const void* p, size_t n) { g_act_lo[i] = (const char*)p; g_act_n[i] = n; } +static inline CUtensorMapL2promotion l2p_for(const void* p) { + if (!g_l2_split) return g_gemm_l2p; + const char* c = (const char*)p; + for (int i = 0; i < 4; ++i) + if (g_act_lo[i] && c >= g_act_lo[i] && c < g_act_lo[i] + g_act_n[i]) return (CUtensorMapL2promotion)2; // 128B + return (CUtensorMapL2promotion)3; // 256B +} +#define CU_TENSOR_MAP_L2_PROMOTION_L2_128B (::l2p_for(gmem_address)) + +#include "cutlass/cutlass.h" +#include "cute/tensor.hpp" +#include "cutlass/numeric_types.h" +// ---- Large-M QKV wave-tail overlap: dependency-sync placement of the plain CUTLASS sm100 GEMM kernel ---- +// (pick_qkv == 2 chain: quant_x -> K/V GEMM -> Q GEMM -> rope_tail -> attention.) +// Inside sm100_gemm_tma_warpspecialized.hpp ONLY (function-like macros active while that header is parsed): +// * `scheduler.fetch_next_work(...)` -> `... | pdlhook::Hook{}`. For kernels whose epilogue type is +// tagged EarlyTrig (K/V GEMM, Q GEMM, O-proj T2SM256), a warp that fetches an INVALID next tile (its CTA holds its +// last tile) executes griddepcontrol.wait THEN launch_dependents (trigger only after the predecessor completed). +// * `cutlass::arch::wait_on_dependent_grids()` -> `gdc_wait_sel()`: a no-op for the Q GEMM +// (NoPreWait). Safe: the Q grid starts only after ALL K/V CTAs triggered, i.e. after quant_x completed. Each Q CTA's +// last-tile wait covers the K/V grid, so rope_tail (launched after all Q CTAs triggered) reads finished K/V without a +// pre-wait and waits for the Q GEMM at its end -> rope completion implies Q completion for attention. +#include "cutlass/workspace.h" +#include "cutlass/kernel_hardware_info.hpp" +#include "cutlass/detail/cluster.hpp" +#include "cutlass/arch/grid_dependency_control.h" +#include "cutlass/fast_math.h" +#include "cute/arch/cluster_sm90.hpp" +#include "cutlass/arch/arch.h" +#include "cutlass/arch/barrier.h" +#include "cutlass/arch/reg_reconfig.h" +#include "cutlass/gemm/gemm.h" +#include "cutlass/gemm/dispatch_policy.hpp" +#include "cutlass/gemm/kernel/gemm_universal_decl.h" +#include "cutlass/detail/mainloop_fusion_helper_scale_factor.hpp" +#include "cutlass/gemm/kernel/tile_scheduler.hpp" +#include "cutlass/gemm/kernel/sm100_tile_scheduler.hpp" +#include "cutlass/pipeline/pipeline.hpp" +#include "cutlass/detail/sm100_tmem_helper.hpp" +#include "cute/arch/tmem_allocator_sm100.hpp" +#include "cute/atom/mma_atom.hpp" +#include +// ================= TLDIAG (compiled out unless -DTLDIAG): device globaltimer chain timeline ================= +// Per launch signature (grid.x, block.x, dynamic smem) one slot: [0] key, [1] ~min CTA entry, [2] ~min post-wait, +// [3] max post-wait, [4] max CTA entry, [5] max warp exit. Min fields stored inverted (atomicMax of ~t, zero-init). +#ifdef TLDIAG +__device__ unsigned long long g_tl[32][6]; +template __device__ char tl_tag; // per-epilogue-type salt (distinguishes GEMM configs with equal launch dims) +__device__ __forceinline__ unsigned long long tl_now() { + unsigned long long t; asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); return t; +} +__device__ __forceinline__ int tl_slot(unsigned long long salt) { + unsigned dsm; asm volatile("mov.u32 %0, %%dynamic_smem_size;" : "=r"(dsm)); + const unsigned long long key = (((unsigned long long)dsm << 40) | ((unsigned long long)blockDim.x << 24) | gridDim.x) + + salt * 0x100000001B3ull; + int h = (int)((key * 0x9E3779B97F4A7C15ull) >> 59); + for (int k = 0; k < 32; ++k) { + const int i = (h + k) & 31; + const unsigned long long o = atomicCAS(&g_tl[i][0], 0ull, key); + if (o == 0ull || o == key) return i; + } + return 31; +} +__device__ __forceinline__ void tl_wait_rec(unsigned long long salt, bool any_warp) { + if (any_warp ? (threadIdx.x & 31) == 0 : threadIdx.x == 0) { + const unsigned long long t = tl_now(); const int s = tl_slot(salt); + atomicMax(&g_tl[s][2], ~t); atomicMax(&g_tl[s][3], t); } +} +struct TLGuard { + unsigned long long salt; + __device__ TLGuard(unsigned long long s_ = 0) : salt(s_) { + if (threadIdx.x == 0) { const unsigned long long t = tl_now(); const int s = tl_slot(salt); + atomicMax(&g_tl[s][1], ~t); atomicMax(&g_tl[s][4], t); } + } + __device__ ~TLGuard() { // CTA end ~ max over warp 0 and the last warp + if (threadIdx.x == 0 || threadIdx.x == blockDim.x - 32) { + const unsigned long long t = tl_now(); atomicMax(&g_tl[tl_slot(salt)][5], t); } + } +}; +#define TLG TLGuard tl_guard_ +#define TLW_REC() tl_wait_rec(0ull, false) +template +struct TLW : K { + CUTLASS_DEVICE void operator()(typename K::Params const& params, char* smem_buf) { + TLGuard g_((unsigned long long)&tl_tag); + K::operator()(params, smem_buf); + } +}; +#define TLWRAP(...) TLW<__VA_ARGS__> +#else +#define TLG do {} while (0) +#define TLW_REC() do {} while (0) +#define TLWRAP(...) __VA_ARGS__ +#endif +namespace pdlhook { +template struct EarlyTrig : std::false_type {}; +template struct NoPreWait : std::false_type {}; +template struct TrigFirst : std::false_type {}; // trigger-before-wait at the last tile (Q GEMM -> attention) +template struct Hook {}; +template struct HasValid : std::false_type {}; +template struct HasValid().is_valid())>> : std::true_type {}; +template +CUTLASS_DEVICE T operator|(T t, Hook) { + if constexpr (EarlyTrig::value) { + bool valid; + if constexpr (HasValid::value) valid = t.is_valid(); + else valid = cute::get<0>(t).is_valid(); // (WorkTileInfo, increment_pipe) tuple + if (!valid) { // this CTA holds its last tile + if constexpr (TrigFirst::value) { + cutlass::arch::launch_dependent_grids(); + cutlass::arch::wait_on_dependent_grids(); + } else { + cutlass::arch::wait_on_dependent_grids(); // predecessor complete + flushed BEFORE the trigger + cutlass::arch::launch_dependent_grids(); + } + } + } + return t; +} +// FUSED QKV GEMM tile rotation: physical N tile n' = (n + 32) % 40 of the CLC/raster tile n, applied to the CTA coordinate +// in EVERY role (load / MMA / epilogue) -> the K/V tiles (n' = 32..39, columns 8192..10239) are scheduled FIRST. +template struct NRot : std::false_type {}; +template struct NRotHook {}; +template +CUTLASS_HOST_DEVICE T operator|(T t, NRotHook) { + if constexpr (NRot::value) { + auto& n = cute::get<1>(t); + n = (n + 32) % 40; + } + return t; +} +} // namespace pdlhook +namespace cutlass::arch { +template +CUTLASS_DEVICE void gdc_wait_sel() { + if constexpr (!pdlhook::NoPreWait::value) { + wait_on_dependent_grids(); +#ifdef TLDIAG + tl_wait_rec((unsigned long long)&tl_tag, true); +#endif + } +} +} // namespace cutlass::arch +#define fetch_next_work(...) fetch_next_work(__VA_ARGS__) | ::pdlhook::Hook{} +#define wait_on_dependent_grids() gdc_wait_sel() +#define work_tile_to_cta_coord(...) work_tile_to_cta_coord(__VA_ARGS__) | ::pdlhook::NRotHook{} +#include "cutlass/gemm/kernel/sm100_gemm_tma_warpspecialized.hpp" +#undef work_tile_to_cta_coord +// Same dependency-sync hooks for the ptr-array sm100 kernels (grouped G2SM192 upstream, batched B2SM192 = patched +// array_pre.hpp): small/mid-M QKV GEMMs tagged EarlyTrig below. +#include "cutlass/gemm/kernel/sm100_gemm_array_tma_warpspecialized.hpp" +#include "array_pre.hpp" // patched CUTLASS batched kernel with host-precomputed TMA descriptors (B2SM192, M <= 512) +#undef wait_on_dependent_grids +#undef fetch_next_work +// Kernel wrapper: griddepcontrol.wait at the end of every CTA (see above; used by the K/V GEMM only). +template +struct TailWait : K { + CUTLASS_DEVICE void operator()(typename K::Params const& params, char* smem_buf) { + K::operator()(params, smem_buf); +#if defined(__CUDA_ARCH__) + asm volatile("griddepcontrol.wait;" ::: "memory"); +#endif + } +}; +// Kernel wrapper: griddepcontrol.launch_dependents at the START of every CTA (first half of the split O GEMM, M > 4096): +// the second quant_o half (no pre-wait, tail wait) may launch and run concurrently with this GEMM. Its launch implies +// this grid launched, i.e. every first-half quant_o CTA triggered after its own wait (attention complete + flushed). +template +struct HeadTrig : K { + CUTLASS_DEVICE void operator()(typename K::Params const& params, char* smem_buf) { +#if defined(__CUDA_ARCH__) + asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); +#endif + K::operator()(params, smem_buf); + } +}; +// ---- K-RoPE inside the Q GEMM (split chain mode 6, M <= 2048): replaces the separate rope_tail launch ---- +// The CUTLASS sm100 kernel's EpilogueLoad warp (warp 3) has no role here (no C source). After the base kernel returns +// for it (barrier init / cluster sync done), it waits for the K/V GEMM grid (griddepcontrol.wait: complete + flushed), +// then rotates K in place in the fused [M,10240] buffer. Work is claimed DYNAMICALLY from scal[7] (CLC: canceled +// clusters never run, so no static split). Counter re-zeroed by the front kernel each call after its wait. The claimer +// of chunk 0 also does rope_tail's per-call scalar reset scal[0..5] (all consumers complete / later in the chain). +struct RopeX { __nv_bfloat16* qkv; const __nv_bfloat16* cs; const __nv_bfloat16* sn; unsigned* scal; int M; int trig0 = 0; int kfuse = 0; }; +// ---- FUSED QKV GEMM (M = 4096, mode 2): K/V computed as extra N tiles of the Q GEMM (one launch). K-RoPE is applied by the +// epilogue-load warp (warp 3) once every K-column D store of the grid is complete: the epilogue's TMA-store issuer adds the +// element count of each K subtile store to g_kdone after cp.async.bulk.wait_group 0 + fence.proxy.async.global (release); +// warp 3 acquires g_kdone == M * 1024, then rotates K in place (chunks claimed from g_kchunk). Both counters are reset by +// amax_wp_kernel (first launch of every M > 2048 chain, after its griddepcontrol.wait). Device globals (no destructor). +__device__ unsigned g_kdone = 0u; +__device__ unsigned g_kchunk = 0u; +__device__ __forceinline__ uint32_t rq_bmul2(uint32_t a, uint32_t b) { + uint32_t d; asm("mul.rn.bf16x2 %0, %1, %2;" : "=r"(d) : "r"(a), "r"(b)); return d; +} +__device__ __forceinline__ uint32_t rq_badd2(uint32_t a, uint32_t b) { + uint32_t d; asm("add.rn.bf16x2 %0, %1, %2;" : "=r"(d) : "r"(a), "r"(b)); return d; +} +__device__ __forceinline__ void rope_in_q_warp(const RopeX& rx) { + const int lane = threadIdx.x & 31; + asm volatile("griddepcontrol.wait;" ::: "memory"); // K/V GEMM complete + flushed (front complete transitively) + const uint32_t n = (uint32_t)rx.M * 8u; + constexpr uint32_t CH = 64; // items per claimed chunk (2 per lane) +#pragma unroll 1 + for (;;) { + uint32_t c0 = 0u; + if (lane == 0) c0 = atomicAdd(rx.scal + 7, 1u); + c0 = __shfl_sync(0xffffffffu, c0, 0); + const uint32_t base = c0 * CH; + if (base >= n) break; + if (c0 == 0u && lane < 6) rx.scal[lane] = 0u; // per-call scalar reset (as rope_tail) +#pragma unroll 1 + for (int u = 0; u < 2; ++u) { + const uint32_t idx = base + (uint32_t)u * 32u + (uint32_t)lane; + if (idx >= n) break; + const int d = (int)(idx & 7u) * 8; + const size_t m = idx >> 3; + const uint4 vc1 = __ldg(reinterpret_cast(rx.cs + m * 128 + d)); + const uint4 vc2 = __ldg(reinterpret_cast(rx.cs + m * 128 + d + 64)); + const uint4 vs1 = __ldg(reinterpret_cast(rx.sn + m * 128 + d)); + const uint4 vs2 = __ldg(reinterpret_cast(rx.sn + m * 128 + d + 64)); + const uint32_t c1[4] = {vc1.x, vc1.y, vc1.z, vc1.w}, c2[4] = {vc2.x, vc2.y, vc2.z, vc2.w}; + const uint32_t s1n[4] = {vs1.x ^ 0x80008000u, vs1.y ^ 0x80008000u, vs1.z ^ 0x80008000u, vs1.w ^ 0x80008000u}; + const uint32_t s2[4] = {vs2.x, vs2.y, vs2.z, vs2.w}; + uint4* rowp = reinterpret_cast(rx.qkv + m * QKV_LD + 8192 + d); +#pragma unroll + for (int hb = 0; hb < 8; hb += 4) { + uint4 x1[4], x2[4]; +#pragma unroll + for (int v = 0; v < 4; ++v) { x1[v] = rowp[(hb + v) * 16]; x2[v] = rowp[(hb + v) * 16 + 8]; } +#pragma unroll + for (int v = 0; v < 4; ++v) { + const uint32_t a[4] = {x1[v].x, x1[v].y, x1[v].z, x1[v].w}, bb[4] = {x2[v].x, x2[v].y, x2[v].z, x2[v].w}; + uint32_t o1[4], o2[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + o1[j] = rq_badd2(rq_bmul2(a[j], c1[j]), rq_bmul2(bb[j], s1n[j])); // x1*cos1 - x2*sin1 + o2[j] = rq_badd2(rq_bmul2(bb[j], c2[j]), rq_bmul2(a[j], s2[j])); // x2*cos2 + x1*sin2 + } + rowp[(hb + v) * 16] = make_uint4(o1[0], o1[1], o1[2], o1[3]); + rowp[(hb + v) * 16 + 8] = make_uint4(o2[0], o2[1], o2[2], o2[3]); + } + } + } + } +} +__device__ __forceinline__ void rope_fused_warp(const RopeX& rx) { + const int lane = threadIdx.x & 31; + asm volatile("griddepcontrol.wait;" ::: "memory"); // front complete (scalar reset of the previous chain visible) + { + const unsigned target = (unsigned)rx.M * 1024u; // all K elements of this call stored + released + unsigned v, spins = 0u; + for (;;) { + asm volatile("ld.acquire.gpu.global.u32 %0, [%1];" : "=r"(v) : "l"(&g_kdone) : "memory"); + if (v >= target) break; + __nanosleep(spins < 256u ? 64 : 256); + if (++spins > (1u << 24)) __trap(); // never expected: fail loudly instead of hanging + } + } + const uint32_t n = (uint32_t)rx.M * 8u; + constexpr uint32_t CH = 64; +#pragma unroll 1 + for (;;) { + uint32_t c0 = 0u; + if (lane == 0) c0 = atomicAdd(&g_kchunk, 1u); + c0 = __shfl_sync(0xffffffffu, c0, 0); + const uint32_t base = c0 * CH; + if (base >= n) break; + if (c0 == 0u && lane < 6) rx.scal[lane] = 0u; // per-call scalar reset (as rope_tail) +#pragma unroll 1 + for (int u = 0; u < 2; ++u) { + const uint32_t idx = base + (uint32_t)u * 32u + (uint32_t)lane; + if (idx >= n) break; + const int d = (int)(idx & 7u) * 8; + const size_t m = idx >> 3; + const uint4 vc1 = __ldg(reinterpret_cast(rx.cs + m * 128 + d)); + const uint4 vc2 = __ldg(reinterpret_cast(rx.cs + m * 128 + d + 64)); + const uint4 vs1 = __ldg(reinterpret_cast(rx.sn + m * 128 + d)); + const uint4 vs2 = __ldg(reinterpret_cast(rx.sn + m * 128 + d + 64)); + const uint32_t c1[4] = {vc1.x, vc1.y, vc1.z, vc1.w}, c2[4] = {vc2.x, vc2.y, vc2.z, vc2.w}; + const uint32_t s1n[4] = {vs1.x ^ 0x80008000u, vs1.y ^ 0x80008000u, vs1.z ^ 0x80008000u, vs1.w ^ 0x80008000u}; + const uint32_t s2[4] = {vs2.x, vs2.y, vs2.z, vs2.w}; + uint4* rowp = reinterpret_cast(rx.qkv + m * QKV_LD + 8192 + d); +#pragma unroll + for (int hb = 0; hb < 8; hb += 4) { + uint4 x1[4], x2[4]; +#pragma unroll + for (int v = 0; v < 4; ++v) { x1[v] = __ldcg(rowp + (hb + v) * 16); x2[v] = __ldcg(rowp + (hb + v) * 16 + 8); } +#pragma unroll + for (int v = 0; v < 4; ++v) { + const uint32_t a[4] = {x1[v].x, x1[v].y, x1[v].z, x1[v].w}, bb[4] = {x2[v].x, x2[v].y, x2[v].z, x2[v].w}; + uint32_t o1[4], o2[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + o1[j] = rq_badd2(rq_bmul2(a[j], c1[j]), rq_bmul2(bb[j], s1n[j])); // x1*cos1 - x2*sin1 + o2[j] = rq_badd2(rq_bmul2(bb[j], c2[j]), rq_bmul2(a[j], s2[j])); // x2*cos2 + x1*sin2 + } + rowp[(hb + v) * 16] = make_uint4(o1[0], o1[1], o1[2], o1[3]); + rowp[(hb + v) * 16 + 8] = make_uint4(o2[0], o2[1], o2[2], o2[3]); + } + } + } + } +} +template +struct RopeInQ : K { + struct Params : K::Params { + RopeX rx{}; + Params() = default; + Params(typename K::Params const& p) : K::Params(p) {} + }; + CUTLASS_DEVICE void operator()(Params const& params, char* smem_buf) { +#if defined(__CUDA_ARCH__) + if (params.rx.trig0) asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); // see RopeX::trig0 +#endif + K::operator()(params, smem_buf); +#if defined(__CUDA_ARCH__) + if (cutlass::canonical_warp_idx_sync() == 3 && params.rx.qkv) { + if (params.rx.kfuse) rope_fused_warp(params.rx); else rope_in_q_warp(params.rx); + } +#endif + } +}; +#include "cutlass/epilogue/thread/linear_combination.h" +#include "cutlass/epilogue/thread/activation.h" +#include "cutlass/epilogue/fusion/operations.hpp" +#include "cutlass/epilogue/fusion/sm90_visitor_tma_warpspecialized.hpp" +#include "cutlass/epilogue/fusion/sm90_visitor_load_tma_warpspecialized.hpp" +#include "cutlass/epilogue/fusion/sm90_visitor_compute_tma_warpspecialized.hpp" +#include "cutlass/gemm/dispatch_policy.hpp" +namespace cute { +struct SM90_TMA_STORE_EF {}; +template +struct Copy_Traits : Copy_Traits { + template + CUTE_HOST_DEVICE friend constexpr void copy_unpack(Copy_Traits const& traits, Tensor const& src, + Tensor& dst) { + static_assert(is_smem::value, "Expected smem src for SM90_TMA_STORE_EF"); +#if defined(__CUDA_ARCH__) + const uint64_t desc = reinterpret_cast(traits.get_tma_descriptor()); + const uint32_t sp = cast_smem_ptr_to_uint(cute::raw_pointer_cast(src.data())); + auto crd = dst.data().coord_; + constexpr int R = decltype(rank(crd))::value; + auto c = append<5>(crd, 0); + const int32_t c0 = int32_t(get<0>(c)), c1 = int32_t(get<1>(c)), c2 = int32_t(get<2>(c)), c3 = int32_t(get<3>(c)), + c4 = int32_t(get<4>(c)); + uint64_t pol; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); + if constexpr (R == 1) { + asm volatile("cp.async.bulk.tensor.1d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%2}], [%1], %3;" + ::"l"(desc), "r"(sp), "r"(c0), "l"(pol) : "memory"); + } else if constexpr (R == 2) { + asm volatile("cp.async.bulk.tensor.2d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%2, %3}], [%1], %4;" + ::"l"(desc), "r"(sp), "r"(c0), "r"(c1), "l"(pol) : "memory"); + } else if constexpr (R == 3) { + asm volatile("cp.async.bulk.tensor.3d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%2, %3, %4}], [%1], %5;" + ::"l"(desc), "r"(sp), "r"(c0), "r"(c1), "r"(c2), "l"(pol) : "memory"); + } else if constexpr (R == 4) { + asm volatile("cp.async.bulk.tensor.4d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%2, %3, %4, %5}], [%1], %6;" + ::"l"(desc), "r"(sp), "r"(c0), "r"(c1), "r"(c2), "r"(c3), "l"(pol) : "memory"); + } else { + static_assert(R == 5, "TMA store rank"); + asm volatile("cp.async.bulk.tensor.5d.global.shared::cta.bulk_group.L2::cache_hint [%0, {%2, %3, %4, %5, %6}], [%1], %7;" + ::"l"(desc), "r"(sp), "r"(c0), "r"(c1), "r"(c2), "r"(c3), "r"(c4), "l"(pol) : "memory"); + } +#endif + } +}; +} // namespace cute +namespace evf { +template struct EvictFirst : std::false_type {}; +template struct Rebind { static constexpr bool ok = false; }; +template +struct Rebind, V>, L, T>> { + static constexpr bool ok = true; + using type = cute::TiledCopy, V>, L, T>; +}; +template struct KSig : std::false_type {}; +// FUSED QKV GEMM: after the TMA store of a K-column subtile (D columns [8192, 9216)) completes (writes performed), release +// its element count to g_kdone (consumed by rope_fused_warp). Called by the single store-issuing thread. +template +CUTE_HOST_DEVICE void ksig_after(S const& src, D const& dst) { +#if defined(__CUDA_ARCH__) + const int c0 = int(cute::get<0>(dst.data().coord_)); + if (c0 >= 8192 && c0 < 9216) { + // the store copy is executed by the whole (converged) epilogue warp, one lane issuing the bulk tensor store: every + // lane waits for its own bulk groups (the issuer's store fully performed), then ONE leader lane releases the count + const unsigned am = __activemask(); + asm volatile("cp.async.bulk.commit_group;" ::: "memory"); + asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); + asm volatile("fence.proxy.async.global;" ::: "memory"); + __syncwarp(am); + __threadfence(); + if ((int)(threadIdx.x & 31) == __ffs(am) - 1) atomicAdd(&g_kdone, (unsigned)cute::size(src)); + } +#endif +} +template +CUTE_HOST_DEVICE void sel_copy(A0&& a0, A&&... a) { + using T0 = std::remove_cv_t>; + if constexpr (KSig::value && Rebind::ok && sizeof...(A) == 2) { + cute::copy(static_cast(a0), a...); + ksig_after(a...); + } else if constexpr (EvictFirst::value && Rebind::ok) { + static_assert(sizeof(typename Rebind::type) == sizeof(T0), "layout-identical re-typed TMA store"); + cute::copy(reinterpret_cast::type const&>(a0), static_cast(a)...); + } else { + cute::copy(static_cast(a0), static_cast(a)...); + } +} +} // namespace evf +// dependencies of the epilogue header first (parsed WITHOUT the copy macro) +#include "cutlass/arch/barrier.h" +#include "cutlass/conv/convnd_problem_shape.hpp" +#include "cutlass/epilogue/dispatch_policy.hpp" +#include "cutlass/epilogue/collective/detail.hpp" +#include "cutlass/epilogue/thread/scale_type.h" +#include "cutlass/epilogue/fusion/callbacks.hpp" +#include "cutlass/epilogue/fusion/sm100_callbacks_tma_warpspecialized.hpp" +#include "cutlass/detail/layout.hpp" +#include "cutlass/detail/helper_macros.hpp" +#include "cutlass/trace.h" +#include "cutlass/conv/detail.hpp" +#include "cutlass/cuda_host_adapter.hpp" +namespace cutlass::epilogue::collective { template class CollectiveEpilogue; } +#define copy(...) ::evf::sel_copy(__VA_ARGS__) +#include "cutlass/epilogue/collective/sm100_epilogue_tma_warpspecialized.hpp" +#undef copy +#include "cutlass/gemm/collective/collective_builder.hpp" +#if !defined(NVFP4_SHADOW_N224) || !defined(NVFP4_SHADOW_N224_BUILDER) || !defined(NVFP4_SHADOW_ARRAY_N160) +#error "shadow sm100 block-scaled collective / builder (N = 224 tiles) not picked up" +#endif +#include "cutlass/epilogue/collective/collective_builder.hpp" +#include "cutlass/detail/sm100_blockscaled_layout.hpp" +#include "cutlass/gemm/device/gemm_universal_adapter.h" +#include "cutlass/gemm/kernel/gemm_universal.hpp" +#include "cutlass/arch/grid_dependency_control.h" +#include +#include +#include + +// ------------------------------------------------------------------------------------ +// Programmatic dependent launch (PDL). Every kernel of the chain (except the first) is launched with +// cudaLaunchAttributeProgrammaticStreamSerialization, so it can be scheduled while its predecessor is +// still draining. Each kernel executes griddepcontrol.wait (full completion + memory flush of the +// predecessor) BEFORE touching any global memory -> transitively ordered after the whole chain; work +// done before the wait is only launch / prologue (barrier init, TMEM alloc, tensormap prefetch). +// launch_dependents is issued right after the wait so the next kernel can get resident early. +// The CUTLASS GEMM uses its built-in GDC (wait before its mainloop loads) -> it MUST be compiled with +// CUTLASS_ENABLE_GDC_FOR_SM100, otherwise its wait would be a no-op and PDL would race. +// ------------------------------------------------------------------------------------ +#if defined(__CUDA_ARCH__) && !defined(CUTLASS_GDC_ENABLED) +#error "CUTLASS GDC must be enabled (-DCUTLASS_ENABLE_GDC_FOR_SM100=1) for the PDL launch chain" +#endif +__device__ __forceinline__ void pdl_wait() { asm volatile("griddepcontrol.wait;" ::: "memory"); TLW_REC(); } +__device__ __forceinline__ void pdl_trigger() { asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); } +static int g_fl_dev = 0; // current device of this call (set by set_cur_device) +typedef CUresult (*LaunchExFn)(const CUlaunchConfig*, CUfunction, void**, void**); +static LaunchExFn get_launch_ex() { + static LaunchExFn fn = nullptr; + static bool tried = false; + if (!tried) { + tried = true; + void* p = nullptr; + cudaDriverEntryPointQueryResult q; + if (cudaGetDriverEntryPointByVersion("cuLaunchKernelEx", &p, 12000, cudaEnableDefault, &q) == cudaSuccess && + q == cudaDriverEntryPointSuccess) + fn = reinterpret_cast(p); + else + cudaGetLastError(); + } + return fn; +} +static CUfunction cu_func_of(const void* sym) { + struct E { const void* s; int dev; CUfunction f; }; + constexpr int N = 128; + static E* tab = new E[N](); // heap, never destroyed + static int n = 0; + // HOST LAUNCH DIET: 64-entry direct-mapped front cache keyed by (symbol, device) -> O(1) hit per launch instead of a + // linear scan of the resolved-function table (5-7 launches per call, ~20 distinct symbols). Same CUfunction values + // (the cache only memoizes table entries) -> identical launches / bit-identical results. + constexpr int HC = 64; + static E* hc = new E[HC](); // heap, never destroyed + const uintptr_t hk = (reinterpret_cast(sym) >> 4) ^ ((uintptr_t)g_fl_dev * 0x9E37u); + E& h = hc[(hk ^ (hk >> 7)) & (HC - 1)]; + if (h.s == sym && h.dev == g_fl_dev && h.f) return h.f; + for (int i = 0; i < n; ++i) if (tab[i].s == sym && tab[i].dev == g_fl_dev) { h = tab[i]; return tab[i].f; } + if (n >= N) return nullptr; + cudaFunction_t f = nullptr; + if (cudaGetFuncBySymbol(&f, sym) != cudaSuccess || !f) { cudaGetLastError(); return nullptr; } + tab[n++] = E{sym, g_fl_dev, reinterpret_cast(f)}; + h = tab[n - 1]; + return reinterpret_cast(f); +} +// ---- STAGE_TIMING diag hook (compiled out unless -DSTAGE_TIMING; see the usage block in kernel.h) ---- +// While armed (st_arm), every launch of the chain (all custom kernels AND the CUTLASS GEMMs go through fast_launch) +// is preceded by a cudaEventRecord on its stream; st_collect() records the final event, synchronizes and writes one +// record per kernel: (stage label set by main.cpp, kernel name, grid, block, dyn smem, span in us). The event between +// two PDL launches serializes them (no programmatic overlap) -> spans are ISOLATED in-chain kernel times. +#ifdef STAGE_TIMING +#include +struct StRec { const void* sym; const char* stage; dim3 grid, block; size_t smem; unsigned long long salt; }; +static unsigned long long g_tl_salt = 0; +struct StTl { cudaEvent_t ev[64]; StRec rec[64]; int n = 0; bool on = false, init = false, noev = false; const char* stage = "?"; cudaStream_t st = 0; }; +static StTl& st_tl() { static StTl* s = new StTl(); return *s; } +void st_stage(const char* s) { st_tl().stage = s; } +void st_arm(cudaStream_t st) { + StTl& t = st_tl(); + if (!t.init) { for (int i = 0; i < 64; ++i) cudaEventCreate(&t.ev[i]); t.init = true; } + t.n = 0; t.on = true; t.noev = false; t.st = st; t.stage = "?"; +} +static void st_on_launch(const cudaLaunchConfig_t& cfg, const void* sym) { + StTl& t = st_tl(); + if (!t.on || t.n >= 63) return; + if (!t.noev) cudaEventRecord(t.ev[t.n], cfg.stream); + t.rec[t.n] = StRec{sym, t.stage, cfg.gridDim, cfg.blockDim, cfg.dynamicSmemBytes, g_tl_salt}; + g_tl_salt = 0; + ++t.n; +} +static void st_name(const void* sym, char* out, size_t n) { + const char* mn = nullptr; + snprintf(out, n, "?"); + if (cudaFuncGetName(&mn, sym) != cudaSuccess || !mn) { cudaGetLastError(); return; } + const char* p = mn; + if (p[0] == '_' && p[1] == 'Z') { + p += 2; + if (*p == 'N') ++p; + int len = 0; + while (*p >= '0' && *p <= '9') len = len * 10 + (*p++ - '0'); + if (len > 0 && !strncmp(p, "cutlass", 7) && len == 7) { snprintf(out, n, "G"); return; } + snprintf(out, n, "%.*s", len > 0 ? len : 0, p); + } else { + snprintf(out, n, "%s", mn); + } + static const char* tab[][2] = {{"amax_kernel", "amax"}, {"quant_wprep_ps_kernel", "qwp"}, {"amax_quant_fused_kernel", "aqf"}, + {"rope_kernel", "rope"}, {"rope_tail_kernel", "ropet"}, {"attn_s256_kernel", "s256"}, + {"attn_s512_kernel", "s512"}, {"attn_s512t_kernel", "s512t"}, {"attn_short64_kernel", "s64"}, + {"quant_ps_kernel", "qo"}, {"quant_ps2_kernel", "qo2"}, {"amax_wp_kernel", "amaxw"}, {"quant_ring_kernel", "qr"}, {"quant_o_ring_kernel", "qor"}}; + for (auto& e : tab) if (!strcmp(out, e[0])) { snprintf(out, n, "%s", e[1]); return; } +} +// Ends the armed window: final event, sync; ms[i] = span of launch i (until the next launch / the final event). +// Returns the number of launches recorded (0 if nothing was launched). +int st_collect(float* ms, int maxn) { + StTl& t = st_tl(); + t.on = false; + if (t.n == 0) return 0; + cudaEventRecord(t.ev[t.n], t.st); + cudaEventSynchronize(t.ev[t.n]); + const int n = t.n < maxn ? t.n : maxn; + for (int i = 0; i < n; ++i) { ms[i] = 0.f; cudaEventElapsedTime(&ms[i], t.ev[i], t.ev[i + 1]); } + return n; +} + +#ifdef TLDIAG +// Timeline window: launches recorded WITHOUT events (true PDL overlap); device slots reset in stream order. +void st_tl_arm(cudaStream_t st) { + st_arm(st); + st_tl().noev = true; + static unsigned long long z[32][6]; + cudaMemcpyToSymbolAsync(g_tl, z, sizeof(z), 0, cudaMemcpyHostToDevice, st); +} +// per launch i: entry-min, wait-min, wait-max, entry-max, exit-max in us relative to the first launch's entry (-1: none) +int st_tl_collect(float (*o)[5], int maxn) { + StTl& t = st_tl(); + t.on = false; t.noev = false; + cudaStreamSynchronize(t.st); + unsigned long long h[32][6]; + cudaMemcpyFromSymbol(h, g_tl, sizeof(h)); + const int n = t.n < maxn ? t.n : maxn; + unsigned long long t0 = ~0ull; + int sl[64]; + for (int i = 0; i < n; ++i) { + const unsigned long long key = (((unsigned long long)t.rec[i].smem << 40) | ((unsigned long long)t.rec[i].block.x << 24) | t.rec[i].grid.x) + t.rec[i].salt * 0x100000001B3ull; + sl[i] = -1; + for (int k = 0; k < 32; ++k) if (h[k][0] == key) sl[i] = k; + if (sl[i] >= 0 && h[sl[i]][1]) t0 = std::min(t0, ~h[sl[i]][1]); + } + for (int i = 0; i < n; ++i) { + for (int f = 0; f < 5; ++f) o[i][f] = -1.f; + if (sl[i] < 0) continue; + const unsigned long long* r = h[sl[i]]; + auto rel = [&](unsigned long long v) { return v ? (float)((double)(v - t0) * 1e-3) : -1.f; }; + o[i][0] = r[1] ? rel(~r[1]) : -1.f; + o[i][1] = r[2] ? rel(~r[2]) : -1.f; + o[i][2] = rel(r[3]); + o[i][3] = rel(r[4]); + o[i][4] = rel(r[5]); + } + return n; +} +#endif +// label of launch i of the last window: "" (GEMMs: "G") +void st_desc(int i, char* buf, size_t cap) { + StTl& t = st_tl(); + if (i < 0 || i >= t.n) { snprintf(buf, cap, "?"); return; } + char nm[96]; + st_name(t.rec[i].sym, nm, sizeof(nm)); + if (!strcmp(nm, "G")) snprintf(buf, cap, "G%u", t.rec[i].grid.x); + else snprintf(buf, cap, "%s", nm); +} +#endif +static cudaError_t fast_launch(const cudaLaunchConfig_t& cfg, const void* sym, void** args) { +#ifdef STAGE_TIMING + st_on_launch(cfg, sym); +#endif + LaunchExFn fn = get_launch_ex(); + CUfunction f = fn ? cu_func_of(sym) : nullptr; + if (!f) return cudaLaunchKernelExC(&cfg, sym, args); + CUlaunchConfig c = {}; + c.gridDimX = cfg.gridDim.x; c.gridDimY = cfg.gridDim.y; c.gridDimZ = cfg.gridDim.z; + c.blockDimX = cfg.blockDim.x; c.blockDimY = cfg.blockDim.y; c.blockDimZ = cfg.blockDim.z; + c.sharedMemBytes = (unsigned)cfg.dynamicSmemBytes; + c.hStream = reinterpret_cast(cfg.stream); + CUlaunchAttribute a[4]; + unsigned na = 0; + for (unsigned i = 0; i < cfg.numAttrs && i < 4; ++i) { + const cudaLaunchAttribute& s = cfg.attrs[i]; + a[na] = CUlaunchAttribute{}; + if (s.id == cudaLaunchAttributeClusterDimension) { + a[na].id = CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION; + a[na].value.clusterDim.x = s.val.clusterDim.x; + a[na].value.clusterDim.y = s.val.clusterDim.y; + a[na].value.clusterDim.z = s.val.clusterDim.z; + } else if (s.id == cudaLaunchAttributeProgrammaticStreamSerialization) { + a[na].id = CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_STREAM_SERIALIZATION; + a[na].value.programmaticStreamSerializationAllowed = s.val.programmaticStreamSerializationAllowed; + } else { + return cudaLaunchKernelExC(&cfg, sym, args); // unknown attribute: runtime path + } + ++na; + } + c.attrs = a; c.numAttrs = na; + return fn(&c, f, args, nullptr) == CUDA_SUCCESS ? cudaSuccess : cudaErrorLaunchFailure; +} +template static void* argp(T& v) { return const_cast(static_cast(&v)); } +template +static cudaError_t launch_tuple(const cudaLaunchConfig_t& cfg, const void* sym, Tup& t, std::index_sequence) { + void* ptrs[sizeof...(I) + 1] = {argp(std::get(t))..., nullptr}; + return fast_launch(cfg, sym, ptrs); +} +template +static void launch_k(void (*kern)(KArgs...), dim3 grid, dim3 block, size_t smem, cudaStream_t st, bool pdl, + Args&&... args) { + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = grid; cfg.blockDim = block; cfg.dynamicSmemBytes = smem; cfg.stream = st; + cudaLaunchAttribute attr[1]; + attr[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attr[0].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = attr; cfg.numAttrs = pdl ? 1 : 0; + { // kernel parameters converted to the exact kernel parameter types (as the runtime template does) + std::tuple...> t(std::forward(args)...); + launch_tuple(cfg, reinterpret_cast(kern), t, std::index_sequence_for{}); + } +} + +// ------------------------------------------------------------------------------------ +// 1. global amax +// ------------------------------------------------------------------------------------ +// Amax part of the fused amax+weight-prep launch: CTAs 0..nblk-1 of the grid (bid = blockIdx.x). +// ef_cut (M = 8192 path only, x > L2): loads of x elements [0, ef_cut) carry an L2::evict_first policy. quant_x re-reads +// x in REVERSE order right after this pass, i.e. the FRONT of x last; with x (134 MB) > L2 the front would be evicted +// anyway, so marking it evict_first lets the tail (re-read first by quant_x) survive in L2. Cache hint only -> bit-identical. +__device__ __forceinline__ void amax_body(const uint4* __restrict__ x, size_t n8, unsigned* amax_bits, int bid, int nblk, + size_t ef_cut = 0, bool el = false) { + // el (M <= 2048 fused amax->quant launch): x (<= 32 MB) is re-read by the quant phase of the SAME launch right after the + // grid barrier -> amax loads carry an L2::evict_last policy so the second read hits L2. Cache hint only -> bit-identical. + unsigned long long efpol = 0ull; + if (ef_cut) asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(efpol)); + else if (el) asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(efpol)); + auto ldx = [&](size_t k) -> uint4 { + if (k < ef_cut || el) { + uint4 r; + asm volatile("ld.global.nc.L2::cache_hint.v4.u32 {%0, %1, %2, %3}, [%4], %5;" + : "=r"(r.x), "=r"(r.y), "=r"(r.z), "=r"(r.w) : "l"(x + k), "l"(efpol)); + return r; + } + return __ldg(x + k); + }; + // Memory-level parallelism: 4 independent 16 B loads in flight per thread per iteration (the + // single-load loop reached only ~4.8 TB/s at M=8192, long-scoreboard bound). Loads at i, i+gs, i+2gs, + // i+3gs keep the grid streaming x front-to-back (quant_kernel's reverse-order L2 reuse relies on it). + // |bf16| max is taken on the raw bits (clear sign bit; non-negative bf16 order == integer order). + unsigned mb = 0u; + const size_t gs = (size_t)nblk * blockDim.x; + size_t i = bid * (size_t)blockDim.x + threadIdx.x; + // Instruction diet: packed unsigned 16-bit max (VIMNMX.U16x2) on the sign-cleared bf16 pairs, 2 ops per word + // (was 5: two masks, shift, two max). Same integer order as before -> bit-identical (incl. NaN patterns). + uint32_t m2 = 0u; + auto acc = [&](const uint4& v) { + m2 = __vmaxu2(m2, v.x & 0x7fff7fffu); + m2 = __vmaxu2(m2, v.y & 0x7fff7fffu); + m2 = __vmaxu2(m2, v.z & 0x7fff7fffu); + m2 = __vmaxu2(m2, v.w & 0x7fff7fffu); + }; + for (; i < n8; i += 8 * gs) { + const uint4 z = make_uint4(0u, 0u, 0u, 0u); + uint4 v[8]; + v[0] = ldx(i); +#pragma unroll + for (int j = 1; j < 8; ++j) v[j] = (i + j * gs < n8) ? ldx(i + j * gs) : z; +#pragma unroll + for (int j = 0; j < 8; ++j) acc(v[j]); + } + // Hierarchical max on the fp32 BIT patterns of |bf16| (non-negative -> uint order == float order): + // one redux.sync.max.u32 per warp (replaces the 5-step shuffle + FMNMX tree), smem, one redux + atomicMax per CTA. + mb = max(m2 & 0xffffu, m2 >> 16) << 16; + asm volatile("redux.sync.max.u32 %0, %0, 0xffffffff;" : "+r"(mb)); + __shared__ uint32_t red[32]; + if ((threadIdx.x & 31) == 0) red[threadIdx.x >> 5] = mb; + __syncthreads(); + if (threadIdx.x < 32) { + uint32_t w = threadIdx.x < (blockDim.x >> 5) ? red[threadIdx.x] : 0u; + asm volatile("redux.sync.max.u32 %0, %0, 0xffffffff;" : "+r"(w)); + if (threadIdx.x == 0) atomicMax(amax_bits, w); + } +} + +// ------------------------------------------------------------------------------------ +// 2. activation quantization (one thread = one 16-element block) +// ------------------------------------------------------------------------------------ +__device__ __forceinline__ uint32_t e2m1_code(float x) { + // Same thresholds (round-half-even) as BlockWiseScalerNVFP4._cast_to_fp4x2 + float a = fabsf(x); + uint32_t c = a <= 0.25f ? 0u : a < 0.75f ? 1u : a <= 1.25f ? 2u : a < 1.75f ? 3u + : a <= 2.5f ? 4u : a < 3.5f ? 5u : a <= 5.0f ? 6u : 7u; + return x < 0.f ? (c | 8u) : c; +} + +// 8 floats -> 8 packed e2m1 nibbles (element 0 in the lowest nibble), RNE + saturate to +-6. +__device__ __forceinline__ uint32_t cvt_e2m1x8(float a0, float a1, float a2, float a3, float a4, float a5, float a6, float a7) { + uint32_t r; + asm("{\n\t.reg .b8 b0, b1, b2, b3;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 b0, %2, %1;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 b1, %4, %3;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 b2, %6, %5;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 b3, %8, %7;\n\t" + "mov.b32 %0, {b0, b1, b2, b3};\n\t}" + : "=r"(r) : "f"(a0), "f"(a1), "f"(a2), "f"(a3), "f"(a4), "f"(a5), "f"(a6), "f"(a7)); + return r; +} + +// offset of scale (row r, k-block c) in the blocked SF layout (Kb = K/16, multiple of 4) +__device__ __forceinline__ size_t sf_offset(int r, int c, int Kb) { + return ((size_t)(r >> 7) * (Kb >> 2) + (c >> 2)) * 512 + (r & 31) * 16 + ((r >> 5) & 3) * 4 + (c & 3); +} + +// SF store vectorization: 4 consecutive k-blocks (c & 3 = 0..3, same row) of one blocked-SF atom row are 4 +// consecutive bytes. The 4 owning threads are 4 consecutive lanes (c = idx % Kb, Kb % 4 == 0, idx consecutive per +// lane) -> combine their bytes with 2 shuffles and let the lane with c & 3 == 0 write ONE aligned 32-bit word +// (4x fewer SF store instructions / partial-sector L2 writes; identical bytes). Must be called by the FULL warp. +__device__ __forceinline__ void sf_store4(uint8_t* __restrict__ xsf, size_t off, uint32_t sfb, int c, bool ok) { + uint32_t v = sfb | (__shfl_down_sync(0xffffffffu, sfb, 1) << 8); + v |= __shfl_down_sync(0xffffffffu, v, 2) << 16; + if (ok && (c & 3) == 0) *reinterpret_cast(xsf + off) = v; +} + +__device__ __forceinline__ void global_scales(const unsigned* amax_bits, float& genc, float& gdec) { + float amax = __uint_as_float(*amax_bits); + genc = 2688.0f / amax; // 448 * 6 / amax + genc = fminf(genc, FLT_MAX); + if (genc == 0.f) genc = 1.f; + gdec = 1.0f / genc; +} + +// Quantization body; bid / nblk = this CTA's index among the quant CTAs of the launch (the fused +// quant + weight-prep launch prepends weight-prep CTAs). +__device__ __forceinline__ void quant_body(const uint4* __restrict__ x, int M, int Mp, int K, const unsigned* amax_bits, + uint2* __restrict__ xq, uint8_t* __restrict__ xsf, + float* alpha_vec, int ncols, int n0, int n1, float w0, float w1, float w2, + int bid, int nblk) { + // L2 reuse: amax_kernel streams x front-to-back just before this kernel; when x exceeds L2 (M=8192: + // 134 MB > 126 MB) the FRONT of x is already evicted. Blocks are therefore processed in REVERSE order + // (CTA b handles chunk gridDim-1-b): the tail of x, read last by amax, is re-read first while still in L2. + const size_t idx = (size_t)(nblk - 1 - bid) * blockDim.x + threadIdx.x; + // COMPILE-TIME SPECIALIZATION: hidden_size K = 8192 is a problem constant (host-checked) -> Kb = 512 folds into + // shifts / masks / immediate compares (the runtime K argument is ignored). Same indices -> bit-identical. + (void)K; + constexpr int Kb = 8192 >> 4; + const uint32_t i32 = (uint32_t)idx; + const bool inr = idx < (size_t)Mp * Kb; + const int r = (int)(i32 >> 9); + const int c = (int)(i32 & (uint32_t)(Kb - 1)); + uint4 v0 = make_uint4(0u, 0u, 0u, 0u), v1 = v0; + if (inr && r < M) { + const uint4* px = x + idx * 2; + asm volatile("ld.global.nc.v4.u32 {%0, %1, %2, %3}, [%4];" : "=r"(v0.x), "=r"(v0.y), "=r"(v0.z), "=r"(v0.w) : "l"(px)); + asm volatile("ld.global.nc.v4.u32 {%0, %1, %2, %3}, [%4];" : "=r"(v1.x), "=r"(v1.y), "=r"(v1.z), "=r"(v1.w) : "l"(px + 1)); + } + unsigned ab; + asm volatile("ld.global.u32 %0, [%1];" : "=r"(ab) : "l"(amax_bits) : "memory"); + float genc, gdec; + { // == global_scales() + const float amax = __uint_as_float(ab); + genc = 2688.0f / amax; // 448 * 6 / amax + genc = fminf(genc, FLT_MAX); + if (genc == 0.f) genc = 1.f; + gdec = 1.0f / genc; + } + { + // alpha is written in PHYSICAL block order so it is ready as early as possible. + const size_t aidx = (size_t)bid * blockDim.x + threadIdx.x; + const float a0 = __bfloat162float(__float2bfloat16(gdec * w0)); + const float a1 = __bfloat162float(__float2bfloat16(gdec * w1)); + const float a2 = __bfloat162float(__float2bfloat16(gdec * w2)); + const size_t gs = (size_t)nblk * blockDim.x; +#pragma unroll 1 + for (size_t cc = aidx; cc < (size_t)ncols; cc += gs) alpha_vec[cc] = (int)cc < n0 ? a0 : (int)cc < n1 ? a1 : a2; + } + // SF padding rows M..Mp-1 (read by the GEMM's padded SF tiles): zero scales, no data (sfb stays 0). + // (Replaces the per-call at::zeros of the SF buffers -> the buffers live in a reused arena.) + uint32_t sfb = 0u; + if (inr && r < M) { + // Instruction diet (bit-identical to the scalar fp32 path): + // * bf16 -> fp32 is a pure bit move: even element = w << 16, odd element = w & 0xffff0000. + // * block |max| on bf16 bit patterns: abs = and 0x7fff7fff, max.bf16x2 tree (exact for finite values). + // * x * enc with packed mul.f32x2 (same RN fp32 product per lane), e2m1x2 cvt per pair, 4 bytes -> 1 word. + const uint32_t w[8] = {v0.x, v0.y, v0.z, v0.w, v1.x, v1.y, v1.z, v1.w}; + // packed |max| tree: max.xorsign.abs.bf16x2 takes |.| of both operands itself (no 8 abs-mask ANDs); + // result magnitude = max(|a|,|b|), sign bit cleared once at the end. Bit-identical for finite inputs. + uint32_t m01, m23, m45, m67; + asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(m01) : "r"(w[0]), "r"(w[1])); + asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(m23) : "r"(w[2]), "r"(w[3])); + asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(m45) : "r"(w[4]), "r"(w[5])); + asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(m67) : "r"(w[6]), "r"(w[7])); + asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(m01) : "r"(m01), "r"(m23)); + asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(m45) : "r"(m45), "r"(m67)); + asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(m01) : "r"(m01), "r"(m45)); + m01 &= 0x7fff7fffu; + // both halves non-negative bf16 -> integer max of the 16-bit patterns == float max + const float bmax = __uint_as_float(max(m01 << 16, m01 & 0xffff0000u)); + // torch computes `block_max / 6.0` (CPU-scalar divisor) as block_max * (1/6) in fp32 + float ds = (bmax * (1.0f / 6.0f)) * genc; + ds = fminf(ds, 448.0f); + __nv_fp8_e4m3 sf8(ds); // RNE, satfinite + float sf = float(sf8); + float enc = __frcp_rn(sf * gdec) /* IEEE RN reciprocal == RN(1/x) */; + enc = fminf(enc, FLT_MAX); + uint32_t q[2]; +#pragma unroll + for (int h = 0; h < 2; ++h) { + asm("{\n\t.reg .b8 b0, b1, b2, b3;\n\t" + ".reg .b32 e, o;\n\t" + ".reg .b64 p, sc;\n\t" + ".reg .f32 x0, x1;\n\t" + "mov.b64 sc, {%5, %5};\n\t" + // word j: even element (low half) -> fp32 bits w<<16, odd element (high half) -> w & 0xffff0000 + "shl.b32 e, %1, 16;\n\tand.b32 o, %1, 0xffff0000;\n\tmov.b64 p, {e, o};\n\t" + "mul.rn.f32x2 p, p, sc;\n\tmov.b64 {x0, x1}, p;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 b0, x1, x0;\n\t" + "shl.b32 e, %2, 16;\n\tand.b32 o, %2, 0xffff0000;\n\tmov.b64 p, {e, o};\n\t" + "mul.rn.f32x2 p, p, sc;\n\tmov.b64 {x0, x1}, p;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 b1, x1, x0;\n\t" + "shl.b32 e, %3, 16;\n\tand.b32 o, %3, 0xffff0000;\n\tmov.b64 p, {e, o};\n\t" + "mul.rn.f32x2 p, p, sc;\n\tmov.b64 {x0, x1}, p;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 b2, x1, x0;\n\t" + "shl.b32 e, %4, 16;\n\tand.b32 o, %4, 0xffff0000;\n\tmov.b64 p, {e, o};\n\t" + "mul.rn.f32x2 p, p, sc;\n\tmov.b64 {x0, x1}, p;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 b3, x1, x0;\n\t" + "mov.b32 %0, {b0, b1, b2, b3};\n\t}" + : "=r"(q[h]) : "r"(w[4 * h]), "r"(w[4 * h + 1]), "r"(w[4 * h + 2]), "r"(w[4 * h + 3]), "f"(enc)); + } + xq[idx] = make_uint2(q[0], q[1]); + sfb = sf8.__x; + } + sf_store4(xsf, sf_offset(r, c, Kb), sfb, c, inr); // all lanes (no early return before the shuffles) +} +// Pipelined quant phase of amax_quant_fused_kernel (MID-M front fix): same per-block math as quant_body (math section +// shared verbatim), but genc/gdec / alpha computed once per thread and the NEXT block's x loads issued before the +// current block is quantized (2 blocks = 64 B in flight per thread instead of one serialized L2 round trip per block). +// Block set / order-independent writes identical -> bit-identical xq / xsf / alpha. +// ENC TABLE fill (no barrier): tab[code] = fminf(__frcp_rn(float(e4m3(code)) * gdec), FLT_MAX), exactly the per-block +// encode-scale expression of quant_body / quant_blk -> a table lookup is bit-identical. Threads t, t+nthr, ... fill. +__device__ __forceinline__ void enc_tab_fill_n(float* tab, float gdec, int t, int nthr) { + for (int c = t; c < 256; c += nthr) { + __nv_fp8_e4m3 v; + v.__x = (__nv_fp8_storage_t)c; + tab[c] = fminf(__frcp_rn(float(v) * gdec), FLT_MAX); + } +} +__device__ __forceinline__ void quant_core(const uint4& v0, const uint4& v1, size_t idx, int M, float genc, const float* __restrict__ etab, + uint2* __restrict__ xq, uint8_t* __restrict__ xsf) { + constexpr int Kb = 8192 >> 4; + const uint32_t i32 = (uint32_t)idx; + const bool inr = true; + const int r = (int)(i32 >> 9); + const int c = (int)(i32 & (uint32_t)(Kb - 1)); + uint32_t sfb = 0u; + if (inr && r < M) { + // Instruction diet (bit-identical to the scalar fp32 path): + // * bf16 -> fp32 is a pure bit move: even element = w << 16, odd element = w & 0xffff0000. + // * block |max| on bf16 bit patterns: abs = and 0x7fff7fff, max.bf16x2 tree (exact for finite values). + // * x * enc with packed mul.f32x2 (same RN fp32 product per lane), e2m1x2 cvt per pair, 4 bytes -> 1 word. + const uint32_t w[8] = {v0.x, v0.y, v0.z, v0.w, v1.x, v1.y, v1.z, v1.w}; + // packed |max| tree: max.xorsign.abs.bf16x2 takes |.| of both operands itself (no 8 abs-mask ANDs); + // result magnitude = max(|a|,|b|), sign bit cleared once at the end. Bit-identical for finite inputs. + uint32_t m01, m23, m45, m67; + asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(m01) : "r"(w[0]), "r"(w[1])); + asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(m23) : "r"(w[2]), "r"(w[3])); + asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(m45) : "r"(w[4]), "r"(w[5])); + asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(m67) : "r"(w[6]), "r"(w[7])); + asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(m01) : "r"(m01), "r"(m23)); + asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(m45) : "r"(m45), "r"(m67)); + asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(m01) : "r"(m01), "r"(m45)); + m01 &= 0x7fff7fffu; + // both halves non-negative bf16 -> integer max of the 16-bit patterns == float max + const float bmax = __uint_as_float(max(m01 << 16, m01 & 0xffff0000u)); + // torch computes `block_max / 6.0` (CPU-scalar divisor) as block_max * (1/6) in fp32 + float ds = (bmax * (1.0f / 6.0f)) * genc; + ds = fminf(ds, 448.0f); + __nv_fp8_e4m3 sf8(ds); // RNE, satfinite + const float enc = etab[(uint32_t)sf8.__x]; // == fminf(__frcp_rn(float(sf8) * gdec), FLT_MAX) + uint32_t q[2]; +#pragma unroll + for (int h = 0; h < 2; ++h) { + asm("{\n\t.reg .b8 b0, b1, b2, b3;\n\t" + ".reg .b32 e, o;\n\t" + ".reg .b64 p, sc;\n\t" + ".reg .f32 x0, x1;\n\t" + "mov.b64 sc, {%5, %5};\n\t" + // word j: even element (low half) -> fp32 bits w<<16, odd element (high half) -> w & 0xffff0000 + "shl.b32 e, %1, 16;\n\tand.b32 o, %1, 0xffff0000;\n\tmov.b64 p, {e, o};\n\t" + "mul.rn.f32x2 p, p, sc;\n\tmov.b64 {x0, x1}, p;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 b0, x1, x0;\n\t" + "shl.b32 e, %2, 16;\n\tand.b32 o, %2, 0xffff0000;\n\tmov.b64 p, {e, o};\n\t" + "mul.rn.f32x2 p, p, sc;\n\tmov.b64 {x0, x1}, p;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 b1, x1, x0;\n\t" + "shl.b32 e, %3, 16;\n\tand.b32 o, %3, 0xffff0000;\n\tmov.b64 p, {e, o};\n\t" + "mul.rn.f32x2 p, p, sc;\n\tmov.b64 {x0, x1}, p;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 b2, x1, x0;\n\t" + "shl.b32 e, %4, 16;\n\tand.b32 o, %4, 0xffff0000;\n\tmov.b64 p, {e, o};\n\t" + "mul.rn.f32x2 p, p, sc;\n\tmov.b64 {x0, x1}, p;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 b3, x1, x0;\n\t" + "mov.b32 %0, {b0, b1, b2, b3};\n\t}" + : "=r"(q[h]) : "r"(w[4 * h]), "r"(w[4 * h + 1]), "r"(w[4 * h + 2]), "r"(w[4 * h + 3]), "f"(enc)); + } + xq[idx] = make_uint2(q[0], q[1]); + sfb = sf8.__x; + } + sf_store4(xsf, sf_offset(r, c, Kb), sfb, c, inr); +} + +// ------------------------------------------------------------------------------------ +// 3. weight prep (ONE launch, first kernel of the chain): no weight copies at all. +// The QKV projection is a 3-group ptr-array GEMM that reads q_w / k_w / v_w in place, so only the +// e4m3 scales need re-layout: rows 0..10239 of the q|k|v scale matrices -> one blocked SF buffer +// (8192 and 1024 are multiples of 128, so the 128-row SF blocks of q/k/v simply concatenate and +// group g's SFB pointer is an offset into it), rows 10240.. -> the O-proj scales (also Kb = 512). +// 4 consecutive k-blocks x 4 rows (r, r+32, r+64, r+96) are one contiguous 16 B chunk of the blocked layout. +// Block 0 also copies the grouped-GEMM argument arrays (problem shapes, pointers, strides, +// SF layouts; built on the host, passed by value) to device memory. +// ------------------------------------------------------------------------------------ +constexpr int ARG_BLOB_U4 = 96; // 1536 B max for the grouped-GEMM device argument arrays +struct ArgBlob { uint4 w[ARG_BLOB_U4]; }; +// 16 B stand-in for the fused small/mid-M front when the device argument arrays already hold this call's blob +// (blob_n = 0: nothing copied) -> 1520 B less kernel-parameter marshalling per launch. See launch_amax_wprep. +struct ArgBlob1 { uint4 w[1]; }; + +// Swizzle items: 1024 per 128-row block; rb 0..79 = q|k|v scales (needed by the QKV GEMM), rb 80..143 = O-proj +// scales (needed only by the O GEMM at the end of the chain). +constexpr int WP_ITEMS_QKV = 80 * 32 * 32, WP_ITEMS_ALL = 144 * 32 * 32; +// O-proj scale swizzle moved off the critical path: for 128 < S < 2048 the idle warps 14-15 of attn_tc_kernel +// do items WP_ITEMS_QKV..WP_ITEMS_ALL concurrently with the (compute-bound) attention; amax_wprep then only +// swizzles the q|k|v scales (16 of its 34 MB at M=1024 removed from the launch before quant_x). + +__device__ __forceinline__ void wprep_item(int j, const uint4* __restrict__ qs, const uint4* __restrict__ ks, + const uint4* __restrict__ vs, const uint4* __restrict__ os, + uint8_t* __restrict__ sfqkv, uint8_t* __restrict__ osf) { + const int lane_c = j & 3, lane_r = (j >> 2) & 7, cgh = (j >> 5) & 7, rgh = (j >> 8) & 3, rb = j >> 10; + const int c16 = cgh * 4 + lane_c; // 0..31 + const int rl = rgh * 8 + lane_r; // 0..31 + const uint4* src; uint8_t* dst; int rbl; + if (rb < 64) { src = qs + (size_t)rb * 128 * 32; dst = sfqkv; rbl = rb; } + else if (rb < 72) { src = ks + (size_t)(rb - 64) * 128 * 32; dst = sfqkv; rbl = rb; } + else if (rb < 80) { src = vs + (size_t)(rb - 72) * 128 * 32; dst = sfqkv; rbl = rb; } + else { src = os + (size_t)(rb - 80) * 128 * 32; dst = osf; rbl = rb - 80; } + uint4 w[4]; +#pragma unroll + for (int q = 0; q < 4; ++q) w[q] = __ldg(src + (size_t)(q * 32 + rl) * 32 + c16); + uint8_t* atom = dst + ((size_t)rbl * 128 + c16 * 4) * 512 + rl * 16; + *reinterpret_cast(atom + 0 * 512) = make_uint4(w[0].x, w[1].x, w[2].x, w[3].x); + *reinterpret_cast(atom + 1 * 512) = make_uint4(w[0].y, w[1].y, w[2].y, w[3].y); + *reinterpret_cast(atom + 2 * 512) = make_uint4(w[0].z, w[1].z, w[2].z, w[3].z); + *reinterpret_cast(atom + 3 * 512) = make_uint4(w[0].w, w[1].w, w[2].w, w[3].w); +} + +// ---- PADDED O-proj scale layout (O GEMM with 2SM 256x224 tiles, M == 2048): N-tile t's 224 weight rows live at +// VIRTUAL rows [256t, 256t+224) of the blocked SF buffer (virtual N = 256 * 37 = 9472 = 74 128-row blocks), so every +// tile's SFB starts at a 128-row block boundary. Item jv in [0, WP_ITEMS_OPAD): same per-item mapping as wprep_item +// over VIRTUAL row blocks; each of the 4 rows of a 16 B chunk loads its own real o_scale row (virtual padding rows +// 224..255 of a tile / rows >= 8192 are written as zero). Same bytes per real row -> bit-identical GEMM inputs. +constexpr int OPAD_ROWS = 256 * ((8192 + 223) / 224); // 9472 virtual rows +constexpr int WP_ITEMS_OPAD = (OPAD_ROWS / 128) * 32 * 32; // 74 blocks x 1024 items +__device__ __forceinline__ void wprep_o_vitem(int j, const uint4* __restrict__ os, uint8_t* __restrict__ osf) { + const int lane_c = j & 3, lane_r = (j >> 2) & 7, cgh = (j >> 5) & 7, rgh = (j >> 8) & 3, vb = j >> 10; + const int c16 = cgh * 4 + lane_c, rl = rgh * 8 + lane_r; + uint4 w[4]; +#pragma unroll + for (int q = 0; q < 4; ++q) { + const int vr = vb * 128 + q * 32 + rl; + const int ti = vr & 255, n = (vr >> 8) * 224 + ti; + w[q] = (ti < 224 && n < 8192) ? __ldg(os + (size_t)n * 32 + c16) : make_uint4(0u, 0u, 0u, 0u); + } + uint8_t* atom = osf + ((size_t)vb * 128 + c16 * 4) * 512 + rl * 16; + *reinterpret_cast(atom + 0 * 512) = make_uint4(w[0].x, w[1].x, w[2].x, w[3].x); + *reinterpret_cast(atom + 1 * 512) = make_uint4(w[0].y, w[1].y, w[2].y, w[3].y); + *reinterpret_cast(atom + 2 * 512) = make_uint4(w[0].z, w[1].z, w[2].z, w[3].z); + *reinterpret_cast(atom + 3 * 512) = make_uint4(w[0].w, w[1].w, w[2].w, w[3].w); +} +// ---- PADDED per-slice q|k|v scale layout of the 2SM 256x160 batched QKV GEMM (B2SM160, M <= 256): slice gg (1024 +// weight rows: Q0..Q7, K, V) occupies 1792 virtual rows (7 N tiles x 256); tile t's 160 rows sit at virtual rows 256t.., +// virtual padding rows / rows past the slice are zero. Same per-item mapping as wprep_o_vitem over virtual row blocks. +constexpr int S160_VROWS = 1792; +constexpr int WP_ITEMS_S160 = 10 * (S160_VROWS / 128) * 32 * 32; // 140 virtual 128-row blocks x 1024 items +__device__ __forceinline__ void wprep_s160_item(int j, const uint4* __restrict__ qs, const uint4* __restrict__ ks, + const uint4* __restrict__ vs, uint8_t* __restrict__ dst) { + const int lane_c = j & 3, lane_r = (j >> 2) & 7, cgh = (j >> 5) & 7, rgh = (j >> 8) & 3, vb = j >> 10; + const int c16 = cgh * 4 + lane_c, rl = rgh * 8 + lane_r; + const int gg = vb / (S160_VROWS / 128), vbl = vb - gg * (S160_VROWS / 128); + uint4 w[4]; +#pragma unroll + for (int q = 0; q < 4; ++q) { + const int vr = vbl * 128 + q * 32 + rl; + const int ti = vr >> 8, o = vr & 255, n = ti * 160 + o; + const int R = gg * 1024 + n; // global q|k|v row + const uint4* src = R < 8192 ? qs + (size_t)R * 32 : R < 9216 ? ks + (size_t)(R - 8192) * 32 : vs + (size_t)(R - 9216) * 32; + w[q] = (o < 160 && n < 1024) ? __ldg(src + c16) : make_uint4(0u, 0u, 0u, 0u); + } + uint8_t* atom = dst + ((size_t)vb * 128 + c16 * 4) * 512 + rl * 16; + *reinterpret_cast(atom + 0 * 512) = make_uint4(w[0].x, w[1].x, w[2].x, w[3].x); + *reinterpret_cast(atom + 1 * 512) = make_uint4(w[0].y, w[1].y, w[2].y, w[3].y); + *reinterpret_cast(atom + 2 * 512) = make_uint4(w[0].z, w[1].z, w[2].z, w[3].z); + *reinterpret_cast(atom + 3 * 512) = make_uint4(w[0].w, w[1].w, w[2].w, w[3].w); +} +// PADDED O-scale swizzle (256x224 O GEMM layout, see wprep_o_vitem), virtual items [j0, WP_ITEMS_OPAD) grid-strided by +// nthr, THREE items (12 x 16 B loads) in flight per thread before any store. Same per-item bytes as wprep_o_vitem. +__device__ __forceinline__ void wprep_o_vitems3(int j0, int nthr, const uint4* __restrict__ os, uint8_t* __restrict__ osf) { +#pragma unroll 1 + for (int jb = j0; jb < WP_ITEMS_OPAD; jb += 3 * nthr) { + uint4 w[3][4]; +#pragma unroll + for (int u = 0; u < 3; ++u) { + const int j = jb + u * nthr; + if (j < WP_ITEMS_OPAD) { + const int lane_c = j & 3, lane_r = (j >> 2) & 7, cgh = (j >> 5) & 7, rgh = (j >> 8) & 3, vb = j >> 10; + const int c16 = cgh * 4 + lane_c, rl = rgh * 8 + lane_r; +#pragma unroll + for (int q = 0; q < 4; ++q) { + const int vr = vb * 128 + q * 32 + rl; + const int ti = vr & 255, n = (vr >> 8) * 224 + ti; + w[u][q] = (ti < 224 && n < 8192) ? __ldg(os + (size_t)n * 32 + c16) : make_uint4(0u, 0u, 0u, 0u); + } + } + } +#pragma unroll + for (int u = 0; u < 3; ++u) { + const int j = jb + u * nthr; + if (j < WP_ITEMS_OPAD) { + const int lane_c = j & 3, lane_r = (j >> 2) & 7, cgh = (j >> 5) & 7, rgh = (j >> 8) & 3, vb = j >> 10; + const int c16 = cgh * 4 + lane_c, rl = rgh * 8 + lane_r; + uint8_t* atom = osf + ((size_t)vb * 128 + c16 * 4) * 512 + rl * 16; + *reinterpret_cast(atom + 0 * 512) = make_uint4(w[u][0].x, w[u][1].x, w[u][2].x, w[u][3].x); + *reinterpret_cast(atom + 1 * 512) = make_uint4(w[u][0].y, w[u][1].y, w[u][2].y, w[u][3].y); + *reinterpret_cast(atom + 2 * 512) = make_uint4(w[u][0].z, w[u][1].z, w[u][2].z, w[u][3].z); + *reinterpret_cast(atom + 3 * 512) = make_uint4(w[u][0].w, w[u][1].w, w[u][2].w, w[u][3].w); + } + } + } +} +// O-proj scale swizzle items [j0, WP_ITEMS_ALL) grid-strided by nthr, THREE items in flight per thread (12 x 16 B loads +// issued before any store): same per-item mapping / bytes as wprep_item -> bit-identical blocked SF layout. Used by the +// otherwise idle warp 6 of attn_short64 (few threads -> memory-level parallelism matters). +__device__ __forceinline__ void wprep_o_items3(int j0, int nthr, const uint4* __restrict__ os, uint8_t* __restrict__ osf) { +#pragma unroll 1 + for (int jb = j0; jb < WP_ITEMS_ALL; jb += 3 * nthr) { + uint4 w[3][4]; +#pragma unroll + for (int u = 0; u < 3; ++u) { + const int j = jb + u * nthr; + if (j < WP_ITEMS_ALL) { + const int lane_c = j & 3, lane_r = (j >> 2) & 7, cgh = (j >> 5) & 7, rgh = (j >> 8) & 3, rbl = (j >> 10) - 80; + const int c16 = cgh * 4 + lane_c, rl = rgh * 8 + lane_r; + const uint4* src = os + (size_t)rbl * 128 * 32; +#pragma unroll + for (int q = 0; q < 4; ++q) w[u][q] = __ldg(src + (size_t)(q * 32 + rl) * 32 + c16); + } + } +#pragma unroll + for (int u = 0; u < 3; ++u) { + const int j = jb + u * nthr; + if (j < WP_ITEMS_ALL) { + const int lane_c = j & 3, lane_r = (j >> 2) & 7, cgh = (j >> 5) & 7, rgh = (j >> 8) & 3, rbl = (j >> 10) - 80; + const int c16 = cgh * 4 + lane_c, rl = rgh * 8 + lane_r; + uint8_t* atom = osf + ((size_t)rbl * 128 + c16 * 4) * 512 + rl * 16; + *reinterpret_cast(atom + 0 * 512) = make_uint4(w[u][0].x, w[u][1].x, w[u][2].x, w[u][3].x); + *reinterpret_cast(atom + 1 * 512) = make_uint4(w[u][0].y, w[u][1].y, w[u][2].y, w[u][3].y); + *reinterpret_cast(atom + 2 * 512) = make_uint4(w[u][0].z, w[u][1].z, w[u][2].z, w[u][3].z); + *reinterpret_cast(atom + 3 * 512) = make_uint4(w[u][0].w, w[u][1].w, w[u][2].w, w[u][3].w); + } + } + } +} + +// Weight-prep part of the fused launch: CTAs n_amax.. of the grid (bid = blockIdx.x - n_amax, nblk of them). +// Swizzles items 0..nitems-1 (all 144 row blocks, or only the q|k|v ones when attention does the O part). +template +__device__ __forceinline__ void wprep_body(const uint4* __restrict__ qs, const uint4* __restrict__ ks, + const uint4* __restrict__ vs, const uint4* __restrict__ os, + uint8_t* __restrict__ sfqkv, uint8_t* __restrict__ osf, + const BT& blob, uint4* __restrict__ blob_dst, int blob_n, + int bid, int nblk, int nitems, + const uint4* __restrict__ kwp, const uint4* __restrict__ vwp, + uint4* __restrict__ kvw, uint8_t* __restrict__ sfqpad = nullptr, + uint8_t* __restrict__ sfb160 = nullptr) { + // Vectorized swizzle. Scales are row-major [rows][512 B] (Kb = 512 e4m3 per row = 32 uint4). + // Blocked layout: 512 B atom per (128-row block rb, 4-col group c4); inside an atom row r sits at + // (r&31)*16 + ((r>>5)&3)*4 + (c&3) -> rows rl, rl+32, rl+64, rl+96 of one c4 form ONE 16 B chunk. + // Thread item = (rb, rl = r&31, c16 = 16-col group): reads one uint4 (16 scales) from each of the + // 4 rows rb*128 + q*32 + rl, transposes, writes 4 uint4 (one per c4 = 4*c16 + i) at atom offset rl*16. + // Warp lanes = (rl&7) x (c16&3): reads 8 rows x 64 B contiguous, writes 128 B contiguous per atom. + if (bid == 0 && threadIdx.x < blob_n) blob_dst[threadIdx.x] = blob.w[threadIdx.x]; + const int stride = nblk * blockDim.x; + // unroll 1: under quant_wprep_kernel's 32-register cap (launch_bounds 256,8) an unrolled body (2 x 4 uint4 in + // flight) spilled 4 B to local memory (ptxas audit, -O3 + allow-expensive-optimizations). + if constexpr (MLP2) { + // Small-M fused amax->quant launch (64-register cap): TWO swizzle items per thread per iteration, all 8 x 16 B loads + // issued before any store (memory-level parallelism; the 1-item loop serialized one DRAM round trip per item while + // the grid barrier waited). Same per-item mapping / bytes as wprep_item -> bit-identical blocked SF layout. + // sfqpad != nullptr (Q GEMM with 2SM 256x224 tiles, M in {1024, 2048}): the Q scales (rows 0..8191) are written ONLY + // in the PADDED virtual-row layout (tile t's 224 rows at virtual rows 256t.., same as the O-scale padded layout, + // wprep_o_vitem) into sfqpad; the plain Q items of sfqkv are skipped (unread by that Q GEMM). K / V items unchanged. + int jstart = 0; + if (sfb160) { // B2SM160: ALL q|k|v scales only in the padded per-slice layout (plain sfqkv items unread -> skipped) +#pragma unroll 1 + for (int j = bid * blockDim.x + threadIdx.x; j < WP_ITEMS_S160; j += stride) wprep_s160_item(j, qs, ks, vs, sfb160); + jstart = 80 * 1024; + } else if (sfqpad) { +#pragma unroll 1 + for (int j = bid * blockDim.x + threadIdx.x; j < WP_ITEMS_OPAD; j += stride) wprep_o_vitem(j, qs, sfqpad); + jstart = 64 * 1024; + } +#pragma unroll 1 + for (int jb = jstart + bid * blockDim.x + threadIdx.x; jb < nitems; jb += 2 * stride) { + uint4 w[2][4]; + uint8_t* atom[2]; +#pragma unroll + for (int u = 0; u < 2; ++u) { + const int j = jb + u * stride; + atom[u] = nullptr; + if (j < nitems) { + const int lane_c = j & 3, lane_r = (j >> 2) & 7, cgh = (j >> 5) & 7, rgh = (j >> 8) & 3, rb = j >> 10; + const int c16 = cgh * 4 + lane_c, rl = rgh * 8 + lane_r; + const uint4* src; uint8_t* dst; int rbl; + if (rb < 64) { src = qs + (size_t)rb * 128 * 32; dst = sfqkv; rbl = rb; } + else if (rb < 72) { src = ks + (size_t)(rb - 64) * 128 * 32; dst = sfqkv; rbl = rb; } + else if (rb < 80) { src = vs + (size_t)(rb - 72) * 128 * 32; dst = sfqkv; rbl = rb; } + else { src = os + (size_t)(rb - 80) * 128 * 32; dst = osf; rbl = rb - 80; } +#pragma unroll + for (int q = 0; q < 4; ++q) w[u][q] = __ldg(src + (size_t)(q * 32 + rl) * 32 + c16); + atom[u] = dst + ((size_t)rbl * 128 + c16 * 4) * 512 + rl * 16; + } + } +#pragma unroll + for (int u = 0; u < 2; ++u) { + if (atom[u]) { + *reinterpret_cast(atom[u] + 0 * 512) = make_uint4(w[u][0].x, w[u][1].x, w[u][2].x, w[u][3].x); + *reinterpret_cast(atom[u] + 1 * 512) = make_uint4(w[u][0].y, w[u][1].y, w[u][2].y, w[u][3].y); + *reinterpret_cast(atom[u] + 2 * 512) = make_uint4(w[u][0].z, w[u][1].z, w[u][2].z, w[u][3].z); + *reinterpret_cast(atom[u] + 3 * 512) = make_uint4(w[u][0].w, w[u][1].w, w[u][2].w, w[u][3].w); + } + } + } + } else { +#pragma unroll 1 + for (int j = bid * blockDim.x + threadIdx.x; j < nitems; j += stride) wprep_item(j, qs, ks, vs, os, sfqkv, osf); + } + // Large-M QKV path (pick_qkv == 2): concatenate the fp4 K and V weights into ONE [2048, K/2] buffer so the + // K/V projection runs as a single PLAIN GEMM (no grouped ptr-array tensormap updates). 2 x 4 MB, 16 B per item. + // (Their blocked scales are already contiguous in sfqkv: K rows 8192.., V rows 9216..) + if (kvw) { + constexpr int NKV = 1024 * 4096 / 16; // uint4 per weight matrix + // Memory-level parallelism: 4 independent 16 B loads in flight per thread (all issued before any store), so the + // 8 MB copy (on the KV GEMM's critical path: it depends on this whole launch) finishes in ~1/4 of the serialized + // load->store round trips. Same bytes / destinations -> bit-identical. + constexpr int NKV2 = 2 * NKV; +#pragma unroll 1 + for (int j0 = bid * blockDim.x + threadIdx.x; j0 < NKV2; j0 += 4 * stride) { + uint4 w[4]; +#pragma unroll + for (int u = 0; u < 4; ++u) { + const int j = j0 + u * stride; + if (j < NKV2) w[u] = j < NKV ? __ldg(kwp + j) : __ldg(vwp + (j - NKV)); + } +#pragma unroll + for (int u = 0; u < 4; ++u) { + const int j = j0 + u * stride; + if (j < NKV2) kvw[j] = w[u]; + } + } + } +} + +// ---- Optional L2 weight prefetch (small/mid M, per-M autotuned on the host with a cold-L2 emulation) ---- +// Up to 4 byte ranges (QKV fp4 weights, then the O-proj fp4 weights) are pulled into L2 with +// cp.async.bulk.prefetch.L2 (16 KB chunks, L2::evict_last policy) by the first launch of the chain, so the +// QKV / O GEMMs read their B operands from L2 instead of HBM. Pure hint: no data dependence, no completion tracking. +struct L2Pf { const char* p[4]; unsigned long long n[4]; }; +__device__ __forceinline__ void l2pf_issue(const L2Pf& pf, int part, int nparts) { + constexpr unsigned long long CH = 16384; + unsigned long long pol; + asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol)); + unsigned long long base = 0; +#pragma unroll + for (int r = 0; r < 4; ++r) { // fully unrolled: constant indices keep pf in parameter space (no local copy) + if (!pf.p[r]) continue; + const unsigned long long nch = (pf.n[r] + CH - 1) / CH; + // global chunk index base + j distributed round-robin over all prefetching threads + unsigned long long j0 = (unsigned long long)((part - (long long)(base % nparts) + nparts) % nparts); +#pragma unroll 1 + for (unsigned long long j = j0; j < nch; j += nparts) { + const unsigned long long off = j * CH; + const uint32_t sz = (uint32_t)((pf.n[r] - off) < CH ? (pf.n[r] - off) : CH); + asm volatile("cp.async.bulk.prefetch.L2.global.L2::cache_hint [%0], %1, %2;" ::"l"(pf.p[r] + off), "r"(sz), "l"(pol) + : "memory"); + } + base += nch; + } +} + +// Amax-only launch (first kernel of the chain). The weight prep moved into the x-quant launch below. +// early != 0 (host: the dependent quant_wprep_ps does NOT swizzle osf, i.e. wp_items != WP_ITEMS_ALL): EARLY TRIGGER +// before the wait, so quant_wprep_ps (weight-prep CTAs + waiting quant CTAs) launches while the previous call's O GEMM +// tail still runs. Cross-call WAR audit of the dependent's pre-wait work (wprep CTAs never wait): they write sfqkv (read +// only by the previous call's QKV GEMMs), kvw (previous K/V GEMM), dev_args (previous QKV GEMM) -- all of which completed +// before the previous call's attention started, hence before the previous O GEMM triggered (EarlyTrig: wait, then +// trigger) and thus before this grid launched. osf (read by the previous O GEMM) is never written pre-wait (early == 0 +// then). Quant CTAs of quant_wprep_ps wait for THIS grid's completion, which follows this grid's own wait (previous +// chain complete) -> xq / xsf / alpha / chunk counter unchanged. Sync-only -> bit-identical. +__global__ void amax_kernel(const uint4* __restrict__ x, size_t n8, unsigned* amax_bits, int early, size_t ef_cut) { + TLG; + if (early) pdl_trigger(); + pdl_wait(); // previous call's chain done (rope re-zeroed amax) + if (!early) pdl_trigger(); // quant_wprep's weight-prep CTAs may start right away (they do not need the amax) + amax_body(x, n8, amax_bits, blockIdx.x, gridDim.x, ef_cut); +} +__global__ void amax_wp_kernel(const uint4* __restrict__ x, size_t n8, unsigned* amax_bits, size_t ef_cut, int n_wpc, + const uint4* __restrict__ qs, const uint4* __restrict__ ks, + const uint4* __restrict__ vs, const uint4* __restrict__ os, + uint8_t* __restrict__ sfqkv, uint8_t* __restrict__ osf, + const __grid_constant__ ArgBlob blob, uint4* __restrict__ blob_dst, int blob_n, + int wp_items, const uint4* __restrict__ kwp, const uint4* __restrict__ vwp, + uint4* __restrict__ kvw, const L2Pf pf) { + TLG; + pdl_trigger(); + pdl_wait(); // previous call's chain done (rope re-zeroed amax) + if (blockIdx.x == 0 && threadIdx.x == 0) { g_kdone = 0u; g_kchunk = 0u; } // fused QKV GEMM counters (this call) + if ((int)blockIdx.x < n_wpc) { // block-uniform: weight-prep CTA + if (pf.p[0]) l2pf_issue(pf, blockIdx.x * blockDim.x + threadIdx.x, n_wpc * blockDim.x); + wprep_body(qs, ks, vs, os, sfqkv, osf, blob, blob_dst, blob_n, blockIdx.x, n_wpc, wp_items, kwp, vwp, kvw); + return; + } + amax_body(x, n8, amax_bits, blockIdx.x - n_wpc, gridDim.x - n_wpc, ef_cut); +} +// Small-M fusion (M <= 512, x <= 8 MB, L2-resident): amax + weight prep + x quantization in ONE launch. +// Persistent grid (<= 4 CTAs/SM, all co-resident: 256 threads, <= 64 regs, ~128 B static smem) : +// phase A: amax_body over x (grid-stride, same body as amax_kernel) -> atomicMax, then each CTA arrives on a +// grid-barrier counter (bar_ctr = scal[3], re-zeroed each call by rope_kernel); +// phase B: weight-scale swizzle / grouped-GEMM args (independent of the amax) while the barrier fills; +// phase C: wait until all CTAs arrived, then quant_body over the virtual quant blocks vb = blockIdx.x, +// +gridDim.x, ... (identical per-block math / layout as quant_wprep_kernel -> bit-identical). +// Deadlock-free: the dependent QKV GEMM can only launch once every CTA of this grid has executed +// launch_dependents (each does right after its own griddepcontrol.wait), so no later kernel can occupy the +// SM slots a not-yet-resident CTA of this grid needs; the predecessor finishes independently. +template +__global__ void __launch_bounds__(256, 4) amax_quant_fused_kernel(const uint4* __restrict__ x, size_t n8, int M, int Mp, int K, + unsigned* amax_bits, unsigned* bar_ctr, + uint2* __restrict__ xq, uint8_t* __restrict__ xsf, + float* alpha_vec, int ncols, int n0, int n1, float w0, float w1, float w2, int n_q, + const uint4* __restrict__ qs, const uint4* __restrict__ ks, + const uint4* __restrict__ vs, const uint4* __restrict__ os, + uint8_t* __restrict__ sfqkv, uint8_t* __restrict__ osf, + const __grid_constant__ BT blob, uint4* __restrict__ blob_dst, int blob_n, + int wp_items, const uint4* __restrict__ kwp, const uint4* __restrict__ vwp, + uint4* __restrict__ kvw, const L2Pf pf, uint8_t* __restrict__ sfqpad, + uint8_t* __restrict__ sfb160) { + TLG; + // EARLY TRIGGER (before the wait): the QKV GEMM grid may launch / its CTAs get resident (barrier init, TMEM alloc, + // param-space tensormap prefetch) while the previous call's O GEMM tail still runs. Transitivity audit of the + // dependents' pre-wait work: QKV GEMMs (batched / grouped / split K/V) touch only kernel params + their private + // workspace before griddepcontrol.wait, then wait for THIS grid's completion, which happens only after this grid's + // own wait (previous chain complete). rope_kernel's pre-wait osf swizzle (overwrites what the previous O GEMM read) + // stays legal: rope launches only after every QKV GEMM CTA triggered AFTER its wait (EarlyTrig at last tile) => + // this grid complete => previous O GEMM complete. (Hence the QKV GEMM itself must NOT trigger before its wait.) + // Co-residency of the grid barrier: dependents launch only after every CTA of this grid executed the trigger, + // i.e. all CTAs resident. Sync-only -> bit-identical. + // VALIDITY AUDIT (cross-call WAR / RAW of the early trigger): + // * Pre-wait work of every QKV-GEMM dependent touches only kernel params (param-space TMA descriptors, prefetch), + // smem barriers, TMEM, and (grouped mode 3 only) its PRIVATE tensormap workspace wsq; xq / xsf / sfqkv / kvw / + // dev_args / alpha_qkv (all written by THIS grid after its wait) are read only after the GEMM's own + // griddepcontrol.wait (alpha lazily in the epilogue). NoPreWait Q GEMMs of the split chain launch only after every + // K/V CTA passed its wait (=> this grid complete). + // * Every buffer this grid writes (xq, xsf, sfqkv, osf when not deferred, kvw, dev_args, alpha_qkv, scal via atomics) + // is written only AFTER the wait below, i.e. after the previous call's O GEMM (reader of aq / asf / osf / alpha_o) + // completed. aq / asf / alpha_o / osf are rewritten later in this call only by kernels transitively after this wait + // (rope pre-wait osf: rope launches only after all QKV CTAs triggered post-wait; rope_tail likewise after K/V). + // * Grid-barrier co-residency: dependents launch only after ALL CTAs of this grid executed the trigger (= resident). + pdl_trigger(); + pdl_wait(); // previous call's chain done (rope re-zeroed amax / barrier counter) + if (blockIdx.x == 0 && threadIdx.x == 0) { amax_bits[7] = 0u; amax_bits[6] = 0u; } // [6]: attention K-RoPE grid barrier // RoPE-in-Q chunk counter (previous chain complete) + amax_body(x, n8, amax_bits, blockIdx.x, gridDim.x, 0, true); // evict_last x loads; ends with thread 0's atomicMax + // GENERATION-BASED grid barrier (validity hardening): the arrival returns the old count; this CTA waits until the + // count reaches the END of its generation, (old / grid + 1) * grid. With the per-call reset by rope (count 0 at entry) + // this is identical to the former "count >= grid" test; if a chain were ever aborted between this launch and the reset + // (count left at a multiple of grid), the next call still waits for all of ITS CTAs instead of passing immediately + // with a partial amax. Sync only -> bit-identical. + unsigned bar_target = 0u; + if (threadIdx.x == 0) { + unsigned old; + asm volatile("atom.release.gpu.global.add.u32 %0, [%1], 1;" : "=r"(old) : "l"(bar_ctr) : "memory"); + bar_target = (old / gridDim.x + 1u) * gridDim.x; + } + // optional L2 prefetch of the QKV / O GEMM weights (after the critical amax pass, overlapping wprep + barrier) + if (pf.p[0]) l2pf_issue(pf, blockIdx.x * blockDim.x + threadIdx.x, gridDim.x * blockDim.x); + wprep_body(qs, ks, vs, os, sfqkv, osf, blob, blob_dst, blob_n, blockIdx.x, gridDim.x, wp_items, kwp, vwp, kvw, sfqpad, sfb160); + if (threadIdx.x < 32) { + bar_target = __shfl_sync(0xffffffffu, bar_target, 0); + unsigned v, spins = 0u; + for (;;) { + asm volatile("ld.acquire.gpu.global.u32 %0, [%1];" : "=r"(v) : "l"(bar_ctr) : "memory"); + if (__any_sync(0xffffffffu, (int)(v - bar_target) >= 0)) break; // wrap-safe generation test + if (++spins > 4096u) __nanosleep(32); + } + __threadfence(); + } + __syncthreads(); // global amax final + visible to the whole CTA +#pragma unroll 1 + { + // virtual quant block vb (n_q = Mp*512/256 chunks, exactly covering Mp rows) -> physical chunk n_q-1-vb (as quant_body) + (void)K; + unsigned long long xefp; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(xefp)); + auto ldb = [&](int vb, uint4& a0, uint4& a1) { + a0 = make_uint4(0u, 0u, 0u, 0u); a1 = a0; + if (vb < n_q) { + const size_t idx = (size_t)(n_q - 1 - vb) * 256 + threadIdx.x; + if ((int)(idx >> 9) < M) { + const uint4* px = x + idx * 2; + // last use of x (L2-hot from the evict_last amax pass): evict_first so the lines are demoted. Cache hint only. + asm volatile("ld.global.nc.L2::cache_hint.v4.u32 {%0, %1, %2, %3}, [%4], %5;" : "=r"(a0.x), "=r"(a0.y), "=r"(a0.z), "=r"(a0.w) : "l"(px), "l"(xefp)); + asm volatile("ld.global.nc.L2::cache_hint.v4.u32 {%0, %1, %2, %3}, [%4], %5;" : "=r"(a1.x), "=r"(a1.y), "=r"(a1.z), "=r"(a1.w) : "l"(px + 1), "l"(xefp)); + } + } + }; + int vb = blockIdx.x; + uint4 v0, v1; + ldb(vb, v0, v1); + unsigned ab; + asm volatile("ld.global.u32 %0, [%1];" : "=r"(ab) : "l"(amax_bits) : "memory"); + float genc, gdec; + { // == global_scales() + const float amax = __uint_as_float(ab); + genc = 2688.0f / amax; + genc = fminf(genc, FLT_MAX); + if (genc == 0.f) genc = 1.f; + gdec = 1.0f / genc; + } + { // per-output-column alpha (same values as quant_body: depends only on the column) + const float a0 = __bfloat162float(__float2bfloat16(gdec * w0)); + const float a1 = __bfloat162float(__float2bfloat16(gdec * w1)); + const float a2 = __bfloat162float(__float2bfloat16(gdec * w2)); +#pragma unroll 1 + for (int cc = blockIdx.x * 256 + threadIdx.x; cc < ncols; cc += gridDim.x * 256) + alpha_vec[cc] = cc < n0 ? a0 : cc < n1 ? a1 : a2; + } + __shared__ float etab[256]; + enc_tab_fill_n(etab, gdec, threadIdx.x, 256); // blockDim == 256 + __syncthreads(); + if (M >= 2048) { + // M = 2048 front (fixed rule): TWO quant blocks per iteration (vb, vb + G) with the next pair prefetched + // (4 x 32 B of x in flight per thread instead of 2): the quant phase ran ~7 serialized L2 round trips per thread. + // Same blocks / per-block math (quant_core) / writes -> bit-identical. + const int G = (int)gridDim.x; + uint4 v2, v3; + ldb(vb + G, v2, v3); +#pragma unroll 1 + for (; vb < n_q; vb += 2 * G) { // block-uniform trip count / conditions + uint4 p0, p1, p2, p3; + ldb(vb + 2 * G, p0, p1); + ldb(vb + 3 * G, p2, p3); + quant_core(v0, v1, (size_t)(n_q - 1 - vb) * 256 + threadIdx.x, M, genc, etab, xq, xsf); + if (vb + G < n_q) quant_core(v2, v3, (size_t)(n_q - 1 - (vb + G)) * 256 + threadIdx.x, M, genc, etab, xq, xsf); + v0 = p0; v1 = p1; v2 = p2; v3 = p3; + } + } else { +#pragma unroll 1 + for (; vb < n_q; vb += gridDim.x) { // block-uniform trip count + uint4 p0, p1; + ldb(vb + gridDim.x, p0, p1); // prefetch the next block + quant_core(v0, v1, (size_t)(n_q - 1 - vb) * 256 + threadIdx.x, M, genc, etab, xq, xsf); + v0 = p0; v1 = p1; + } + } + } +} +template struct PkAlphaBf16 {}; +namespace cutlass::epilogue::fusion { +template +struct Sm90Compute : Sm90VisitorImpl<> { + using Sm90VisitorImpl<>::Sm90VisitorImpl; + struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { + template + CUTLASS_DEVICE Array + visit(Array const& frg_acc, int epi_v, int epi_m, int epi_n, + Array const& frg_alpha, Array const& frg_x) { + static_assert(FragmentSize % 2 == 0, "packed epilogue needs even fragments"); + static_assert(cute::is_same_v, "bf16 output"); + Array out; + uint32_t* o = reinterpret_cast(&out); + const float a = static_cast(frg_alpha[0]); // scalar broadcast: all lanes equal + uint32_t a2; + asm("cvt.rn.bf16x2.f32 %0, %1, %1;" : "=r"(a2) : "f"(a)); // exact (alpha is a bf16 value) + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < FragmentSize / 2; ++i) { + uint32_t b; + asm("cvt.rn.bf16x2.f32 %0, %1, %2;" : "=r"(b) : "f"(static_cast(frg_x[2 * i + 1])), + "f"(static_cast(frg_x[2 * i]))); + asm("mul.rn.bf16x2 %0, %1, %2;" : "=r"(o[i]) : "r"(b), "r"(a2)); + } + return out; + } + }; + template + CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs const& args) { + return ConsumerStoreCallbacks(); + } +}; +} // namespace cutlass::epilogue::fusion +// ---- PACKED per-column-alpha epilogue node (K/V GEMMs, CfgV): same as PkAlphaBf16 but alpha differs per element +// (per-column RowBroadcast, values bf16-EXACT: bf16(gdec * w_g) written by the x-quant kernels). The alpha pair is +// packed with one cvt.rn.bf16x2 (exact), the acc pair with one cvt.rn.bf16x2 (RNE), then one mul.rn.bf16x2 == +// bf16(fp32(alpha * bf16(acc))) (bf16*bf16 exact in fp32). Bit-identical to the multiplies(alpha, Identity->bf16) EVT. +template struct PkAlphaVecBf16 {}; +namespace cutlass::epilogue::fusion { +template +struct Sm90Compute : Sm90VisitorImpl<> { + using Sm90VisitorImpl<>::Sm90VisitorImpl; + struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { + template + CUTLASS_DEVICE Array + visit(Array const& frg_acc, int epi_v, int epi_m, int epi_n, + Array const& frg_alpha, Array const& frg_x) { + static_assert(FragmentSize % 2 == 0, "packed epilogue needs even fragments"); + static_assert(cute::is_same_v, "bf16 output"); + Array out; + uint32_t* o = reinterpret_cast(&out); + // SASS-audit diet: the K/V alpha vector (alpha3 + 4) is piecewise constant on 1024-column blocks (K alpha, then V + // alpha) and every visited fragment (FragmentSize = 64 = one 64-column epilogue subtile row, 64-aligned) lies inside + // one block -> ONE alpha cvt per fragment (frg_alpha[0]) instead of one smem alpha load + cvt per element pair. + // Same alpha value per element -> bit-identical. + static_assert(FragmentSize <= 64 && 1024 % FragmentSize == 0, "fragment must not straddle a K/V alpha block"); + uint32_t a2; + asm("cvt.rn.bf16x2.f32 %0, %1, %1;" : "=r"(a2) : "f"(static_cast(frg_alpha[0]))); // exact (bf16 value) + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < FragmentSize / 2; ++i) { + uint32_t b; + asm("cvt.rn.bf16x2.f32 %0, %1, %2;" : "=r"(b) : "f"(static_cast(frg_x[2 * i + 1])), + "f"(static_cast(frg_x[2 * i]))); + asm("mul.rn.bf16x2 %0, %1, %2;" : "=r"(o[i]) : "r"(b), "r"(a2)); + } + return out; + } + }; + template + CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs const& args) { + return ConsumerStoreCallbacks(); + } +}; +} // namespace cutlass::epilogue::fusion +using namespace cute; +namespace g { +using ElementA = cutlass::nv_float4_t; +using ElementB = cutlass::nv_float4_t; +using LayoutA = cutlass::layout::RowMajor; // A [M,K] K-major +using LayoutB = cutlass::layout::ColumnMajor; // B [N,K] K-major +using ElementC = void; // no source tensor +using ElementD = cutlass::bfloat16_t; +using LayoutC = cutlass::layout::RowMajor; +constexpr int AlignA = 32, AlignB = 32, AlignC = 8, AlignD = 8; +using Acc = float; +using DataT = typename ElementA::DataType; +using SFT = typename ElementA::ScaleFactorType; +namespace fu = cutlass::epilogue::fusion; +constexpr auto RN = cutlass::FloatRoundStyle::round_to_nearest; + +static int sm_count() { + static int n = 0; + if (n == 0) { int dev; cudaGetDevice(&dev); cudaDeviceGetAttribute(&n, cudaDevAttrMultiProcessorCount, dev); } + return n; +} + +// CUTLASS adapter run() with launch_with_pdl = true; newer CUTLASS has an extra kernel_index argument. +template +struct HasKernelIndex : std::false_type {}; +template +struct HasKernelIndex().run(std::declval(), + (cutlass::CudaHostAdapter*)nullptr, int32_t(0), true))>> + : std::true_type {}; +template +static cutlass::Status run_pdl_adapter(G& gemm, cudaStream_t st) { + if constexpr (HasKernelIndex::value) return gemm.run(st, (cutlass::CudaHostAdapter*)nullptr, int32_t(0), true); + else return gemm.run(st, (cutlass::CudaHostAdapter*)nullptr, true); +} +// Host-overhead fast path: +// launch the already-initialized kernel directly from its cached Params with the SAME launch configuration the +// adapter uses (grid from get_grid_shape, cached per Params build; static cluster shape; dynamic smem = +// SharedStorageSize, set by initialize(); PDL attribute). Identical kernel + params -> bit-identical results. +template +static cutlass::Status run_pdl(G& gemm, cudaStream_t st, dim3& grid, bool& gvalid) { + using K = typename G::GemmKernel; + auto const& params = gemm.params(); + if (!gvalid) { grid = G::get_grid_shape(params); gvalid = true; } + using CS = typename K::ClusterShape; + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = grid; cfg.blockDim = K::get_block_shape(); cfg.dynamicSmemBytes = (size_t)K::SharedStorageSize; + cfg.stream = st; + cudaLaunchAttribute at[2]; + at[0].id = cudaLaunchAttributeClusterDimension; + at[0].val.clusterDim.x = (unsigned)cute::size<0>(CS{}); + at[0].val.clusterDim.y = (unsigned)cute::size<1>(CS{}); + at[0].val.clusterDim.z = (unsigned)cute::size<2>(CS{}); + at[1].id = cudaLaunchAttributeProgrammaticStreamSerialization; + at[1].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = at; cfg.numAttrs = 2; + void* pp_[2] = {const_cast(static_cast(¶ms)), nullptr}; +#ifdef TLDIAG + { void* tp = nullptr; if (cudaGetSymbolAddress(&tp, tl_tag) == cudaSuccess) g_tl_salt = (unsigned long long)tp; else cudaGetLastError(); } +#endif + return fast_launch(cfg, reinterpret_cast(&cutlass::device_kernel), pp_) == cudaSuccess ? cutlass::Status::kSuccess + : cutlass::Status::kErrorInternal; +} + +// Same direct launch for kernels run from an explicitly held Params copy (batched GemmArrayPre configs with the +// host-precomputed descriptor table). Replaces the static GemmUniversalAdapter::run(params, ...), whose static-cluster +// path re-runs ClusterLauncher::init (cudaGetLastError + cudaFuncSetAttribute) and get_grid_shape on EVERY call. +// Same kernel, params, grid, block, cluster dims, dynamic smem (attribute set once by initialize()) -> bit-identical. +template +static cutlass::Status run_pdl_p(typename G::GemmKernel::Params const& params, cudaStream_t st, dim3& grid, bool& gvalid) { + using K = typename G::GemmKernel; + if (!gvalid) { grid = G::get_grid_shape(params); gvalid = true; } + using CS = typename K::ClusterShape; + cudaLaunchConfig_t cfg = {}; + cfg.gridDim = grid; cfg.blockDim = K::get_block_shape(); cfg.dynamicSmemBytes = (size_t)K::SharedStorageSize; + cfg.stream = st; + cudaLaunchAttribute at[2]; + at[0].id = cudaLaunchAttributeClusterDimension; + at[0].val.clusterDim.x = (unsigned)cute::size<0>(CS{}); + at[0].val.clusterDim.y = (unsigned)cute::size<1>(CS{}); + at[0].val.clusterDim.z = (unsigned)cute::size<2>(CS{}); + at[1].id = cudaLaunchAttributeProgrammaticStreamSerialization; + at[1].val.programmaticStreamSerializationAllowed = 1; + cfg.attrs = at; cfg.numAttrs = 2; + void* pp_[2] = {const_cast(static_cast(¶ms)), nullptr}; +#ifdef TLDIAG + { void* tp = nullptr; if (cudaGetSymbolAddress(&tp, tl_tag) == cudaSuccess) g_tl_salt = (unsigned long long)tp; else cudaGetLastError(); } +#endif + return fast_launch(cfg, reinterpret_cast(&cutlass::device_kernel), pp_) == cudaSuccess ? cutlass::Status::kSuccess + : cutlass::Status::kErrorInternal; +} + +typedef CUresult (*ReplaceAddrFn)(CUtensorMap*, void*); +static ReplaceAddrFn get_replace_addr() { + static ReplaceAddrFn fn = nullptr; + static bool tried = false; + if (!tried) { + tried = true; + void* p = nullptr; + cudaDriverEntryPointQueryResult q; + if (cudaGetDriverEntryPointByVersion("cuTensorMapReplaceAddress", &p, 12000, cudaEnableDefault, &q) == cudaSuccess && + q == cudaDriverEntryPointSuccess) + fn = reinterpret_cast(p); + else + cudaGetLastError(); + } + return fn; +} +static bool tm_replace(const cute::TmaDescriptor* d, const void* ptr) { + ReplaceAddrFn fn = get_replace_addr(); + if (!fn || !ptr) return false; + return fn(reinterpret_cast(const_cast(d)), const_cast(ptr)) == CUDA_SUCCESS; +} +#define PDL_HAS_FIELD(NAME) \ + template struct Has_##NAME : std::false_type {}; \ + template struct Has_##NAME().NAME)>> : std::true_type {}; +PDL_HAS_FIELD(tma_load_a_fallback) +PDL_HAS_FIELD(tma_load_b_fallback) +PDL_HAS_FIELD(tma_load_sfa_fallback) +PDL_HAS_FIELD(tma_load_sfb_fallback) +#undef PDL_HAS_FIELD +// * fallback descriptors are patched only for a dynamic cluster (static cluster: the kernel reads only the primary +// tma_load_* atoms, see CollectiveMma's observed_tma_load_* selection) -> fewer driver calls; +// * validation compares exactly the descriptors the kernel reads (A, SFA, B, SFB, D: 128 B each, fully written by +// the encoder) against a fresh build. Every other Params field depends only on (shape, strides, layouts, alpha, +// workspace), none of which is part of the rebind key except alpha (unchanged here: ok[5] == nk[5] required). +// Kernel params are then identical to a full update() in every byte the kernel reads -> bit-identical results. +template +static bool patch_params(P& p, const void* const* ok, const void* const* nk) { + if (ok[5] != nk[5]) return false; + constexpr bool DYN = !cute::is_static_v; + bool r = true; + auto& ml = p.mainloop; + using ML = std::remove_reference_t; + if (ok[0] != nk[0]) { + r = r && tm_replace(ml.tma_load_a.get_tma_descriptor(), nk[0]); + if constexpr (DYN && Has_tma_load_a_fallback::value) r = r && tm_replace(ml.tma_load_a_fallback.get_tma_descriptor(), nk[0]); + } + if (ok[1] != nk[1]) { + r = r && tm_replace(ml.tma_load_sfa.get_tma_descriptor(), nk[1]); + if constexpr (DYN && Has_tma_load_sfa_fallback::value) r = r && tm_replace(ml.tma_load_sfa_fallback.get_tma_descriptor(), nk[1]); + } + if (ok[2] != nk[2]) { + r = r && tm_replace(ml.tma_load_b.get_tma_descriptor(), nk[2]); + if constexpr (DYN && Has_tma_load_b_fallback::value) r = r && tm_replace(ml.tma_load_b_fallback.get_tma_descriptor(), nk[2]); + } + if (ok[3] != nk[3]) { + r = r && tm_replace(ml.tma_load_sfb.get_tma_descriptor(), nk[3]); + if constexpr (DYN && Has_tma_load_sfb_fallback::value) r = r && tm_replace(ml.tma_load_sfb_fallback.get_tma_descriptor(), nk[3]); + } + if (ok[4] != nk[4]) r = r && tm_replace(p.epilogue.tma_store_d.get_tma_descriptor(), nk[4]); + return r; +} +template +static bool desc_equal(const P& x, const P& y) { + auto eq = [](const cute::TmaDescriptor* u, const cute::TmaDescriptor* v) { return memcmp(u, v, sizeof(cute::TmaDescriptor)) == 0; }; + bool r = eq(x.mainloop.tma_load_a.get_tma_descriptor(), y.mainloop.tma_load_a.get_tma_descriptor()) && + eq(x.mainloop.tma_load_sfa.get_tma_descriptor(), y.mainloop.tma_load_sfa.get_tma_descriptor()) && + eq(x.mainloop.tma_load_b.get_tma_descriptor(), y.mainloop.tma_load_b.get_tma_descriptor()) && + eq(x.mainloop.tma_load_sfb.get_tma_descriptor(), y.mainloop.tma_load_sfb.get_tma_descriptor()) && + eq(x.epilogue.tma_store_d.get_tma_descriptor(), y.epilogue.tma_store_d.get_tma_descriptor()); + if constexpr (!cute::is_static_v) { + using ML = std::remove_reference_t; + if constexpr (Has_tma_load_a_fallback::value) + r = r && eq(x.mainloop.tma_load_a_fallback.get_tma_descriptor(), y.mainloop.tma_load_a_fallback.get_tma_descriptor()) && + eq(x.mainloop.tma_load_b_fallback.get_tma_descriptor(), y.mainloop.tma_load_b_fallback.get_tma_descriptor()) && + eq(x.mainloop.tma_load_sfa_fallback.get_tma_descriptor(), y.mainloop.tma_load_sfa_fallback.get_tma_descriptor()) && + eq(x.mainloop.tma_load_sfb_fallback.get_tma_descriptor(), y.mainloop.tma_load_sfb_fallback.get_tma_descriptor()); + } + return r; +} +// vst: 0 = not validated yet, 1 = validated, -1 = disabled. Returns false -> caller does the full update(). +template +static bool fast_rebind(G& gemm, const void* const* ok, const void* const* nk, int& vst, MA&& ma, void* ws) { + if (vst < 0) return false; + auto& p = const_cast(gemm.params()); + if (!patch_params(p, ok, nk)) return false; + if (vst == 0) { + auto* fresh = new typename K::Params(K::to_underlying_arguments(ma(), ws)); + const bool same = desc_equal(*fresh, p); + delete fresh; + if (!same) { + vst = -1; + fprintf(stderr, "[rebind] descriptor address patch != fresh descriptors: disabled for this config\n"); + return false; + } + vst = 1; + } + return true; +} +// Same for the host-precomputed descriptor tables of the batched kernels (GemmArrayPre). pf(g, key, out[5]) gives the +// {A, SFA, B, SFB, D} addresses of batch g for a 7-pointer key. +template +static bool patch_table(cutlass::gemm::kernel::PreDescTable& t, PF&& pf, const void* const* ok, + const void* const* nk) { + constexpr int PER = NB / NAD; + bool r = true; + for (int g = 0; g < NB && r; ++g) { + const void* o[5]; const void* n[5]; + pf(g, ok, o); pf(g, nk, n); + if (g % PER == 0) { + if (o[0] != n[0]) r = r && tm_replace(&t.a[g / PER], n[0]); + if (o[1] != n[1]) r = r && tm_replace(&t.sfa[g / PER], n[1]); + } + if (o[2] != n[2]) r = r && tm_replace(&t.b[g], n[2]); + if (o[3] != n[3]) r = r && tm_replace(&t.sfb[g], n[3]); + if (o[4] != n[4]) r = r && tm_replace(&t.d[g], n[4]); + } + return r; +} + +// Legality: this grid launches only after every quant_o CTA executed launch_dependents, which each does right after its +// own griddepcontrol.wait on the attention grid -> attention (and everything before it) complete + flushed, so B / SFB +// are final. Used only when quant_o runs as a separate launch (not when quant_o is fused into the attention tail, whose +// predecessor would then be the osf writer itself). The kernel-level pre-mainloop waits of this config are disabled +// (pdlhook::NoPreWait): the only global reads besides A / SFA are alpha (epilogue, after the accumulators, i.e. causally +// after this wait) and D stores. Same data / stages / MMA order -> bit-identical. +// KVS = SPLIT-B (K/V GEMM, M > 2048): the N = 2048 B operand is NOT a concatenated [K;V] copy. N tiles whose rows lie in +// [0, 1024) use the primary B descriptor (k_w), tiles in [1024, 2048) the descriptor stored in the (static-cluster, +// otherwise never-read) tma_load_b_fallback slot of the Params, whose global address is v_w - 1024 rows (host-set), so the +// same coordinates address v_w rows 0..1023. Same bytes into the same stages -> bit-identical; no 16 MB K|V concat pass. +template +struct EarlyBMainloop : Base { + using TmaB_ = typename Base::Params::TMA_B; + TmaB_ const* tb_hi_ = nullptr; + cute::TmaDescriptor const* kdesc_ = nullptr; + cute::TmaDescriptor const* vdesc_ = nullptr; + template + CUTLASS_DEVICE EarlyBMainloop(typename Base::Params const& p, CS cs, uint32_t r) : Base(p, cs, r) { + if constexpr (KVS) tb_hi_ = &p.tma_load_b_fallback; + if constexpr (F3) { + kdesc_ = p.tma_load_b_fallback.get_tma_descriptor(); + vdesc_ = reinterpret_cast(p.tma_load_a_fallback.get_tma_descriptor()); + } + } + template + CUTLASS_DEVICE void copy_b(Bar* bar, uint16_t mask, Src const& s, Dst&& d, TileCoordMNKL const& c) const { + if constexpr (F3) { + constexpr int NTILE = (int)cute::size<1>(typename Base::CtaShape_MNK{}); + static_assert(1024 % NTILE == 0, "fused tiles must not straddle the Q/K/V boundaries"); + const int col = (int)get<1>(c) * NTILE; + cute::TmaDescriptor const* dsc = col < 8192 ? this->observed_tma_load_b_->get_tma_descriptor() + : (col < 9216 ? kdesc_ : vdesc_); + copy(this->observed_tma_load_b_->with(dsc, *bar, mask), s, static_cast(d)); + } else { + copy(bsel(c)->with(*bar, mask), s, static_cast(d)); + } + } + bool eb_first_ = true; + template + CUTLASS_DEVICE TmaB_ const* bsel(TileCoordMNKL const& c) const { + if constexpr (KVS) { + constexpr int NTILE = (int)cute::size<1>(typename Base::CtaShape_MNK{}); + static_assert(1024 % NTILE == 0, "split-B tiles must not straddle the K/V boundary"); + return ((int)get<1>(c) * NTILE >= 1024) ? tb_hi_ : this->observed_tma_load_b_; + } else { + return this->observed_tma_load_b_; + } + } + template + CUTLASS_DEVICE auto load(Pipe mainloop_pipeline, PState st, LoadParams const& load_inputs, + TileCoordMNKL const& cta_coord_mnkl, KTileIterator k_tile_iter, int k_tile_count) { + if (!eb_first_) { + if constexpr (!KVS && !F3) return Base::load(mainloop_pipeline, st, load_inputs, cta_coord_mnkl, k_tile_iter, k_tile_count); + else { // == CollectiveMma::load with the per-tile B descriptor + auto [unused_k_tiles, + tAgA_mkl, tBgB_nkl, tAsA, tBsB, + tAgSFA_mkl, tBgSFB_nkl, tAsSFA, tBsSFB, + mcast_mask_a, mcast_mask_b, mcast_mask_sfa, mcast_mask_sfb] = load_inputs; + using TM = typename Base::TiledMma; + Tensor tAgA = tAgA_mkl(_, get<0>(cta_coord_mnkl) / size(typename TM::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgB = tBgB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + Tensor tAgSFA = tAgSFA_mkl(_, get<0>(cta_coord_mnkl) / size(typename TM::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgSFB = tBgSFB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + using BarrierType = typename Pipe::ProducerBarrierType; + auto barrier_token = mainloop_pipeline.producer_try_acquire(st); + CUTLASS_PRAGMA_NO_UNROLL + while (k_tile_count > 0) { + mainloop_pipeline.producer_acquire(st, barrier_token); + BarrierType* tma_barrier = mainloop_pipeline.producer_get_barrier(st); + const int write_stage = st.index(); + ++st; + barrier_token = mainloop_pipeline.producer_try_acquire(st); + if (cute::elect_one_sync()) { + copy(this->observed_tma_load_a_->with(*tma_barrier, mcast_mask_a), tAgA(_, *k_tile_iter), tAsA(_, write_stage)); + copy_b(tma_barrier, mcast_mask_b, tBgB(_, *k_tile_iter), tBsB(_, write_stage), cta_coord_mnkl); + copy(this->observed_tma_load_sfa_->with(*tma_barrier, mcast_mask_sfa), tAgSFA(_, *k_tile_iter), tAsSFA(_, write_stage)); + copy(this->observed_tma_load_sfb_->with(*tma_barrier, mcast_mask_sfb), tBgSFB(_, *k_tile_iter), tBsSFB(_, write_stage)); + } + --k_tile_count; + ++k_tile_iter; + } + return cute::make_tuple(st, k_tile_iter); + } + } + eb_first_ = false; + auto [unused_k_tiles, + tAgA_mkl, tBgB_nkl, tAsA, tBsB, + tAgSFA_mkl, tBgSFB_nkl, tAsSFA, tBsSFB, + mcast_mask_a, mcast_mask_b, mcast_mask_sfa, mcast_mask_sfb] = load_inputs; + using TM = typename Base::TiledMma; + Tensor tAgA = tAgA_mkl(_, get<0>(cta_coord_mnkl) / size(typename TM::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgB = tBgB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + Tensor tAgSFA = tAgSFA_mkl(_, get<0>(cta_coord_mnkl) / size(typename TM::AtomThrID{}), _, get<3>(cta_coord_mnkl)); + Tensor tBgSFB = tBgSFB_nkl(_, get<1>(cta_coord_mnkl), _, get<3>(cta_coord_mnkl)); + using BarrierType = typename Pipe::ProducerBarrierType; + const PState st0 = st; + const KTileIterator it0 = k_tile_iter; + // phase 1: arm the first EB_PRE prologue stages, weight operands only. + constexpr int EB_PRE = PRE; + const int n_pre = k_tile_count < EB_PRE ? k_tile_count : EB_PRE; + auto barrier_token = mainloop_pipeline.producer_try_acquire(st); + CUTLASS_PRAGMA_NO_UNROLL + for (int n = 0; n < n_pre; ++n) { + mainloop_pipeline.producer_acquire(st, barrier_token); + BarrierType* tma_barrier = mainloop_pipeline.producer_get_barrier(st); + const int write_stage = st.index(); + ++st; + barrier_token = mainloop_pipeline.producer_try_acquire(st); + if (cute::elect_one_sync()) { + copy_b(tma_barrier, mcast_mask_b, tBgB(_, *k_tile_iter), tBsB(_, write_stage), cta_coord_mnkl); + if constexpr (!BO) + copy(this->observed_tma_load_sfb_->with(*tma_barrier, mcast_mask_sfb), tBgSFB(_, *k_tile_iter), tBsSFB(_, write_stage)); + } + ++k_tile_iter; + } + cutlass::arch::wait_on_dependent_grids(); // quant_o complete + flushed: A / SFA are final +#if defined(__CUDA_ARCH__) + if constexpr (TRG) asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); +#endif + // phase 2: activation operands into the same (already armed) stages + PState s2 = st0; + KTileIterator it = it0; + CUTLASS_PRAGMA_NO_UNROLL + for (int n = 0; n < n_pre; ++n) { + BarrierType* tma_barrier = mainloop_pipeline.producer_get_barrier(s2); + const int write_stage = s2.index(); + ++s2; + if (cute::elect_one_sync()) { + copy(this->observed_tma_load_a_->with(*tma_barrier, mcast_mask_a), tAgA(_, *it), tAsA(_, write_stage)); + copy(this->observed_tma_load_sfa_->with(*tma_barrier, mcast_mask_sfa), tAgSFA(_, *it), tAsSFA(_, write_stage)); + if constexpr (BO) // SFB after the wait (osf final: predecessor complete + flushed) + copy(this->observed_tma_load_sfb_->with(*tma_barrier, mcast_mask_sfb), tBgSFB(_, *it), tBsSFB(_, write_stage)); + } + ++it; + } + // phase 3: remaining prologue stages, all four operands (standard order) + CUTLASS_PRAGMA_NO_UNROLL + for (int n = n_pre; n < k_tile_count; ++n) { + mainloop_pipeline.producer_acquire(st, barrier_token); + BarrierType* tma_barrier = mainloop_pipeline.producer_get_barrier(st); + const int write_stage = st.index(); + ++st; + barrier_token = mainloop_pipeline.producer_try_acquire(st); + if (cute::elect_one_sync()) { + copy(this->observed_tma_load_a_->with(*tma_barrier, mcast_mask_a), tAgA(_, *k_tile_iter), tAsA(_, write_stage)); + copy_b(tma_barrier, mcast_mask_b, tBgB(_, *k_tile_iter), tBsB(_, write_stage), cta_coord_mnkl); + copy(this->observed_tma_load_sfa_->with(*tma_barrier, mcast_mask_sfa), tAgSFA(_, *k_tile_iter), tAsSFA(_, write_stage)); + copy(this->observed_tma_load_sfb_->with(*tma_barrier, mcast_mask_sfb), tBgSFB(_, *k_tile_iter), tBsSFB(_, write_stage)); + } + ++k_tile_iter; + } + return cute::make_tuple(st, k_tile_iter); + } +}; +// distinct epilogue functor type of the early-B O GEMM (own adapter state / pdlhook tag) +template struct IdentityEB : cutlass::epilogue::thread::Identity {}; + +// One GEMM configuration. MmaTile = tile of one (1SM) or two (2SM, cluster 2x1) CTAs; CtaTile = per-CTA +// output tile (used by the per-column alpha broadcast to size its smem slice; 2SM splits only M). +// EB = early-B mainloop (see EarlyBMainloop), Ident = epilogue identity functor type. +template class Ident = cutlass::epilogue::thread::Identity, bool BO = false> +struct Cfg { + using AccToBf16 = fu::Sm90EVT, + fu::Sm90AccFetch>; + // alpha vector indexed by output column n (stride (0,1,0)), fp32 + using AlphaCol = fu::Sm90RowBroadcast<0, CtaTile, float, float, Stride<_0, _1, int64_t>, 4>; + using FusionEVT = fu::Sm90EVT, AlphaCol, AccToBf16>; + + using CollectiveEpilogue = typename cutlass::epilogue::collective::CollectiveBuilder< + cutlass::arch::Sm100, cutlass::arch::OpClassTensorOp, MmaTile, Cluster, + cutlass::epilogue::collective::EpilogueTileAuto, Acc, Acc, + ElementC, LayoutC, AlignC, ElementD, LayoutC, AlignD, + cutlass::epilogue::collective::EpilogueScheduleAuto, FusionEVT>::CollectiveOp; + + using CollectiveMainloop0 = typename cutlass::gemm::collective::CollectiveBuilder< + cutlass::arch::Sm100, cutlass::arch::OpClassBlockScaledTensorOp, + ElementA, LayoutA, AlignA, ElementB, LayoutB, AlignB, Acc, MmaTile, Cluster, + cutlass::gemm::collective::StageCountAutoCarveout(sizeof(typename CollectiveEpilogue::SharedStorage))>, + cutlass::gemm::collective::KernelScheduleAuto>::CollectiveOp; + using CollectiveMainloop = std::conditional_t, CollectiveMainloop0>; + + using Kernel = TLWRAP(cutlass::gemm::kernel::GemmUniversal, CollectiveMainloop, CollectiveEpilogue, void>); + using Gemm = cutlass::gemm::device::GemmUniversalAdapter; + using StrideA = typename Kernel::StrideA; + using StrideB = typename Kernel::StrideB; + using StrideC = typename Kernel::StrideC; + using StrideD = typename Kernel::StrideD; + using SfCfg = typename Kernel::CollectiveMainloop::Sm1xxBlkScaledConfig; + + static typename Gemm::Arguments make_args(const void* A, const void* SFA, const void* B, const void* SFB, void* D, + const float* alpha, int M, int N, int K) { + StrideA sA{}; get<0>(sA) = K; get<2>(sA) = (int64_t)M * K; + StrideB sB{}; get<0>(sB) = K; get<2>(sB) = (int64_t)N * K; + StrideC sC{}; get<0>(sC) = N; get<2>(sC) = (int64_t)M * N; + StrideD sD{}; get<0>(sD) = N; get<2>(sD) = (int64_t)M * N; + auto lSFA = SfCfg::tile_atom_to_shape_SFA(make_shape(M, N, K, 1)); + auto lSFB = SfCfg::tile_atom_to_shape_SFB(make_shape(M, N, K, 1)); + typename Gemm::Arguments args{ + cutlass::gemm::GemmUniversalMode::kGemm, + {M, N, K, 1}, + {reinterpret_cast(A), sA, reinterpret_cast(B), sB, + reinterpret_cast(SFA), lSFA, reinterpret_cast(SFB), lSFB}, + {{}, nullptr, sC, reinterpret_cast(D), sD}}; + // EVT args: { per-column alpha vector (device ptr), { acc fetch, identity->bf16 }, multiplies } + args.epilogue.thread = { + {alpha, 0.0f, {}}, + {{}, {}}, + {}}; + args.hw_info.device_id = 0; + args.hw_info.sm_count = sm_count(); + return args; + } + static size_t workspace(int M, int N, int K) { + auto args = make_args(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, M, N, K); + return Gemm::get_workspace_size(args); + } + static int run(const void* A, const void* SFA, const void* B, const void* SFB, void* D, const float* alpha, + int M, int N, int K, void* ws, cudaStream_t st) { + // Host-overhead cache: one heap-allocated (never destroyed) adapter per config. can_implement + + // initialize (smem attribute, workspace init) run only when the problem shape / workspace changes; + // otherwise update() just rebuilds the kernel Params (TMA descriptors for the per-call pointers). + // Pointer key: when every operand pointer is unchanged the cached Params (TMA descriptors) are still valid + // -> no make_args / update() (cuTensorMapEncodeTiled x5) on the host. + struct State { Gemm gemm; int M = -1, N = -1, K = -1; void* ws = nullptr; const void* key[6] = {}; dim3 grid; bool gv = false; int vst = 0; }; + static State& s = *new State(); + const void* key[6] = {A, SFA, B, SFB, D, alpha}; + if (s.M != M || s.N != N || s.K != K || s.ws != ws) { + s.M = -1; + auto args = make_args(A, SFA, B, SFB, D, alpha, M, N, K); + if (s.gemm.can_implement(args) != cutlass::Status::kSuccess) return 1; + if (s.gemm.initialize(args, ws, st) != cutlass::Status::kSuccess) return 2; + s.M = M; s.N = N; s.K = K; s.ws = ws; s.gv = false; + memcpy(s.key, key, sizeof(key)); + } else if (memcmp(s.key, key, sizeof(key)) != 0) { + if (!fast_rebind(s.gemm, s.key, key, s.vst, [&] { return make_args(A, SFA, B, SFB, D, alpha, M, N, K); }, ws)) { + auto args = make_args(A, SFA, B, SFB, D, alpha, M, N, K); + if (s.gemm.update(args, ws) != cutlass::Status::kSuccess) { s.M = -1; return 2; } + } + memcpy(s.key, key, sizeof(key)); + s.gv = false; + } + if (run_pdl(s.gemm, st, s.grid, s.gv) != cutlass::Status::kSuccess) return 3; + return 0; + } +}; + +// Scalar-alpha variant with explicit schedules (used for the 2SM 256x256 O-projection tile): +// D = bf16(alpha * bf16(acc)) with alpha a single fp32 device scalar (the O-proj alpha vector is uniform, +// so alpha[0] is used). No per-column smem slice -> any CTA tile width. +// IdentityQ: the same identity functor under a distinct type, so the Q-projection GEMM's epilogue type (and thus its +// pdlhook dependency-sync tags) differs from the O-projection GEMM's (identical math -> bit-identical results). +template struct IdentityQ : cutlass::epilogue::thread::Identity {}; +// IdentityO: distinct epilogue type for the 256x192 O-projection candidate (own cached adapter / pdlhook tag). +template struct IdentityO : cutlass::epilogue::thread::Identity {}; +// Distinct epilogue types (own cached adapters / pdlhook tags) for the mid-M O-projection candidates: +// IdentityS1 / IdentityS2 = the two halves of the N-split pair, IdentityO1 = the 1SM 128x256 config. +template struct IdentityS1 : cutlass::epilogue::thread::Identity {}; +template struct IdentityS2 : cutlass::epilogue::thread::Identity {}; +template struct IdentityO1 : cutlass::epilogue::thread::Identity {}; +// IdentityQ2: distinct epilogue type for the 256x192 Q-projection GEMM of split mode 10 (own adapter / pdlhook tags). +template struct IdentityQ2 : cutlass::epilogue::thread::Identity {}; +// ---- Single-D-stage epilogue for the 2SM 256x256x256 GEMMs (StagesD 2 -> 1) ---- +// Rebinds the builder's Sm100TmaWarpSpecialized dispatch policy to StagesD = 1 (every other +// template argument unchanged): 16 KB instead of 32 KB of epilogue smem per CTA (128x64 bf16 subtile). With the delayed +// TMA store, the previous subtile's store is committed and drained (acquire: 0 in flight) before the next smem write. +// Same per-element epilogue math -> bit-identical. +// O-GEMM mainloop PDL trigger trait (CfgS EB configs): true -> EarlyBMainloop TRG = launch_dependents right after the +// first-tile mainloop griddepcontrol.wait in EVERY CTA of each 2SM pair (incl. the scheduler-less odd CTA). +template