Upload folder using huggingface_hub (part 7)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_large2.cuAdded+1702
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_large2.hAdded+25
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_largev.cuAdded+524
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_largev.hAdded+7
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128c.cuAdded+956
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128c.hAdded+13
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128x2.cuAdded+530
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128x2.hAdded+7
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256.cuAdded+863
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256.hAdded+9
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256c.cuAdded+666
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256c.hAdded+11
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256p.cuAdded+768
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256p.hAdded+7
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256v.cuAdded+864
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256v.hAdded+14
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256x2.cuAdded+526
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256x2.hAdded+7
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk.cuAdded+786
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk.hAdded+6
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk2c.cuAdded+1568
- kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk2c.hAdded+20
- kernels/Quant/015_fp8_mla_attention_output_projection/src/main.cppAdded+694
- kernels/Quant/015_fp8_mla_attention_output_projection/src/raw_push.hAdded+34
- kernels/Quant/015_fp8_mla_attention_output_projection/src/tmap_cache.hAdded+46
- kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/README.mdAdded+10
- kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/kernel.jsonAdded+64
- kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/src/kernel.cuAdded
- kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/src/kernel.hAdded+153
- kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/src/main.cppAdded+1049
- kernels/Quant/017_fp8_shared_expert_mlp/README.mdAdded+10
- kernels/Quant/017_fp8_shared_expert_mlp/kernel.jsonAdded+76
- kernels/Quant/017_fp8_shared_expert_mlp/src/bw2wg.hAdded
- kernels/Quant/017_fp8_shared_expert_mlp/src/kernel.cuAdded
- kernels/Quant/017_fp8_shared_expert_mlp/src/kernel.hAdded+21
- kernels/Quant/017_fp8_shared_expert_mlp/src/main.cppAdded+55
- kernels/Quant/017_fp8_shared_expert_mlp/src/smallm.cuAdded+1308
- kernels/Quant/018_nvfp4_attention_output_projection_with_residual/README.mdAdded+10
- kernels/Quant/018_nvfp4_attention_output_projection_with_residual/kernel.jsonAdded+72
- kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/collective_anyn.hppAdded+1102
- kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/kernel.cuAdded
- kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/kernel.hAdded+28
- kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/main.cppAdded+329
- kernels/Quant/019_nvfp4_grouped_query_attention/README.mdAdded+11
- kernels/Quant/019_nvfp4_grouped_query_attention/kernel.jsonAdded+97
- kernels/Quant/019_nvfp4_grouped_query_attention/src/array_pre.hppAdded+1598
- kernels/Quant/019_nvfp4_grouped_query_attention/src/cutlass/gemm/collective/builders/sm100_common.inlAdded+1010
- kernels/Quant/019_nvfp4_grouped_query_attention/src/cutlass/gemm/collective/sm100_blockscaled_mma_array_warpspecialized.hppAdded
- kernels/Quant/019_nvfp4_grouped_query_attention/src/cutlass/gemm/collective/sm100_blockscaled_mma_warpspecialized.hppAdded
- kernels/Quant/019_nvfp4_grouped_query_attention/src/kernel.cuAdded
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702//// 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 <cstdint>#include <type_traits>#include <cstdio>#include <cuda.h>#include <cuda_runtime.h>#include <cuda_bf16.h>#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 KBconstexpr int TILE_B_BYTES = BLOCK_N * BLOCK_K; // 32 KBconstexpr int STAGE_BYTES = TILE_A_BYTES + TILE_B_BYTES;constexpr int NUM_EPI_WARPS = 8; // 2 promotion warpgroups x 128 colsconstexpr 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 KBconstexpr int SC_SLOTS = 8; // scale ring depth (k-blocks)constexpr int SC_BYTES = SC_SLOTS * 256 * 4; // 8 KB: [slot][half][128 rows] fp32constexpr int EPI_WARP0 = 4; // first epilogue warp (warpgroup 1)constexpr int NUM_THREADS = 128 + NUM_EPI_WARPS * 32; // 12 warps = 3 warpgroupsconstexpr int TMEM_COLS = 512; // 2 accumulator buffers x 256 colsconstexpr 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 +12constexpr 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 @ +80constexpr 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 <bool EVEN>__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<uint32_t>(__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<uint64_t>(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<uint64_t>(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<uint64_t>(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 <bool CLAIMER, bool REAL, bool OWNERS_FIRST = false>__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 <bool ELECT, bool TF_FIRST>__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<uint64_t>(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 <int LDN, int MODE, int UNI = 12>__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<uint8_t*>((reinterpret_cast<uintptr_t>(smem_raw) + 1023) & ~uintptr_t(1023)); uint8_t* out_stage = smem + STAGES * STAGE_BYTES; // 32 KB, 1024-aligned float* sc_ring = reinterpret_cast<float*>(out_stage + OUT_STAGE_BYTES); // 8 KB scale ring uint64_t* full_bar = reinterpret_cast<uint64_t*>(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<uint32_t*>(claim_bar + 1); uint64_t* mfull_bar = reinterpret_cast<uint64_t*>(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<int4*>(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<uint64_t>(&tmap_a)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&tmap_b)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&tmap_out)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&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<SPF>(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<true, REAL, (MODE & 32) != 0>(direct, tail, split, claim_ctr, u); if (u < 0) break; } unit_coords_t<SPF>(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<false, REAL>(direct, tail, split, claim_ctr, u); if (u < 0) break; } unit_coords_t<SPF>(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<ELECT, ORD>(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<false, REAL>(direct, tail, split, claim_ctr, u); if (u < 0) break; } unit_coords_t<SPF>(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<bool, EISS>{}, 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<false, REAL>(direct, tail, split, claim_ctr, u); if (u < 0) break; } unit_coords_t<SPF>(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<SPF>(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<const float4*>(pa + kb)); const float4 vb = __ldg(reinterpret_cast<const float4*>(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<const float2*>(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<const float2*>(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<uint4*>(wst + lane * 64 + ((j ^ ((lane >> 1) & 3)) << 4)) = pkf(c0 / 8 + j); } else {#pragma unroll for (int j = 0; j < 2; ++j) *reinterpret_cast<uint4*>(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<SPF>(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<SPF>(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<float4*>(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<float*>(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<uint32_t*>(&h0); dpk[v * 4 + 1] = *reinterpret_cast<uint32_t*>(&h1); dpk[v * 4 + 2] = *reinterpret_cast<uint32_t*>(&h2); dpk[v * 4 + 3] = *reinterpret_cast<uint32_t*>(&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<uint32_t*>(&h0); pk.y = *reinterpret_cast<uint32_t*>(&h1); pk.z = *reinterpret_cast<uint32_t*>(&h2); pk.w = *reinterpret_cast<uint32_t*>(&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<false, REAL>(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<uint32_t*>(&h0); pk.y = *reinterpret_cast<uint32_t*>(&h1); pk.z = *reinterpret_cast<uint32_t*>(&h2); pk.w = *reinterpret_cast<uint32_t*>(&h3); *reinterpret_cast<uint4*>(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<void*>(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<const void*>(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_PROFvoid 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)); }#endif12345678910111213141516171819202122232425#pragma once#include <cuda_runtime.h>#include <cstddef>// 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);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524// 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 <cstdint>#include <cstdio>#include <cuda.h>#include <cuda_runtime.h>#include <cuda_bf16.h>#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 KBconstexpr 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 KBconstexpr 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<uint32_t>(__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<uint64_t>(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<uint64_t>(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 <int NC>__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<uint32_t*>(&h0)), "r"(*reinterpret_cast<uint32_t*>(&h1)), "r"(*reinterpret_cast<uint32_t*>(&h2)), "r"(*reinterpret_cast<uint32_t*>(&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<uint8_t*>((reinterpret_cast<uintptr_t>(smem_raw) + 1023) & ~uintptr_t(1023)); uint8_t* out_stage = smem + STAGES * STAGE_BYTES; float* sc_ring = reinterpret_cast<float*>(out_stage + OUT_STAGE_BYTES); uint64_t* full_bar = reinterpret_cast<uint64_t*>(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<uint32_t*>(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<uint64_t>(&tmap_a)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&tmap_b_lo)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&tmap_b_hi)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&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<const float4*>(pa + kb)); const float4 vb = __ldg(reinterpret_cast<const float4*>(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<void*>(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);}1234567#pragma once#include <cuda_runtime.h>// 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);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956// 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 <cstdint>#include <cstdio>#include <cuda.h>#include <cuda_runtime.h>#include <cuda_bf16.h>#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#endifnamespace {
constexpr int BLOCK_M = 128;constexpr int TILE_N = 160;constexpr int BLOCK_K = 128;constexpr int CL = 3; // cluster size = split-K factorconstexpr int NBUF = 3; // TMEM accumulator buffersconstexpr int STAGES = 6;constexpr int TILE_A_BYTES = BLOCK_M * BLOCK_K; // 16 KBconstexpr int TILE_B_BYTES = TILE_N * BLOCK_K; // 20 KBconstexpr 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 stageconstexpr 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 warpgroupconstexpr int NCHUNK = EPI_COLS / 16; // 5constexpr int EPI_WARP0 = 4;constexpr int NUM_THREADS = 128 + NUM_EPI_WARPS * 32; // 384constexpr int TMEM_COLS = 512; // 3 buffers at cols 0, 160, 320constexpr 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+1constexpr 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 Bstatic_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<uint32_t>(__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<uint64_t>(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<uint64_t>(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<uint64_t>(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<uint64_t>(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 <int V>__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<uint8_t*>((reinterpret_cast<uintptr_t>(smem_raw) + 1023) & ~uintptr_t(1023)); float* sc_ring = reinterpret_cast<float*>(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<uint64_t*>(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<uint32_t*>(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<uint64_t>(&tmap_a)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&tmap_b)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&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<uint64_t>(&tmap_a), mb_b = reinterpret_cast<uint64_t>(&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<uint64_t>(&tmap_bw), mb_bh = reinterpret_cast<uint64_t>(&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<const float4*>(pa + kb)) : make_float4(0.f, 0.f, 0.f, 0.f); const float4 vb = rb < M ? __ldg(reinterpret_cast<const float4*>(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<uint32_t*>(&h0)), "r"(*reinterpret_cast<uint32_t*>(&h1)), "r"(*reinterpret_cast<uint32_t*>(&h2)), "r"(*reinterpret_cast<uint32_t*>(&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<void*>(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);}12345678910111213#pragma once#include <cuda_runtime.h>// 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);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530// 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 <cstdint>#include <cstdio>#include <cuda.h>#include <cuda_runtime.h>#include <cuda_bf16.h>#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 factorconstexpr int STAGES = 3;constexpr int TILE_A_BYTES = BLOCK_M * BLOCK_K; // 16 KBconstexpr int TILE_B_BYTES = TILE_N * BLOCK_K; // 16 KBconstexpr 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; // 256constexpr 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 KBconstexpr 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 addedconstexpr 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 consumedconstexpr uint32_t BF_BOX = 32 * TILE_N * 2; // 8 KBstatic_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<uint32_t>(__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<uint64_t>(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<uint64_t>(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<uint8_t*>((reinterpret_cast<uintptr_t>(smem_raw) + 1023) & ~uintptr_t(1023)); float* sc_ring = reinterpret_cast<float*>(smem + STAGES * STAGE_BYTES); uint64_t* full_bar = reinterpret_cast<uint64_t*>(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<uint32_t*>(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<uint64_t>(&tmap_a)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&tmap_b)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&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<const float4*>(pa + kb)) : make_float4(0.f, 0.f, 0.f, 0.f); const float4 vb = rb < M ? __ldg(reinterpret_cast<const float4*>(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<TILE_N>(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<TILE_N>(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<uint32_t*>(&h0)), "r"(*reinterpret_cast<uint32_t*>(&h1)), "r"(*reinterpret_cast<uint32_t*>(&h2)), "r"(*reinterpret_cast<uint32_t*>(&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<void*>(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);}1234567#pragma once#include <cuda_runtime.h>// 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);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863// 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 <cstdint>#include <cstdio>#include <cuda.h>#include <cuda_runtime.h>#include <cuda_bf16.h>#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)#endifnamespace {
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 KBconstexpr 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 colsconstexpr int EPI_COLS = 128;constexpr int EPI_WARP0 = 4;constexpr int NUM_THREADS = 128 + NUM_EPI_WARPS * 32; // 384constexpr 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] fp32constexpr 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 tilesconstexpr 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<uint32_t>(__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<uint64_t>(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<uint64_t>(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<uint64_t>(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<uint64_t>(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<uint64_t>(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<uint64_t>(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<uint64_t>(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<uint8_t*>((reinterpret_cast<uintptr_t>(smem_raw) + 1023) & ~uintptr_t(1023)); uint8_t* out_stage = smem + STAGES * STAGE_BYTES; // 16 KB bf16 output staging float* sc_ring = reinterpret_cast<float*>(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<uint64_t*>(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<uint32_t*>(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<uint64_t>(&tmap_a)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&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<uint64_t>(&tmap_out)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&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<const float2*>(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<float4*>(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<float*>(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<uint32_t*>(&h0); pk.y = *reinterpret_cast<uint32_t*>(&h1); pk.z = *reinterpret_cast<uint32_t*>(&h2); pk.w = *reinterpret_cast<uint32_t*>(&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<uint32_t*>(&h0); pk.y = *reinterpret_cast<uint32_t*>(&h1); pk.z = *reinterpret_cast<uint32_t*>(&h2); pk.w = *reinterpret_cast<uint32_t*>(&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<void*>(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);}123456789#pragma once#include <cuda_runtime.h>#include <cstddef>// 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);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666// 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 <cstdint>#include <cstdio>#include <cuda.h>#include <cuda_runtime.h>#include <cuda_bf16.h>#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 warpgroupconstexpr 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 KBconstexpr int TILE_B_BYTES = TN * BLOCK_K; // 28 KBconstexpr 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 warpgroupconstexpr int PARK_F4 = HALF_N / 4; // 28 float4 per threadstatic_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 Bconstexpr 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<uint32_t>(__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<uint64_t>(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<uint64_t>(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<uint64_t>(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 <int NP>__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<uint8_t*>((reinterpret_cast<uintptr_t>(smem_raw) + 1023) & ~uintptr_t(1023)); float* sc_ring = reinterpret_cast<float*>(smem + STAGES * STAGE_BYTES); uint64_t* full_bar = reinterpret_cast<uint64_t*>(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<uint32_t*>(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<uint64_t>(&tmap_a)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&tmap_b)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&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<const float4*>(pa + kb)) : make_float4(0.f, 0.f, 0.f, 0.f); const float4 vb = rb < M ? __ldg(reinterpret_cast<const float4*>(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<HALF_N>(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<HALF_N>(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<uint32_t*>(&h0); pk.y = *reinterpret_cast<uint32_t*>(&h1); pk.z = *reinterpret_cast<uint32_t*>(&h2); pk.w = *reinterpret_cast<uint32_t*>(&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<void*>(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);}1234567891011#pragma once#include <cuda_runtime.h>// 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);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768// 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 <cstdint>#include <cstdio>#include <cuda.h>#include <cuda_runtime.h>#include <cuda_bf16.h>#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 KBconstexpr int STAGE_BYTES = TILE_A_BYTES + MAX_HALF * BLOCK_K; // 30 KB (1024-multiple), widest possible stageconstexpr 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 swconstexpr int SC_BYTES = SC_SLOTS * SC_SLOT_FLOATS * 4;constexpr int ALIGN_SLACK = 512; // dynamic smem base declared __align__(1024); device trap guards the slackconstexpr int SMEM_BYTES = RING_BYTES + SC_BYTES + ALIGN_SLACK + 320; // barriers: 34 x 8 B + tmem slotstatic_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 Bconstexpr 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<uint32_t>(__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<uint64_t>(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<uint64_t>(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<uint64_t>(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<uint64_t>(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 <int NC>__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<NCOL>(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<uint32_t*>(&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<uint8_t*>((reinterpret_cast<uintptr_t>(smem_raw) + 1023) & ~uintptr_t(1023)); if (smem - smem_raw > ALIGN_SLACK) __trap(); // never expected: base is 1024-aligned float* sc_ring = reinterpret_cast<float*>(smem + RING_BYTES); uint64_t* full_bar = reinterpret_cast<uint64_t*>(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<uint32_t*>(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<uint64_t>(&tmap_a)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&tmap_b_lo)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&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<const float4*>(pa + kb)) : make_float4(0.f, 0.f, 0.f, 0.f); const float4 vb = rb < M ? __ldg(reinterpret_cast<const float4*>(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<void*>(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));}1234567#pragma once#include <cuda_runtime.h>// 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);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864// 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 <cstdint>#include <cstdio>#include <cuda.h>#include <cuda_runtime.h>#include <cuda_bf16.h>#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)#endifnamespace {
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 warpgroupconstexpr 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 KBconstexpr int TILE_B_BYTES = TN * BLOCK_K; // 28 KBconstexpr 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 warpgroupconstexpr int PARK_F4 = HALF_N / 4; // 28 float4 per threadstatic_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 Bconstexpr 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<uint32_t>(__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<uint64_t>(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<uint64_t>(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<uint64_t>(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<uint64_t>(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<uint64_t>(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 <int NCOL>__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 <int NCOL>__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 rawpushstatic_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 <int NC, bool RAW, bool KQ4>__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<NCOL>(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<NCOL>(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<uint32_t*>(&h0); pk.y = *reinterpret_cast<uint32_t*>(&h1); pk.z = *reinterpret_cast<uint32_t*>(&h2); pk.w = *reinterpret_cast<uint32_t*>(&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<NCOL>(acc, ring + OUT_OFF + q * WSL, lane); else pushfmt::pack<NCOL>(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<NCOL>(acc, ring + q * WSL, lane); else pushfmt::add<NCOL>(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<uint32_t*>(&h0); pk.y = *reinterpret_cast<uint32_t*>(&h1); pk.z = *reinterpret_cast<uint32_t*>(&h2); pk.w = *reinterpret_cast<uint32_t*>(&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 <bool RAW, bool KQ4 = false>__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<uint8_t*>((reinterpret_cast<uintptr_t>(smem_raw) + 1023) & ~uintptr_t(1023)); float* sc_ring = reinterpret_cast<float*>(smem + STAGES * STAGE_BYTES); uint64_t* full_bar = reinterpret_cast<uint64_t*>(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<uint32_t*>(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<uint64_t>(&tmap_a)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(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<const float4*>(pa + kb)) : make_float4(0.f, 0.f, 0.f, 0.f); const float4 vb = rb < M ? __ldg(reinterpret_cast<const float4*>(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<void*>(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<false>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); cudaFuncSetAttribute(fp8_m256v_kernel<true>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); cudaFuncSetAttribute(fp8_m256v_kernel<true, true>, 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<false>, &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<true>, ta, tbl, tbh, tol, toh, sx, sw, M, N, K, q, rr, wpol, pro); else cudaLaunchKernelEx(&cfg, fp8_m256v_kernel<false>, ta, tbl, tbh, tol, toh, sx, sw, M, N, K, q, rr, wpol, pro);}
// M <= 128 K-QUARTER variant (kernel_m256v<RAW=true, KQ4=true>): 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<true, true>, ta, tbl, tbh, tol, toh, sx, sw, M, N, K, q, rr, 8, pro);}1234567891011121314#pragma once#include <cuda_runtime.h>// 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);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526// 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 <cstdint>#include <cstdio>#include <cuda.h>#include <cuda_runtime.h>#include <cuda_bf16.h>#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-halvesconstexpr int STAGES = 3;constexpr int TILE_A_BYTES = BLOCK_M * BLOCK_K; // 16 KBconstexpr int TILE_B_BYTES = TILE_N * BLOCK_K; // 16 KBconstexpr 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; // 256constexpr 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 KBconstexpr 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 KBstatic_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<uint32_t>(__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<uint64_t>(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<uint64_t>(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<uint64_t>(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<uint64_t>(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<uint8_t*>((reinterpret_cast<uintptr_t>(smem_raw) + 1023) & ~uintptr_t(1023)); float* sc_ring = reinterpret_cast<float*>(smem + STAGES * STAGE_BYTES); uint64_t* full_bar = reinterpret_cast<uint64_t*>(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<uint32_t*>(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<uint64_t>(&tmap_a)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&tmap_b)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&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<TILE_N>(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<TILE_N>(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<uint32_t*>(&h0)), "r"(*reinterpret_cast<uint32_t*>(&h1)), "r"(*reinterpret_cast<uint32_t*>(&h2)), "r"(*reinterpret_cast<uint32_t*>(&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<void*>(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);}1234567#pragma once#include <cuda_runtime.h>// 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);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786// 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 <cstdint>#include <cstdio>#include <cuda.h>#include <cuda_runtime.h>#include <cuda_bf16.h>#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 KBconstexpr int TILE_B_BYTES = BLOCK_N * BLOCK_K; // 32 KBconstexpr 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 KBconstexpr int OUT_SLOTS = 3; // per-warp staging ring: up to 2 TMA stores in flight while packing the next boxconstexpr int OUT_STAGE_BYTES = NUM_EPI_WARPS * OUT_SLOTS * WARP_STAGE_BYTES; // 24 KBconstexpr int SC_SLOTS = 8; // scale ring depth (k-blocks)constexpr int SC_BYTES = SC_SLOTS * 256 * 4; // 8 KB: [slot][half][128 rows] fp32constexpr int EPI_WARP0 = 4;constexpr int NUM_THREADS = 128 + NUM_EPI_WARPS * 32; // 384constexpr 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<uint32_t>(__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<uint64_t>(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<uint64_t>(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<uint8_t*>((reinterpret_cast<uintptr_t>(smem_raw) + 1023) & ~uintptr_t(1023)); uint8_t* out_stage = smem + STAGES * STAGE_BYTES; // 16 KB, 1024-aligned float* sc_ring = reinterpret_cast<float*>(out_stage + OUT_STAGE_BYTES); // 8 KB scale ring uint64_t* full_bar = reinterpret_cast<uint64_t*>(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<uint32_t*>(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<int4*>(reinterpret_cast<uint8_t*>(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<uint64_t>(&tmap_a)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&tmap_b)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&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<const float4*>(pa + kb)); const float4 vb = __ldg(reinterpret_cast<const float4*>(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<const float2*>(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<const float2*>(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<float4*>(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<float*>(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<uint32_t*>(&h0); pk.y = *reinterpret_cast<uint32_t*>(&h1); pk.z = *reinterpret_cast<uint32_t*>(&h2); pk.w = *reinterpret_cast<uint32_t*>(&h3); *reinterpret_cast<uint4*>(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<uint32_t*>(&h0); pk.y = *reinterpret_cast<uint32_t*>(&h1); pk.z = *reinterpret_cast<uint32_t*>(&h2); pk.w = *reinterpret_cast<uint32_t*>(&h3); *reinterpret_cast<uint4*>(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<void*>(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;}123456#pragma once#include <cuda_runtime.h>// 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);12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568// 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 <cstdint>#include <cstdio>#include <cuda.h>#include <cuda_runtime.h>#include <cuda_bf16.h>#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 KBconstexpr int TILE_B_BYTES = (BLOCK_N / 2) * BLOCK_K; // 16 KB: own 128-row W halfconstexpr 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 KBconstexpr int OUT_SLOTS = 3; // per-warp staging ring: up to 2 TMA stores in flight while packing the next boxconstexpr int OUT_STAGE_BYTES = NUM_EPI_WARPS * OUT_SLOTS * WARP_STAGE_BYTES; // 24 KBconstexpr int SC_SLOTS = 8; // scale ring depth (k-blocks)constexpr int SC_BYTES = SC_SLOTS * 256 * 4; // 8 KB: [slot][half][128 rows] fp32constexpr int EPI_WARP0 = 4;constexpr int NUM_THREADS = 128 + NUM_EPI_WARPS * 32; // 384constexpr 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 <bool Q = false>__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 <bool Q>__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 <bool Q>__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<uint32_t>(__cvta_generic_to_shared(dst))), "l"(reinterpret_cast<uint64_t>(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<uint32_t>(__cvta_generic_to_shared(dst))), "l"(reinterpret_cast<uint64_t>(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<uint32_t>(__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<uint32_t>(__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<uint64_t>(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<uint64_t>(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<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<Q>(w_, d_, nkb_, T_, k0_, k1_, ws_); else return work_next(w_, d_, t_, sp_, sk_, nkb_, T_, k0_, k1_, ws_); }())template <bool FM, int V = 0>__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<uint8_t*>((reinterpret_cast<uintptr_t>(smem_raw) + 1023) & ~uintptr_t(1023)); uint8_t* out_stage = smem + STAGES * STAGE_BYTES; // 16 KB, 1024-aligned float* sc_ring = reinterpret_cast<float*>(out_stage + OUT_STAGE_BYTES); // 8 KB scale ring uint64_t* full_bar = reinterpret_cast<uint64_t*>(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<uint32_t*>(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<int4*>(reinterpret_cast<uint8_t*>(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<uint64_t*>(reinterpret_cast<uint8_t*>(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<uint64_t>(&tmap_a)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&tmap_b)) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"(reinterpret_cast<uint64_t>(&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<Q>(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<uint64_t>(&tmap_a), lmap_b = reinterpret_cast<uint64_t>(&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<Q>(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<uint64_t>(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<Q>(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<const float4*>(pa + kr)); const float4 vb = __ldg(reinterpret_cast<const float4*>(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<const float2*>(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<const float2*>(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<const float4*>(pa + kb)); const float4 vb = __ldg(reinterpret_cast<const float4*>(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<const float2*>(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<const float2*>(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<float4*>(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<float*>(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<float*>(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<uint32_t*>(&h0); pk.y = *reinterpret_cast<uint32_t*>(&h1); pk.z = *reinterpret_cast<uint32_t*>(&h2); pk.w = *reinterpret_cast<uint32_t*>(&h3); *reinterpret_cast<uint4*>(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<void*>(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<false>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); cudaFuncSetAttribute(fp8_sk2c_kernel<true>, 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<false>, &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 clustersint g_quad_clusters = -1; // cached cudaOccupancyMaxActiveClusters of the quad (4-CTA) configbool sk2c_quad_ok(int ncl) { int& v = g_quad_clusters; if (v < 0) { cudaFuncSetAttribute(fp8_sk2c_kernel<true, 8>, 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<true, 8>, &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<true, 8>, 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<true, 128>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); attr128 = true; } cudaLaunchKernelEx(&cfg, fp8_sk2c_kernel<true, 128>, 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<true, 32>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); attr32 = true; } cudaLaunchKernelEx(&cfg, fp8_sk2c_kernel<true, 32>, 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<true, 1> : (var & 3) == 2 ? fp8_sk2c_kernel<true, 2> : fp8_sk2c_kernel<true, 3>; 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<true, 16>, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM_BYTES); attr16 = true; } cudaLaunchKernelEx(&cfg, fp8_sk2c_kernel<true, 16>, ta, tb, to, sx, sw, S.ws, S.cnt, M, N, K, direct, tail, rot, BT); } else if (fm) cudaLaunchKernelEx(&cfg, fp8_sk2c_kernel<true>, ta, tb, to, sx, sw, S.ws, S.cnt, M, N, K, direct, tail, rot, BT); else cudaLaunchKernelEx(&cfg, fp8_sk2c_kernel<false>, ta, tb, to, sx, sw, S.ws, S.cnt, M, N, K, direct, tail, rot, BT);}1234567891011121314151617181920#pragma once#include <cuda_runtime.h>#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);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694#include <torch/extension.h>#include <algorithm>#include <ATen/cuda/CUDAContext.h>#include <ATen/cuda/EmptyTensor.h>#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 <string>#include <cstdio>#include <functional>#include <vector>
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<const uint8_t*>(x) + (size_t)M1 * K; const float* sx2 = sx + (size_t)M1 * (K / 128); uint16_t* o2 = static_cast<uint16_t*>(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<const uint8_t*>(x) + (size_t)M1 * K; const float* sx2 = sx + (size_t)M1 * (K / 128); uint16_t* o2 = static_cast<uint16_t*>(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<const uint8_t*>(x) + (size_t)M2 * K; const float* sx3 = sx + (size_t)M2 * (K / 128); uint16_t* o3 = static_cast<uint16_t*>(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<float>(), scale_w.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<std::function<void()>> fns; std::vector<int> kinds; if (x2_ok) { kinds.push_back(FK_M128X2); fns.push_back([&]() { launch_fp8_m128x2(x.data_ptr(), w.data_ptr(), sx.data_ptr<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<std::function<void()>> fns; std::vector<int> 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<std::function<void()>> fns; std::vector<int> 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<L2Desc> 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<std::function<void()>> 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<L2Desc> 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<std::function<void()>> 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<float>(); } launch_fp8_large(x.data_ptr(), w.data_ptr(), sx.data_ptr<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<std::function<void()>> fns; std::vector<int> 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(), sw.data_ptr<float>(), 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<float>(); } launch_fp8_bs_gemm(x.data_ptr(), w.data_ptr(), sx.data_ptr<float>(), sw.data_ptr<float>(), 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"); }12345678910111213141516171819202122232425262728293031323334#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 <cstdint>namespace rawpush {__host__ __device__ constexpr uint32_t slice_bytes(int ncol) { return (uint32_t)ncol * 128u; }template <int NCOL>__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 <int NCOL>__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 rawpush12345678910111213141516171819202122232425262728293031323334353637383940414243444546#pragma once#include <cuda.h>#include <cstring>#include <cstdint>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<uint64_t>(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 tmc12345678910# 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.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364{ "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" ] }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153// Host-callable launchers implemented in kernel.cu (raw pointers; no torch types).#pragma once#include <cstdint>#include <cstddef>#include <cuda_runtime.h>
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]^Tint 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 workspaceint 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 chainvoid 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 lockstepint 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_kernelvoid 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 triggervoid 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-blocksvoid 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 replayvoid 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);12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049// 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 <torch/extension.h>#include <ATen/cuda/CUDAContext.h>#include <c10/cuda/CUDAStream.h>#include <c10/cuda/CUDACachingAllocator.h>#include <map>#include <array>#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_PROBEvoid 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 <string>#include <cmath>#include <cstdlib>#include <vector>#include <algorithm>
#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<uintptr_t, 11>;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<Slot> 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 epochstatic 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 drainsstatic constexpr int kDYN = 1 << 27; // wq bit27 (small M, combined gq + bit18): GV_DYN dynamic tile claimingstatic 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 chainstatic constexpr int kPAIR = 1 << 26; // wq bit26 (large M, full grids, MODE 2-SM npw8 both): q_b + kv_b in ONE 2-SM launchint 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<false>) // 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::TensorImpl>(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<at::Tensor> 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<int, Entry*>& cache = *new std::map<int, Entry*>();
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<float> 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<c10::TensorImpl>(std::move(stor), c10::DispatchKeySet(c10::DispatchKey::CUDA), caffe2::TypeMeta::Make<at::BFloat16>()); 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"); }12345678910# 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.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576{ "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" ] }}123456789101112131415161718192021#pragma once#include <cstdint>#include <cuda_runtime.h>
// 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 launchesint 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);12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455// Torch binding: allocates scratch buffers (fp8 activations/weights, scales, bf16 gate_up output)// and calls the CUDA/CUTLASS pipeline in kernel.cu.#include <torch/extension.h>#include <ATen/cuda/CUDAContext.h>#include <ATen/cuda/EmptyTensor.h>#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<float>(), up_w.data_ptr(), up_s.data_ptr<float>(), 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<float>(), 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<OutCtx*>(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<float>(), up_w.data_ptr(), up_s.data_ptr<float>(), down_w.data_ptr(), down_s.data_ptr<float>(), 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"); }
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308// ---------------------------------------------------------------------------------------------------------// 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 <cstdint>#include <cstring>#include <cstdio>#include <cuda.h>#include <cuda_runtime.h>#include <cuda_bf16.h>#include <cuda_fp8.h>
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#endifconstexpr 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<uint32_t*>(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<const uint4*>(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<uint2*>(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 KBconstexpr int OFF_BAR = OFF_A + NA * ASUB; // 224 KBconstexpr int OFF_SWS = OFF_BAR + 512;constexpr int SMEM = OFF_SWS + 512 + 1024; // + 1 KB alignment slackstatic_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 <int EPI, int S>__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<uint8_t*>(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023); uint8_t* wring = smem; uint8_t* aring = smem + OFF_A; uint64_t* bars = reinterpret_cast<uint64_t*>(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<uint32_t*>(accempty + NTS); float* sws = reinterpret_cast<float*>(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<float4*>(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<const uint32_t*>(&g01)), gb2 = bf2f2(*reinterpret_cast<const uint32_t*>(&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<const uint32_t*>(&h01), hw1 = *reinterpret_cast<const uint32_t*>(&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<uint32_t*>(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#endifconstexpr 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; // 480constexpr int DN_KPS = 2; // k blocks per pipeline stepconstexpr 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)#endifstatic_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 KBconstexpr int DN_B8 = DN_KPS * DN_BN * 128; // fp8 KPS x [64 rows x 128 k] = 16 KBconstexpr int DN_AST = DN_KPS * ASUB; // fp8 KPS x [128 rows x 128 k] = 32 KBconstexpr 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] fp32constexpr 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 <int DN_OUT>__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<uint8_t*>(((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<uint64_t*>(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<uint32_t*>(accempty + DN_NT); float* sws = reinterpret_cast<float*>(smem + DN_OFF_SWS); // [0,64) block scales, [64,128) reciprocals float* ssa = reinterpret_cast<float*>(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<uint32_t*>(&b0), *reinterpret_cast<uint32_t*>(&b1), *reinterpret_cast<uint32_t*>(&b2), *reinterpret_cast<uint32_t*>(&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<uint4*>(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<void*>(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<void*>(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<EPI,S> over n_tiles * S CTAs (<= SM count: all co-resident, required by the split-K wait)template <int EPI, int S>static int launch_gemm(GemmParams& p, int n_tiles, cudaStream_t st) { static bool attr = false; if (!attr) { cudaFuncSetAttribute(sm_gemm<EPI, S>, 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<EPI, S>, 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<EPI_SWIGLU, S_GU>): 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<EPI_SWIGLU, S_GU>(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<float4*>(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);}
12345678910# 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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172{ "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" ] }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102// 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 <class ElementPairA, class ElementPairB, class ElementAccumulator, class ClusterShape_MNK, \ UMMA::Major UmmaMajorA, UMMA::Major UmmaMajorB, detail::blockscaled::BlockScaledInstr Instr, \ class BuilderScheduleTag> \struct TrivialBlockscaledMma<ElementPairA, ElementPairB, ElementAccumulator, Shape<_256, Int<ANYN_N>, _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<BuilderScheduleTag, ElementPairA>::sf_type; \ using ElementA = typename detail::blockscaled::blockscaled_type<BuilderScheduleTag, ElementPairA>::data_type; \ using ElementB = typename detail::blockscaled::blockscaled_type<BuilderScheduleTag, ElementPairB>::data_type; \ static constexpr uint32_t VSA = detail::blockscaled::blockscaled_type<BuilderScheduleTag, ElementPairA>::SfVectorSize; \ static constexpr uint32_t VSB = detail::blockscaled::blockscaled_type<BuilderScheduleTag, ElementPairB>::SfVectorSize; \ static constexpr int SfVectorSize = VSA > VSB ? VSA : VSB; \ using ElementAMma = decltype(cutlass::gemm::collective::detail::sm1xx_kernel_input_element_to_mma_input_element<ElementA, false>()); \ using ElementBMma = decltype(cutlass::gemm::collective::detail::sm1xx_kernel_input_element_to_mma_input_element<ElementB, false>()); \ using type = decltype(make_tiled_mma(cute::SM100_MMA_MXF4_2x1SM_SS<ElementAMma, ElementBMma, ElementAccumulator, ElementSF, \ 256, ANYN_N, SfVectorSize, UmmaMajorA, UmmaMajorB>{})); \};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_onetemplate < 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<decltype(shape<0>(typename TiledMma::ThrLayoutVMNK{})), _1, _1>;
using DispatchPolicy = MainloopSm100TmaUmmaWarpSpecializedBlockScaled< Stages, SchedulerPipelineStageCount, AccumulatorPipelineStageCount, ClusterShape>; using TileShape = TileShape_; using TiledMMA_SF = TiledMMA<MMA_Atom<typename TiledMma::MMA_ScaleFactor>, Layout<Shape<_1,_1,_1>>, Tile<Underscore,Underscore,Underscore>>;
static constexpr bool IsDynamicCluster = not cute::is_static_v<ClusterShape>; static constexpr int SFVecSize = TiledMma::SFVecSize; static constexpr bool IsOverlappingAccum = DispatchPolicy::IsOverlappingAccum; static constexpr bool kDirectRelease = cute::is_static_v<ClusterShape> && (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<SFVecSize>; 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<CTA_N_SF>{} * 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<remove_cvref_t<decltype(get<1>(ElementPairA{}))>, remove_cvref_t<decltype(get<1>(ElementPairB{}))>>, "SFA and SFB data types should be the same");
// A and B matrices using ElementA = remove_cvref_t<decltype(get<0>(ElementPairA{}))>; using StrideA = remove_cvref_t<decltype(get<0>(StridePairA{}))>;
using ElementB = remove_cvref_t<decltype(get<0>(ElementPairB{}))>; using StrideB = remove_cvref_t<decltype(get<0>(StridePairB{}))>;
static constexpr bool IsRuntimeDataTypeA = cutlass::gemm::collective::detail::is_sm10x_runtime_f8f6f4<ElementA>(); static constexpr bool IsRuntimeDataTypeB = cutlass::gemm::collective::detail::is_sm10x_runtime_f8f6f4<ElementB>();
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<decltype(get<1>(ElementPairA{}))>; using LayoutSFA = remove_cvref_t<decltype(get<1>(StridePairA{}))>; using LayoutSFB = remove_cvref_t<decltype(get<1>(StridePairB{}))>;
using ElementAccumulator = typename TiledMma::ValTypeC; using GmemTiledCopyPairA = GmemTiledCopyPairA_; using GmemTiledCopyPairB = GmemTiledCopyPairB_; using GmemTiledCopyA = remove_cvref_t<decltype(get<0>(GmemTiledCopyPairA{}))>; using GmemTiledCopySFA = remove_cvref_t<decltype(get<1>(GmemTiledCopyPairA{}))>; using GmemTiledCopyB = remove_cvref_t<decltype(get<0>(GmemTiledCopyPairB{}))>; using GmemTiledCopySFB = remove_cvref_t<decltype(get<1>(GmemTiledCopyPairB{}))>;
using SmemLayoutAtomA = remove_cvref_t<decltype(get<0>(SmemLayoutAtomPairA{}))>; using SmemLayoutAtomSFA = remove_cvref_t<decltype(get<1>(SmemLayoutAtomPairA{}))>; using SmemLayoutAtomB = remove_cvref_t<decltype(get<0>(SmemLayoutAtomPairB{}))>; using SmemLayoutAtomSFB = remove_cvref_t<decltype(get<1>(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<SmemCopyAtomA>, "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<SmemCopyAtomB>, "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<DispatchPolicy::Stages>{}), cute::conditional_t<cutlass::gemm::detail::is_mn_major<StrideA>(), 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<DispatchPolicy::Stages>{}), cute::conditional_t<cutlass::gemm::detail::is_mn_major<StrideB>(), 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<DispatchPolicy::Stages>{}), append(stride(SmemLayoutAtomSFA{}), size(filter_zeros(SmemLayoutAtomSFA{}))) )); using SmemLayoutSFB = decltype(make_layout( append(shape(SmemLayoutAtomSFB{}), Int<DispatchPolicy::Stages>{}), append(stride(SmemLayoutAtomSFB{}), size(filter_zeros(SmemLayoutAtomSFB{}))) ));
static_assert(cute::is_base_of<cute::UMMA::DescriptorIterator, typename TiledMma::FrgTypeA>::value && cute::is_base_of<cute::UMMA::DescriptorIterator, typename TiledMma::FrgTypeB>::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<GmemTiledCopyA, SM90_TMA_LOAD> || cute::is_same_v<GmemTiledCopyA, SM90_TMA_LOAD_MULTICAST>)) || (size(AtomThrShapeMNK{}) == 2 && (cute::is_same_v<GmemTiledCopyA, SM100_TMA_2SM_LOAD> || cute::is_same_v<GmemTiledCopyA, SM100_TMA_2SM_LOAD_MULTICAST>)), "GmemTiledCopy - invalid TMA copy atom specified."); static_assert( (size(AtomThrShapeMNK{}) == 1 && (cute::is_same_v<GmemTiledCopyB, SM90_TMA_LOAD> || cute::is_same_v<GmemTiledCopyB, SM90_TMA_LOAD_MULTICAST>)) || (size(AtomThrShapeMNK{}) == 2 && (cute::is_same_v<GmemTiledCopyB, SM100_TMA_2SM_LOAD> || cute::is_same_v<GmemTiledCopyB, SM100_TMA_2SM_LOAD_MULTICAST>)), "GmemTiledCopy - invalid TMA copy atom specified.");
static constexpr bool IsF8F6F4 = detail::is_sm100_mma_f8f6f4<TiledMma, ElementA, ElementB>();
using TmaInternalElementA = cute::conditional_t<IsF8F6F4, ElementAMma, ElementA>; using TmaInternalElementB = cute::conditional_t<IsF8F6F4, ElementBMma, ElementB>;
using SmemAllocTypeA = cute::conditional_t<IsF8F6F4 && cute::sizeof_bits_v<ElementAMma> < 8, uint8_t, ElementAMma>; using SmemAllocTypeB = cute::conditional_t<IsF8F6F4 && cute::sizeof_bits_v<ElementBMma> < 8, uint8_t, ElementBMma>;
using BitTypeElementA = cute::uint_bit_t<cute::sizeof_bits_v<ElementA>>; using BitTypeElementB = cute::uint_bit_t<cute::sizeof_bits_v<ElementB>>;
using ArrayElementA = cute::conditional_t<IsRuntimeDataTypeA, BitTypeElementA, ElementA>; using ArrayElementB = cute::conditional_t<IsRuntimeDataTypeB, BitTypeElementB, ElementB>;
using RuntimeDataTypeA = typename detail::sm10x_block_scale_runtime_input_t<ElementAMma, IsRuntimeDataTypeA>::Type; using RuntimeDataTypeB = typename detail::sm10x_block_scale_runtime_input_t<ElementBMma, IsRuntimeDataTypeB>::Type;
struct SharedStorage { struct TensorStorage : cute::aligned_struct<128, _0> { cute::ArrayEngine<SmemAllocTypeA, cute::cosize_v<SmemLayoutA>> smem_A; cute::ArrayEngine<SmemAllocTypeB, cute::cosize_v<SmemLayoutB>> smem_B; cute::ArrayEngine<ElementSF, cute::cosize_v<SmemLayoutSFA>> smem_SFA; cute::ArrayEngine<ElementSF, cute::cosize_v<SmemLayoutSFB>> 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<ElementSF>) + cutlass::bits_to_bytes(size(AtomThrShapeMNK{}) * cosize(take<0,3>(SmemLayoutSFB{})) * cute::sizeof_bits_v<ElementSF>); static constexpr uint32_t ABTmaTransactionBytes = cutlass::bits_to_bytes(size(AtomThrShapeMNK{}) * cosize(take<0,3>(SmemLayoutA{})) * cute::sizeof_bits_v<ElementA>) + cutlass::bits_to_bytes(size(AtomThrShapeMNK{}) * cosize(take<0,3>(SmemLayoutB{})) * cute::sizeof_bits_v<ElementB>); static constexpr uint32_t TmaTransactionBytes = ABTmaTransactionBytes + SFTransactionBytes;
template <class AccTensor, class SfaTensor, class SfbTensor> 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<IsDynamicCluster>(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<IsDynamicCluster>(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<TmaInternalElementA>( GmemTiledCopyA{}, make_tensor(recast_ptr<TmaInternalElementA>(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<TmaInternalElementB>( GmemTiledCopyB{}, make_tensor(recast_ptr<TmaInternalElementB>(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<uint16_t>( GmemTiledCopySFA{}, make_tensor(static_cast<ElementSF const*>(nullptr), LayoutSFA{}), SmemLayoutSFA{}(_,_,_,cute::Int<0>{}), TileShape{}, TiledMma{}, ClusterLayout_VMNK{}) );
using TMA_SFB = decltype(make_tma_atom_B_sm100<uint16_t>( GmemTiledCopySFB{}, make_tensor(static_cast<ElementSF const*>(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 <class ProblemShape> 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<TmaInternalElementA>(args.ptr_A); auto ptr_B = recast_ptr<TmaInternalElementB>(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<TmaInternalElementA>( GmemTiledCopyA{}, tensor_a, SmemLayoutA{}(_,_,_,cute::Int<0>{}), TileShape{}, TiledMma{}, cluster_layout_vmnk);
typename Params::TMA_B tma_load_b = make_tma_atom_B_sm100<TmaInternalElementB>( 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<TmaInternalElementA>( 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<TmaInternalElementB>( 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<uint16_t>( GmemTiledCopySFA{}, tensor_sfa, SmemLayoutSFA{}(_,_,_,cute::Int<0>{}), TileShape{}, TiledMma{}, cluster_layout_vmnk);
typename Params::TMA_SFB tma_load_sfb = make_tma_atom_B_sm100<uint16_t>( 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<uint16_t>( 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<uint16_t>( 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 <class ProblemShape> 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<ElementA, IsF8F6F4>(); constexpr int tma_alignment_bits_B = cutlass::detail::get_input_alignment_bits<ElementB, IsF8F6F4>();
bool implementable = true; constexpr int min_tma_aligned_elements_A = tma_alignment_bits_A / cute::sizeof_bits<ElementA>::value; implementable = implementable && cutlass::detail::check_alignment<min_tma_aligned_elements_A>(cute::make_shape(M,K,L), StrideA{}); constexpr int min_tma_aligned_elements_B = tma_alignment_bits_B / cute::sizeof_bits<ElementB>::value; implementable = implementable && cutlass::detail::check_alignment<min_tma_aligned_elements_B>(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 <class TmemStorage> CUTLASS_DEVICE static auto slice_accumulator(TmemStorage tmem_storage, int stage) { return cute::make_tuple(tmem_storage.accumulators(_,_,_,stage)); }
template <class EpilogueTile, bool IsOverlappingAccum = false> 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<AccumulatorPipelineStageCount, IsOverlappingAccum>( tiled_mma, acc_shape, EpilogueTile{}); Tensor tCtSFA = make_tensor<typename TiledMma::FrgTypeSFA>(shape(SmemLayoutAtomSFA{})); Tensor tCtSFB = make_tensor<typename TiledMma::FrgTypeSFB>(shape(SmemLayoutAtomSFB{}));
TmemStorage<decltype(accumulators), decltype(tCtSFA), decltype(tCtSFB)> tmem_storage; tmem_storage.accumulators = accumulators; tmem_storage.tCtSFA = tCtSFA; tmem_storage.tCtSFB = tCtSFB;
return tmem_storage; }
template <class TmemStorage> 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 <class ProblemShape_MNKL> 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 <class TmemStorage> 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<DispatchPolicy::Stages>{} == size<3>(sA)); // PIPE CUTE_STATIC_ASSERT_V(Int<DispatchPolicy::Stages>{} == 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<UtccpOp>(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<UtccpOp>(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<MainloopPipeline, AccumulatorPipeline> pipelines, cute::tuple<MainloopPipelineState, typename AccumulatorPipeline::PipelineState> pipeline_states, cute::tuple<cute::Tensor<FrgEngine, FrgLayout>> 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<FrgEngine>::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<MainloopSm100TmaUmmaWarpSpecializedBlockScaled<..>, ..>// to CollectiveMmaAnyN with identical template arguments (the builder alias is never instantiated).template <class C> struct RebindAnyN;template <int S, int SS, int AS, class CS, class... Rest>struct RebindAnyN<CollectiveMma<MainloopSm100TmaUmmaWarpSpecializedBlockScaled<S, SS, AS, CS>, Rest...>> { using type = CollectiveMmaAnyN<S, SS, AS, CS, Rest...>;};} // namespace cutlass::gemm::collective12345678910111213141516171819202122232425262728// kernel.h -- interface between main.cpp (torch binding) and kernel.cu#pragma once#include <cstdint>#include <cstddef>#include <cuda_runtime.h>
// 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;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329// 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 <torch/extension.h>#include <c10/cuda/CUDAStream.h>#include <cuda_runtime.h>#include <ATen/cuda/EmptyTensor.h>#include <cstring>#include <climits>#include <cstdint>#include <vector>#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<cudaGraphNode_t> from(n), to(n); std::vector<cudaGraphEdgeData> 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<float*>(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<PyCFunction>(reinterpret_cast<void (*)(void)>(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<pybind11::object>(f));}1234567891011# 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.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697{ "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" ] }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598/*************************************************************************************************** * 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 <int NB, int NAD = 1>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 <M,N,K> or <M,N,K,L>");
// 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<CollectiveMainloop>::type; using LayoutSFB = typename cutlass::detail::LayoutSFBType<CollectiveMainloop>::type; using ElementSF = typename cutlass::detail::ElementSFType<CollectiveMainloop>::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<StrideB, InternalStrideB>); using TileSchedulerTag = cute::conditional_t<IsGroupedGemmKernel, GroupScheduler, TileSchedulerTag_>;
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<ClusterShape>; 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<AccumulatorPipelineStageCount, AtomThrShapeMNK>; using AccumulatorPipelineState = typename AccumulatorPipeline::PipelineState;
using CLCPipeline = cute::conditional_t<IsSchedDynamicPersistent, cutlass::PipelineCLCFetchAsync<SchedulerPipelineStageCount, ClusterShape>, cutlass::PipelineAsync<SchedulerPipelineStageCount>>; using CLCPipelineState = typename CLCPipeline::PipelineState; using TensorMapReadyPipeline = cute::conditional_t<IsTensorMapUpdateAsync, cutlass::PipelineAsync<SchedulerPipelineStageCount>, CLCPipeline >; using TensorMapReadyPipelineState = typename TensorMapReadyPipeline::PipelineState; using CLCThrottlePipeline = cute::conditional_t<IsSchedDynamicPersistent, cutlass::PipelineAsync<SchedulerPipelineStageCount>, cutlass::PipelineEmpty>; using CLCThrottlePipelineState = typename CLCThrottlePipeline::PipelineState;
template <class BaseResponse> 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>, typename TileScheduler::CLCResponse >;
using TmemAllocator = cute::conditional_t<cute::size(cute::shape<0>(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<false> and PipelineStorageImpl<true> using TensorMapReadyPipelineStorage = typename TensorMapReadyPipeline::SharedStorage; alignas(16) TensorMapReadyPipelineStorage tensor_map_ready; };
using PipelineStorage = cute::conditional_t<IsTensorMapUpdateAsync, PipelineStorageImplWithAsyncUpdate, PipelineStorageImplWithoutAsyncUpdate>;
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<NB_, NAD_> 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<uint8_t*>(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<typename ProblemShape::UnderlyingProblemShape, ElementAccumulator>( 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<AtomThrShapeMNK>(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<ElementSF>; if constexpr (IsBlockscaled) { if constexpr (IsDynamicCluster) { implementable &= cutlass::detail::preferred_cluster_can_implement<AtomThrShapeMNK>(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<typename ProblemShape::UnderlyingProblemShape, ElementAccumulator>( 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<uint8_t*>(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<typename ProblemShape::UnderlyingProblemShape, ElementAccumulator>( 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<typename ProblemShape::UnderlyingProblemShape, ElementAccumulator>( 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<int>(WarpCategory::Epilogue) ? WarpCategory(warp_idx) : warp_idx < static_cast<int>(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<SharedStorage*>(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<int32_t>(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<IsTensorMapUpdateAsync>( 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<true /*IsLoad*/, IsTensorMapUpdateAsync>( 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<CLCThrottlePipeline>();
// 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<MainloopPipeline>();
EpiLoadPipelineState epi_load_pipe_consumer_state; EpiLoadPipelineState epi_load_pipe_producer_state = cutlass::make_producer_start_state<EpiLoadPipeline>();
// epilogue store pipe is producer-only (consumer is TMA unit, waits via scoreboarding) EpiStorePipelineState epi_store_pipe_producer_state = cutlass::make_producer_start_state<EpiStorePipeline>();
CLCPipelineState clc_pipe_consumer_state; CLCPipelineState clc_pipe_producer_state = cutlass::make_producer_start_state<CLCPipeline>();
TensorMapReadyPipelineState tensor_map_ready_pipe_consumer_state; TensorMapReadyPipelineState tensor_map_ready_pipe_producer_state = cutlass::make_producer_start_state<TensorMapReadyPipeline>();
AccumulatorPipelineState accumulator_pipe_consumer_state; AccumulatorPipelineState accumulator_pipe_producer_state = cutlass::make_producer_start_state<AccumulatorPipeline>();
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, IsOverlappingAccum>(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<IsTensorMapUpdateAsync>( 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<idx>(inputs); } } (load_inputs);
if constexpr (IsTensorMapUpdateAsync) { // Register reconfiguration arch::warpgroup_reg_dealloc<GenericRegisterRequirement>(); }
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<cute::TmaDescriptor*>(¶ms.pre.a[curr_batch / (NB_ / NAD_)]), const_cast<cute::TmaDescriptor*>(¶ms.pre.b[curr_batch]), const_cast<cute::TmaDescriptor*>(¶ms.pre.sfa[curr_batch / (NB_ / NAD_)]), const_cast<cute::TmaDescriptor*>(¶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<GenericRegisterRequirement>(); }
// 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<GenericRegisterRequirement>(); }
// 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<int>(WarpCategory::TensorMapUpdater);
clc_pipe_consumer_state += updater_id; tensor_map_ready_pipe_producer_state += updater_id;
auto tensormaps_mainloop = collective_mainloop.tensormaps_init<IsTensorMapUpdateAsync>( 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<true /*IsLoad*/, IsTensorMapUpdateAsync /*IsTmaAsyncUpdate*/>( 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<false /*IsLoad*/, IsTensorMapUpdateAsync /*IsTmaAsyncUpdate*/>( 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<false /*WaitForInflightTmaRequests*/>( 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<true /*IsLoad*/, false /*WaitForInflightTmaRequests*/>( 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<false /*IsLoad*/, false /*WaitForInflightTmaRequests*/>( 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<true /* IsEpiLoad */>(tensormaps_epilogue_load[tma_desc_offset]); } collective_epilogue.template tensormaps_fence_acquire<false /* IsEpiLoad */>(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<GenericRegisterRequirement>(); }
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<GenericRegisterRequirement>(); }
// 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<IsTensorMapUpdateAsync>( 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<IsTensorMapUpdateAsync>( 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<IsEpiLoad, !IsTensorMapUpdateAsync>( 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<IsOverlappingAccum>( 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<AccumRegisterRequirement>(); }
// 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<int>(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<IsTensorMapUpdateAsync /*IsTmaAsyncUpdate*/>( params.epilogue, shared_storage.tensormaps[0].epilogue, params.hw_info.sm_count, sm_id ); return collective_epilogue.template tensormaps_init<false /*IsLoad*/, IsTensorMapUpdateAsync /*IsTmaAsyncUpdate*/>( 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<IsTensorMapUpdateAsync>( 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<IsOverlappingAccum>( 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<cute::TmaDescriptor*>(¶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<GenericRegisterRequirement>(); }
} }};
///////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::gemm::kernel12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010/*************************************************************************************************** * 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 Declarationstruct 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<Shape<_1,_1,_1>,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_K0template <cute::UMMA::Major major, class ElementType, class BLK_MN, class BLK_K>CUTE_HOST_DEVICE constexprautosm100_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<ElementType>{}) == 0, "for mn-major tf32 operands, SW128_32B is the only available smem layout"); return UMMA::Layout_MN_SW128_32B_Atom<ElementType>{}; } else { // All other data types are handled as SM90 if constexpr (BLK_MN0 % size<0>(UMMA::Layout_MN_SW128_Atom<ElementType>{}) == 0) { return UMMA::Layout_MN_SW128_Atom<ElementType>{}; } else if constexpr (BLK_MN0 % size<0>(UMMA::Layout_MN_SW64_Atom<ElementType>{}) == 0) { return UMMA::Layout_MN_SW64_Atom<ElementType>{}; } else if constexpr (BLK_MN0 % size<0>(UMMA::Layout_MN_SW32_Atom<ElementType>{}) == 0) { return UMMA::Layout_MN_SW32_Atom<ElementType>{}; } else if constexpr (BLK_MN0 % size<0>(UMMA::Layout_MN_INTER_Atom<ElementType>{}) == 0) { return UMMA::Layout_MN_INTER_Atom<ElementType>{}; } else { static_assert(BLK_MN0 % size<0>(UMMA::Layout_MN_INTER_Atom<ElementType>{}) == 0, "BLK_MN0 must be a multiple of size<0>(UMMA::Layout_MN_INTER_Atom<ElementType>{})"); } } } else if constexpr (major == cute::UMMA::Major::K) { if constexpr (BLK_K0 % size<1>(UMMA::Layout_K_SW128_Atom<ElementType>{}) == 0) { return UMMA::Layout_K_SW128_Atom<ElementType>{}; } else if constexpr (BLK_K0 % size<1>(UMMA::Layout_K_SW64_Atom<ElementType>{}) == 0) { return UMMA::Layout_K_SW64_Atom<ElementType>{}; } else if constexpr (BLK_K0 % size<1>(UMMA::Layout_K_SW32_Atom<ElementType>{}) == 0) { return UMMA::Layout_K_SW32_Atom<ElementType>{}; } else if constexpr (BLK_K0 % size<1>(UMMA::Layout_K_INTER_Atom<ElementType>{}) == 0) { return UMMA::Layout_K_INTER_Atom<ElementType>{}; } else { static_assert(BLK_K0 % size<1>(UMMA::Layout_K_INTER_Atom<ElementType>{}) == 0, "BLK_K0 must be a multiple of size<1>(UMMA::Layout_K_INTER_Atom<ElementType>{})"); } }}
// 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_K0template <cute::UMMA::Major major, class ElementType, class BLK_MN, class BLK_K, class Sparsity>CUTE_HOST_DEVICE constexprautosm100_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<ElementType, Sparsity{}>{}) == 0))) { return UMMA::Layout_MN_SW128_32B_SpAtom<ElementType, Sparsity{}>{}; } else { // All other data types are handled as SM90 if constexpr (BLK_MN0 % size<0>(UMMA::Layout_MN_SW128_SpAtom<ElementType, Sparsity{}>{}) == 0) { return UMMA::Layout_MN_SW128_SpAtom<ElementType, Sparsity{}>{}; } else if constexpr (BLK_MN0 % size<0>(UMMA::Layout_MN_SW64_SpAtom<ElementType, Sparsity{}>{}) == 0) { return UMMA::Layout_MN_SW64_SpAtom<ElementType, Sparsity{}>{}; } else if constexpr (BLK_MN0 % size<0>(UMMA::Layout_MN_SW32_SpAtom<ElementType, Sparsity{}>{}) == 0) { return UMMA::Layout_MN_SW32_SpAtom<ElementType, Sparsity{}>{}; } else if constexpr (BLK_MN0 % size<0>(UMMA::Layout_MN_INTER_SpAtom<ElementType, Sparsity{}>{}) == 0) { return UMMA::Layout_MN_INTER_SpAtom<ElementType, Sparsity{}>{}; } else { static_assert(BLK_MN0 % size<0>(UMMA::Layout_MN_INTER_SpAtom<ElementType, Sparsity{}>{}) == 0, "BLK_MN0 must be a multiple of size<0>(UMMA::Layout_MN_INTER_SpAtom<ElementType, Sparsity{}>{})"); } } } else if constexpr (major == cute::UMMA::Major::K) { if constexpr (BLK_K0 % size<1>(UMMA::Layout_K_SW128_SpAtom<ElementType, Sparsity{}>{}) == 0) { return UMMA::Layout_K_SW128_SpAtom<ElementType, Sparsity{}>{}; } else if constexpr (BLK_K0 % size<1>(UMMA::Layout_K_SW64_SpAtom<ElementType, Sparsity{}>{}) == 0) { return UMMA::Layout_K_SW64_SpAtom<ElementType, Sparsity{}>{}; } else if constexpr (BLK_K0 % size<1>(UMMA::Layout_K_SW32_SpAtom<ElementType, Sparsity{}>{}) == 0) { return UMMA::Layout_K_SW32_SpAtom<ElementType, Sparsity{}>{}; } else if constexpr (BLK_K0 % size<1>(UMMA::Layout_K_INTER_SpAtom<ElementType, Sparsity{}>{}) == 0) { return UMMA::Layout_K_INTER_SpAtom<ElementType, Sparsity{}>{}; } else { static_assert(BLK_K0 % size<1>(UMMA::Layout_K_INTER_SpAtom<ElementType, Sparsity{}>{}) == 0, "BLK_K0 must be a multiple of size<1>(UMMA::Layout_K_INTER_SpAtom<ElementType, Sparsity{}>{})"); } }}
template <class ClusterShapeMNK, class AtomThrId>constexpr autosm100_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<ClusterShapeMNK>;
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<ClusterShapeMNK>, "Unsupported Configuration for SM100 TMA"); }}
template <class ClusterShapeMNK, class AtomThrId>constexpr autosm100_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<ClusterShapeMNK>;
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<ClusterShapeMNK>, "Unsupported Configuration for SM100 TMA"); }}
template <class ClusterShapeMNK, class AtomThrId>constexpr autosm100_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<ClusterShapeMNK>; 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<ClusterShapeMNK>, "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 autosm100_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<ElementAMma, cutlass::tfloat32_t>) { static_assert(cute::is_same_v<ElementAMma, ElementBMma>, "ElementAMma and ElementBMma must match."); return make_tiled_mma(cute::SM100_MMA_TF32_SS<ElementAMma, ElementBMma, ElementAMmaccumulator, M, N, UmmaMajorA, UmmaMajorB, ANeg, BNeg>{}); } else if constexpr (cute::is_same_v<ElementAMma, cutlass::half_t> || cute::is_same_v<ElementAMma, cutlass::bfloat16_t>) { static_assert(cute::is_same_v<ElementAMma, ElementBMma>, "ElementAMma and ElementBMma must match."); return make_tiled_mma(cute::SM100_MMA_F16BF16_SS<ElementAMma, ElementBMma, ElementAMmaccumulator, M, N, UmmaMajorA, UmmaMajorB, ANeg, BNeg>{}); } else if constexpr (cute::is_same_v<ElementAMma, int8_t> || cute::is_same_v<ElementAMma, uint8_t>) { return make_tiled_mma(cute::SM100_MMA_S8_SS<ElementAMma, ElementBMma, ElementAMmaccumulator, M, N, UmmaMajorA, UmmaMajorB>{}); } else if constexpr (cute::is_same_v<ElementAMma, cutlass::type_erased_dynamic_float8_t> || cute::is_same_v<ElementAMma, cutlass::detail::type_erased_dynamic_float6_unpacksmem_t> || cute::is_same_v<ElementAMma, cutlass::detail::type_erased_dynamic_float4_unpacksmem_t> || cute::is_same_v<ElementAMma, cutlass::float_e4m3_t> || cute::is_same_v<ElementAMma, cutlass::float_e5m2_t> || cute::is_same_v<ElementAMma, cutlass::detail::float_e2m3_unpacksmem_t> || cute::is_same_v<ElementAMma, cutlass::detail::float_e3m2_unpacksmem_t> || cute::is_same_v<ElementAMma, cutlass::detail::float_e2m1_unpacksmem_t> ) {
return make_tiled_mma( cute::MMA_Traits< cute::SM100_MMA_F8F6F4_SS, ElementAMma, ElementBMma, ElementAMmaccumulator, cute::C<M>, cute::C<N>, cute::integral_constant<UMMA::Major, UmmaMajorA>, cute::integral_constant<UMMA::Major, UmmaMajorB>, cute::integral_constant<UMMA::ScaleIn, ANeg>, cute::integral_constant<UMMA::ScaleIn, BNeg> >{} ); } else { static_assert(cutlass::detail::dependent_false<ElementAMma>, "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 autosm100_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<ElementAMma, cutlass::tfloat32_t>) { static_assert(cute::is_same_v<ElementAMma, ElementBMma>, "ElementAMma and ElementBMma must match."); return make_tiled_mma(cute::SM100_MMA_TF32_2x1SM_SS<ElementAMma, ElementBMma, ElementAMmaccumulator, M, N, UmmaMajorA, UmmaMajorB, ANeg, BNeg>{}); } else if constexpr (cute::is_same_v<ElementAMma, cutlass::half_t> || cute::is_same_v<ElementAMma, cutlass::bfloat16_t>) { static_assert(cute::is_same_v<ElementAMma, ElementBMma>, "ElementAMma and ElementBMma must match."); return make_tiled_mma(cute::SM100_MMA_F16BF16_2x1SM_SS<ElementAMma, ElementBMma, ElementAMmaccumulator, M, N, UmmaMajorA, UmmaMajorB, ANeg, BNeg>{}); } else if constexpr (cute::is_same_v<ElementAMma, int8_t> || cute::is_same_v<ElementAMma, uint8_t>) { return make_tiled_mma(cute::SM100_MMA_S8_2x1SM_SS<ElementAMma, ElementBMma, ElementAMmaccumulator, M, N, UmmaMajorA, UmmaMajorB>{}); } else if constexpr (cute::is_same_v<ElementAMma, cutlass::type_erased_dynamic_float8_t> || cute::is_same_v<ElementAMma, cutlass::detail::type_erased_dynamic_float6_unpacksmem_t> || cute::is_same_v<ElementAMma, cutlass::detail::type_erased_dynamic_float4_unpacksmem_t> || cute::is_same_v<ElementAMma, cutlass::float_e4m3_t> || cute::is_same_v<ElementAMma, cutlass::float_e5m2_t> || cute::is_same_v<ElementAMma, cutlass::detail::float_e2m3_unpacksmem_t> || cute::is_same_v<ElementAMma, cutlass::detail::float_e3m2_unpacksmem_t> || cute::is_same_v<ElementAMma, cutlass::detail::float_e2m1_unpacksmem_t> ) {
return make_tiled_mma( cute::MMA_Traits< cute::SM100_MMA_F8F6F4_2x1SM_SS, ElementAMma, ElementBMma, ElementAMmaccumulator, cute::C<M>, cute::C<N>, cute::integral_constant<UMMA::Major, UmmaMajorA>, cute::integral_constant<UMMA::Major, UmmaMajorB>, cute::integral_constant<UMMA::ScaleIn, ANeg>, cute::integral_constant<UMMA::ScaleIn, BNeg> >{} );
} else { static_assert(cutlass::detail::dependent_false<ElementAMma>, "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 autosm100_make_trivial_tiled_mma() { // MMA_2SM requested if constexpr (cute::is_base_of_v<KernelSchedule2Sm, BuilderScheduleTag> ) { return sm100_make_2sm_trivial_tiled_mma<ElementAMma, ElementBMma, ElementAccumulator, TileShape_MNK, ClusterShape_MNK, UmmaMajorA, UmmaMajorB, ANeg, BNeg>(); } // MMA_1SM requested else if constexpr (cute::is_base_of_v<KernelSchedule1Sm, BuilderScheduleTag> ) { return sm100_make_1sm_trivial_tiled_mma<ElementAMma, ElementBMma, ElementAccumulator, TileShape_MNK, ClusterShape_MNK, UmmaMajorA, UmmaMajorB, ANeg, BNeg>(); } // Auto scheduling requested else if constexpr (cute::is_same_v<BuilderScheduleTag, KernelScheduleAuto>) { // Static cluster if constexpr (cute::is_static_v<ClusterShape_MNK>) { // 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<ElementAMma, ElementBMma, ElementAccumulator, TileShape_MNK, ClusterShape_MNK, UmmaMajorA, UmmaMajorB, ANeg, BNeg>(); } else { return sm100_make_1sm_trivial_tiled_mma<ElementAMma, ElementBMma, ElementAccumulator, TileShape_MNK, ClusterShape_MNK, UmmaMajorA, UmmaMajorB, ANeg, BNeg>(); } // Dynamic cluster shape means we cannot assume we can use 2SM MMA } else { return sm100_make_1sm_trivial_tiled_mma<ElementAMma, ElementBMma, ElementAccumulator, TileShape_MNK, ClusterShape_MNK, UmmaMajorA, UmmaMajorB, ANeg, BNeg>(); } }}
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 autosm100_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<ElementAMma, cutlass::tfloat32_t>) { static_assert(cute::is_same_v<ElementAMma, ElementBMma>, "ElementA and ElementB must match."); return make_tiled_mma(cute::SM100_MMA_TF32_TS<ElementAMma, ElementBMma, ElementAccumulator, M, N, UmmaMajorA, UmmaMajorB, ANeg, BNeg>{}); } else if constexpr (cute::is_same_v<ElementAMma, cutlass::half_t> || cute::is_same_v<ElementAMma, cutlass::bfloat16_t>) { static_assert(cute::is_same_v<ElementAMma, ElementBMma>, "ElementA and ElementB must match."); return make_tiled_mma(cute::SM100_MMA_F16BF16_TS<ElementAMma, ElementBMma, ElementAccumulator, M, N, UmmaMajorA, UmmaMajorB, ANeg, BNeg>{}); } else if constexpr (cute::is_same_v<ElementAMma, int8_t> || cute::is_same_v<ElementAMma, uint8_t>) { return make_tiled_mma(cute::SM100_MMA_S8_TS<ElementAMma, ElementBMma, ElementAccumulator, M, N, UmmaMajorA, UmmaMajorB>{}); } else { static_assert(cutlass::detail::dependent_false<ElementAMma>, "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 autosm100_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<ElementAMma, cutlass::tfloat32_t>) { static_assert(cute::is_same_v<ElementAMma, ElementBMma>, "For SM100 TF32 MMA, ElementA and ElementB must match."); return make_tiled_mma(cute::SM100_MMA_TF32_2x1SM_TS<ElementAMma, ElementBMma, ElementAccumulator, M, N, UmmaMajorA, UmmaMajorB, ANeg, BNeg>{}); } else if constexpr (cute::is_same_v<ElementAMma, cutlass::half_t> || cute::is_same_v<ElementAMma, cutlass::bfloat16_t>) { static_assert(cute::is_same_v<ElementAMma, ElementBMma>, "For SM100 F16F32 MMA, ElementA and ElementB must match."); return make_tiled_mma(cute::SM100_MMA_F16BF16_2x1SM_TS<ElementAMma, ElementBMma, ElementAccumulator, M, N, UmmaMajorA, UmmaMajorB, ANeg, BNeg>{}); } else if constexpr (cute::is_same_v<ElementAMma, int8_t> || cute::is_same_v<ElementAMma, uint8_t>) { return make_tiled_mma(cute::SM100_MMA_S8_2x1SM_TS<ElementAMma, ElementBMma, ElementAccumulator, M, N, UmmaMajorA, UmmaMajorB>{}); } else { static_assert(cutlass::detail::dependent_false<ElementAMma>, "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 autosm100_make_trivial_fastFP32_tiled_mma() { constexpr bool TagHasUmmaSs = ( cute::is_base_of_v<KernelTmaWarpSpecializedFastFP32SmemSm100, BuilderScheduleTag> );
// MMA_2SM requested if constexpr (cute::is_base_of_v<KernelSchedule2Sm, BuilderScheduleTag> ) { 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<ElementAMma, ElementBMma, ElementAccumulator, M, N, UmmaMajorA, UmmaMajorB, Scale>{}); } 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<ElementAMma, ElementBMma, ElementAccumulator, M, N, UmmaMajorA, UmmaMajorB, Scale>{}); } } // MMA_1SM requested else if constexpr (cute::is_base_of_v<KernelSchedule1Sm, BuilderScheduleTag> ) { // using AtomLayout_MNK = Layout<ClusterShape_MNK>; 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<ElementAMma, ElementBMma, ElementAccumulator, M, N, UmmaMajorA, UmmaMajorB, Scale>{}); } 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<ElementAMma, ElementBMma, ElementAccumulator, M, N, UmmaMajorA, UmmaMajorB, Scale>{}); } } else if constexpr (cute::is_same_v<BuilderScheduleTag, KernelScheduleSm100FastFP32Gemm> || cute::is_same_v<BuilderScheduleTag, KernelTmaWarpSpecializedFastFP32SmemSm100> || cute::is_same_v<BuilderScheduleTag, KernelScheduleSm100PtrArrayFastFP32Gemm> || cute::is_same_v<BuilderScheduleTag, KernelTmaWarpSpecializedPtrArrayFastFP32SmemSm100>) { // Static cluster if constexpr (cute::is_static_v<ClusterShape_MNK>) { // 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<ElementAMma, ElementBMma, ElementAccumulator, TileShape_MNK, ClusterShape_MNK, UmmaMajorA, UmmaMajorB, Scale, KernelTmaWarpSpecialized2SmFastFP32Sm100>(); } else { return sm100_make_trivial_fastFP32_tiled_mma<ElementAMma, ElementBMma, ElementAccumulator, TileShape_MNK, ClusterShape_MNK, UmmaMajorA, UmmaMajorB, Scale, KernelTmaWarpSpecialized2SmFastFP32SmemSm100>(); } } else { if constexpr (!TagHasUmmaSs) { return sm100_make_trivial_fastFP32_tiled_mma<ElementAMma, ElementBMma, ElementAccumulator, TileShape_MNK, ClusterShape_MNK, UmmaMajorA, UmmaMajorB, Scale, KernelTmaWarpSpecialized1SmFastFP32Sm100>(); } else { return sm100_make_trivial_fastFP32_tiled_mma<ElementAMma, ElementBMma, ElementAccumulator, TileShape_MNK, ClusterShape_MNK, UmmaMajorA, UmmaMajorB, Scale, KernelTmaWarpSpecialized1SmFastFP32SmemSm100>(); } } } // Dynamic cluster shape means we cannot assume we can use 2SM MMA else { if constexpr (!TagHasUmmaSs) { return sm100_make_trivial_fastFP32_tiled_mma<ElementAMma, ElementBMma, ElementAccumulator, TileShape_MNK, ClusterShape_MNK, UmmaMajorA, UmmaMajorB, Scale, KernelTmaWarpSpecialized1SmFastFP32Sm100>(); } else { return sm100_make_trivial_fastFP32_tiled_mma<ElementAMma, ElementBMma, ElementAccumulator, TileShape_MNK, ClusterShape_MNK, UmmaMajorA, UmmaMajorB, Scale, KernelTmaWarpSpecialized1SmFastFP32SmemSm100>(); } } } else { static_assert(cutlass::detail::dependent_false<TileShape_MNK> == 0, "Unsupported policy for SM100 collective builder."); }}
template< class TileShape_MNK, class ClusterShape_MNK, class BuilderScheduleTag>constexpr autosm100_make_trivial_interleaved_complex_tf32_tiled_mma() { // MMA_2SM requested if constexpr (cute::is_base_of_v<KernelSchedule2Sm, BuilderScheduleTag> ) { 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<M, N, cute::UMMA::Major::K, cute::UMMA::Major::K>{}); } // MMA_1SM requested else if constexpr (cute::is_base_of_v<KernelSchedule1Sm, BuilderScheduleTag> ) { 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<M, N, cute::UMMA::Major::K, cute::UMMA::Major::K>{}); } else if constexpr (cute::is_same_v<BuilderScheduleTag, KernelScheduleAuto>) { // Static cluster if constexpr (cute::is_static_v<ClusterShape_MNK>) { // 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<TileShape_MNK,ClusterShape_MNK,KernelTmaWarpSpecialized2SmInterleavedComplexTF32Sm100>(); } else { return sm100_make_trivial_interleaved_complex_tf32_tiled_mma<TileShape_MNK,ClusterShape_MNK,KernelTmaWarpSpecialized1SmInterleavedComplexTF32Sm100>(); } } // Dynamic cluster shape means we cannot assume we can use 2SM MMA else { return sm100_make_trivial_interleaved_complex_tf32_tiled_mma<TileShape_MNK,ClusterShape_MNK,KernelTmaWarpSpecialized1SmInterleavedComplexTF32Sm100>(); } }}
//Setting mma for Mixed input gemm. Here, ElementAMma should be TAComputetemplate< class ElementAMma, class ElementBMma, class ElementAccumulator, class TileShape_MNK, class ClusterShape_MNK, UMMA::Major UmmaMajorA, UMMA::Major UmmaMajorB, class KernelScheduleType>constexpr autosm100_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<KernelSchedule1Sm, KernelScheduleType> ) { if constexpr (UmmaMajorA == cute::UMMA::Major::K && !cute::is_base_of_v<KernelTmaWarpSpecializedMixedInputSmemSm100, KernelScheduleType>) { if constexpr (cute::is_same_v<ElementBMma, cutlass::half_t> || cute::is_same_v<ElementBMma, cutlass::bfloat16_t>) { return make_tiled_mma(cute::SM100_MMA_F16BF16_TS<ElementAMma, ElementBMma, ElementAccumulator, M, N, UmmaMajorA, UmmaMajorB>{}); } if constexpr (cute::is_same_v<ElementBMma, cutlass::float_e4m3_t>) { return make_tiled_mma(cute::SM100_MMA_F8F6F4_TS<ElementAMma, ElementBMma, ElementAccumulator, M, N, UmmaMajorA, UmmaMajorB>{}); } } else { // If A needs to be transposed by MMA, fall back to SMEM from A MMA instructions if constexpr (cute::is_same_v<ElementBMma, cutlass::half_t> || cute::is_same_v<ElementBMma, cutlass::bfloat16_t>) { return make_tiled_mma(cute::SM100_MMA_F16BF16_SS<ElementAMma, ElementBMma, ElementAccumulator, M, N, UmmaMajorA, UmmaMajorB>{}); } if constexpr (cute::is_same_v<ElementBMma, cutlass::float_e4m3_t>) { return make_tiled_mma( cute::MMA_Traits< cute::SM100_MMA_F8F6F4_SS, ElementAMma, ElementBMma, ElementAccumulator, cute::C<M>, cute::C<N>, cute::integral_constant<UMMA::Major, UmmaMajorA>, cute::integral_constant<UMMA::Major, UmmaMajorB>, cute::integral_constant<UMMA::ScaleIn, cute::UMMA::ScaleIn::One>, cute::integral_constant<UMMA::ScaleIn, cute::UMMA::ScaleIn::One>>{}); } } } //MMA 2Sm requested else if constexpr (cute::is_base_of_v<KernelSchedule2Sm, KernelScheduleType>) { if constexpr (UmmaMajorA == cute::UMMA::Major::K && !cute::is_base_of_v<KernelTmaWarpSpecializedMixedInputSmemSm100, KernelScheduleType>) { if constexpr (cute::is_same_v<ElementBMma, cutlass::half_t> || cute::is_same_v<ElementBMma, cutlass::bfloat16_t>) { return make_tiled_mma(cute::SM100_MMA_F16BF16_2x1SM_TS<ElementAMma, ElementBMma, ElementAccumulator, M, N, UmmaMajorA, UmmaMajorB>{}); } if constexpr (cute::is_same_v<ElementBMma, cutlass::float_e4m3_t>) { return make_tiled_mma(cute::SM100_MMA_F8F6F4_2x1SM_TS<ElementAMma, ElementBMma, ElementAccumulator, M, N, UmmaMajorA, UmmaMajorB>{}); } } } else { static_assert(cutlass::detail::dependent_false<TileShape_MNK> == 0, "Unsupported policy for SM100 collective builder."); }}
template< class CtaShape_MNK>constexpr autosm100_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 autosm100_make_blockscaled_1sm_trivial_tiled_mma() { // For MMA_1sm atoms, the MMA's AtomLayout is same as the ClusterShape using AtomLayout_MNK = Layout<ClusterShape_MNK>; 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<BuilderScheduleTag, ElementPairA>::sf_type; using ElementSFB = typename detail::blockscaled::blockscaled_type<BuilderScheduleTag, ElementPairB>::sf_type; using ElementA = typename detail::blockscaled::blockscaled_type<BuilderScheduleTag, ElementPairA>::data_type; using ElementB = typename detail::blockscaled::blockscaled_type<BuilderScheduleTag, ElementPairB>::data_type; constexpr uint32_t SfVectorSizeA = detail::blockscaled::blockscaled_type<BuilderScheduleTag, ElementPairA>::SfVectorSize; [[maybe_unused]] constexpr uint32_t SfVectorSizeB = detail::blockscaled::blockscaled_type<BuilderScheduleTag, ElementPairB>::SfVectorSize;
using ElementAMma = decltype(cutlass::gemm::collective::detail::sm1xx_kernel_input_element_to_mma_input_element<ElementA, Instr == detail::blockscaled::BlockScaledInstr::MXF4F6F8>()); using ElementBMma = decltype(cutlass::gemm::collective::detail::sm1xx_kernel_input_element_to_mma_input_element<ElementB, Instr == detail::blockscaled::BlockScaledInstr::MXF4F6F8>());
using ElementSF = ElementSFA;
if constexpr (Instr == detail::blockscaled::BlockScaledInstr::MXF4F6F8) { if constexpr (cute::is_base_of_v<KernelScheduleBlockScaledSparseGemmSm100, BuilderScheduleTag> ) { return make_tiled_mma(cute::SM100_MMA_MXF8F6F4_SS_SPARSE<ElementAMma, ElementBMma, ElementAccumulator, ElementSF, M, N, UmmaMajorA, UmmaMajorB>{}); } else { return make_tiled_mma(cute::SM100_MMA_MXF8F6F4_SS<ElementAMma, ElementBMma, ElementAccumulator, ElementSF, M, N, UmmaMajorA, UmmaMajorB>{}); } } else if constexpr (Instr == detail::blockscaled::BlockScaledInstr::MXF4_NVF4) { constexpr int SfVectorSize = SfVectorSizeA; if constexpr (cute::is_base_of_v<KernelScheduleBlockScaledSparseGemmSm100, BuilderScheduleTag> ) { return make_tiled_mma(cute::SM100_MMA_MXF4NVF4_SS_SPARSE<ElementAMma, ElementBMma, ElementAccumulator, ElementSF, M, N, SfVectorSize, UmmaMajorA, UmmaMajorB>{}); } else { return make_tiled_mma(cute::SM100_MMA_MXF4_SS<ElementAMma, ElementBMma, ElementAccumulator, ElementSF, M, N, SfVectorSize, UmmaMajorA, UmmaMajorB>{}); } } else { static_assert(cutlass::detail::dependent_false<ElementAMma>, "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 autosm100_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<BuilderScheduleTag, ElementPairA>::sf_type; using ElementSFB = typename detail::blockscaled::blockscaled_type<BuilderScheduleTag, ElementPairB>::sf_type; using ElementA = typename detail::blockscaled::blockscaled_type<BuilderScheduleTag, ElementPairA>::data_type; using ElementB = typename detail::blockscaled::blockscaled_type<BuilderScheduleTag, ElementPairB>::data_type; constexpr uint32_t SfVectorSizeA = detail::blockscaled::blockscaled_type<BuilderScheduleTag, ElementPairA>::SfVectorSize; [[maybe_unused]] constexpr uint32_t SfVectorSizeB = detail::blockscaled::blockscaled_type<BuilderScheduleTag, ElementPairB>::SfVectorSize; using ElementAMma = decltype(cutlass::gemm::collective::detail::sm1xx_kernel_input_element_to_mma_input_element<ElementA, Instr == detail::blockscaled::BlockScaledInstr::MXF4F6F8>()); using ElementBMma = decltype(cutlass::gemm::collective::detail::sm1xx_kernel_input_element_to_mma_input_element<ElementB, Instr == detail::blockscaled::BlockScaledInstr::MXF4F6F8>());
using ElementSF = ElementSFA;
if constexpr (Instr == detail::blockscaled::BlockScaledInstr::MXF4F6F8) { if constexpr (cute::is_base_of_v<KernelScheduleBlockScaledSparseGemmSm100, BuilderScheduleTag> ) { return make_tiled_mma(cute::SM100_MMA_MXF8F6F4_2x1SM_SS_SPARSE<ElementAMma, ElementBMma, ElementAccumulator, ElementSF, M, N, UmmaMajorA, UmmaMajorB>{}); } else { return make_tiled_mma(cute::SM100_MMA_MXF8F6F4_2x1SM_SS<ElementAMma, ElementBMma, ElementAccumulator, ElementSF, M, N, UmmaMajorA, UmmaMajorB>{}); } } else if constexpr (Instr == detail::blockscaled::BlockScaledInstr::MXF4_NVF4) { constexpr int SfVectorSize = SfVectorSizeA > SfVectorSizeB ? SfVectorSizeA : SfVectorSizeB; if constexpr (cute::is_base_of_v<KernelScheduleBlockScaledSparseGemmSm100, BuilderScheduleTag> ) { return make_tiled_mma(cute::SM100_MMA_MXF4NVF4_2x1SM_SS_SPARSE<ElementAMma, ElementBMma, ElementAccumulator, ElementSF, M, N, SfVectorSize, UmmaMajorA, UmmaMajorB>{}); } else { return make_tiled_mma(cute::SM100_MMA_MXF4_2x1SM_SS<ElementAMma, ElementBMma, ElementAccumulator, ElementSF, M, N, SfVectorSize, UmmaMajorA, UmmaMajorB>{}); } } else { static_assert(cutlass::detail::dependent_false<ElementAMma>, "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<ElementPairA, ElementPairB, ElementAccumulator, TileShape_MNK, ClusterShape_MNK, UmmaMajorA, UmmaMajorB, Instr, BuilderScheduleTag>()); };
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<ElementPairA, ElementPairB, ElementAccumulator, TileShape_MNK, ClusterShape_MNK, UmmaMajorA, UmmaMajorB, Instr, BuilderScheduleTag>());};
} // namespace detail
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::gemm::collectivekernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_large2.cuAdded+1702
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_large2.hAdded+25
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_largev.cuAdded+524
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_largev.hAdded+7
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128c.cuAdded+956
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128c.hAdded+13
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128x2.cuAdded+530
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m128x2.hAdded+7
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256.cuAdded+863
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256.hAdded+9
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256c.cuAdded+666
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256c.hAdded+11
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256p.cuAdded+768
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256p.hAdded+7
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256v.cuAdded+864
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256v.hAdded+14
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256x2.cuAdded+526
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_m256x2.hAdded+7
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk.cuAdded+786
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk.hAdded+6
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk2c.cuAdded+1568
kernels/Quant/015_fp8_mla_attention_output_projection/src/kernel_sk2c.hAdded+20
kernels/Quant/015_fp8_mla_attention_output_projection/src/main.cppAdded+694
kernels/Quant/015_fp8_mla_attention_output_projection/src/raw_push.hAdded+34
kernels/Quant/015_fp8_mla_attention_output_projection/src/tmap_cache.hAdded+46
kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/README.mdAdded+10
kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/kernel.jsonAdded+64
kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/src/kernel.cuAdded
kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/src/kernel.hAdded+153
kernels/Quant/016_fp8_multi_latent_attention_qkv_projection/src/main.cppAdded+1049
kernels/Quant/017_fp8_shared_expert_mlp/README.mdAdded+10
kernels/Quant/017_fp8_shared_expert_mlp/kernel.jsonAdded+76
kernels/Quant/017_fp8_shared_expert_mlp/src/bw2wg.hAdded
kernels/Quant/017_fp8_shared_expert_mlp/src/kernel.cuAdded
kernels/Quant/017_fp8_shared_expert_mlp/src/kernel.hAdded+21
kernels/Quant/017_fp8_shared_expert_mlp/src/main.cppAdded+55
kernels/Quant/017_fp8_shared_expert_mlp/src/smallm.cuAdded+1308
kernels/Quant/018_nvfp4_attention_output_projection_with_residual/README.mdAdded+10
kernels/Quant/018_nvfp4_attention_output_projection_with_residual/kernel.jsonAdded+72
kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/collective_anyn.hppAdded+1102
kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/kernel.cuAdded
kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/kernel.hAdded+28
kernels/Quant/018_nvfp4_attention_output_projection_with_residual/src/main.cppAdded+329
kernels/Quant/019_nvfp4_grouped_query_attention/README.mdAdded+11
kernels/Quant/019_nvfp4_grouped_query_attention/kernel.jsonAdded+97
kernels/Quant/019_nvfp4_grouped_query_attention/src/array_pre.hppAdded+1598
kernels/Quant/019_nvfp4_grouped_query_attention/src/cutlass/gemm/collective/builders/sm100_common.inlAdded+1010
kernels/Quant/019_nvfp4_grouped_query_attention/src/cutlass/gemm/collective/sm100_blockscaled_mma_array_warpspecialized.hppAdded
kernels/Quant/019_nvfp4_grouped_query_attention/src/cutlass/gemm/collective/sm100_blockscaled_mma_warpspecialized.hppAdded
kernels/Quant/019_nvfp4_grouped_query_attention/src/kernel.cuAdded