QianQu's picture
Upload folder using huggingface_hub (part 3)
bdebe19 verified
Raw History Blame Contribute Delete
289 kB
// (1) conv_s2_umma_kernel<false,32> -- W % 4 == 0 (16B aligned x): tcgen05.mma kind::f16 // (M128 px x N64 cout x K16, accumulators in TMEM) fed by a TMA ring and a smem K-major // conversion stage. Tile = 4 out rows x 32 out cols. One MMA "stage" = 16 input channels // (2 per tile). TMA ring = U_NT sub-stages of 8 input channels (box 68 cols x 9 rows x 8 ch = // 19584 B each) = U_NT/4 tiles of raw input in flight per SM; every stage consumes two // sub-stages (one per channel octet), each released by the 9 converter warps of its octet. // Converted ring = U_NC_TMA stages. To make room for the deeper TMA ring, this path has NO // output smem staging: the epilogue writes y directly from TMEM regs with streaming // st.global.cs (each warp store = one 128 B row segment of one cout). // (3) conv_s2_band_kernel -- odd/unaligned W with Wo <= 256: full-width 1-row bands fed by one 1D // bulk copy per channel (see its header); autotuned per shape against (2). // PDL: the conv prologue overlaps wprep; thread 0 issues only stage 0's input TMAs at startup; after // setup the MMA thread (griddepcontrol.wait, then 1D bulk copies of the pre-swizzled weights, one 18 KB // copy per 16-channel K-chunk with its own mbarrier wbar[c]) and the producer (rest of the input ring) // run concurrently, so the L2-hot weights are not queued behind the cold-DRAM input flood. Grid = min(#tiles, #SM). // (4) PHASE path, conv_s2_umma_kernel<false,32,16> -- W % 4 != 0 (16B-aligned x, H >= 4): the TMA // pipeline of (1) fed through 16 (row phase x channel phase) tensor maps, 4 TMAs per 8-channel // sub-stage, converters undo the per-map column shift (see P_* defines). Autotuned per shape // (cudaEvent timing, cached by (N,H,W)) against gather (2) and band (3). // (5) DUAL, conv_s2_umma_kernel<false,32,1,true> -- the (1) pipeline at 2 CTAs/SM (480 thr, 105.7 KB smem, // see D_* defines); per-shape cold-L2 autotune single vs DUAL for aligned shapes. // (7) aligned converter shuffles the packed fp16x2 kx=0 column (half the SHFLs, 4 fewer F2FP). // (8) aligned converter uses explicit 32-bit ld/st.shared with immediate offsets (no generic 64-bit LD/ST). // (9) phase-path converter: packed kx=0 SHFL + 32-bit ld.shared with immediate offsets. // (10) phase converter lane -> px (m, m+16): bank-conflict-free stride-2 LDS.32, templated channel stride. // (11) phase path box 72->68 cols, ring depth 6/7 (template) x tail halves on/off, cold-L2 autotuned. // (12) fused weight transform remapped (cout per lane, per-lane element rotation): conflict-free LDS/STS. // (13) BULK-ROW path, conv_s2_umma_kernel<false,32,2,false,PNT> -- W % 4 != 0, 16B-aligned x: same pipeline // and converter as the phase path, but the producer WARP loads each 8-channel sub-stage (channel phase j: // ci = 4i+j) with plain 1D cp.async.bulk copies, one per (channel, input row): the contiguous segment from the // 16B-aligned element at/below col 64tx-1 (col 0 for tx = 0) to min(64tx+64, W), rounded up to 16 B (<= 68 // cols), into a dense [8 ch][9 rows][68] slot. The column shift is uniform over the 8 channels of a phase // (4*H*W = 0 mod 4), so it is uniform per converter half-warp; pad rows are zeroed by the converter, col W // (odd W) is masked. Autotuned against phase/gather/band. // (14) bulk-row producer = one warp-reduced arrive.expect_tx (lane 0) then the copies; bulk-row ring 6 // or 7 x tail halves on/off, all cold-L2 autotuned per shape. // (15) shapes with 2*tiles <= #SM run as ALL half tiles (2 out rows x 32, grid = 2*tiles): shorter // per-CTA critical path for tiny shapes (e.g. 1x131: 51 tiles -> 102 CTAs). Autotuned (odd W) via 'halves'. // (16) MINI: conv_s2_mini_kernel -- non-persistent half-tile CTAs, 75 KB smem, 3 CTAs/SM (see its header); // cold-L2 autotuned per shape against every other path (aligned and odd W). // (17) mini path template ring depth MNT (2 or 4 slots); MNT = 4 issues the CTA's whole input up front // (roofline calibration: tiny shapes were furthest from a streaming kernel). Autotuned as another option. // (18) mini path with 2-CTA clusters splitting the weight transform (DSMEM stores), autotuned option. // (19) parity-alias guard in the 2-group TMA converter loop (latent intermittent hang fix). // (20) the guard is replaced by per-converter-group full barriers tfull[slot][group] (alias-free by // construction, no extra wait in steady state). // (21) PDL audit: every PDL kernel triggers launch_dependents only AFTER its TMEM alloc (no // secondary-holds-TMEM / primary-blocked-in-alloc deadlock); every thread griddepcontrol.waits before // its first global access (band/gather paths included). // (22) autotune score = trimmed mean of 11 cold-L2 reps. // (24) per-shape choice = majority over 3 independent tune passes (tune_select_vote). // (25) tuner options 14/15 (odd W) = phase ring7/6 + halves with wfused = 3: same raw smem weight copy, // but the converters build the fp16 B image with one (cout, 4-chunk) item per thread from 8 LDS.128 // (phase K order makes 4 consecutive chunks = the components of aligned float4s) instead of 4 rotated // chunks from 32 LDS.32 + barrel shifts. (An epilogue-warp transform from global w was probed: no gain.) // (26) aligned tuner option 6 = single TMA path with a vectorized natural-order B-image transform // (wfused = 3 on the aligned path: (co, octet, half) items, 9 LDS.128 + 9 STS.64 per thread). // (27) the vectorized transforms (natural order: aligned single/DUAL; phase order: phase/bulk-row/mini) // are the ONLY in-CTA weight transforms (old scalar/barrel-shift ones removed); options 6/14/15 retired. // (28) tuner options (aligned 6/7, odd 14/15) = mini / mini4 launched with a ~100 KB smem carveout preference. // (29) aligned tuner option 8 = converter-free tf32 direct kernel (raw fp32 TMA planes as MN-major A, // kx folded into N=192, stride-2 in the epilogue, in-CTA vectorized tf32 B image); voted cold-L2 tune. // (31) aligned tuner options 10/11 = option 9 + producer TMA L2 prefetches (cp.async.bulk.prefetch.tensor) // of the input boxes 2 / 4 MMA stages beyond the smem ring (more DRAM bytes in flight, no extra smem). // (32) aligned tuner options 12/13 = option 10 / 9 with the producer NOT waiting for the raw weight copy // before issuing the rest of the input ring (cuts the startup DRAM-idle gap on mid shapes, e.g. 2x512). // (6) aligned TMA path fetches each input row as a 128B-line-aligned 64-col main box + a 4-col halo box. // (35) odd-W tuner options 2/3 = phase ring7/6 + halves with the PAIR-LOAD converter (ph2_pair: LDS.64 + // LDS.32 per channel and px, no SHFL, destination planes permuted per lane). // (37) natural-order (aligned) weight-transform item map permuted: STS.64 2-way -> conflict-free, LDS.128 stays clean. // (36) phase-order weight-transform item map rotated (co = it%64, rb = (it/64 + co)%9): STS conflicts 8 -> <=2-way. // (38) aligned tuner options 6/7 = split-stage converters with a 3-deep converted ring (ANC = 3, // TMA ring 7 -> 5 sub-stages to fit smem): converting stages s+1, s+2 overlaps the MMAs of stage s; each // converted slot is released per 16-channel K-chunk (umma_commit -> cempty). Plain / +ef+early flood. // (39) aligned tuner options 8/9 = split-stage with a 4-deep converted ring (ANC = 4, TMA ring 4 sub-stages, // 227840 B smem), plain / +ef+early flood. (NC = 3 + TMA ring 6 does not fit: 239104 B.) // (41) odd-W phase path input TMA loads always use the L2 evict_first cache hint (replacement, no new option). // (42) direct-store epilogue drains TMEM as two x16 loads, chunk-0 stores overlap chunk-1's tcgen05.ld. // (44) aligned-path halo tensor map encoded with L2 promotion NONE (bit-identical). // (45) DEAD-CODE PRUNE: removed the never-instantiated bulk-row (NPM==2) producer/converter, the DUAL template // parameter (2 CTAs/SM variant, never launched) and the legacy non-gather branch of the gather converter loop. // Same kernel instantiations / tuner options; output bit-identical. // (47) direct-store epilogue walks one running output pointer (+Ho*Wo per cout); bit-identical. // (46) phase converter tracks the tile column incrementally (no per-stage div/mod); bit-identical. // (49) phase converter outer loop specialised per (v2, channel stride), hoisted half-tile column, // toggled cempty parity; bit-identical. // (48) MMA-issuer loop diet (precomputed descriptor bases + immediate offsets, incremental slot/parity, // unrolled K-chunk loop, hoisted weight wait); bit-identical. // (51) raw fp32 weight copy split into 4 parallel 18 KB bulk copies on one barrier; bit-identical. // (52) direct-store epilogue drains TMEM as four pipelined 32x32b.x8 loads; bit-identical. // (53) ROBUSTNESS AUDIT (no kernel change): in-process stress of every tuner option (aligned 0-9, odd-W gather + // phase 1-4) on 8x256, 2x512, 16x384, 2x449, 1x131: ~84k launches, back-to-back PDL chains + cold-L2 memsets, // fresh inputs, NaN-prefilled rotated outputs -> 0 hangs, 0 bit mismatches, 0 tolerance failures. Barrier audit: // every ring (tfull per group, tempty, cfull/cempty, afull/aempty) waits phases in order and the producer of // phase k+1 is gated on the consumer of phase k, so parity bits cannot alias; 1 CTA/SM (>116 KB smem) means a // PDL secondary never shares an SM (TMEM) with its primary; launch_dependents follows the TMEM alloc. // (54) phase converter left-pad zeroing moved out of the per-pair conversion into a warp-uniform tx == 0 // branch (no per-pair SEL on tx > 0 stages); bit-identical. // (55) aligned converters (conv_ld16 / split conv_ld8) drop the per-pair halo select before the SHFL; lane m = 0 // loads its own octet's halo column in one m == 0 branch after the shuffles; bit-identical. // (57) odd-W phase path epilogue stores are plain write-back st.global (aligned path keeps.cs). // (58) MERGE: (a) TMEM accumulator ring 4 -> 8 slots (alloc 512 cols; 1 CTA/SM so the full TMEM is ours); // (b) epilogue per-tile address math hoisted before the afull wait; (c) converter loops form slot/source // addresses before the tfull waits. Bit-identical. // (59) aligned path always uses the early input flood (wfused bit 32); option 2 = plain + early. // (60) EPILOGUE: aligned path direct stores are plain write-back st.global too (was.cs): y is written // once in full 128 B lines, but evict-first output lines compete with the streamed input for early L2 // eviction/write-back slots; normal priority lets L2 batch the write-back. Bit-identical. // (63) producer loop decodes the next sub-stage's tile coordinates before its tempty wait; bit-identical. // (65) PARALLEL STARTUP: thread 0 issues the raw-weight copies while thread 64 concurrently inits the stage-0 full // barriers and issues the stage-0 input TMAs (see the startup block); bit-identical. // (66) epilogue bias from a per-warp smem slot (2 broadcast LDS.128 per 8-cout chunk, no SHFL); bit-identical. // (67) drain issues each chunk's bias LDS before its tcgen05.wait::ld (latency overlap); bit-identical. // (68) MMA issuer commits afull before the last chunk's cempty; bit-identical. // (80) HOST FAST PATH: a repeat call (same x/w/b/shape/stream) replays the recorded launch (cudaLaunchKernelExC, // pre-built PDL config + argument array, only y swapped); skips map/tune-cache lookups and grid math. // (82) BIAS-AS-MMA: bias folded into one extra K=16 MMA per tile (ones A slab x hi/lo-split fp16 bias B slab, // accumulate = 0) -> the epilogue does no bias LDS/FADD; barrier region 1536 -> 2048 B (slabs at +512/+1024). // (83) TF32 TRANSFORM-FREE OPTION: conv_s2_tf32_kernel re-added; for small outputs // (N*Ho*Wo <= 40000) a voted cold-L2 tune picks per shape between the chosen f16 path and it. // (85) SMALL-SMEM option: conv_s2_small_kernel (4 CTAs/SM, half tile per CTA, entry bulk-row input, mma.sync f16), // per-shape voted against the chosen odd-W path (see its header). // (86) WP: phase ring-6 layouts fetch the raw weights as 4 pieces on 4 barriers, piece 3 outside the B image; // converters transform their piece as soon as it lands (transform overlaps the weight landing). // (87) COUT-SPLIT TF32 option: conv_s2_tf32s_kernel (2 CTAs per half tile, 32 couts each, 36 KB raw weights // TMA'd into the tf32 B layout, A ring of 3, 106 KB smem -> 2 CTAs/SM); 3-way voted with f16 / tf32 on small shapes. // (90) S0 TABLE: thread 64's stage-0 TMA coordinates come from a host-precomputed per-CTA int4 in the param block // (PhaseMaps::s0), no runtime-divisor decode; bit-identical. // (92) split-stage aligned converter lane map -> conflict-free STS.64 (bit-identical). // (94) MERGE: NRW odd-W narrow-last-column converter skip + conflict-free bias slab STS. // (95) odd-W phase path balanced grid when the last wave is partial and no half split applies (1x373: 141 x 2 tiles). // (97) SPLIT STAGE-0 ISSUE: stage-0 sub-stages 0/1 issued concurrently by threads 64 / 96 (see the startup block). // Host: tensor maps (pure CPU encodes) are cached keyed by (pointer, shape). #include "kernel.h" #include <cuda_runtime.h> #include <cuda_fp16.h> #include <stdint.h> #include <cuda.h> #include <stdio.h> #include <stdlib.h> #include <type_traits> #include <string.h> #define CIN 32 #ifdef CONV_PROBE __device__ long long g_probe[1024 * 64]; #define PST(i) g_probe[blockIdx.x * 64 + (i)] = clock64() #define PSR(i) _pr[i] = clock64() #else #define PST(i) #define PSR(i) #endif #define COUT 64 #ifdef GT_PROBE __device__ unsigned long long g_gt[1024 * 16]; __device__ __forceinline__ unsigned long long gtime() { unsigned long long t; asm volatile("mov.u64 %0, %globaltimer;" : "=l"(t)); return t; } #define GTS(i) g_gt[blockIdx.x * 16 + (i)] = gtime() #define GTMAX(i) atomicMax(&g_gt[blockIdx.x * 16 + (i)], gtime()) #else #define GTS(i) #define GTMAX(i) #endif #define TW 32 // output cols per tile (TMA path) #define CK 16 // channels per MMA stage (fp16 K=16) #define TCK 8 // channels per TMA sub-stage (= one channel octet) #define NCH (CIN / CK) // 2 chunks per tile // pack two fp32 -> fp16x2 (lo in the low 16 bits = lower K index) __device__ __forceinline__ uint32_t pack_h2(float lo, float hi) { uint32_t r; asm("cvt.rn.f16x2.f32 %0, %1, %2;" : "=r"(r) : "f"(hi), "f"(lo)); return r; } // smem row length (input cols, TMA path): cols 64tx-4 .. 64tx+63 (tile needs 64tx-1 .. 64tx+63) #define T_RW 68 __device__ __forceinline__ void mbar_init(uint64_t* bar, int cnt) { asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" :: "r"((uint32_t)__cvta_generic_to_shared(bar)), "r"(cnt) : "memory"); } __device__ __forceinline__ void mbar_expect_tx(uint64_t* bar, uint32_t bytes) { asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" :: "r"((uint32_t)__cvta_generic_to_shared(bar)), "r"(bytes) : "memory"); } __device__ __forceinline__ void mbar_expect_tx_only(uint64_t* bar, uint32_t bytes) { // no arrive asm volatile("mbarrier.expect_tx.relaxed.cta.shared::cta.b64 [%0], %1;" :: "r"((uint32_t)__cvta_generic_to_shared(bar)), "r"(bytes) : "memory"); } __device__ __forceinline__ void mbar_arrive(uint64_t* bar) { asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" :: "r"((uint32_t)__cvta_generic_to_shared(bar)) : "memory"); } __device__ __forceinline__ void mbar_wait(uint64_t* bar, uint32_t parity) { uint32_t a = (uint32_t)__cvta_generic_to_shared(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}" :: "r"(a), "r"(parity) : "memory"); } // wait with a large suspend-time hint: the waiting thread is suspended in hardware until the phase // completes (or the hint expires) instead of re-polling -- used by the 8 epilogue warps' afull wait so their // spin does not compete for issue slots with the converter warps (converter-issue bound steady state). __device__ __forceinline__ void mbar_wait_sleep(uint64_t* bar, uint32_t parity) { uint32_t a = (uint32_t)__cvta_generic_to_shared(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}" :: "r"(a), "r"(parity), "r"(1000000u) : "memory"); } // XA8: non-blocking test_wait polling loop __device__ __forceinline__ void mbar_wait_test(uint64_t* bar, uint32_t parity) { uint32_t a = (uint32_t)__cvta_generic_to_shared(bar); asm volatile("{\n .reg .pred p;\n WAITT_%=:\n" " mbarrier.test_wait.parity.shared::cta.b64 p, [%0], %1;\n" " @!p bra WAITT_%=;\n}" :: "r"(a), "r"(parity) : "memory"); } // converter tfull wait selection: XV&256 sleep, XV&2048 test_wait poll, else try_wait spin template <long long XVv> __device__ __forceinline__ void mbar_wait_tf(uint64_t* bar, uint32_t parity) { if (XVv & 256) mbar_wait_sleep(bar, parity); else if (XVv & 2048) mbar_wait_test(bar, parity); else mbar_wait(bar, parity); } // compile-time selected wait: SL != 0 -> suspend-hint wait, else spin template <int SL> __device__ __forceinline__ void mbar_wait_x(uint64_t* bar, uint32_t parity) { if (SL) mbar_wait_sleep(bar, parity); else mbar_wait(bar, parity); } __device__ __forceinline__ void tma_load4(uint32_t* dst, const CUtensorMap* map, uint64_t* bar, int c0, int c1, int c2, int c3) { asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.tile.mbarrier::complete_tx::bytes" " [%0], [%1, {%2, %3, %4, %5}], [%6];" :: "r"((uint32_t)__cvta_generic_to_shared(dst)), "l"((uint64_t)map), "r"(c0), "r"(c1), "r"(c2), "r"(c3), "r"((uint32_t)__cvta_generic_to_shared(bar)) : "memory"); } // same TMA load with an L2 cache-policy hint (createpolicy evict_first): the input is streamed once, so // its lines are marked first-to-evict in L2 (keeps L2 capacity for the halo re-reads / write-back of y). __device__ __forceinline__ void tma_load4_ef(uint32_t* dst, const CUtensorMap* map, uint64_t* bar, int c0, int c1, int c2, int c3, uint64_t pol) { asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.tile.mbarrier::complete_tx::bytes.L2::cache_hint" " [%0], [%1, {%2, %3, %4, %5}], [%6], %7;" :: "r"((uint32_t)__cvta_generic_to_shared(dst)), "l"((uint64_t)map), "r"(c0), "r"(c1), "r"(c2), "r"(c3), "r"((uint32_t)__cvta_generic_to_shared(bar)), "l"(pol) : "memory"); } // CLU: TMA load multicast to the CTAs in ctaMask (same CTA-relative smem / mbarrier offsets in each destination) __device__ __forceinline__ void tma_load4_mc(uint32_t dst, const CUtensorMap* map, uint32_t bar, int c0, int c1, int c2, int c3, uint16_t mask) { asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.tile.mbarrier::complete_tx::bytes.multicast::cluster" " [%0], [%1, {%2, %3, %4, %5}], [%6], %7;" :: "r"(dst), "l"((uint64_t)map), "r"(c0), "r"(c1), "r"(c2), "r"(c3), "r"(bar), "h"(mask) : "memory"); } // CLU: release an mbarrier of CTA `rank` in the cluster (same CTA-relative offset) __device__ __forceinline__ void mbar_arrive_remote(uint64_t* bar, uint32_t rank) { uint32_t a = (uint32_t)__cvta_generic_to_shared(bar), r; asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(r) : "r"(a), "r"(rank)); asm volatile("mbarrier.arrive.release.cluster.shared::cluster.b64 _, [%0];" :: "r"(r) : "memory"); } __device__ __forceinline__ void cluster_sync_all() { asm volatile("barrier.cluster.arrive.release.aligned;\n\tbarrier.cluster.wait.acquire.aligned;" ::: "memory"); } // HEL: L2 evict_last policy for the aligned halo-box loads __device__ __forceinline__ uint64_t pol_evict_last() { uint64_t p; asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(p)); return p; } __device__ __forceinline__ uint64_t pol_evict_first() { uint64_t p; asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(p)); return p; } // async TMA tensor store smem -> global (bulk-group completion) __device__ __forceinline__ void tma_store4(const CUtensorMap* map, const void* src, int c0, int c1, int c2, int c3) { asm volatile("cp.async.bulk.tensor.4d.global.shared::cta.tile.bulk_group" " [%0, {%1, %2, %3, %4}], [%5];" :: "l"((uint64_t)map), "r"(c0), "r"(c1), "r"(c2), "r"(c3), "r"((uint32_t)__cvta_generic_to_shared(src)) : "memory"); } __device__ __forceinline__ void bulk_commit() { asm volatile("cp.async.bulk.commit_group;" ::: "memory"); } __device__ __forceinline__ void bulk_wait_read0() { asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); } __device__ __forceinline__ void bulk_wait0() { asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); } // 1D bulk copy global -> shared (bytes multiple of 16, 16B-aligned addresses) __device__ __forceinline__ void bulk_g2s(void* 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"((uint32_t)__cvta_generic_to_shared(dst)), "l"((uint64_t)src), "r"(bytes), "r"((uint32_t)__cvta_generic_to_shared(bar)) : "memory"); } // streaming (evict-first) global store: output is written once, never re-read by this kernel __device__ __forceinline__ void st_cs(float* p, float v) { asm volatile("st.global.cs.f32 [%0], %1;" :: "l"(p), "f"(v) : "memory"); } // policy-selected output store. WB = plain write-back st.global (normal L2 priority); else.cs. // Odd-W phase path: Wo*4 B output rows are not 32 B-sector aligned, so the sectors at row boundaries are // written by two different tiles at different times; keeping them at normal L2 priority (instead of // evict-first) lets the two partial writes merge in L2 before write-back. template <bool WB> __device__ __forceinline__ void st_out(float* p, float v) { if (WB) asm volatile("st.global.f32 [%0], %1;" :: "l"(p), "f"(v) : "memory"); else asm volatile("st.global.cs.f32 [%0], %1;" :: "l"(p), "f"(v) : "memory"); } // ===================================================================================== // tcgen05 (UMMA) path: input staging -> smem K-major fp16 conversion -> tcgen05.mma kind::f16 // (accumulators in TMEM) -> epilogue. // Tile = one image, ROWS out rows x TWC out cols = 128 px = UMMA M (M index = row*TWC + px). // N = 64 couts. K per MMA = 16 input channels of one tap; per tile 2 chunks x 9 taps = 18 MMAs. // Warp roles (896 threads, 1 CTA/SM): // warps 0-7 : epilogue (warp e: TMEM quadrant e&3, couts (e>>2)*32..+31; tcgen05.ld 32x32b.x32 // -> +bias -> direct st.global.cs / TMA store) // warp 8 : TMEM allocator + (GATHER=false) TMA producer (lane 0): two 4D TMAs per // (tile, 16-ci chunk) -- sub-stage u = 2*stage + octet, box 68 cols x 9 rows x 8 ch, // start col 64tx-4 (16B aligned), OOB zero-filled. // warp 9 : single-thread MMA issuer (+ PDL wait + progressive weight bulk copies). // warps 10-27: converters. // TWC=32: warp owns item (input row rr 0..8, channel octet q); lane = px. // TWC=16: warp owns input row rr = cw (0..16; warp 17 idle-but-arrives); // half-warp lane>>4 is channel octet q, px = lane&15. // Each item writes 8 fp16 channels = one 16 B chunk per kx plane. // Output: 6 "parity planes" P[kx][py][r][px] (K-major, SWIZZLE_32B: one pixel // row = 16 fp16 ci = 32 B, 8-row atoms of 256 B, 16B-chunk ^= (px>>2)&1). // Tap (ky,kx) of out row e reads plane (kx, ky&1) row e+(ky>>1). // Rings: TMA ring (U_NT x 8ch) tfull/tempty, converted ring (NC) cfull/cempty, // TMEM accumulator ring 8 x 64 cols (512 TMEM cols, ) afull/aempty. Weights resident. // ===================================================================================== #define U_BOXR 9 // 2*4+1 input rows per 4-row tile (TMA path) #define U_TSTG (TCK * U_BOXR * T_RW) // 4896 words per TMA sub-stage #define U_TBYTES (U_TSTG * 4) // 19584 (multiple of 128) #define U_HROWS 5 // input rows of a half tile (2 out rows) #define U_HTBYTES (TCK * U_HROWS * T_RW * 4) // 10880 B per half-tile sub-stage // LINE-ALIGNED FETCH (aligned TMA path): each sub-stage = MAIN box (64 cols from 64tx, 128B-aligned when // W % 32 == 0) stored dense [8 ch][rows][64] at slot+0, plus a tiny HALO box (4 cols from 64tx-4, 9 rows) // stored dense [8 ch][9][4] at slot+A_HOFF; only its col 3 (= global col 64tx-1) is used. #define A_MC 64 // main box cols #define A_HOFF (TCK * U_BOXR * A_MC * 4) // 18432: halo region offset in the slot #define A_HBYTES (TCK * U_BOXR * 4 * 4) // 1152 B halo box #define A_HMBYTES (TCK * U_HROWS * A_MC * 4) // 10240 B half-tile main box #define U_CBYTES 27648 // converted stage stride (>= 3*KXB for both tile shapes) #define U_WBLK 2048 // (chunk,tap) weight block: 64 couts x 32 B (16 fp16) #define U_WCHB (9 * U_WBLK) // 18432 B of weights per 16-channel K-chunk #define U_WBYTES (NCH * U_WCHB) // 36864 #define U_OBYTES 4096 // per-epilogue-warp output staging (gather path only) #ifndef U_NT #define U_NT 7 // TMA sub-stages (8 ch each) = U_NT/4 tiles in flight #endif #ifndef U_NC_TMA #define U_NC_TMA 2 // converted stages, TMA path #endif #define U_NC_G 2 // converted stages, gather path #define U_TRING (((U_NT * U_TBYTES) + 1023) & ~1023) // TMA ring bytes, padded to 1024B // aligned split-stage variant with a 3-deep converted ring (ANC = 3) shrinks the TMA ring to 5 sub-stages // (3*27648 + 36864 + 98304 + 1536 = 219648 B): converting stage s+1 / s+2 overlaps the MMAs of stage s. #define U_NT3 5 // NC = 4 split-stage variant: TMA ring 4 sub-stages (4*27648 + 36864 + 78848 + 1536 = 227840 B). NC = 3 with a // 6-deep TMA ring would need 3*27648 + 36864 + 117760 + 1536 = 239104 B > 232448 B opt-in max (infeasible). #define U_NT4 4 #define U_TRING_N(n) ((((n) * U_TBYTES) + 1023) & ~1023) #define P_RW 68 // smem row length (cols) in the phase path #define P_RB (TCK * 2 * P_RW * 4) // 4352 B per 2-row phase box (p = 0..2) #define P_TBYTES (3 * P_RB + TCK * 3 * P_RW * 4) // 19584 B per sub-stage (128B multiple) #define P_TRING_N(n) ((((n) * P_TBYTES) + 1023) & ~1023) // S0 TABLE: s0[b] = host-precomputed stage-0 TMA coordinates of CTA b (TMA paths): {n0, cx = 64*tx0, row coord // (aligned: r0 = 8ty0-1+4hs, phase: pr = 2ty0+hs), flags (bit0 CTA has work, bit1 full tile, bit2 evict_first main box)}. // Thread 64 reads ONE int4 (plus the 8 phase shifts, adjacent) instead of 5 scalar params + 3 divisions. #define S0MAX 160 template <int NPM> struct PhaseMaps { CUtensorMap m[NPM]; int sh[NPM]; int4 s0[S0MAX]; }; // NPM = 16 (PH) or 1 // NPM = 16 (PH) or 1 (unused dummy) #define U_NACC 8 // TMEM accumulator ring depth (8 x 64 cols = 512) #define U_NCW 18 // converter warps #define U_NEPI 8 // epilogue warps (2 per TMEM lane quadrant) #define U_WTMA U_NEPI // TMA producer / TMEM allocator warp #define U_WMMA (U_NEPI + 1) // MMA issuer warp #define U_WCV (U_NEPI + 2) // first converter warp #define U_THREADS (32 * (U_WCV + U_NCW)) // 896 // DUAL TMA variant (aligned W, 2 CTAs/SM): 4 epilogue warps (both cout halves each), producer, MMA, // 9 converter warps (one group: every stage, both octets) = 480 threads; ring = 2 raw sub-stages (one MMA // stage), 1 converted stage, weights read straight from global/L2 by the converters (no raw smem copy). // smem = 27648 + 36864 + 39936 + 256 + 1024 = 105728 B per CTA -> 2 CTAs/SM. Autotuned per shape (cold L2). __device__ __forceinline__ void fence_before() { asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory"); } __device__ __forceinline__ void fence_after() { asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); } // Weight pre-transform: w[co][ci][ky][kx] fp32 -> rn fp16 at the smem-image byte offset // (chunk ch=ci/16, tap) block * 2048 + co*32 + swizzled 16B chunk ((cil>>3) ^ (co>>2))&1 + (cil&7)*2. __global__ void wprep_kernel(const float* __restrict__ w, uint16_t* __restrict__ wimg) { // PDL secondary of the PREVIOUS call's conv kernel (which triggers early): this CTA may be resident // while that conv still runs; wait for it to fully complete (it reads wimg; it may also have produced // x/w) before touching anything, then let this call's conv kernel launch. asm volatile("griddepcontrol.wait;" ::: "memory"); asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); // let the conv kernel start now const int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < COUT * CIN * 9) { const int co = i / (CIN * 9), rem = i - co * (CIN * 9); const int ci = rem / 9, tap = rem - ci * 9; const int ch = ci >> 4, cil = ci & 15; const uint32_t off = (ch * 9 + tap) * U_WBLK + co * 32 + ((((cil >> 3) ^ (co >> 2)) & 1) << 4) + (cil & 7) * 2; wimg[off >> 1] = __half_as_ushort(__float2half_rn(__ldg(w + i))); } } // UMMA shared-memory descriptor: K-major, SWIZZLE_32B (mode 6), SBO = 256 B, LBO unused (1). __device__ __forceinline__ uint64_t make_desc(uint32_t saddr) { uint64_t d = 0; d |= (uint64_t)((saddr >> 4) & 0x3FFF); d |= (uint64_t)1 << 16; d |= (uint64_t)(256 >> 4) << 32; d |= (uint64_t)1 << 46; // sm100 descriptor version d |= (uint64_t)6 << 61; // SWIZZLE_32B return d; } // A operand in the SWIZZLE_NONE K-major canonical layout. Core matrix = 8 pixel // rows x 16 B (8 fp16 channels, 128 B contiguous); the two channel octets (K 0-7, 8-15) of an 8-row group // sit at +0 / +128 (LBO = 128 B, K direction), consecutive 8-row groups at +256 (SBO = 256 B, M direction). // Same 32 B per pixel row footprint as the SW32 layout, so every plane/row offset is unchanged. __device__ __forceinline__ uint64_t make_desc_ns(uint32_t saddr) { uint64_t d = 0; d |= (uint64_t)((saddr >> 4) & 0x3FFF); d |= (uint64_t)(128 >> 4) << 16; // LBO: K-adjacent core matrices d |= (uint64_t)(256 >> 4) << 32; // SBO: M-adjacent 8-row groups d |= (uint64_t)1 << 46; // sm100 descriptor version return d; // layout type 0 = SWIZZLE_NONE } // Instruction descriptor: kind::f16, D=F32, A=B=F16, K-major both, N=64, M=128. __host__ __device__ constexpr uint32_t make_idesc() { return (1u << 4) | (0u << 7) | (0u << 10) | ((64u >> 3) << 17) | ((128u >> 4) << 24); } // compile-time accumulate flag variant (predicate from an immediate -> no per-tap register test) template <int ACC> __device__ __forceinline__ void umma_f16c(uint32_t tmem_d, uint64_t da, uint64_t db) { asm volatile("{\n .reg .pred p;\n setp.ne.b32 p, %4, 0;\n" " tcgen05.mma.cta_group::1.kind::f16 [%0], %1, %2, %3, p;\n}" :: "r"(tmem_d), "l"(da), "l"(db), "r"(make_idesc()), "n"(ACC) : "memory"); } // CSP: compile-time accumulate flag + MMA N (cout-split path issues N = 32) template <int ACC, int NN> __device__ __forceinline__ void umma_f16n(uint32_t tmem_d, uint64_t da, uint64_t db) { constexpr uint32_t ID = (1u << 4) | ((uint32_t)(NN >> 3) << 17) | ((128u >> 4) << 24); asm volatile("{\n .reg .pred p;\n setp.ne.b32 p, %4, 0;\n" " tcgen05.mma.cta_group::1.kind::f16 [%0], %1, %2, %3, p;\n}" :: "r"(tmem_d), "l"(da), "l"(db), "r"(ID), "n"(ACC) : "memory"); } __device__ __forceinline__ void umma_f16(uint32_t tmem_d, uint64_t da, uint64_t db, uint32_t acc) { asm volatile("{\n .reg .pred p;\n setp.ne.b32 p, %4, 0;\n" " tcgen05.mma.cta_group::1.kind::f16 [%0], %1, %2, %3, p;\n}" :: "r"(tmem_d), "l"(da), "l"(db), "r"(make_idesc()), "r"(acc) : "memory"); } __device__ __forceinline__ void umma_commit(uint64_t* bar) { asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" :: "r"((uint32_t)__cvta_generic_to_shared(bar)) : "memory"); } // 32 lanes x 32 consecutive fp32 columns -> 32 regs per thread __device__ __forceinline__ void tmem_ld32(uint32_t taddr, float* v) { uint32_t* r = (uint32_t*)v; asm volatile("tcgen05.ld.sync.aligned.32x32b.x32.b32 " "{%0,%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11,%12,%13,%14,%15," "%16,%17,%18,%19,%20,%21,%22,%23,%24,%25,%26,%27,%28,%29,%30,%31}, [%32];" : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]), "=r"(r[4]), "=r"(r[5]), "=r"(r[6]), "=r"(r[7]), "=r"(r[8]), "=r"(r[9]), "=r"(r[10]), "=r"(r[11]), "=r"(r[12]), "=r"(r[13]), "=r"(r[14]), "=r"(r[15]), "=r"(r[16]), "=r"(r[17]), "=r"(r[18]), "=r"(r[19]), "=r"(r[20]), "=r"(r[21]), "=r"(r[22]), "=r"(r[23]), "=r"(r[24]), "=r"(r[25]), "=r"(r[26]), "=r"(r[27]), "=r"(r[28]), "=r"(r[29]), "=r"(r[30]), "=r"(r[31]) : "r"(taddr)); } // 32 lanes x 16 consecutive fp32 columns (async; consume only after tmem_wait_ld16 on the same regs) __device__ __forceinline__ void tmem_ld16(uint32_t taddr, float* 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];" : "=f"(v[0]), "=f"(v[1]), "=f"(v[2]), "=f"(v[3]), "=f"(v[4]), "=f"(v[5]), "=f"(v[6]), "=f"(v[7]), "=f"(v[8]), "=f"(v[9]), "=f"(v[10]), "=f"(v[11]), "=f"(v[12]), "=f"(v[13]), "=f"(v[14]), "=f"(v[15]) : "r"(taddr)); } __device__ __forceinline__ void tmem_wait_ld16(float* v) { asm volatile("tcgen05.wait::ld.sync.aligned;" : "+f"(v[0]), "+f"(v[1]), "+f"(v[2]), "+f"(v[3]), "+f"(v[4]), "+f"(v[5]), "+f"(v[6]), "+f"(v[7]), "+f"(v[8]), "+f"(v[9]), "+f"(v[10]), "+f"(v[11]), "+f"(v[12]), "+f"(v[13]), "+f"(v[14]), "+f"(v[15]) :: "memory"); } // 32 lanes x 8 consecutive fp32 columns (async; consume only after tmem_wait_ld8 on the same regs) __device__ __forceinline__ void tmem_ld8(uint32_t taddr, float* v) { asm volatile("tcgen05.ld.sync.aligned.32x32b.x8.b32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];" : "=f"(v[0]), "=f"(v[1]), "=f"(v[2]), "=f"(v[3]), "=f"(v[4]), "=f"(v[5]), "=f"(v[6]), "=f"(v[7]) : "r"(taddr)); } // 16 lanes x 256 bit, 2 column repetitions: thread t gets lane base+t/4 (regs 0,1 / 4,5) and base+8+t/4 (2,3 / 6,7), // columns 2(t%4), 2(t%4)+1 (+8 for the second repetition) __device__ __forceinline__ void tmem_ld16x256(uint32_t taddr, float* v) { asm volatile("tcgen05.ld.sync.aligned.16x256b.x2.b32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];" : "=f"(v[0]), "=f"(v[1]), "=f"(v[2]), "=f"(v[3]), "=f"(v[4]), "=f"(v[5]), "=f"(v[6]), "=f"(v[7]) : "r"(taddr)); } __device__ __forceinline__ void tmem_wait_ld8(float* v) { asm volatile("tcgen05.wait::ld.sync.aligned;" : "+f"(v[0]), "+f"(v[1]), "+f"(v[2]), "+f"(v[3]), "+f"(v[4]), "+f"(v[5]), "+f"(v[6]), "+f"(v[7]) :: "memory"); } // GATHER converter cursor: per-tile state computed ONCE per tile (divisions, row/col predicates, // 64-bit base pointer); per 16-channel chunk the pointer just advances by 16*H*W. // rr = input row within the tile's 2*ROWS+1 rows, q = channel octet, px = out col. struct GatherCursor { const float* p; // &x[n][chunk*16 + 8q][iy][ixb] (never dereferenced unpredicated) bool ok0, ok1, ok2; // per-kx validity (row in range && col in range) int s; // next stage to load }; template <int TWC> __device__ __forceinline__ void gather_next(GatherCursor& c, float (&v)[8][3], const float* __restrict__ x, int rr, int q, int px, int H, int W, int tilesX, int tilesPer, size_t hw, size_t chunk_stride) { constexpr int ROWS = 128 / TWC, BOXR = 2 * ROWS + 1; if ((c.s % NCH) == 0) { // new tile: recompute tile coordinates + predicates + base pointer const int tile = blockIdx.x + (c.s / NCH) * gridDim.x; const int n = tile / tilesPer; const int rem = tile - n * tilesPer; const int ty = rem / tilesX, tx = rem - ty * tilesX; const int ixb = 2 * TWC * tx + 2 * px - 1; // input col for kx = 0 const int iy = 2 * ROWS * ty - 1 + rr; const bool rowok = rr < BOXR && iy >= 0 && iy < H; c.ok0 = rowok && ixb >= 0 && ixb < W; c.ok1 = rowok && ixb + 1 < W; // ixb+1 >= 0 always c.ok2 = rowok && ixb + 2 < W; const int ixc = ixb < 0 ? 0 : ixb; // keep the base pointer inside the tensor c.p = x + (((size_t)n * CIN + q * 8) * H + (rowok ? iy : 0)) * W + ixc; if (ixb < 0) c.p -= 1; // only px 0 of tx 0 (its kx=0 load is masked) } else { c.p += chunk_stride; // next 16-channel chunk of the same tile } #pragma unroll for (int k = 0; k < 8; k++) { const float* pk = c.p + k * hw; v[k][0] = c.ok0 ? __ldg(pk) : 0.f; v[k][1] = c.ok1 ? __ldg(pk + 1) : 0.f; v[k][2] = c.ok2 ? __ldg(pk + 2) : 0.f; } c.s++; } template <int OFF> __device__ __forceinline__ float4 lds128(uint32_t a) { float4 v; asm volatile("ld.shared.v4.f32 {%0,%1,%2,%3}, [%4+%5];" : "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w) : "r"(a), "n"(OFF) : "memory"); return v; } template <int OFF> __device__ __forceinline__ float lds32(uint32_t a) { float v; asm volatile("ld.shared.f32 %0, [%1+%2];" : "=f"(v) : "r"(a), "n"(OFF) : "memory"); return v; } template <int OFF> __device__ __forceinline__ void sts128(uint32_t a, uint32_t x0, uint32_t x1, uint32_t x2, uint32_t x3) { asm volatile("st.shared.v4.b32 [%0+%1], {%2,%3,%4,%5};" :: "r"(a), "n"(OFF), "r"(x0), "r"(x1), "r"(x2), "r"(x3) : "memory"); } // TMA-path converter load: one lane = 2 adjacent out px (2m, 2m+1) x 8 channels (its octet q). // src = 32-bit smem addr of (channel 0, row rr, main col 4m) of the lane's own octet sub-stage: ONE LDS.128 // per channel; col 4m-1 (px 2m kx=0) = lane m-1's packed (.w) via SHFL; edge lanes (m=15) send the other // octet's halo column (esrc). px 2m+1 kx=0 == px 2m kx=2. pk[i][kx][j] = fp16x2 (ch 2j,2j+1) of px 2m+i. template <int CHS, int ECHS> // CHS: main-box channel stride, ECHS: halo-box channel stride (words) // HALO HOIST: the per-channel-pair edge select (edge ? halo pack: pk[1][2]) before the SHFL is gone -- every // lane sends its own pk[1][2][j]; the px-2m kx=0 value of lane m = 0 (global col 64tx-1, from the halo box of its // OWN octet, esrc) is patched afterwards in ONE branch on m == 0 (8 LDS.32 + 4 F2FP for 2 lanes, no per-j SEL on // the other 30 lanes). TMA OOB zero-fill makes col -1 = 0 for tx == 0. Same values -> bit-identical. __device__ __forceinline__ void conv_ld16(uint32_t src, uint32_t esrc, bool m0, int srcl, uint32_t (&pk)[2][3][4]) { #pragma unroll for (int j = 0; j < 4; j++) { float4 a, b; switch (j) { // immediate channel offsets case 0: a = lds128<0 * CHS * 4>(src); b = lds128<1 * CHS * 4>(src); break; case 1: a = lds128<2 * CHS * 4>(src); b = lds128<3 * CHS * 4>(src); break; case 2: a = lds128<4 * CHS * 4>(src); b = lds128<5 * CHS * 4>(src); break; default: a = lds128<6 * CHS * 4>(src); b = lds128<7 * CHS * 4>(src); break; } pk[0][1][j] = pack_h2(a.x, b.x); pk[0][2][j] = pack_h2(a.y, b.y); pk[1][0][j] = pk[0][2][j]; pk[1][1][j] = pack_h2(a.z, b.z); pk[1][2][j] = pack_h2(a.w, b.w); pk[0][0][j] = __shfl_sync(0xffffffffu, pk[1][2][j], srcl); } if (m0) { // lane m = 0: px 0 kx = 0 = halo col 64tx-1 of its own octet pk[0][0][0] = pack_h2(lds32<0 * ECHS * 4>(esrc), lds32<1 * ECHS * 4>(esrc)); pk[0][0][1] = pack_h2(lds32<2 * ECHS * 4>(esrc), lds32<3 * ECHS * 4>(esrc)); pk[0][0][2] = pack_h2(lds32<4 * ECHS * 4>(esrc), lds32<5 * ECHS * 4>(esrc)); pk[0][0][3] = pack_h2(lds32<6 * ECHS * 4>(esrc), lds32<7 * ECHS * 4>(esrc)); } } // XA4: conv_ld16 split into the LDS phase (raw) and the pack/SHFL phase (same values -> same pk) template <int CHS, int ECHS> __device__ __forceinline__ void conv_raw16(uint32_t src, uint32_t esrc, bool m0, float4 (&ra)[8], float (&rh)[8]) { ra[0] = lds128<0 * CHS * 4>(src); ra[1] = lds128<1 * CHS * 4>(src); ra[2] = lds128<2 * CHS * 4>(src); ra[3] = lds128<3 * CHS * 4>(src); ra[4] = lds128<4 * CHS * 4>(src); ra[5] = lds128<5 * CHS * 4>(src); ra[6] = lds128<6 * CHS * 4>(src); ra[7] = lds128<7 * CHS * 4>(src); if (m0) { rh[0] = lds32<0 * ECHS * 4>(esrc); rh[1] = lds32<1 * ECHS * 4>(esrc); rh[2] = lds32<2 * ECHS * 4>(esrc); rh[3] = lds32<3 * ECHS * 4>(esrc); rh[4] = lds32<4 * ECHS * 4>(esrc); rh[5] = lds32<5 * ECHS * 4>(esrc); rh[6] = lds32<6 * ECHS * 4>(esrc); rh[7] = lds32<7 * ECHS * 4>(esrc); } else { #pragma unroll for (int i = 0; i < 8; i++) rh[i] = 0.f; } } __device__ __forceinline__ void conv_pack16(const float4 (&ra)[8], const float (&rh)[8], bool m0, int srcl, uint32_t (&pk)[2][3][4]) { #pragma unroll for (int j = 0; j < 4; j++) { const float4 a = ra[2 * j], b = ra[2 * j + 1]; pk[0][1][j] = pack_h2(a.x, b.x); pk[0][2][j] = pack_h2(a.y, b.y); pk[1][0][j] = pk[0][2][j]; pk[1][1][j] = pack_h2(a.z, b.z); pk[1][2][j] = pack_h2(a.w, b.w); pk[0][0][j] = __shfl_sync(0xffffffffu, pk[1][2][j], srcl); } if (m0) { #pragma unroll for (int j = 0; j < 4; j++) pk[0][0][j] = pack_h2(rh[2 * j], rh[2 * j + 1]); } } // SPLIT-STAGE converter load (aligned path, wfused bit 128): both converter groups convert the SAME stage, // group g = channel octet g (its own sub-stage u = 2s+g); lane (qs = lane>>4, m) = px pair 2m, 2m+1 x channels // 4qs..4qs+3 of the octet (2 fp16x2 per px/kx -> one STS.64 at +8qs in the 16 B chunk). src -> (channel 4qs, row rr, // main col 4m); edge lane m = 15 sends the halo col (global 64tx-1) of the OTHER channel half (esrc -> channel // 4(qs^1)) to lane m = 0 of the other half-warp (wrap-around SHFL source lane-1). pk[i][kx][j]: pairs 4qs+2j, +1. template <int CHS, int ECHS> // same halo hoist as conv_ld16 (esrc -> the lane's OWN channel half's halo col, patched on m == 0 lanes). __device__ __forceinline__ void conv_ld8(uint32_t src, uint32_t esrc, bool m0, int srcl, uint32_t (&pk)[2][3][2]) { #pragma unroll for (int j = 0; j < 2; j++) { float4 a, b; if (j == 0) { a = lds128<0 * CHS * 4>(src); b = lds128<1 * CHS * 4>(src); } else { a = lds128<2 * CHS * 4>(src); b = lds128<3 * CHS * 4>(src); } pk[0][1][j] = pack_h2(a.x, b.x); pk[0][2][j] = pack_h2(a.y, b.y); pk[1][0][j] = pk[0][2][j]; pk[1][1][j] = pack_h2(a.z, b.z); pk[1][2][j] = pack_h2(a.w, b.w); pk[0][0][j] = __shfl_sync(0xffffffffu, pk[1][2][j], srcl); } if (m0) { pk[0][0][0] = pack_h2(lds32<0 * ECHS * 4>(esrc), lds32<1 * ECHS * 4>(esrc)); pk[0][0][1] = pack_h2(lds32<2 * ECHS * 4>(esrc), lds32<3 * ECHS * 4>(esrc)); } } // XA4 split-stage variant: LDS phase / pack phase of conv_ld8 template <int CHS, int ECHS> __device__ __forceinline__ void conv_raw8(uint32_t src, uint32_t esrc, bool m0, float4 (&ra)[4], float (&rh)[4]) { ra[0] = lds128<0 * CHS * 4>(src); ra[1] = lds128<1 * CHS * 4>(src); ra[2] = lds128<2 * CHS * 4>(src); ra[3] = lds128<3 * CHS * 4>(src); if (m0) { rh[0] = lds32<0 * ECHS * 4>(esrc); rh[1] = lds32<1 * ECHS * 4>(esrc); rh[2] = lds32<2 * ECHS * 4>(esrc); rh[3] = lds32<3 * ECHS * 4>(esrc); } else { rh[0] = rh[1] = rh[2] = rh[3] = 0.f; } } __device__ __forceinline__ void conv_pack8(const float4 (&ra)[4], const float (&rh)[4], bool m0, int srcl, uint32_t (&pk)[2][3][2]) { #pragma unroll for (int j = 0; j < 2; j++) { const float4 a = ra[2 * j], b = ra[2 * j + 1]; pk[0][1][j] = pack_h2(a.x, b.x); pk[0][2][j] = pack_h2(a.y, b.y); pk[1][0][j] = pk[0][2][j]; pk[1][1][j] = pack_h2(a.z, b.z); pk[1][2][j] = pack_h2(a.w, b.w); pk[0][0][j] = __shfl_sync(0xffffffffu, pk[1][2][j], srcl); } if (m0) { pk[0][0][0] = pack_h2(rh[0], rh[1]); pk[0][0][1] = pack_h2(rh[2], rh[3]); } } template <int OFF> __device__ __forceinline__ void sts64(uint32_t a, uint32_t x0, uint32_t x1) { asm volatile("st.shared.v2.b32 [%0+%1], {%2,%3};" :: "r"(a), "n"(OFF), "r"(x0), "r"(x1) : "memory"); } __device__ __forceinline__ float lds32_pred(uint32_t a, bool p) { float v; asm volatile("{\n .reg .pred q;\n setp.ne.b32 q, %2, 0;\n mov.b32 %0, 0;\n @q ld.shared.f32 %0, [%1];\n}" : "=f"(v) : "r"(a), "r"((int)p) : "memory"); return v; } template <int J, int CHS4, bool MSK, bool HP = false> __device__ __forceinline__ void ph_pair(uint32_t src, bool zl, bool m15, int srcl, uint32_t (&pk)[2][3][4], bool zB, bool zD) { constexpr int OA = 2 * J * CHS4, OB = OA + CHS4; // channels 2J, 2J+1 if (HP) { // NRW: px m only (px m+16 not needed) const float a0 = lds32<OA>(src), a1 = lds32<OA + 4>(src), b0 = lds32<OB>(src), b1 = lds32<OB + 4>(src); pk[0][1][J] = pack_h2(a0, b0); pk[0][2][J] = pack_h2(a1, b1); pk[0][0][J] = pack_h2(lds32<OA>(src - 4), lds32<OB>(src - 4)); return; } const float a0 = lds32<OA>(src), a1 = lds32<OA + 4>(src), a2 = lds32<OA + 128>(src), a3 = lds32<OA + 132>(src); const float b0 = lds32<OB>(src), b1 = lds32<OB + 4>(src), b2 = lds32<OB + 128>(src), b3 = lds32<OB + 132>(src); uint32_t pA = pack_h2(a0, b0), pB = pack_h2(a1, b1), pC = pack_h2(a2, b2), pD = pack_h2(a3, b3); if (MSK) { // bulk-row path: kx=2 column == W (odd W right pad) is not zero-filled -> mask it if (zB) pB = 0u; if (zD) pD = 0u; } pk[0][1][J] = pA; pk[0][2][J] = pB; // px m: kx 1, 2 pk[1][1][J] = pC; pk[1][2][J] = pD; // px m+16: kx 1, 2 const uint32_t s2 = __shfl_sync(0xffffffffu, m15 ? pB : pD, srcl); pk[1][0][J] = s2; // px m kx=0 (smem col 2m+e-1 = src - 4) is loaded directly by EVERY lane with a plain LDS.32 (always // inside the slot row: e >= 1), replacing the SHFL from lane m-1 + the 3-instruction predicated load // (setp/mov/@p ld) of lane 0. Bank-conflict-free like the other loads (lane stride 2 words, the two // half-warps have opposite shift parity for odd H*W). zl = lane 0 at tx == 0: global col -1 = left zero pad // (real data of the previous row when the map shift s > 0) -> 0. const float e0 = lds32<OA>(src - 4), e1 = lds32<OB>(src - 4); pk[0][0][J] = zl ? 0u : pack_h2(e0, e1); } template <int CHS4, bool MSK = false, bool HP = false> __device__ __forceinline__ void conv_ld_ph(uint32_t src, bool zl, bool m15, int srcl, uint32_t (&pk)[2][3][4], bool zB = false, bool zD = false) { ph_pair<0, CHS4, MSK, HP>(src, zl, m15, srcl, pk, zB, zD); ph_pair<1, CHS4, MSK, HP>(src, zl, m15, srcl, pk, zB, zD); ph_pair<2, CHS4, MSK, HP>(src, zl, m15, srcl, pk, zB, zD); ph_pair<3, CHS4, MSK, HP>(src, zl, m15, srcl, pk, zB, zD); } // PAIR-LOAD phase converter (tuner options 2/3, wfused bit 64). px m needs smem cols e-1, e, e+1 (+2m), // px m+16 the same +32. With f = e & ~1 (even -> 8B-aligned word pair) and o = e & 1, every lane does ONE // LDS.64 at col 2m+f (pair P) and ONE LDS.32 at col 2m+(o ? f+2 : f-1) (single S) per channel and px: the window // is (P.x, P.y, S) for o = 1 and (S, P.x, P.y) for o = 0. Instead of selecting values, the per-lane STS // destination plane is permuted (address registers computed once): P.x -> plane o?0:1, P.y -> o?1:2, S -> o?2:0. // No SHFL, no per-px select; left pad zeroing hits S (o = 0) or P.x (o = 1) of the zl lane. // Output: v[i][0] = P.x vec, v[i][1] = P.y vec, v[i][2] = S vec for px m (i=0) / m+16 (i=1). template <int OFF> __device__ __forceinline__ float2 lds64(uint32_t a) { float2 v; asm volatile("ld.shared.v2.f32 {%0,%1}, [%2+%3];" : "=f"(v.x), "=f"(v.y) : "r"(a), "n"(OFF) : "memory"); return v; } template <int J, int CHS4, bool HP = false> __device__ __forceinline__ void ph2_pair(uint32_t pa, uint32_t sa, bool zS, bool zP, uint32_t (&pk)[2][3][4]) { constexpr int OA = 2 * J * CHS4, OB = OA + CHS4; // channels 2J, 2J+1 if (HP) { // NRW: px m only const float2 a0 = lds64<OA>(pa), b0 = lds64<OB>(pa); const float as0 = lds32<OA>(sa), bs0 = lds32<OB>(sa); pk[0][0][J] = pack_h2(a0.x, b0.x); pk[0][1][J] = pack_h2(a0.y, b0.y); pk[0][2][J] = pack_h2(as0, bs0); return; } const float2 a0 = lds64<OA>(pa), a1 = lds64<OA + 128>(pa); const float2 b0 = lds64<OB>(pa), b1 = lds64<OB + 128>(pa); const float as0 = lds32<OA>(sa), as1 = lds32<OA + 128>(sa); const float bs0 = lds32<OB>(sa), bs1 = lds32<OB + 128>(sa); const uint32_t px0 = pack_h2(a0.x, b0.x), ps0 = pack_h2(as0, bs0); pk[0][0][J] = zP ? 0u : px0; pk[0][1][J] = pack_h2(a0.y, b0.y); pk[0][2][J] = zS ? 0u : ps0; pk[1][0][J] = pack_h2(a1.x, b1.x); pk[1][1][J] = pack_h2(a1.y, b1.y); pk[1][2][J] = pack_h2(as1, bs1); } template <int CHS4, bool HP = false> __device__ __forceinline__ void conv_ld_ph2(uint32_t pa, uint32_t sa, bool zS, bool zP, uint32_t (&pk)[2][3][4]) { ph2_pair<0, CHS4, HP>(pa, sa, zS, zP, pk); ph2_pair<1, CHS4, HP>(pa, sa, zS, zP, pk); ph2_pair<2, CHS4, HP>(pa, sa, zS, zP, pk); ph2_pair<3, CHS4, HP>(pa, sa, zS, zP, pk); } // PSP PHASE SPLIT-STAGE converter (ring-7 phase path). Warp = (input row, channel octet g of the stage = ONE channel // phase j) -> the map's column shift e (smem col of global col 64tx; e = s or 4 when s = 0) is WARP-UNIFORM, so it is a // template parameter here (switch outside). Lane (q = channel half, m) = px 2m, 2m+1 x channels 4q..4q+3 (aligned split // lane map). px 2m needs global cols 4m-1..4m+1, px 2m+1 cols 4m+1..4m+3 (relative to 64tx) = smem cols 4m+e-1 .. 4m+e+3. // One 16 B-aligned LDS.128 per channel at smem col 4m (e <= 2) or 4m+4 (e >= 3); the 1-2 missing columns come from the // neighbour lane m+1 (e <= 2) / m-1 (e >= 3) as packed fp16x2 via SHFL; edge lanes m = 15 / m = 0 load them themselves // (smem cols 64..65 / 2..3 are inside the 68-col box). src0 = smem addr of (channel 4q, row, col 4m). // pk[i][kx][jj] = fp16x2 (channels 4q+2jj, +1) of px 2m+i, tap column kx. Same values as the old converters. template <int E, int CHS4> __device__ __forceinline__ void phs_conv(uint32_t src0, bool m0, bool m15, int snx, int spv, uint32_t (&pk)[2][3][2]) { constexpr int B = (E <= 2) ? 0 : 16; #pragma unroll for (int jj = 0; jj < 2; jj++) { float4 a, b; if (jj == 0) { a = lds128<0 * CHS4 + B>(src0); b = lds128<1 * CHS4 + B>(src0); } else { a = lds128<2 * CHS4 + B>(src0); b = lds128<3 * CHS4 + B>(src0); } const uint32_t A0 = pack_h2(a.x, b.x), A1 = pack_h2(a.y, b.y), A2 = pack_h2(a.z, b.z), A3 = pack_h2(a.w, b.w); if (E == 1) { uint32_t N0 = __shfl_sync(0xffffffffu, A0, snx); if (m15) { float c0, d0; if (jj == 0) { c0 = lds32<0 * CHS4 + 16>(src0); d0 = lds32<1 * CHS4 + 16>(src0); } else { c0 = lds32<2 * CHS4 + 16>(src0); d0 = lds32<3 * CHS4 + 16>(src0); } N0 = pack_h2(c0, d0); } pk[0][0][jj] = A0; pk[0][1][jj] = A1; pk[0][2][jj] = A2; pk[1][0][jj] = A2; pk[1][1][jj] = A3; pk[1][2][jj] = N0; } else if (E == 2) { uint32_t N0 = __shfl_sync(0xffffffffu, A0, snx), N1 = __shfl_sync(0xffffffffu, A1, snx); if (m15) { float2 c, d; if (jj == 0) { c = lds64<0 * CHS4 + 16>(src0); d = lds64<1 * CHS4 + 16>(src0); } else { c = lds64<2 * CHS4 + 16>(src0); d = lds64<3 * CHS4 + 16>(src0); } N0 = pack_h2(c.x, d.x); N1 = pack_h2(c.y, d.y); } pk[0][0][jj] = A1; pk[0][1][jj] = A2; pk[0][2][jj] = A3; pk[1][0][jj] = A3; pk[1][1][jj] = N0; pk[1][2][jj] = N1; } else if (E == 3) { uint32_t P2 = __shfl_sync(0xffffffffu, A2, spv), P3 = __shfl_sync(0xffffffffu, A3, spv); if (m0) { float2 c, d; if (jj == 0) { c = lds64<0 * CHS4 + 8>(src0); d = lds64<1 * CHS4 + 8>(src0); } else { c = lds64<2 * CHS4 + 8>(src0); d = lds64<3 * CHS4 + 8>(src0); } P2 = pack_h2(c.x, d.x); P3 = pack_h2(c.y, d.y); } pk[0][0][jj] = P2; pk[0][1][jj] = P3; pk[0][2][jj] = A0; pk[1][0][jj] = A0; pk[1][1][jj] = A1; pk[1][2][jj] = A2; } else { uint32_t P3 = __shfl_sync(0xffffffffu, A3, spv); if (m0) { float c0, d0; if (jj == 0) { c0 = lds32<0 * CHS4 + 12>(src0); d0 = lds32<1 * CHS4 + 12>(src0); } else { c0 = lds32<2 * CHS4 + 12>(src0); d0 = lds32<3 * CHS4 + 12>(src0); } P3 = pack_h2(c0, d0); } pk[0][0][jj] = P3; pk[0][1][jj] = A0; pk[0][2][jj] = A1; pk[1][0][jj] = A1; pk[1][1][jj] = A2; pk[1][2][jj] = A3; } } } // VECTORIZED WEIGHT-TRANSFORM ITEMS (the only in-CTA transforms). Raw word (co, ci, tap) = co*288 + 9ci + tap. // wld4: 4 consecutive raw words at byte offset OFFB from the item base: mode 0 = smem (32-bit addr sa, LDS.128 // with immediate offset), 1 = global float4 (16B-aligned w), 2 = global scalar loads (unaligned w). template <int OFFB> __device__ __forceinline__ float4 wld4(int mode, uint32_t sa, const float* g) { if (mode == 0) return lds128<OFFB>(sa); const float* p = g + OFFB / 4; if (mode == 1) return __ldg((const float4*)p); return make_float4(__ldg(p), __ldg(p + 1), __ldg(p + 2), __ldg(p + 3)); } // NATURAL K order (aligned paths): item it (0..511) = (co, octet o4, half eh) = ci 8o4+4eh..+3 x 9 taps = // 36 contiguous raw words -> h2[tap] = the 8 B half eh of chunk (co, o4, tap); byte offset hoff + tap*U_WBLK. __device__ __forceinline__ void wt_nat_item(int it, int mode, uint32_t sbase, const float* wg, uint32_t (&h2)[9][2], uint32_t& hoff) { // BANK-CONFLICT-FREE ITEM MAP (aligned path). Lane bits: eh = b0, o4&1 = b1, o4>>1 = b2, qb = b3, hb = b4; // co = 4*(it>>5) + 2*qb + ((o4>>1) ^ hb). Quarter warp (8 lanes) = all 8 (o4, eh) -> LDS.128 banks 8o4+4eh // distinct (conflict-free); half warp (16 lanes) = all 16 (co%4, o4&1, eh) -> STS.64 words // 8co + 4((o4&1)^..) + 2eh distinct (old map co = it>>3 put o4 and o4+2, 9*2048 B apart = same bank, in one // half warp: 2-way). Still a bijection over the 512 items; output bit-identical. const int eh = it & 1, ol = (it >> 1) & 1, oh = (it >> 2) & 1, qb = (it >> 3) & 1, hb = (it >> 4) & 1; const int o4 = 2 * oh + ol, co = 4 * (it >> 5) + 2 * qb + (oh ^ hb); const int wb = co * (CIN * 9) + 72 * o4 + 36 * eh; const uint32_t sa = sbase + 4u * (uint32_t)wb; const float* g = wg + wb; float L[36]; float4 t4; t4 = wld4<0>(mode, sa, g); L[0] = t4.x; L[1] = t4.y; L[2] = t4.z; L[3] = t4.w; t4 = wld4<16>(mode, sa, g); L[4] = t4.x; L[5] = t4.y; L[6] = t4.z; L[7] = t4.w; t4 = wld4<32>(mode, sa, g); L[8] = t4.x; L[9] = t4.y; L[10] = t4.z; L[11] = t4.w; t4 = wld4<48>(mode, sa, g); L[12] = t4.x; L[13] = t4.y; L[14] = t4.z; L[15] = t4.w; t4 = wld4<64>(mode, sa, g); L[16] = t4.x; L[17] = t4.y; L[18] = t4.z; L[19] = t4.w; t4 = wld4<80>(mode, sa, g); L[20] = t4.x; L[21] = t4.y; L[22] = t4.z; L[23] = t4.w; t4 = wld4<96>(mode, sa, g); L[24] = t4.x; L[25] = t4.y; L[26] = t4.z; L[27] = t4.w; t4 = wld4<112>(mode, sa, g); L[28] = t4.x; L[29] = t4.y; L[30] = t4.z; L[31] = t4.w; t4 = wld4<128>(mode, sa, g); L[32] = t4.x; L[33] = t4.y; L[34] = t4.z; L[35] = t4.w; // L[9k + tap] = ci 8o4+4eh+k, tap #pragma unroll for (int tap = 0; tap < 9; tap++) { h2[tap][0] = pack_h2(L[tap], L[9 + tap]); h2[tap][1] = pack_h2(L[18 + tap], L[27 + tap]); } hoff = (uint32_t)((o4 >> 1) * 9 * U_WBLK + co * 32 + ((((o4 & 1) ^ (co >> 2)) & 1) << 4) + eh * 8); } // PHASE K order (phase / bulk-row / mini paths): chunk (co, o4 = channel phase, tap) holds ci = o4 + 4e, raw words // co*288 + r + 36e (r = 9o4 + tap). Item it (0..575) = (co, rb): chunks r = 4rb..4rb+3 = components of 8 float4s. __device__ __forceinline__ void wt_phase_item(int it, int mode, uint32_t sbase, const float* wg, uint32_t (&pw)[4][4], uint32_t (&woff)[4]) { // BANK-CONFLICT-FREE ITEM MAP: a warp = 32 consecutive couts at one k = it / 64, // rb rotated per cout (rb = (k + co) % 9; still a bijection over (co, rb) for it < 576). The old map // (co = it / 9) put ~9 lanes of one cout on blocks 2048 B apart -> 8-way conflicted STS.128; now the 8 lanes of // a quarter warp hit 8 different couts: STS <= 2-way, LDS banks 4*rb + const -> <= 2-way. Bit-identical output. const int co = it & 63, kk = it >> 6; int rb = kk + co; rb -= 9 * (rb / 9); const int wb = co * (CIN * 9) + 4 * rb; const uint32_t sa = sbase + 4u * (uint32_t)wb; const float* g = wg + wb; float4 f4[8]; f4[0] = wld4<0 * 144>(mode, sa, g); f4[1] = wld4<1 * 144>(mode, sa, g); f4[2] = wld4<2 * 144>(mode, sa, g); f4[3] = wld4<3 * 144>(mode, sa, g); f4[4] = wld4<4 * 144>(mode, sa, g); f4[5] = wld4<5 * 144>(mode, sa, g); f4[6] = wld4<6 * 144>(mode, sa, g); f4[7] = wld4<7 * 144>(mode, sa, g); // +36 words per e #pragma unroll for (int i = 0; i < 4; i++) { const int r = 4 * rb + i, o4 = r / 9, tap = r - 9 * o4; float g8[8]; #pragma unroll for (int ee = 0; ee < 8; ee++) g8[ee] = i == 0 ? f4[ee].x : (i == 1 ? f4[ee].y : (i == 2 ? f4[ee].z : f4[ee].w)); #pragma unroll for (int jj = 0; jj < 4; jj++) pw[i][jj] = pack_h2(g8[2 * jj], g8[2 * jj + 1]); woff[i] = (uint32_t)(((o4 >> 1) * 9 + tap) * U_WBLK + co * 32 + ((((o4 & 1) ^ (co >> 2)) & 1) << 4)); } } #define XF_BIT (1 << 17) #define XW_BIT (1 << 18) // C70 exploration bits (dormant; 64-bit XV): AEL per-lane aempty arrive, PFT stage-0 thread prefetches its tensor maps // before the barrier inits, MSD (host) remote memSyncDomain launch attribute, GRD (host) grid nsm-4 on >2-wave shapes, // X16 aligned drain as two 32x32b.x16 TMEM loads #define C70_AEL (1LL << 32) #define C70_PFT (1LL << 33) #define C70_MSD (1LL << 34) #define C70_GRD (1LL << 35) #define C70_X16 (1LL << 36) #define C70_TA2 (1LL << 37) // aligned non-split converter: lanes 0/1 release the two raw slots in parallel #define C70_NRL (1LL << 38) // no relinquish_alloc_permit after the TMEM alloc #define C70_EB2 (1LL << 39) // epilogue write bursts: drain tiles in pairs (wait afull of t+1 before draining t) #define C70_EB4 (1LL << 40) // same, groups of 4 tiles #define C70_ESP (1LL << 41) // epilogue write spreading: nanosleep between 8-cout store chunks #define C70_EBL (1LL << 42) // EB without the burst on the CTA's last tile group (tail drains immediately) #define C70_EB6 (1LL << 43) // EB group size 6 #define C70_EBA (1LL << 48) // EB: group size 5 if myTiles >= 12 else 4 #define C70_EBA2 (1LL << 50) // EBA: group size 4 again for myTiles >= 24 // HF HALF-FIRST (aligned TMA path): a CTA that owns a tail half tile (blockIdx < nhalf, nfull > 0) processes it as // its FIRST item (5-row boxes, half the stage-0 bytes -> earlier first accumulator / epilogue start), its full tiles after. #define HF_BIT (1LL << 49) #define YCS_BIT (1LL << 29) // LSW: phase-ordered (odd-W) paths stage the raw fp32 weights with cp.async.cg from the 576 // converter threads (LSU path) instead of the thread-0 TMA bulk copies queued ahead of the stage-0 input TMAs. #define LSW_BIT (1LL << 51) // D15: bits 47/49/51/61/62 (old EBF/LAG/EBE/EXC) are free again; 47 = identical-code probe control #define D15_CTL (1LL << 47) // control: no code effect #define NRW_BIT (1LL << 61) // CLU 2-CTA CLUSTER HALO MULTICAST (aligned TMA path, non-split NC2 only; tuner option 10): the CTA pair of a 2-CTA cluster // processes VERTICALLY ADJACENT tiles (ty = 2p, 2p+1) of the same (n, tx) in lockstep. Input row 8ty+7 is the last row of the top // tile's 9-row window AND the first row of the bottom tile's window. Sub-stage slot layout in this mode: [0,16384) = 8 LOCAL rows // [8 ch][8][64] (top: window rows 0..7, bottom: window rows 1..8), [16384,18432) = the SHARED row [8 ch][1][64] (top: window row 8, // bottom: window row 0), halo box unchanged. Rank 0's producer fetches the shared row ONCE with a .multicast::cluster TMA into the // same slot offset of both CTAs (complete_tx on the same-offset full barrier in each CTA, which each CTA arms with the full // sub-stage byte count). Rank 1's converters additionally release rank 0's tempty (remote mbarrier arrive, rank 0 tempty count x2), // so rank 0 never overwrites a peer slot still in use. Sub-stages 0/1 (issued before the cluster sync) load the shared row locally. #define CLU_BIT (1LL << 31) // CW COLUMN WALK (aligned TMA path, non-split NC2 only; tuner option 11): CTA b owns the CONTIGUOUS run of K tiles // L = b*K .. b*K+K-1 in column-major tile order (L = (n*tilesX + tx)*tilesY + ty; K = wfused bits 16-27), so consecutive // items are vertically adjacent tiles of one column. For a SUCCESSOR item (k > 0, ty > 0) input row 8ty-1 (window row 0) is // the previous tile's window row 8, already converted in the converted slot of the same K-chunk (NC = 2: slot = chunk): the // producer fetches only rows 8ty..8ty+7 (8-row box, omap) and the rr = 0 converter warp COPIES the converted row (py0 row 4 // -> py0 row 0, 6 LDS/STS.128 per lane) after its cempty wait instead of LDS + pack + SHFL; the rr = 8 warp waits on a named // barrier (2+g, 64 threads) for that copy before overwriting py0 row 4. 9 -> 8 rows TMA'd and converted per 4 out rows. #define CW_BIT (1LL << 24) // PPOL PRODUCER POLICY HOIST: the L2 evict_first cache-policy register (createpolicy, asm volatile -> re-executed on // every call) is created ONCE by the producer lane before its issue loop instead of once per sub-stage issue (phase path: // every sub-stage; aligned evict_first options 1/5/9: every main box). Same policy value, same TMAs -> bit-identical. #define PPOL_BIT (1LL << 25) #define EFL_BIT (1LL << 20) #define EF4_BIT (1LL << 22) // EFL variant: fill only stages 0-1 (u < 4) at startup #define PFX_BIT ((long long)(1ULL << 63)) #define PFH_BIT (1LL << 62) // PF0 (8x256, table g 11): PFX restricted to the octet-0 stage-0 thread (64): half the pre-wait prefetch bytes, so less // competition with the raw-weight copy at the head of the DRAM queue. Kernel bit // (1<<21 is otherwise only an XPROBE host bit). Same TMAs -> bit-identical. #define PF0_BIT (1LL << 21) // MSL: the single MMA-issuer thread waits each converted stage (cfull) with the suspend-time-hint try_wait (thread is // parked in hardware until the phase completes) instead of re-polling, so its spin does not take issue slots from the 9 converter // warps sharing its SM sub-partitions (the producer tempty wait keeps spinning). Same MMAs -> bit-identical. #define MSL_BIT (1LL << 19) // TST (16x384, table g 9, split-stage option 4/5 only): y stores via TMA tensor store from a per-epilogue-warp // 2 x 1 KB smem staging (8 couts x 32 px per chunk, box {32 px, 1 row, 8 couts, 1}, map passed as omap -- no half tiles // on that grid). The staging (16 KB) is carved out of the TMA ring (7 -> 6 sub-stages; split mode: slot parity = // octet, so each slot is used by one group only -> still alias-free). Same values -> bit-identical. #define TST_BIT (1LL << 26) #define WPN_BIT (1LL << 27) #define TST_SB (U_NEPI * 2048) // MS0 (table g 20 users: 8x256, 1x384): the MMA issuer spin-waits (no suspend hint) the cfull barriers of its FIRST tile //. Steady state keeps MSL. #define MS0_BIT (1LL << 23) // CSP COUT SPLIT + WPN-style half weights (odd-W PXS ring-6 path only; 1x131 via the host table, odd option 9): grid = // (items, 2); CTA part = blockIdx.y owns couts 32*part..+31 of every item. Its raw-weight fetch is only ITS 2 pieces // (16 couts each, 18432 B) on 2 per-piece barriers (BAR+640+8i, the WP barriers); converter warps of its half wait only // their own piece, transform it and store the B-image half at once (B image overlaps no raw piece); the other half of the // converter warps skip the transform. N=32 MMAs (B descriptor +1024 B = cout 32 row, bias slab +512 B) into the first 32 // columns of each 64-column TMEM slot; its 8 epilogue warps drain 16 columns each. Input staging / conversion is duplicated // per part. Same per-output K accumulation order -> bit-identical. #define CSP_BIT (1LL << 30) #define DYN_BIT (1LL << 28) // merge: bit 30 is CSP_BIT #define DYN_SLOTS 1024 __device__ unsigned int g_dyn[2 * DYN_SLOTS]; #ifndef XV_DEF #define D1_C8 (1LL << 58) // D1: class field FC = 1 -> burst group size 8 when myTiles >= 24 #define XV_DEF (1028LL | MSL_BIT | PPOL_BIT | XF_BIT | C70_EB4 | C70_EBL | C70_EBA | D1_C8 | HF_BIT | NRW_BIT | C70_NRL) // + consumer-side converter proxy fence (XF, bit 1<<17); other bits dormant #endif // ===================================================================================== // SMEM LAYOUT AUDIT TABLE (compile-time). Every kernel instantiation's dynamic smem layout is derived here ONCE // (same formulas as the kernel's pointer setup, which static_asserts equality) and checked for overlaps: // [0, CONV) converted A stages NC x 27648 (raw fp32 weight staging 73728 B aliases [0, 73728) on TMA // [CONV, ST) fp16 B image 36864 paths -- consumed into regs before bar.sync 1, then the B // [ST, SO) raw TMA ring (TMA paths) image / converted stores; it must NOT reach the ring, which // [SO, BAR) gather output staging 8 x 4 KB the early input flood fills concurrently) // [BAR, BAR+NBAR*8) mbarriers tfull(2*U_NT) tempty(U_NT) cfull/cempty(NC) afull/aempty(8) wbar(2) wraw(1) // [BAR+NBAR*8, +4) TMEM base slot word (barend = NBAR*8+4 below; NC=4 reaches 388 > 384 = the race) // [BAR+512, BAR+1536) 8 epilogue-warp bias slots (128 B each) // host size = BAR + 2048 + 1024 (worst-case 1023 B re-alignment slack of the dynamic smem base) <= 232448 opt-in. // Table (bytes; BAR = barrier region offset, TOT = host dynamic smem): // aligned single <0,32,1,6,2> NC2 NT7 : CONV 55296 ST 92160 ring 137216 BAR 229376 barend 356 TOT 231936 // aligned NC3 <0,32,1,6,3> NC3 NT5 : CONV 82944 ST 119808 ring 98304 BAR 218112 barend 372 TOT 220672 // aligned NC4 <0,32,1,6,4> NC4 NT4 : CONV 110592 ST 147456 ring 78848 BAR 226304 barend 388 TOT 228864 // phase ring6 <0,32,16,6,2> NC2 NT6 : CONV 55296 ST 92160 ring 117760 BAR 209920 barend 356 TOT 212480 // phase ring7 <0,32,16,7,2> NC2 NT7 : CONV 55296 ST 92160 ring 137216 BAR 229376 barend 356 TOT 231936 // PXS ring5 <0,32,16,5,3> NC3 NT5 : CONV 82944 ST 119808 ring 98304 BAR 218112 barend 372 TOT 220672 // PXS ring6/7 <0,32,16,6|7,3> NC2 : as phase ring6 / ring7 // gather 4x32/8x16 <1,32|16,1,6,2> NC2 : CONV 55296 ST 92160 ring 0 SO 92160 BAR 124928 barend 356 TOT 127488 // All: barrier+slot end <= 512 (bias slots), raw weights 73728 <= ST, 3*KXB <= 27648, sub-stage boxes <= slot stride, // TOT > 116224 (half the opt-in max) -> 1 CTA/SM, so the 512-column TMEM alloc never contends. // ===================================================================================== template <bool GATHER, int TWC, int NPM, int PNT, int ANC, int TSB = 0> struct SmemLayout { static constexpr bool PHC = (NPM == 16); static constexpr bool PXS = PHC && ANC == 3; static constexpr int NT = TSB ? 6 : PHC ? PNT : (ANC == 3 ? U_NT3 : (ANC == 4 ? U_NT4 : U_NT)); static constexpr int NC = GATHER ? U_NC_G : (PXS ? (PNT >= 6 ? 2 : 3) : (ANC >= 3 ? ANC : U_NC_TMA)); static constexpr int CONV = NC * U_CBYTES; // end of converted stages / start of B image static constexpr int ST = CONV + U_WBYTES; // raw TMA ring start static constexpr int RING = GATHER ? 0 : (PHC ? P_TRING_N(PNT) : U_TRING_N(NT)); static constexpr int SO = ST + RING; // gather output staging static constexpr int BAR = SO + (GATHER ? U_NEPI * U_OBYTES : TSB); static constexpr int NBAR = 2 * U_NT + U_NT + 2 * NC + 2 * U_NACC + NCH + 1; static constexpr int SLOT_END = NBAR * 8 + 4; // tmem_slot word end, relative to BAR static constexpr int BIAS0 = 512, BIAS_END = 2048; // [512,640) bias A slab, [1024,2048) bias B slab // WP: phase ring-6 layouts park raw weight piece 3 in an extra 18432 B region after the barrier region static constexpr int WPX = (PHC && PNT == 6) ? COUT * CIN * 9 : 0; static constexpr int TOT = BAR + 2048 + WPX + 1024; static constexpr int ROWS = 128 / TWC, PROW = TWC * 32, PY0 = (ROWS + 1) * PROW, KXB = PY0 + ROWS * PROW; static_assert(SLOT_END <= BIAS0, "barrier region / TMEM slot overlaps the epilogue bias slots"); static_assert(BIAS_END <= 2048, "bias slabs overflow the 2048 B barrier region"); static_assert(GATHER || COUT * CIN * 9 * 4 <= ST, "raw fp32 weight staging overlaps the TMA ring"); static_assert(GATHER || PHC || ANC < 3 || COUT * CIN * 9 * 4 <= CONV, "v214 WPA: B image must not overlap the raw staging"); static_assert(3 * KXB <= U_CBYTES, "converted stage overflow"); static_assert(U_TBYTES == A_HOFF + A_HBYTES && A_HMBYTES <= A_HOFF, "aligned sub-stage boxes overflow the slot"); static_assert(P_TBYTES == 3 * P_RB + TCK * 3 * P_RW * 4, "phase sub-stage boxes overflow the slot"); static_assert(RING == 0 || RING >= NT * (PHC ? P_TBYTES : U_TBYTES), "TMA ring too small"); static_assert(ST % 1024 == 0 && BAR % 8 == 0, "alignment"); static_assert(TOT <= 232448, "exceeds the sm_100 opt-in dynamic smem max"); static_assert(2 * TOT > 232448, "must be 1 CTA/SM (512-column TMEM alloc)"); static_assert(NT <= U_NT && PNT <= U_NT, "barrier arrays sized by U_NT"); }; template <bool GATHER, int TWC, int NPM, int PNT, int ANC = 2, long long XV = XV_DEF> __global__ void __launch_bounds__(U_THREADS, 1) conv_s2_umma_kernel(const __grid_constant__ CUtensorMap tmap, const __grid_constant__ CUtensorMap omap, const __grid_constant__ CUtensorMap hmap, const __grid_constant__ PhaseMaps<NPM> pm, const float* __restrict__ x, const uint16_t* __restrict__ wimg, const float* __restrict__ b, float* __restrict__ y, int H, int W, int Ho, int Wo, int tilesX, int tilesY, int ntiles, int use_tstore_in, int nfull, int nhalf, const float* __restrict__ wraw_g, int wfused) { static_assert(GATHER || TWC == 32, "TMA path only supports 4x32 tiles"); #ifdef CONV_PROBE long long _pr[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; long long _pa = 0, _ps = 0; if (threadIdx.x == 0) PSR(0); #endif if (threadIdx.x == 0) GTS(0); constexpr bool PH = (NPM == 16); // odd-W phase-map TMA variant (implies !GATHER) constexpr bool PHC = PH; // phase-ordered K (weights) + phase-style converter static_assert(!PH || !GATHER, "phase path is a TMA path"); static_assert(PNT <= U_NT, "barrier arrays sized by U_NT"); static_assert(ANC == 2 || ((ANC == 3 || ANC == 4) && !GATHER && (!PHC || ANC == 3)), "ANC=3/4 = split-stage only"); // B8 PXS: phase path with ANC = 3 = px-split converters (both groups convert EVERY stage, group = px half) + NC 3 constexpr bool PXS = PHC && ANC == 3; constexpr bool CSP = (XV & CSP_BIT) != 0; // cout split (part = blockIdx.y) static_assert(!CSP || (PXS && PNT == 6), "CSP = PXS ring-6 path only"); constexpr int MMN = CSP ? 32 : 64; // MMA N constexpr bool CLU = (XV & CLU_BIT) != 0; // 2-CTA cluster halo multicast (aligned non-split path only) constexpr bool CW = (XV & CW_BIT) != 0; // column walk (see CW_BIT) static_assert(!CW || (!GATHER && !PH && !CLU && ANC == 2 && !(XV & 1) && !(XV & 2) && (XV & 1024) && !(XV & 512)), "CW = aligned non-split NC2 path only"); static_assert(!CLU || (!GATHER && !PH && ANC == 2 && !(XV & 1) && !(XV & 2) && (XV & 1024) && !(XV & 512)), "CLU = aligned non-split NC2 path only"); constexpr bool TST = (XV & TST_BIT) != 0; // TMA-store epilogue static_assert(!TST || (!GATHER && !PHC && ANC == 2), "TST = aligned NC2 path only"); constexpr int TSB = TST ? TST_SB : 0; constexpr int NT = TST ? 6 : PHC ? PNT : (ANC == 3 ? U_NT3 : (ANC == 4 ? U_NT4 : U_NT)); // TMA ring depth constexpr int NEPI = U_NEPI; // epilogue warps constexpr int WTMA = NEPI, WMMA = NEPI + 1, WCV = NEPI + 2; constexpr int NCW = U_NCW; // converter warps constexpr int NG = 2; // TMA converter groups (9 warps each) constexpr int NHF = 1; // 32-cout halves per epilogue warp constexpr int TB = PHC ? P_TBYTES : U_TBYTES; // TMA sub-stage slot stride constexpr int ROWS = 128 / TWC; // out rows per tile (4 or 8) constexpr int BOXR = 2 * ROWS + 1; // input rows per tile (9 or 17) constexpr int PROW = TWC * 32; // plane row bytes (TWC px x 32 B) constexpr int PY0 = (ROWS + 1) * PROW; // even-input-row plane bytes constexpr int KXB = PY0 + ROWS * PROW; // per-kx plane pair bytes constexpr int NC = GATHER ? U_NC_G : (PXS ? (PNT >= 6 ? 2 : 3) : (ANC >= 3 ? ANC : U_NC_TMA)); // B8 PXS: ring 6/7 -> NC 2 // converted ring depth static_assert(3 * KXB <= U_CBYTES, "converted stage overflow"); // TMA-store epilogue only on the gather 4x32 path (TMA path spends that smem on the input ring) const bool use_tstore = GATHER && (TWC == 32) && use_tstore_in; extern __shared__ uint8_t smem_raw[]; uint8_t* smem = (uint8_t*)(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023); uint8_t* sc = smem; // NC converted (K-major fp16) stages uint8_t* sw = sc + NC * U_CBYTES; // resident fp16 weights uint8_t* st = sw + U_WBYTES; // U_NT raw TMA sub-stages (unused if GATHER) uint8_t* so = st + (GATHER ? 0 : (PHC ? P_TRING_N(PNT) : U_TRING_N(NT))); // 4 x 4 KB output staging (GATHER only) uint64_t* tfull = (uint64_t*)(so + (GATHER ? U_NEPI * U_OBYTES : TSB)); // tfull[slot + g*U_NT] = full barrier of ring slot `slot` for converter GROUP g (2*U_NT entries). uint64_t* tempty = tfull + 2 * U_NT; uint64_t* cfull = tempty + U_NT; uint64_t* cempty = cfull + NC; uint64_t* afull = cempty + NC; uint64_t* aempty = afull + U_NACC; uint64_t* wbar = aempty + U_NACC; // wbar[c]: weight K-chunk c landed in smem uint64_t* wraw = wbar + NCH; // (TMA path) raw fp32 weight bulk copy landed uint32_t* tmem_slot = (uint32_t*)(wraw + 1); // the pointer setup above must match the audited layout table (SmemLayout) using LY = SmemLayout<GATHER, TWC, NPM, PNT, ANC, TSB>; static_assert(LY::NC == NC && LY::NT == NT && LY::KXB == KXB, "layout table mismatch"); constexpr bool PSP = PHC && !PXS && PNT == 7; // PSP: ring-7 phase path runs split-stage converters const bool spl = (!GATHER && !PHC && ((wfused & 128) || ANC >= 3)) || PSP; // split-stage mode (see below) // EFL: this CTA's startup threads fill the whole initial ring (items 0 and 1 = full tiles bid, bid + grid) constexpr bool EFLc = (XV & EFL_BIT) && !GATHER && !PHC && !CLU && !CW && !(XV & 2) && !(XV & 1); constexpr int EFN = (XV & EF4_BIT) ? (NT < 4 ? NT : 4) : NT; // first sub-stage the producer issues under EFL const bool efl = EFLc && spl && ((int)blockIdx.x + (int)gridDim.x < nfull) && (int)blockIdx.x >= nhalf; if (!GATHER && (threadIdx.x == 0 || threadIdx.x == 64 || threadIdx.x == 96)) { const bool doW = threadIdx.x == 0; // weights thread (else: stage-0 input thread) const int h0s = threadIdx.x == 96 ? 1 : 0; // sub-stage (octet) issued by this stage-0 thread if ((XV & C70_PFT) && !doW) { // C70 PFT: param-space tensor maps, legal before the PDL wait if (PH) { #pragma unroll for (int p = 0; p < 4; p++) { asm volatile("prefetch.tensormap [%0];" :: "l"((uint64_t)&pm.m[p * 4]) : "memory"); asm volatile("prefetch.tensormap [%0];" :: "l"((uint64_t)&pm.m[p * 4 + 1]) : "memory"); } } else { asm volatile("prefetch.tensormap [%0];" :: "l"((uint64_t)&tmap) : "memory"); asm volatile("prefetch.tensormap [%0];" :: "l"((uint64_t)&hmap) : "memory"); } } PSR(9); // STARTUP DECODE: sub-stages 0/1 are stage 0 (tile item 0, K-chunk 0, octets 0/1, ring slots 0/1). // Item 0 is a full tile iff blockIdx < nfull (myFull > 0, no division by gridDim); its tile coordinates // are decoded ONCE for both sub-stages. Octet 1's full barrier is tfull[1] (stage-alternating groups) // or tfull[U_NT + 1] (split mode: group = octet) -- thread 0 inits exactly the barriers it arms. // ENTRY DIET: every smem address thread 0 needs is ONE cvta of the dynamic smem base + compile-time // offsets (same layout as the generic pointers above), and ALL index math / param reads / the L2 policy // are done BEFORE griddepcontrol.wait (pinned there by an empty asm), so after the wait only the copy // instructions remain. Same copies, same order -> bit-identical output. constexpr uint32_t O_ST = (uint32_t)(NC * U_CBYTES + U_WBYTES); constexpr uint32_t O_TF = O_ST + (uint32_t)(PHC ? P_TRING_N(PNT) : U_TRING_N(NT)) + (uint32_t)TSB; // !GATHER: no so constexpr uint32_t O_WRAW = O_TF + 8u * (uint32_t)(2 * U_NT + U_NT + 2 * NC + 2 * U_NACC + NCH); const uint32_t sb = ((uint32_t)__cvta_generic_to_shared(smem_raw) + 1023u) & ~1023u; const uint32_t a_wraw = sb + O_WRAW, a_f0 = sb + O_TF, a_f1 = a_f0 + 8u * (1u + (spl ? U_NT : 0u)); static_assert(GATHER || O_WRAW == (uint32_t)(LY::BAR + 8 * (LY::NBAR - 1)), "startup offsets != layout table (block is dead code on GATHER: its O_TF omits the output staging)"); constexpr bool WA = (XV & 65536) != 0; // B8 probe W-A: thread 64 issues stage 0 THEN the raw weights // WP (weight pieces): phase ring-6 layouts -- 4 raw-weight pieces (16 couts each) on 4 barriers at BAR+640+8i // (free bytes between the bias A slab [512,640) and B slab [1024,2048)); piece 3 lands in the extra region at // BAR+2048 (outside the B image), so the converters transform each piece as soon as it lands (no bar.sync). constexpr bool WPc = PHC && PNT == 6; // WPA (aligned split-stage NC >= 3, i.e. options 6-9: 2x256 / 1x384): the 4 raw-weight pieces land at their natural // contiguous offsets (the converted ring >= 82944 B covers the 73728 B staging, the B image lies above it), each on its // own barrier; converter warp cw (items 128*(cw>>2)..) only reads piece cw>>2 -> transforms overlap the landing. constexpr bool WPA = !PHC && !GATHER && ANC >= 3; constexpr bool WPN = !PHC && !GATHER && ANC == 2 && (XV & WPN_BIT) != 0; // WPN (see WPN_BIT) constexpr bool WPx = WPc || WPA || WPN; const uint32_t a_wp = sb + O_TF + 640u; int pd_n0 = 0, pd_cx = 0, pd_r0 = 0, pd_pr = 0, pd_any = 0, pd_efm = 0; uint32_t pd_txb = 0; uint64_t pd_mm = 0; int pd_sh[8] = {0, 0, 0, 0, 0, 0, 0, 0}; if (!doW && (int)blockIdx.x < S0MAX) { // one int4 param read, no division const int4 e = pm.s0[blockIdx.x]; pd_n0 = e.x; pd_cx = e.y; pd_r0 = e.z; pd_pr = e.z; pd_any = e.w & 1; pd_efm = (e.w >> 2) & 1; const bool full = (e.w & 2) != 0; pd_txb = PH ? (uint32_t)P_TBYTES : (uint32_t)((full ? A_HOFF : A_HMBYTES) + A_HBYTES); pd_mm = (uint64_t)(full ? &tmap : &omap); if (PH) { #pragma unroll for (int i = 0; i < 8; i++) pd_sh[i] = pm.sh[(i >> 1) * 4 + (i & 1)]; // [p][h] } } else if (!doW) { const int bid = (int)blockIdx.x; const bool f0 = bid < nfull && !((XV & HF_BIT) && !PH && bid < nhalf); // HF: half item first pd_any = (f0 || bid < nhalf) ? 1 : 0; // myTiles > 0 const int hs0 = f0 ? -1 : (bid & 1); const int tile0 = f0 ? bid : nfull + (bid >> 1); int ty0, tx0; if ((XV & 2) && !PH) { // XV&2: column-major tile order within an image pd_n0 = tile0 / (tilesX * tilesY); const int rem0 = tile0 - pd_n0 * (tilesX * tilesY); tx0 = rem0 / tilesY; ty0 = rem0 - tx0 * tilesY; } else { pd_n0 = tile0 / (tilesX * tilesY); const int q0 = tile0 / tilesX; ty0 = q0 - pd_n0 * tilesY; tx0 = tile0 - q0 * tilesX; } pd_efm = (wfused & 4) != 0; pd_cx = 64 * tx0; pd_r0 = 8 * ty0 - 1 + (hs0 < 0 ? 0 : 4 * hs0); pd_pr = 2 * ty0 + (hs0 < 0 ? 0 : hs0); pd_txb = PH ? (uint32_t)P_TBYTES : (uint32_t)((hs0 < 0 ? A_HOFF : A_HMBYTES) + A_HBYTES); pd_mm = (uint64_t)(hs0 < 0 ? &tmap : &omap); if (PH) { #pragma unroll for (int i = 0; i < 8; i++) pd_sh[i] = pm.sh[(i >> 1) * 4 + (i & 1)]; // [p][h] } } if ((XV & PFX_BIT) && !doW && !PH && !CLU && pd_any && (!(XV & PF0_BIT) || h0s == 0)) { asm volatile("cp.async.bulk.prefetch.tensor.4d.L2.global.tile [%0, {%1, %2, %3, %4}];" :: "l"(pd_mm), "r"(pd_cx), "r"(pd_r0), "r"(h0s * TCK), "r"(pd_n0) : "memory"); if (XV & PFH_BIT) asm volatile("cp.async.bulk.prefetch.tensor.4d.L2.global.tile [%0, {%1, %2, %3, %4}];" :: "l"((uint64_t)&hmap), "r"(pd_cx - 4), "r"(pd_r0), "r"(h0s * TCK), "r"(pd_n0) : "memory"); } if (doW) { if (WPx) { #pragma unroll for (int i = 0; i < 4; i++) asm volatile("mbarrier.init.shared::cta.b64 [%0], 1;" :: "r"(a_wp + 8u * i) : "memory"); } if (!WA) asm volatile("mbarrier.init.shared::cta.b64 [%0], 1;" :: "r"(a_wraw) : "memory"); } else { asm volatile("mbarrier.init.shared::cta.b64 [%0], 1;" :: "r"(h0s ? a_f1 : a_f0) : "memory"); // own sub-stage if (efl) { // EFL: full barriers of the own-octet initial ring slots u = 2.. NT-1 (split: group = octet) #pragma unroll for (int u = 2 + h0s; u < EFN; u += 2) asm volatile("mbarrier.init.shared::cta.b64 [%0], 1;" :: "r"(a_f0 + 8u * (uint32_t)(u + h0s * U_NT)) : "memory"); } if (WA && h0s == 0) asm volatile("mbarrier.init.shared::cta.b64 [%0], 1;" :: "r"(a_wraw) : "memory"); } asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); PSR(1); // FUSED WEIGHTS: wait for the previous kernel in the stream before touching global memory, // then put the 73 KB raw fp32 weight copy FIRST in the queue (into the still-unused converted-stage // region sc[0..73728)), ahead of the input flood; stage 0's two input sub-stages follow (ring slots // start empty). The producer issues the rest of the ring. if (!doW) asm volatile("" :: "r"(pd_n0), "r"(pd_cx), "r"(pd_r0), "r"(pd_pr), "r"(pd_any), "r"(pd_efm), "r"(pd_txb), "l"(pd_mm), "r"(pd_sh[0]), "r"(pd_sh[1]), "r"(pd_sh[2]), "r"(pd_sh[3]), "r"(pd_sh[4]), "r"(pd_sh[5]), "r"(pd_sh[6]), "r"(pd_sh[7])); asm volatile("griddepcontrol.wait;" ::: "memory"); PSR(2); if (!doW) GTS(14); if (WPx && doW && (wfused & 1) && !(PHC && (XV & LSW_BIT))) { // LSW: converters stage the weights #pragma unroll for (int i = 0; i < 4; i++) { if (CSP && (i >> 1) != (int)blockIdx.y) continue; // CSP: only this part's 2 pieces asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" :: "r"(a_wp + 8u * i), "n"(COUT * CIN * 9) : "memory"); asm volatile("cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1], %2, [%3];" :: "r"((i < 3 || WPA || WPN) ? sb + (uint32_t)(i * COUT * CIN * 9) : sb + O_TF + 2048u), "l"((uint64_t)wraw_g + (uint64_t)(i * COUT * CIN * 9)), "n"(COUT * CIN * 9), "r"(a_wp + 8u * i) : "memory"); } } else if (WA ? false : (doW && (wfused & 1) && !(PHC && (XV & LSW_BIT)))) { asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" :: "r"(a_wraw), "n"(COUT * CIN * 9 * 4) : "memory"); // 4 back-to-back 18432 B bulk copies on one barrier #pragma unroll for (int i = 0; i < 4; i++) asm volatile("cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1], %2, [%3];" :: "r"(sb + (uint32_t)(i * COUT * CIN * 9)), "l"((uint64_t)wraw_g + (uint64_t)(i * COUT * CIN * 9)), "n"(COUT * CIN * 9), "r"(a_wraw) : "memory"); } PSR(3); if (!doW) { // stage-0 input thread (coordinates pre-decoded before the PDL wait, ) const bool any0 = pd_any != 0, efm = pd_efm != 0; const int n0 = pd_n0, cx = pd_cx, r0 = pd_r0, pr = pd_pr; const uint32_t txb = pd_txb; const uint64_t mmain = pd_mm; const uint64_t pol = pol_evict_first(); GTS(15); if (any0) { #pragma unroll for (int h = h0s; h < h0s + 1; h++) { // this thread's sub-stage only (same TMAs as issue_sub(h)) const uint32_t fb = h ? a_f1 : a_f0; const uint32_t dst = sb + O_ST + (uint32_t)(h * TB); asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" :: "r"(fb), "r"(txb) : "memory"); if (PH) { #pragma unroll for (int pp = 0; pp < 4; pp++) { const int p = (XV & 8) ? 3 - pp : pp; // XV&8: 3-row phase box first asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.tile.mbarrier::complete_tx::bytes.L2::cache_hint" " [%0], [%1, {%2, %3, %4, %5}], [%6], %7;" :: "r"(dst + (uint32_t)(p * P_RB)), "l"((uint64_t)&pm.m[p * 4 + h]), "r"(cx - (pd_sh[p * 2 + h] == 0 ? 4 : 0)), "r"(pr - (p == 3 ? 1 : 0)), "r"(0), "r"(n0), "r"(fb), "l"(p == 3 ? pol_evict_last() : pol) : "memory"); // PEL: 3-row phase box (rows shared with the vertical neighbours) evict_last } } else if (CLU) { // CLU stage 0 (before the cluster sync): 8 local rows + halo + the shared row, all local const int rk = (int)(blockIdx.x & 1); asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.tile.mbarrier::complete_tx::bytes" " [%0], [%1, {%2, %3, %4, %5}], [%6];" :: "r"(dst), "l"((uint64_t)&tmap), "r"(cx), "r"(r0 + rk), "r"(h * TCK), "r"(n0), "r"(fb) : "memory"); asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.tile.mbarrier::complete_tx::bytes" " [%0], [%1, {%2, %3, %4, %5}], [%6];" :: "r"(dst + (uint32_t)A_HOFF), "l"((uint64_t)&hmap), "r"(cx - 4), "r"(r0), "r"(h * TCK), "r"(n0), "r"(fb) : "memory"); asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.tile.mbarrier::complete_tx::bytes" " [%0], [%1, {%2, %3, %4, %5}], [%6];" :: "r"(dst + 16384u), "l"((uint64_t)&omap), "r"(cx), "r"(rk ? r0 : r0 + 8), "r"(h * TCK), "r"(n0), "r"(fb) : "memory"); } else { if (XV & 1) // XV&1: halo box first asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.tile.mbarrier::complete_tx::bytes" " [%0], [%1, {%2, %3, %4, %5}], [%6];" :: "r"(dst + (uint32_t)A_HOFF), "l"((uint64_t)&hmap), "r"(cx - 4), "r"(r0), "r"(h * TCK), "r"(n0), "r"(fb) : "memory"); if (efm) asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.tile.mbarrier::complete_tx::bytes.L2::cache_hint" " [%0], [%1, {%2, %3, %4, %5}], [%6], %7;" :: "r"(dst), "l"(mmain), "r"(cx), "r"(r0), "r"(h * TCK), "r"(n0), "r"(fb), "l"(pol) : "memory"); else asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.tile.mbarrier::complete_tx::bytes" " [%0], [%1, {%2, %3, %4, %5}], [%6];" :: "r"(dst), "l"(mmain), "r"(cx), "r"(r0), "r"(h * TCK), "r"(n0), "r"(fb) : "memory"); if (!(XV & 1)) // HEL: halo box with L2 evict_last hint (keeps the shared 128 B line for the left neighbour's main box) asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.tile.mbarrier::complete_tx::bytes.L2::cache_hint" " [%0], [%1, {%2, %3, %4, %5}], [%6], %7;" :: "r"(dst + (uint32_t)A_HOFF), "l"((uint64_t)&hmap), "r"(cx - 4), "r"(r0), "r"(h * TCK), "r"(n0), "r"(fb), "l"(pol_evict_last()) : "memory"); } } } if (efl) { // EFL: remaining initial ring slots of this octet. u = 2s + h0s, stage s -> item s >> 1 (0 or 1, both // full tiles), K-chunk s & 1; slot = u (ring starts empty), barrier tfull[u + h0s*U_NT]. Item 1 = tile bid + grid. const int tp = tilesX * tilesY, t1 = (int)blockIdx.x + (int)gridDim.x; const int n1 = t1 / tp, rm = t1 - n1 * tp, ty1 = rm / tilesX, tx1 = rm - ty1 * tilesX; const uint64_t pol = pol_evict_first(); #pragma unroll for (int u = 2 + h0s; u < EFN; u += 2) { const int sg = u >> 1, it = sg >> 1, chn = (sg & 1) * CK + h0s * TCK; const int nn = it ? n1 : pd_n0, cc = it ? 64 * tx1 : pd_cx, rr0 = it ? 8 * ty1 - 1 : pd_r0; const uint32_t fb = a_f0 + 8u * (uint32_t)(u + h0s * U_NT); const uint32_t dst = sb + O_ST + (uint32_t)(u * TB); asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" :: "r"(fb), "n"(A_HOFF + A_HBYTES) : "memory"); if (pd_efm) asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.tile.mbarrier::complete_tx::bytes.L2::cache_hint" " [%0], [%1, {%2, %3, %4, %5}], [%6], %7;" :: "r"(dst), "l"((uint64_t)&tmap), "r"(cc), "r"(rr0), "r"(chn), "r"(nn), "r"(fb), "l"(pol) : "memory"); else asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.tile.mbarrier::complete_tx::bytes" " [%0], [%1, {%2, %3, %4, %5}], [%6];" :: "r"(dst), "l"((uint64_t)&tmap), "r"(cc), "r"(rr0), "r"(chn), "r"(nn), "r"(fb) : "memory"); asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.tile.mbarrier::complete_tx::bytes" " [%0], [%1, {%2, %3, %4, %5}], [%6];" :: "r"(dst + (uint32_t)A_HOFF), "l"((uint64_t)&hmap), "r"(cc - 4), "r"(rr0), "r"(chn), "r"(nn), "r"(fb) : "memory"); } } GTS(10); if (WA && h0s == 0 && (wfused & 1)) { asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" :: "r"(a_wraw), "n"(COUT * CIN * 9 * 4) : "memory"); #pragma unroll for (int i = 0; i < 4; i++) asm volatile("cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1], %2, [%3];" :: "r"(sb + (uint32_t)(i * COUT * CIN * 9)), "l"((uint64_t)wraw_g + (uint64_t)(i * COUT * CIN * 9)), "n"(COUT * CIN * 9), "r"(a_wraw) : "memory"); } } } if (PHC && (XV & LSW_BIT) && (wfused & 1) && threadIdx.x >= 32 * U_WCV) { asm volatile("griddepcontrol.wait;" ::: "memory"); constexpr bool WPl = PHC && PNT == 6; const uint32_t sbw = ((uint32_t)__cvta_generic_to_shared(smem_raw) + 1023u) & ~1023u; const int ct = (int)threadIdx.x - 32 * U_WCV; // 0..575 #pragma unroll for (int i = 0; i < 8; i++) { const uint32_t byte = (uint32_t)(ct + 32 * U_NCW * i) * 16u; const uint32_t dst = (WPl && byte >= 3u * (COUT * CIN * 9)) ? sbw + (uint32_t)LY::BAR + 2048u + (byte - 3u * (COUT * CIN * 9)) : sbw + byte; asm volatile("cp.async.cg.shared.global [%0], [%1], 16;" :: "r"(dst), "l"((const uint8_t*)wraw_g + byte) : "memory"); } asm volatile("cp.async.commit_group;" ::: "memory"); } const int tid = threadIdx.x; const int warp = tid >> 5, lane = tid & 31; const int tilesPer = tilesX * tilesY; // split-stage mode (aligned single path only): both converter groups convert every stage (group = octet) // split mode (aligned single path only): both converter groups convert every stage (group = octet); // ANC=3/4 requires split mode. spl is computed above (thread 0 startup needs it). // Work items (TAIL BALANCE, TMA path): items 0..myFull-1 are full 4x32 tiles blockIdx.x + k*grid // (nfull = #full tiles); then CTA b < nhalf gets ONE half-tile h = b: tile nfull + h/2, out rows // 2*(h&1)..+1 of it (M rows 0..63 valid, 5-row TMA box via omap). nhalf = 0 -> plain schedule. // CLU: work unit = tile PAIR p (nfull = #pairs) owned by cluster cid = blockIdx/2 (both CTAs: same items) const int cid = CLU ? ((int)blockIdx.x >> 1) : (int)blockIdx.x; const int ncl = CLU ? ((int)gridDim.x >> 1) : (int)gridDim.x; const int cwK = (wfused >> 16) & 0xFFF; // CW: tiles per CTA int myFull = (nfull - cid + ncl - 1) / ncl; if (CW) { const int r = ntiles - cid * cwK; myFull = r < 0 ? 0 : (r < cwK ? r : cwK); } const int myTiles = myFull + ((!CW && (int)blockIdx.x < nhalf) ? 1 : 0); constexpr bool DYNc = (XV & DYN_BIT) != 0; static_assert(!DYNc || (!GATHER && !PH && !CLU && !CW && ANC == 2), "DYN = aligned split NC2 path only"); const bool dyn = DYNc && use_tstore_in != 0 && nhalf == 0; // host: nfull = myFull*grid static tiles, pool = ntiles - nfull int* const itm = (int*)((uint8_t*)tfull + 768); // [16] claimed tile id per item (k & 15), -1 = end uint64_t* const dynb = (uint64_t*)((uint8_t*)tfull + 704); // [8] MMA -> epilogue: dynamic item k's tile id published const int S = myTiles * NCH; // item k -> (tile index, half sub-row 0/1 or -1 for a full tile) // HF: CTAs with a half item take it as item 0 (full tiles are items 1..myFull) const bool hfirst = (XV & HF_BIT) && !PH && !GATHER && (int)blockIdx.x < nhalf && myFull > 0; auto item_tile = [&](int k, int& hs) -> int { int t; if (CW) { // column-major linear index -> row-major tile index hs = -1; const int L = cid * cwK + k, tyc = L % tilesY, qq = L / tilesY, txc = qq % tilesX, nn = qq / tilesX; return nn * tilesPer + tyc * tilesX + txc; } if (CLU) { // pair p -> tile (n, ty = 2*typ + rank, tx) hs = -1; const int p = cid + k * ncl, pp = tilesX * (tilesY >> 1); const int nn = p / pp, rem = p - nn * pp, typ = rem / tilesX, txx = rem - typ * tilesX; return nn * tilesPer + (2 * typ + (int)(blockIdx.x & 1)) * tilesX + txx; } if (hfirst) { if (k == 0) { hs = blockIdx.x & 1; t = nfull + ((int)blockIdx.x >> 1); } else { hs = -1; t = blockIdx.x + (k - 1) * gridDim.x; } } else if (k < myFull) { hs = -1; t = blockIdx.x + k * gridDim.x; } else { hs = blockIdx.x & 1; t = nfull + ((int)blockIdx.x >> 1); } return t; }; // TMA producer helper: sub-stage u = 2*s + h -> MMA stage s (tile s/NCH, chunk s%NCH), octet h // PRODUCER DECODE HOIST: issue_sub is split into the coordinate decode (sub_decode: item_tile + the // tile/tilesPer, rem/tilesX divisions) and the issue (issue_dec). The producer loop decodes sub-stage u // BEFORE its tempty wait (pinned by an empty asm), so the TMAs issue right after the slot frees instead of // after ~2 dependent integer divisions. Same TMAs, same order -> bit-identical. uint64_t hpol = 0; // HEL: halo evict_last policy (producer lane) uint64_t ppol = 0; // PPOL: producer-lane evict_first policy (set once before the issue loop) struct SubDec { int n, ty, tx, hs, ch; }; auto sub_decode = [&](int u) -> SubDec { const int s = u >> 1; SubDec d; const int tile = item_tile(s / NCH, d.hs); d.ch = s % NCH; d.n = tile / tilesPer; const int rem = tile - d.n * tilesPer; if ((XV & 2) && !PH) { d.tx = rem / tilesY; d.ty = rem - d.tx * tilesY; } else { d.ty = rem / tilesX; d.tx = rem - d.ty * tilesX; } return d; }; auto issue_dec = [&](int u, const SubDec& d) { const int slot = u % NT; const int s = u >> 1, h = u & 1; const int hs = d.hs, ch = d.ch, n = d.n, ty = d.ty, tx = d.tx; // per-group full barrier (stage s is converted by group s % NG) // split mode: sub-stage u = 2s+h is converted by group h (octet h) uint64_t* fb = &tfull[slot + (NG == 2 ? (spl ? h : (PXS ? 0 : (s & 1))) : 0) * U_NT]; if (PH) { // 4 TMAs (row phases p) of channel phase j = 2ch+h; rows 8ty-1+4*max(hs,0) .. +8 (half tiles // reuse the full boxes shifted by 4 rows; only rows 0..4 are converted). Row 8ty-1+4hs+rr has // phase (rr+3)&3 and phase-row k = 2ty-1+hs' (p3) or 2ty+hs' (p0..2), local row rr>>2. const int j = 2 * ch + h, ho = hs < 0 ? 0 : hs; mbar_expect_tx(fb, P_TBYTES); // phase input boxes always carry the L2 evict_first hint (input is streamed once) const uint64_t pol = (XV & PPOL_BIT) ? ppol : pol_evict_first(); #pragma unroll for (int pp = 0; pp < 4; pp++) { const int p = (XV & 8) ? 3 - pp : pp; tma_load4_ef((uint32_t*)(st + slot * TB + p * P_RB), &pm.m[p * 4 + j], fb, 64 * tx - (pm.sh[p * 4 + j] == 0 ? 4 : 0), 2 * ty + ho - (p == 3 ? 1 : 0), 0, n, p == 3 ? hpol : pol); // PEL } } else if (CLU) { // CLU: 8 local rows (tmap = 8-row box) + halo; rank 0 multicasts the shared row (omap = 1-row box) to both const int r0 = 8 * ty - 1, rk = (int)(blockIdx.x & 1); mbar_expect_tx(fb, A_HOFF + A_HBYTES); // own bytes + the multicast shared row if (wfused & 4) tma_load4_ef((uint32_t*)(st + slot * TB), &tmap, fb, 64 * tx, r0 + rk, ch * CK + h * TCK, n, (XV & PPOL_BIT) ? ppol : pol_evict_first()); else tma_load4((uint32_t*)(st + slot * TB), &tmap, fb, 64 * tx, r0 + rk, ch * CK + h * TCK, n); tma_load4((uint32_t*)(st + slot * TB + A_HOFF), &hmap, fb, 64 * tx - 4, r0, ch * CK + h * TCK, n); if (rk == 0) tma_load4_mc((uint32_t)__cvta_generic_to_shared(st + slot * TB + 16384), &omap, (uint32_t)__cvta_generic_to_shared(fb), 64 * tx, r0 + 8, ch * CK + h * TCK, n, (uint16_t)3); } else if (CW && (s >> 1) > 0 && ty > 0) { // CW successor: rows 8ty..8ty+7 only (omap = 8-row box, dense [8 ch][8][64]) + the 9-row halo box const int r0 = 8 * ty - 1; // CW HALO SKIP: the halo of window row 0 (input row 8ty-1, global col 64tx-1) is also already inside the copied // converted row -> the halo box is the 8-row map pm.m[0] (rows 8ty..8ty+7, dense [8 ch][8][4] at A_HOFF): no L2 read // of the reused row's halo either. mbar_expect_tx(fb, TCK * 8 * A_MC * 4 + TCK * 8 * 4 * 4); if (wfused & 4) tma_load4_ef((uint32_t*)(st + slot * TB), &omap, fb, 64 * tx, r0 + 1, ch * CK + h * TCK, n, (XV & PPOL_BIT) ? ppol : pol_evict_first()); else tma_load4((uint32_t*)(st + slot * TB), &omap, fb, 64 * tx, r0 + 1, ch * CK + h * TCK, n); tma_load4((uint32_t*)(st + slot * TB + A_HOFF), &pm.m[0], fb, 64 * tx - 4, r0 + 1, ch * CK + h * TCK, n); } else { // full tile: main 64x9x8 box (tmap) from row 8ty-1; half tile: main 64x5x8 box (omap) from row // 8ty-1+4hs. Both: 4x9x8 halo box (hmap) at col 64tx-4 into slot+A_HOFF (half tiles use rows 0..4). const int r0 = 8 * ty - 1 + (hs < 0 ? 0 : 4 * hs); mbar_expect_tx(fb, (hs < 0 ? A_HOFF : A_HMBYTES) + A_HBYTES); if (XV & 1) tma_load4((uint32_t*)(st + slot * TB + A_HOFF), &hmap, fb, 64 * tx - 4, r0, ch * CK + h * TCK, n); if (wfused & 4) // tuner option 9: main box with L2 evict_first hint (halo box keeps normal) tma_load4_ef((uint32_t*)(st + slot * TB), hs < 0 ? &tmap : &omap, fb, 64 * tx, r0, ch * CK + h * TCK, n, (XV & PPOL_BIT) ? ppol : pol_evict_first()); else tma_load4((uint32_t*)(st + slot * TB), hs < 0 ? &tmap : &omap, fb, 64 * tx, r0, ch * CK + h * TCK, n); if (!(XV & 1)) // HEL: halo box evict_last tma_load4_ef((uint32_t*)(st + slot * TB + A_HOFF), &hmap, fb, 64 * tx - 4, r0, ch * CK + h * TCK, n, hpol); } }; // PROLOGUE SPLIT (TMA paths): thread 0 does ONLY the critical path -- init the 3 barriers the first // copies complete on (wraw, tfull[0], tfull[1]), prefetch the tensor maps those first 2 sub-stages use // (param space, legal before the PDL wait), griddepcontrol.wait, then weight bulk copy + 2 input TMAs. // Thread 32 (warp 1, idle until the epilogue) concurrently inits every other barrier and prefetches the // remaining tensor maps; warp 8 allocates TMEM. All of it is ordered before use by the __syncthreads below. // GATHER path: unchanged (thread 0 inits everything; its weights come via the MMA thread). if (!GATHER) { if (tid == 32) { // thread 0 owns tfull[0] and tfull[1] (or tfull[U_NT + 1] in split mode, see above) for (int i = spl ? 1 : 2; i < NT; i++) if (!(efl && (i & 1) == 0 && i < EFN)) mbar_init(&tfull[i], 1); // EFL: even slots by thread 64 if (NG == 2) for (int i = 0; i < NT; i++) if (!(spl && i == 1) && !(efl && (i & 1) && i < EFN)) mbar_init(&tfull[U_NT + i], 1); // group-1 full barriers // group-1 full barriers for (int i = 0; i < NT; i++) mbar_init(&tempty[i], (PXS ? NCW : NCW / NG) * ((XV & 4096) ? 32 : 1) * ((CLU && (blockIdx.x & 1) == 0) ? 2 : 1)); for (int i = 0; i < NC; i++) { mbar_init(&cfull[i], ((spl || PXS) ? NCW : NCW / NG) * ((XV & 8192) ? 32 : 1)); mbar_init(&cempty[i], 1); } // split = all 18 warps for (int i = 0; i < U_NACC; i++) { mbar_init(&afull[i], 1); mbar_init(&aempty[i], NEPI * ((XV & C70_AEL) ? 32 : 1)); } // wbar[0] = all 18 converter warps finished writing the fp16 B image (both K-chunks) for (int i = 0; i < NCH; i++) mbar_init(&wbar[i], NCW); if (DYNc) for (int i = 0; i < 8; i++) mbar_init(&dynb[i], 1); asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); if (!PH && nhalf > 0) asm volatile("prefetch.tensormap [%0];" :: "l"((uint64_t)&omap) : "memory"); if (PH) { // remaining channel phases j = 2, 3 #pragma unroll for (int p = 0; p < 4; p++) { asm volatile("prefetch.tensormap [%0];" :: "l"((uint64_t)&pm.m[p * 4 + 2]) : "memory"); asm volatile("prefetch.tensormap [%0];" :: "l"((uint64_t)&pm.m[p * 4 + 3]) : "memory"); } } } } else if (tid == 0) { for (int i = 0; i < U_NT; i++) { mbar_init(&tfull[i], 1); mbar_init(&tempty[i], U_NCW / 2); } for (int i = 0; i < NC; i++) { mbar_init(&cfull[i], U_NCW); mbar_init(&cempty[i], 1); } for (int i = 0; i < U_NACC; i++) { mbar_init(&afull[i], 1); mbar_init(&aempty[i], NEPI); } for (int i = 0; i < NCH; i++) mbar_init(&wbar[i], 1); mbar_init(wraw, 1); asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); if (use_tstore) asm volatile("prefetch.tensormap [%0];" :: "l"((uint64_t)&omap) : "memory"); } if (warp == WTMA) { // allocate 256 TMEM columns (4 accumulators x 64) asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], 512;" :: "r"((uint32_t)__cvta_generic_to_shared(tmem_slot)) : "memory"); if (!(XV & C70_NRL)) asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;" ::: "memory"); // C70 NRL: skip #ifdef CONV_PROBE _pa = clock64(); #endif if (lane == 0) GTS(1); } fence_before(); #ifdef CONV_PROBE _ps = clock64(); #endif __syncthreads(); fence_after(); const uint32_t tmem_base = *tmem_slot; if constexpr (CLU) cluster_sync_all(); // peer barriers initialized before any multicast / remote arrive #ifdef CONV_PROBE if (tid == 0) PSR(4); if (tid == 32 * WTMA) g_probe[blockIdx.x * 64 + 20] = _pa; if (tid == 32 * WTMA) g_probe[blockIdx.x * 64 + 21] = clock64(); if (lane == 0) g_probe[blockIdx.x * 64 + 32 + warp] = _ps; #endif // PDL ORDERING: trigger the dependent grid only AFTER this CTA owns its TMEM (the alloc above is // ordered before by __syncthreads). Triggering earlier let a co-resident dependent CTA grab TMEM first and // then spin in griddepcontrol.wait while this (primary) CTA blocked in tcgen05.alloc -> deadlock. if (tid == 0) asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); // Every thread orders ALL its global accesses (bias/x/w reads, y writes) after the previous grid's // completion (TMA path: thread 0 already waited; gather path: wprep already waited) -- immediate after that. asm volatile("griddepcontrol.wait;" ::: "memory"); if (warp == WTMA) { // ------------------------------ TMA producer ------------------------------ // sub-stage u = 2*s + h : MMA stage s (tile s/NCH, chunk s%NCH), channel octet h if (!GATHER && lane == 0) { // sub-stages 0,1 were issued by thread 0 at startup; ring slots start empty (no tempty wait < U_NT) // wfused bit 32 (tuner options 12/13) = do NOT hold the input flood behind the weight copy: the // raw-weight bulk copy is already first in the TMA queue, the ring slots do not overlap its smem // region, so the rest of the ring (+ L2 prefetches) issues immediately -> DRAM busy from CTA start. if ((wfused & 1) && !(wfused & 32)) mbar_wait(wraw, 0); // weights landed first, then the input flood if (XV & PPOL_BIT) ppol = pol_evict_first(); // PPOL: once per CTA hpol = pol_evict_last(); // HEL unsigned int* const dctr = g_dyn + 2 * ((wfused >> 16) & (DYN_SLOTS - 1)); int dpc = 0; (void)dctr; for (int u = efl ? EFN : 2; u < 2 * S; u++) { // EFL: initial ring issued at startup const int slot = u % NT; const SubDec d = sub_decode(u); asm volatile("" :: "r"(d.n), "r"(d.ty), "r"(d.tx), "r"(d.hs), "r"(d.ch)); // decode before the wait if (u >= NT) { if (XV & 32) mbar_wait_sleep(&tempty[slot], ((u / NT) - 1) & 1); else mbar_wait(&tempty[slot], ((u / NT) - 1) & 1); } if (u == 2) PST(16); issue_dec(u, d); if (u == NT - 1) PST(17); } if (DYNc && dyn) { const int P = ntiles - nfull; for (int k = myFull; ; k++) { // claim at the LATEST point: once the item's first ring slot is free (commit horizon = ring depth) const int u0 = 4 * k, sl0 = u0 % NT; mbar_wait(&tempty[sl0], ((u0 / NT) - 1) & 1); dpc = (int)atomicAdd(dctr, 1u); const int tile = dpc < P ? nfull + dpc : -1; ((volatile int*)itm)[k & 15] = tile; if (tile < 0) { // pool exhausted: complete the item's two first-stage full barriers with no bytes mbar_arrive(&tfull[sl0]); const int u1 = u0 + 1, sl1 = u1 % NT; mbar_wait(&tempty[sl1], ((u1 / NT) - 1) & 1); mbar_arrive(&tfull[sl1 + U_NT]); break; } SubDec d; d.hs = -1; d.n = tile / tilesPer; const int rem = tile - d.n * tilesPer; d.ty = rem / tilesX; d.tx = rem - d.ty * tilesX; #pragma unroll 1 for (int h4 = 0; h4 < 4; h4++) { const int u = 4 * k + h4, slot = u % NT; d.ch = h4 >> 1; if (h4 > 0) mbar_wait(&tempty[slot], ((u / NT) - 1) & 1); issue_dec(u, d); } } __threadfence(); const unsigned old = atomicAdd(dctr + 1, 1u); if (old == gridDim.x - 1) { atomicExch(dctr, 0u); atomicExch(dctr + 1, 0u); } // last claimer resets the slot } } __syncwarp(); } else if (warp == WMMA) { // ------------------------- single-thread MMA issuer ------------------------- // BIAS-AS-MMA: the whole warp writes two tiny K-major SWIZZLE_NONE operand slabs in the (former bias-slot) // barrier region: A slab (BAR+512, 128 B = one 8-row core matrix, every row = fp16 [1, 1, 0 x 6]) read with // LBO = SBO = 0 (all 16 row groups and both K octets alias it -> A[m][k] = 1 for k in {0,1,8,9}); B slab // (BAR+1024, 64 couts x 16 B = fp16 [hi, lo, 0 x 6], hi = rn(b/2), lo = rn(b/2 - hi)) read with LBO = 0 // (octet 1 aliases octet 0), SBO = 128. One K=16 MMA (accumulate = 0) per tile therefore writes // D[m][co] = 2*(hi + lo) ~= b[co] (rel. err ~2^-22) into the accumulator; the 18 tap MMAs all accumulate, // and the epilogue adds no bias. const uint32_t bias_a = (uint32_t)__cvta_generic_to_shared(tfull) + 512u; const uint32_t bias_b = (uint32_t)__cvta_generic_to_shared(tfull) + 1024u; { uint32_t bw[2]; #pragma unroll for (int i = 0; i < 2; i++) { const float bh = 0.5f * __ldg(b + lane + 32 * i); // cout lane / lane+32 const __half hh = __float2half_rn(bh); const __half hl = __float2half_rn(bh - __half2float(hh)); bw[i] = (uint32_t)__half_as_ushort(hh) | ((uint32_t)__half_as_ushort(hl) << 16); } // BANK-CONFLICT-FREE BIAS SLAB: lane writes cout rows lane and lane+32 (16 B each) -> every quarter-warp // STS.128 covers 128 contiguous bytes (was rows 2lane, 2lane+1: 32 B lane stride = 2-way). Same slab bytes. sts128<0>(bias_b + 16u * (uint32_t)lane, bw[0], 0u, 0u, 0u); sts128<512>(bias_b + 16u * (uint32_t)lane, bw[1], 0u, 0u, 0u); if (lane < 8) sts128<0>(bias_a + 16u * (uint32_t)lane, 0x3C003C00u, 0u, 0u, 0u); asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // STS -> async proxy (MMA) __syncwarp(); } if (lane == 0) { if (GATHER) { // gather path: pre-transformed weights from wprep_kernel asm volatile("griddepcontrol.wait;" ::: "memory"); #pragma unroll for (int k = 0; k < NCH; k++) { mbar_expect_tx(&wbar[k], U_WCHB); bulk_g2s(sw + k * U_WCHB, (const uint8_t*)wimg + k * U_WCHB, U_WCHB, &wbar[k]); } } // MMA-LOOP INSTRUCTION DIET: the A/B smem descriptors are built ONCE (base addresses) and every // per-(slot, tap) descriptor is the base + a compile-time 16-byte-unit offset added to the 14-bit start // address field (smem < 256 KB -> (addr>>4) < 2^14, the add never carries out of the field). The // converted-slot index / cfull parity are tracked incrementally (no s % NC, s / NC), the K-chunk loop // is fully unrolled (accumulate flag + weight block offsets become immediates), and the t == 0 weight // wait is hoisted out of the tile loop. Same MMAs / commits in the same order -> bit-identical output. const uint32_t sc_a = (uint32_t)__cvta_generic_to_shared(sc); const uint32_t sw_a = (uint32_t)__cvta_generic_to_shared(sw); const uint64_t da0 = GATHER ? make_desc(sc_a) : make_desc_ns(sc_a); const uint64_t db0 = make_desc(sw_a + (CSP ? 1024u * blockIdx.y : 0u)); // CSP: cout 32*part row const uint64_t dab = ((uint64_t)((bias_a >> 4) & 0x3FFF)) | ((uint64_t)1 << 46); // LBO = SBO = 0 const uint64_t dbb = ((uint64_t)(((bias_b + (CSP ? 512u * blockIdx.y : 0u)) >> 4) & 0x3FFF)) | ((uint64_t)(128 >> 4) << 32) | ((uint64_t)1 << 46); // LBO 0, SBO 128 if (!GATHER && myTiles > 0) mbar_wait(&wbar[0], 0); // fused B image written by the converters PST(10); GTS(4); if ((XV & XW_BIT) && !GATHER && myTiles > 0) asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // XW consumer-side fence int slot = 0; // converted slot of stage s = t*NCH + c uint32_t cpar = 0; // parity of the next cfull wait on `slot` uint64_t das = da0; // A descriptor base of `slot` for (int t = 0; ; t++) { if (t >= myTiles && !(DYNc && dyn)) break; const int a = t & (U_NACC - 1); // 8-slot accumulator ring (512 TMEM cols) if (t >= U_NACC) mbar_wait(&aempty[a], ((t >> 3) - 1) & 1); if (DYNc && t >= myTiles) { // DYN: dynamic item -- read its tile id before issuing any MMA mbar_wait_sleep(&cfull[slot], cpar); // slot == 0 at an item boundary (NC == 2); re-waited below (same phase) const int v = ((volatile int*)itm)[t & 15]; mbar_arrive(&dynb[(t - myTiles) & 7]); // publish to the epilogue (release) if (v < 0) break; } fence_after(); const uint32_t dt = tmem_base + a * 64; umma_f16n<0, MMN>(dt, dab, dbb); // accumulator:= bias (independent of the converted stage) #pragma unroll for (int c = 0; c < NCH; c++) { if (GATHER && t == 0) mbar_wait(&wbar[c], 0); // gather: per-chunk weight bulk copy if ((XV & (32 | MSL_BIT)) && !((XV & MS0_BIT) && t == 0)) mbar_wait_sleep(&cfull[slot], cpar); else mbar_wait(&cfull[slot], cpar); // MSL: suspend-hint wait fence_after(); if (XV & XF_BIT) asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); if (t == 0) GTS(11 + c); #ifdef CONV_PROBE if (t == 0 && c == 0) PST(11); if (t == myTiles - 1 && c == NCH - 1) PST(13); #endif #pragma unroll for (int tap = 0; tap < 9; tap++) { const int ky = tap / 3, kx = tap % 3; const uint32_t aoff = (uint32_t)(kx * KXB + (ky & 1) * PY0 + (ky >> 1) * PROW) >> 4; const uint32_t boff = (uint32_t)((c * 9 + tap) * U_WBLK) >> 4; // first MMA of each tile (c == 0, tap == 0) peeled as the only non-accumulating // issue; every other tap uses the compile-time accumulate variant (predicate-free body). umma_f16n<1, MMN>(dt, das + aoff, db0 + boff); // all taps accumulate onto the bias } // on the tile's last K-chunk the accumulator-ready commit (afull) is issued BEFORE the // converted-slot release (both track the same MMAs), so the epilogue's wait is armed first. if (c == NCH - 1) umma_commit(&afull[a]); // accumulator a ready if (t == 0 && c == NCH - 1) GTS(6); umma_commit(&cempty[slot]); // converted slot free once these MMAs finish if (++slot == NC) { slot = 0; cpar ^= 1u; das = da0; } else das += (uint64_t)(U_CBYTES >> 4); } } if (GATHER && myTiles == 0) for (int k = 0; k < NCH; k++) mbar_wait(&wbar[k], 0); } __syncwarp(); } else if (!GATHER && warp >= WCV) { // ---------------- converters (TMA path, 2 px x 8 ch per lane, stage-alternating groups) ------------- // 18 warps = 2 groups of 9; group g converts stages s = g, g+2, ... into converted slot g (NC == 2). // Warp = input row rr (0..8); lane = (q = lane>>4 channel octet, m = lane&15 px pair 2m,2m+1). // Each warp consumes BOTH octet sub-stages (u = 2s, 2s+1) of its stage. // Converted layout permutes M within each 32-px out row: px 2m -> row m, px 2m+1 -> row 16+m, so each // STS.128 instruction writes 16 consecutive 32 B pixel rows (512 B, conflict-free); the epilogue inverts it. static_assert(NC >= 2 && NT >= 4 && (ANC == 2 || ANC == 4 || PXS || (NT & 1)), "TMA converter group / ring config"); const int cw = warp - WCV; const int g = (XV & 32768) ? (cw & 1) : cw / 9, rr = (XV & 32768) ? (cw >> 1) : cw - 9 * g; const int m = lane & 15, q = lane >> 4; const bool edge = (m == 15); const int srcl = (lane + 31) & 31; // shfl source: lane m-1 (wraps) // main box row rr, main cols 4m..4m+3 (= old smem cols 4m+4..4m+7); halo box row rr col 3 uint32_t rd_off = (uint32_t)(rr * A_MC + 4 * m) * 4; // own octet uint32_t ed_off = (uint32_t)A_HOFF + (uint32_t)(rr * 4 + 3) * 4; // other octet, global col 64tx-1 int pchs = 0; // PH: per-channel stride (words) const bool v2 = PH && (wfused & 64); // pair-load converter uint32_t p2_off = 0, s2_off = 0; // P / S load offsets bool odd_e = false; if (PH) { const int p = (rr + 3) & 3; const int rowoff = p * (TCK * 2 * P_RW) + (rr >> 2) * P_RW; const int s_own = pm.sh[p * 4 + 2 * g + q], s_oth = pm.sh[p * 4 + 2 * g + (q ^ 1)]; const int e_own = s_own == 0 ? 4 : s_own; // smem col of global 64tx = e rd_off = (uint32_t)(rowoff + 2 * m + e_own) * 4; // col 2m+e (lane stride 2 words) { // pair at col 2m+f (8B aligned: rowoff even, slot/box strides multiples of 8 B), single S const int f = e_own & ~1; odd_e = (e_own & 1) != 0; p2_off = (uint32_t)(rowoff + 2 * m + f) * 4; s2_off = (uint32_t)(rowoff + 2 * m + (odd_e ? f + 2 : f - 1)) * 4; } (void)s_oth; pchs = (p == 3 ? 3 : 2) * P_RW; } // SWIZZLE_NONE A layout: M row i = (rr>>1)*32 + m -> (i>>3)*256 + (i&7)*16, octet q at +128. // One STS.128 (32 lanes) = 4 contiguous 128 B core matrices = 512 B contiguous -> conflict-free. // The second store (M row +16) is at +2*256 = +512 B, same as before. constexpr bool MP = (XV & 512) && !PH; // XA1: px 2m -> row (m&7)+16(m>>3), px 2m+1 -> +8 (16x256b epilogue) constexpr int R2 = MP ? 256 : 512; // byte offset of the px 2m+1 row from the px 2m row const uint32_t wr_off = (rr & 1) * PY0 + (rr >> 1) * PROW + (m >> 3) * (MP ? 512 : 256) + (m & 7) * 16 + q * 128; uint8_t* wbase = sc + g * U_CBYTES + wr_off; const uint32_t wbase_a = (uint32_t)__cvta_generic_to_shared(wbase); // 32-bit STS base const uint32_t st_a = (uint32_t)__cvta_generic_to_shared(st); // raw ring base // per-lane destination planes for the pair-load converter (P.x, P.y, S vectors) const uint32_t wa0 = wbase_a + (odd_e ? 0u : 1u) * KXB; const uint32_t wa1 = wbase_a + (odd_e ? 1u : 2u) * KXB; const uint32_t wa2 = wbase_a + (odd_e ? 2u : 0u) * KXB; { constexpr bool WPc = PHC && PNT == 6; // per-piece raw weights (see the startup block) constexpr bool LSWc = PHC && (XV & LSW_BIT) != 0; constexpr bool WPA = !PHC && ANC >= 3; // (see the startup block) constexpr bool WPN = !PHC && ANC == 2 && (XV & WPN_BIT) != 0; // WPN (see WPN_BIT) if ((wfused & 1) && !WPc && !WPA && !WPN && !LSWc) mbar_wait(wraw, 0); if (LSWc && (wfused & 1)) { // LSW: own cp.async chunks landed, then every converter's (named barrier) asm volatile("cp.async.wait_all;" ::: "memory"); asm volatile("bar.sync 1, %0;" :: "n"(32 * NCW) : "memory"); } if (tid == 32 * WCV) PST(5); const int ct = tid - 32 * WCV; const int wmode = (wfused & 1) ? 0 : (((((uintptr_t)wraw_g) & 15) == 0) ? 1 : 2); const uint32_t sc_w = (uint32_t)__cvta_generic_to_shared(sc); const uint32_t sw_w = (uint32_t)__cvta_generic_to_shared(sw); if constexpr (PHC) { uint32_t pw[4][4], woff[4]; if (WPc && (wfused & 1)) { // wait only for this item's piece (cout co = ct & 63 -> piece co >> 4); piece 3 sits in the // extra region (rebased so raw word co*288 + r of piece 3 maps to extra + 4*(co*288 + r) - 55296). // The B image does not overlap any raw piece -> store immediately; the bar.sync afterwards orders all // raw reads (pieces 0-2 alias the converted stages) before the first converted-stage store. const int pc = (ct & 63) >> 4; // CSP: only items of this part's cout half (warp-uniform: a warp = 32 consecutive couts) if (!CSP || (pc >> 1) == (int)blockIdx.y) { if (!LSWc) mbar_wait((uint64_t*)((uint8_t*)tfull + 640 + 8 * pc), 0); // LSW: landed (wait_all + bar.sync above) if (ct == 0) GTS(2); if (ct == 48) GTS(3); const uint32_t sbase = pc < 3 ? sc_w : (uint32_t)__cvta_generic_to_shared(tfull) + 2048u - 3u * (COUT * CIN * 9); wt_phase_item(ct, 0, sbase, wraw_g, pw, woff); #pragma unroll for (int i = 0; i < 4; i++) sts128<0>(sw_w + woff[i], pw[i][0], pw[i][1], pw[i][2], pw[i][3]); } asm volatile("bar.sync 1, %0;" :: "n"(32 * NCW) : "memory"); // all raw reads done } else { wt_phase_item(ct, wmode, sc_w, wraw_g, pw, woff); asm volatile("bar.sync 1, %0;" :: "n"(32 * NCW) : "memory"); // all raw reads done #pragma unroll for (int i = 0; i < 4; i++) sts128<0>(sw_w + woff[i], pw[i][0], pw[i][1], pw[i][2], pw[i][3]); } } else { #pragma unroll 1 for (int bt = 0; bt < 1; bt++) { const int it = ct; const bool live = it < 512; uint32_t h2[9][2]; uint32_t hoff = 0; if (WPA) { // wait only this warp's raw piece (it >> 7), transform, store the B image at once (sw does // not overlap the raw staging); the bar.sync then orders all raw reads before converted-stage stores. if (live) { if (wfused & 1) mbar_wait((uint64_t*)((uint8_t*)tfull + 640 + 8 * (it >> 7)), 0); wt_nat_item(it, wmode, sc_w, wraw_g, h2, hoff); #pragma unroll for (int tap = 0; tap < 9; tap++) asm volatile("st.shared.v2.b32 [%0], {%1,%2};" :: "r"(sw_w + hoff + tap * U_WBLK), "r"(h2[tap][0]), "r"(h2[tap][1]) : "memory"); } asm volatile("bar.sync 1, %0;" :: "n"(32 * NCW) : "memory"); } else { if (WPN && live && (wfused & 1)) mbar_wait((uint64_t*)((uint8_t*)tfull + 640 + 8 * (it >> 7)), 0); // own piece if (live) wt_nat_item(it, wmode, sc_w, wraw_g, h2, hoff); // WPN: B-image K-chunk 1 (octets 2-3, sc+[73728,92160)) overlaps no raw piece -> stored right away const bool early = WPN && live && ((it >> 2) & 1); if (early) { #pragma unroll for (int tap = 0; tap < 9; tap++) asm volatile("st.shared.v2.b32 [%0], {%1,%2};" :: "r"(sw_w + hoff + tap * U_WBLK), "r"(h2[tap][0]), "r"(h2[tap][1]) : "memory"); } asm volatile("bar.sync 1, %0;" :: "n"(32 * NCW) : "memory"); // raw reads done if (live && !early) { #pragma unroll for (int tap = 0; tap < 9; tap++) asm volatile("st.shared.v2.b32 [%0], {%1,%2};" :: "r"(sw_w + hoff + tap * U_WBLK), "r"(h2[tap][0]), "r"(h2[tap][1]) : "memory"); } } } } if (!(XV & XW_BIT)) asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // STS -> async proxy (MMA) __syncwarp(); if (lane == 0) mbar_arrive(&wbar[0]); if (tid == 32 * WCV) PST(6); } // PER-GROUP FULL BARRIERS (replaces the tempty(u-NT) guard): group g waits only on // tfull[slot + g*U_NT], which the producer arms only for sub-stages of g's stages. Ordering argument: // group g's k-th wait on barrier (slot,g) happens after it observed phase k-1 (program order), and // phase k+1 cannot complete before g consumes phase k (its issue needs tempty of an earlier use of the // slot, whose issue chain passes through g's tempty arrive for phase k). So the barrier is exactly // at phase k: no parity alias, and no extra wait in steady state. Parity = per-slot bit in tpar. uint64_t* tf = tfull + g * U_NT; uint32_t tpar = 0; // bit sl = parity of this group's next wait on slot sl if (spl) { if constexpr (PSP) { // ---- PSP PHASE SPLIT-STAGE loop (ring-7 phase path): like the aligned split loop, group g converts octet g // (sub-stage u = 2s+g = channel phase j = 2*(s&1)+g) of EVERY stage into converted slot s&1; per-stage column shift // e is warp-uniform (one channel phase per warp) -> phs_conv<E> (LDS.128 + SHFL) instead of 8-10 scalar LDS per // channel pair. Barrier protocol = aligned split mode (tfull per group, tempty 9 warps, cfull 18 warps). const int m = (lane & 7) | ((lane >> 4) << 3), q = (lane >> 3) & 1; const int snx = (((m + 1) & 15) & 7) | (q << 3) | ((((m + 1) & 15) >> 3) << 4); const int spv = (((m + 15) & 15) & 7) | (q << 3) | ((((m + 15) & 15) >> 3) << 4); const int p = (rr + 3) & 3; const int rowoff = p * (TCK * 2 * P_RW) + (rr >> 2) * P_RW; const int sh0 = pm.sh[p * 4 + g], sh1 = pm.sh[p * 4 + 2 + g]; const int e0 = sh0 == 0 ? 4 : sh0, e1 = sh1 == 0 ? 4 : sh1; const uint32_t wr2 = (rr & 1) * PY0 + (rr >> 1) * PROW + (m >> 3) * 256 + (m & 7) * 16 + g * 128 + q * 8; const uint32_t wb2 = (uint32_t)__cvta_generic_to_shared(sc) + wr2; const bool m0 = m == 0, m15 = m == 15; const int txh = (nfull + ((int)blockIdx.x >> 1)) % tilesX; // tile column of the half item int txm = (int)blockIdx.x % tilesX; const int txstep = (int)gridDim.x % tilesX; int slot = g; uint32_t epar = 1u; // fresh cempty: parity-1 wait passes auto run = [&](auto c3c) { constexpr int CHS4 = (decltype(c3c)::value ? 3 : 2) * P_RW * 4; const uint32_t lo = (uint32_t)(rowoff + 4 * m) * 4 + (uint32_t)(q * 4 * CHS4); auto stage = [&](auto csc, bool act, bool zl, int e) { constexpr int CS = decltype(csc)::value; const uint32_t src0 = st_a + (uint32_t)(slot * TB) + lo; mbar_wait_tf<XV>(&tf[slot], (tpar >> slot) & 1u); tpar ^= 1u << slot; uint32_t pk[2][3][2]; if (act) { switch (e) { // warp-uniform case 1: phs_conv<1, CHS4>(src0, m0, m15, snx, spv, pk); break; case 2: phs_conv<2, CHS4>(src0, m0, m15, snx, spv, pk); break; case 3: phs_conv<3, CHS4>(src0, m0, m15, snx, spv, pk); break; default: phs_conv<4, CHS4>(src0, m0, m15, snx, spv, pk); break; } if (zl) { pk[0][0][0] = 0u; pk[0][0][1] = 0u; } // global col -1 = left zero pad (px 0 kx 0) } __syncwarp(); if (lane == 0) mbar_arrive(&tempty[slot]); mbar_wait_x<(XV & 128)>(&cempty[CS], epar); if (act) { sts64<CS * U_CBYTES + 0 * KXB>(wb2, pk[0][0][0], pk[0][0][1]); sts64<CS * U_CBYTES + 0 * KXB + 512>(wb2, pk[1][0][0], pk[1][0][1]); sts64<CS * U_CBYTES + 1 * KXB>(wb2, pk[0][1][0], pk[0][1][1]); sts64<CS * U_CBYTES + 1 * KXB + 512>(wb2, pk[1][1][0], pk[1][1][1]); sts64<CS * U_CBYTES + 2 * KXB>(wb2, pk[0][2][0], pk[0][2][1]); sts64<CS * U_CBYTES + 2 * KXB + 512>(wb2, pk[1][2][0], pk[1][2][1]); } if (!(XV & XF_BIT)) asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); __syncwarp(); if (lane == 0) mbar_arrive(&cfull[CS]); slot += 2; if (slot >= NT) slot -= NT; }; for (int k = 0; k < myTiles; k++) { const bool half = k >= myFull; const int tx = half ? txh : txm; const bool act = !half || rr < U_HROWS; // warp-uniform const bool zl = m0 && tx == 0; stage(std::integral_constant<int, 0>{}, act, zl, e0); stage(std::integral_constant<int, 1>{}, act, zl, e1); epar ^= 1u; txm += txstep; if (txm >= tilesX) txm -= tilesX; } }; if (p == 3) run(std::true_type{}); else run(std::false_type{}); } else { // ---- SPLIT-STAGE loop: group g converts octet g (sub-stage u = 2s+g) of EVERY stage s into converted // slot s&1 (cfull counts all 18 warps). Alias-free like the next phase of barrier (slot, g) after // u is u+2NT (NT odd), whose issue needs tempty of u+NT, whose issue needs g's tempty arrive for u. // BANK-CONFLICT-FREE SPLIT LANE MAP: the STS.64 of a warp is served per half-warp. Old map (q = lane>>4, // m = lane&15): half-warp = fixed q, m 0..15 -> px rows m and m+8 sit 256 B apart = same banks (2-way conflict, // 4 wavefronts per STS.64). New map: m = (lane&7) | ((lane>>4)<<3), q = (lane>>3)&1 -> half-warp h = m 8h..8h+7 x // q 0/1 = 128 contiguous bytes (conflict-free, 2 wavefronts). LDS.128 quarter-warps (fixed q, 8 consecutive m) // still cover 32 distinct banks. The kx=0 SHFL source is the lane holding (q, m-1). Same values -> bit-identical. const int m = (lane & 7) | ((lane >> 4) << 3), q = (lane >> 3) & 1; const int srcl = (m == 0) ? lane : (((m - 1) & 7) | (q << 3) | (((m - 1) >> 3) << 4)); const uint32_t rd_off = (uint32_t)(rr * A_MC + 4 * m) * 4; const uint32_t wr2 = (rr & 1) * PY0 + (rr >> 1) * PROW + (m >> 3) * (MP ? 512 : 256) + (m & 7) * 16 + g * 128 + q * 8; const uint32_t wb2 = (uint32_t)__cvta_generic_to_shared(sc) + wr2; const uint32_t eo2 = ed_off + (uint32_t)(q * 4 * U_BOXR * 4 * 4); // halo, OWN channel half int slot = g; // TMA slot of sub-stage u = 2s+g // LOOP DIET: converted slot cs / cempty parity tracked incrementally. // cempty waits start at parity 1, which a freshly initialized barrier (phase 0 incomplete) reports as // already complete (the "previous phase" convention) -> no s < NC guard, no s % NC, s / NC. int cs = 0; // converted slot of stage s uint32_t epar = 1u; // parity of the next cempty wait on cs const int sHalf = 2 * myFull; // first stage of a half-tile item // per-lane source addresses (full / half box) are loop-invariant offsets from the slot base; // the slot base, both source addresses and the m == 0 test are formed BEFORE the tfull wait so the // first LDS.128 issues right after the wait completes. const uint32_t srcF = rd_off + q * 4 * U_BOXR * A_MC * 4, srcH = rd_off + q * 4 * U_HROWS * A_MC * 4; const bool m0 = m == 0; // PAIR-UNROLLED SPLIT LOOP (NC == 2, XA4 early tempty release, warp-level arrives): S = 2*myTiles is even and // stages 2k / 2k+1 (K-chunks 0/1 of item k) always use converted slots 0 / 1 -> the loop body is instantiated per // (converted slot, box row stride): the converted-slot address, cempty/cfull barrier addresses and the half-tile // source select become compile-time immediates; the half test runs once per item. Same loads / packs / stores / // barrier sequence -> bit-identical output. constexpr bool PAIRc = (NC == 2) && (XV & 1024) && !(XV & 4096) && !(XV & 8192); static_assert(!DYNc || PAIRc, "DYN needs the pair-unrolled split converter loop"); int kcur = 0; if constexpr (PAIRc) { auto stage = [&](auto csc, auto hfc, bool act, bool chk) -> bool { constexpr int CS = decltype(csc)::value; constexpr bool HF = decltype(hfc)::value; const uint32_t sb = st_a + (uint32_t)(slot * TB); const uint32_t sl = sb + (HF ? srcH : srcF), se = sb + eo2; mbar_wait_tf<XV>(&tf[slot], (tpar >> slot) & 1u); tpar ^= 1u << slot; if (DYNc && chk && ((volatile int*)itm)[kcur & 15] < 0) { // DYN: pool exhausted -> wake the MMA, exit mbar_wait_x<(XV & 128)>(&cempty[CS], epar); __syncwarp(); if (lane == 0) mbar_arrive(&cfull[CS]); return false; } uint32_t pk[2][3][2]; if (act) { float4 ra[4]; float rh[4]; conv_raw8<(HF ? U_HROWS : U_BOXR) * A_MC, U_BOXR * 4>(sl, se, m0, ra, rh); __syncwarp(); if (lane == 0) mbar_arrive(&tempty[slot]); conv_pack8(ra, rh, m0, srcl, pk); } else { __syncwarp(); if (lane == 0) mbar_arrive(&tempty[slot]); } mbar_wait_x<(XV & 128)>(&cempty[CS], epar); if (act) { sts64<CS * U_CBYTES + 0 * KXB>(wb2, pk[0][0][0], pk[0][0][1]); sts64<CS * U_CBYTES + 0 * KXB + R2>(wb2, pk[1][0][0], pk[1][0][1]); sts64<CS * U_CBYTES + 1 * KXB>(wb2, pk[0][1][0], pk[0][1][1]); sts64<CS * U_CBYTES + 1 * KXB + R2>(wb2, pk[1][1][0], pk[1][1][1]); sts64<CS * U_CBYTES + 2 * KXB>(wb2, pk[0][2][0], pk[0][2][1]); sts64<CS * U_CBYTES + 2 * KXB + R2>(wb2, pk[1][2][0], pk[1][2][1]); } if (!(XV & XF_BIT)) asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); __syncwarp(); if (lane == 0) mbar_arrive(&cfull[CS]); slot += 2; if (slot >= NT) slot -= NT; return true; }; using I0 = std::integral_constant<int, 0>; using I1 = std::integral_constant<int, 1>; for (int k = 0; ; k++) { kcur = k; const bool dk = k >= myTiles; if (dk && !(DYNc && dyn)) break; const bool half = !dk && (hfirst ? (k == 0) : (k >= myFull)); if (!half) { if (!stage(I0{}, std::false_type{}, true, dk)) break; stage(I1{}, std::false_type{}, true, false); } else { const bool act = rr < U_HROWS; // warp-uniform stage(I0{}, std::true_type{}, act, false); stage(I1{}, std::true_type{}, act, false); } epar ^= 1u; } (void)cs; (void)sHalf; } else for (int s = 0; s < S; s++) { const bool half = hfirst ? (s < 2) : (s >= sHalf); const bool act = !half || rr < U_HROWS; // warp-uniform const uint32_t sb = st_a + (uint32_t)(slot * TB); const uint32_t sl = sb + (half ? srcH : srcF), se = sb + eo2; mbar_wait_tf<XV>(&tf[slot], (tpar >> slot) & 1u); if (s == 0 && tid == 32 * WCV) PST(7); tpar ^= 1u << slot; uint32_t pk[2][3][2]; if ((XV & 1024) && act) { // XA4: all LDS first, release the raw slot, then pack/shuffle float4 ra[4]; float rh[4]; if (!half) conv_raw8<U_BOXR * A_MC, U_BOXR * 4>(sl, se, m0, ra, rh); else conv_raw8<U_HROWS * A_MC, U_BOXR * 4>(sl, se, m0, ra, rh); __syncwarp(); if (lane == 0) mbar_arrive(&tempty[slot]); conv_pack8(ra, rh, m0, srcl, pk); } else { if (act) { if (!half) conv_ld8<U_BOXR * A_MC, U_BOXR * 4>(sl, se, m0, srcl, pk); else conv_ld8<U_HROWS * A_MC, U_BOXR * 4>(sl, se, m0, srcl, pk); } if (XV & 4096) mbar_arrive(&tempty[slot]); else { __syncwarp(); if (lane == 0) mbar_arrive(&tempty[slot]); } } mbar_wait_x<(XV & 128)>(&cempty[cs], epar); // parity 1 on first use: passes immediately if (act) { const uint32_t wa = wb2 + (uint32_t)(cs * U_CBYTES); sts64<0 * KXB>(wa, pk[0][0][0], pk[0][0][1]); sts64<0 * KXB + R2>(wa, pk[1][0][0], pk[1][0][1]); sts64<1 * KXB>(wa, pk[0][1][0], pk[0][1][1]); sts64<1 * KXB + R2>(wa, pk[1][1][0], pk[1][1][1]); sts64<2 * KXB>(wa, pk[0][2][0], pk[0][2][1]); sts64<2 * KXB + R2>(wa, pk[1][2][0], pk[1][2][1]); } if (!(XV & XF_BIT)) asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // STS -> async proxy if (XV & 8192) mbar_arrive(&cfull[cs]); else { __syncwarp(); if (lane == 0) mbar_arrive(&cfull[cs]); } if (++cs == NC) { cs = 0; epar ^= 1u; } slot += 2; if (slot >= NT) slot -= NT; } } // !PSP } else { if constexpr (PXS) { // ---- B8 PX-SPLIT PHASE LOOP (ANC = 3): group g = px half. Every warp (input row rr, half g) converts EVERY // stage s (chunk ch = s & 1, both octet sub-stages u = 2s, 2s+1): lane (q = octet = channel phase 2ch+q, m) // handles out px 16g+m (M row 16g+m, identity order) x 8 channels: 3 LDS.32 per channel (cols c-1, c, c+1), // 3 STS.128 (kx planes). Lane stride 2 words; the two half-warps read different channel phases (opposite // shift parity for odd H*W) -> conflict-free like ph_pair. One full barrier per slot (group 0's) waited by // all 18 warps; tempty / cfull count all 18 warps. Alias-free: phase k+1 of slot sl needs tempty phase k, // which needs every warp's arrive after its own phase-k wait. Converted ring NC = 3 (cempty per slot). const bool nrwL = (XV & NRW_BIT) && (Wo - 32 * (tilesX - 1)) <= 16; // NRW: narrow last tile column auto pxs_loop = [&](auto c3c) { constexpr int CHS4 = (decltype(c3c)::value ? 3 : 2) * P_RW * 4; const int p = (rr + 3) & 3; const int rowoff = p * (TCK * 2 * P_RW) + (rr >> 2) * P_RW; const int px = 16 * g + m; uint32_t xo[2]; #pragma unroll for (int ch = 0; ch < 2; ch++) { const int sf = pm.sh[p * 4 + 2 * ch + q]; xo[ch] = (uint32_t)(rowoff + 2 * px + (sf == 0 ? 4 : sf) - 1) * 4; // smem col of global 64tx+2px-1 } const uint32_t wb = (uint32_t)__cvta_generic_to_shared(sc) + (rr & 1) * PY0 + (rr >> 1) * PROW + (px >> 3) * 256 + (m & 7) * 16 + q * 128; const bool zlane = px == 0; const int txh = (nfull + ((int)blockIdx.x >> 1)) % tilesX; int txm = (int)blockIdx.x % tilesX; const int txstep = (int)gridDim.x % tilesX; int slot0 = 0, cs = 0; uint32_t epar = 1u; // fresh cempty: parity-1 wait passes // PAIR-UNROLLED PXS LOOP (NC == 2: ring 6/7 PXS options, 2x211 / 1x131): S = 2*myTiles is even and stages // 2k / 2k+1 (K-chunks 0/1 of item k) always use converted slots 0 / 1 -> the stage body is instantiated per chunk: // the converted-slot STS offset, cempty/cfull barrier addresses and the chunk source offset select are // compile-time; the half / NRW / left-pad tests and the tile column advance run once per item. Same loads / // packs / stores / barrier sequence -> bit-identical output. if constexpr (NC == 2) { auto stage = [&](auto chc, bool act, bool zl) { constexpr int CH = decltype(chc)::value; int slot1 = slot0 + 1; if (slot1 == NT) slot1 = 0; const int mys = q ? slot1 : slot0; const uint32_t src = st_a + (uint32_t)(mys * TB) + xo[CH]; mbar_wait_tf<XV>(&tfull[slot0], (tpar >> slot0) & 1u); tpar ^= 1u << slot0; mbar_wait_tf<XV>(&tfull[slot1], (tpar >> slot1) & 1u); tpar ^= 1u << slot1; uint32_t pk[3][4]; if (act) { #pragma unroll for (int J = 0; J < 4; J++) { float a0, a1, a2, b0, b1, b2; switch (J) { case 0: a0 = lds32<0 * CHS4>(src); a1 = lds32<0 * CHS4 + 4>(src); a2 = lds32<0 * CHS4 + 8>(src); b0 = lds32<1 * CHS4>(src); b1 = lds32<1 * CHS4 + 4>(src); b2 = lds32<1 * CHS4 + 8>(src); break; case 1: a0 = lds32<2 * CHS4>(src); a1 = lds32<2 * CHS4 + 4>(src); a2 = lds32<2 * CHS4 + 8>(src); b0 = lds32<3 * CHS4>(src); b1 = lds32<3 * CHS4 + 4>(src); b2 = lds32<3 * CHS4 + 8>(src); break; case 2: a0 = lds32<4 * CHS4>(src); a1 = lds32<4 * CHS4 + 4>(src); a2 = lds32<4 * CHS4 + 8>(src); b0 = lds32<5 * CHS4>(src); b1 = lds32<5 * CHS4 + 4>(src); b2 = lds32<5 * CHS4 + 8>(src); break; default: a0 = lds32<6 * CHS4>(src); a1 = lds32<6 * CHS4 + 4>(src); a2 = lds32<6 * CHS4 + 8>(src); b0 = lds32<7 * CHS4>(src); b1 = lds32<7 * CHS4 + 4>(src); b2 = lds32<7 * CHS4 + 8>(src); break; } pk[0][J] = pack_h2(a0, b0); pk[1][J] = pack_h2(a1, b1); pk[2][J] = pack_h2(a2, b2); } if (__builtin_expect(zl, 0)) { pk[0][0] = pk[0][1] = pk[0][2] = pk[0][3] = 0u; } // left zero pad } __syncwarp(); if (lane == 0) { mbar_arrive(&tempty[slot0]); mbar_arrive(&tempty[slot1]); } mbar_wait_x<(XV & 128)>(&cempty[CH], epar); if (act) { sts128<CH * U_CBYTES + 0 * KXB>(wb, pk[0][0], pk[0][1], pk[0][2], pk[0][3]); sts128<CH * U_CBYTES + 1 * KXB>(wb, pk[1][0], pk[1][1], pk[1][2], pk[1][3]); sts128<CH * U_CBYTES + 2 * KXB>(wb, pk[2][0], pk[2][1], pk[2][2], pk[2][3]); } if (!(XV & XF_BIT)) asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); __syncwarp(); if (lane == 0) mbar_arrive(&cfull[CH]); slot0 += 2; if (slot0 >= NT) slot0 -= NT; }; for (int k = 0; k < myTiles; k++) { const bool half = k >= myFull; const int tx = half ? txh : txm; const bool act = (!half || rr < U_HROWS) && !(nrwL && g == 1 && tx == tilesX - 1); // warp-uniform const bool zl = tx == 0 && zlane; stage(std::integral_constant<int, 0>{}, act, zl); stage(std::integral_constant<int, 1>{}, act, zl); epar ^= 1u; txm += txstep; if (txm >= tilesX) txm -= tilesX; } (void)cs; } else { for (int s = 0; s < S; s++) { const int ch = s & 1, k = s >> 1; int slot1 = slot0 + 1; if (slot1 == NT) slot1 = 0; const int mys = q ? slot1 : slot0; const bool half = k >= myFull; const int tx = half ? txh : txm; const bool act = (!half || rr < U_HROWS) && !(nrwL && g == 1 && tx == tilesX - 1); const uint32_t src = st_a + (uint32_t)(mys * TB) + (ch ? xo[1] : xo[0]); mbar_wait_tf<XV>(&tfull[slot0], (tpar >> slot0) & 1u); tpar ^= 1u << slot0; mbar_wait_tf<XV>(&tfull[slot1], (tpar >> slot1) & 1u); tpar ^= 1u << slot1; if (s == 0 && tid == 32 * WCV) GTS(5); if (s == 1 && tid == 32 * WCV) GTS(13); uint32_t pk[3][4]; if (act) { #pragma unroll for (int J = 0; J < 4; J++) { float a0, a1, a2, b0, b1, b2; switch (J) { case 0: a0 = lds32<0 * CHS4>(src); a1 = lds32<0 * CHS4 + 4>(src); a2 = lds32<0 * CHS4 + 8>(src); b0 = lds32<1 * CHS4>(src); b1 = lds32<1 * CHS4 + 4>(src); b2 = lds32<1 * CHS4 + 8>(src); break; case 1: a0 = lds32<2 * CHS4>(src); a1 = lds32<2 * CHS4 + 4>(src); a2 = lds32<2 * CHS4 + 8>(src); b0 = lds32<3 * CHS4>(src); b1 = lds32<3 * CHS4 + 4>(src); b2 = lds32<3 * CHS4 + 8>(src); break; case 2: a0 = lds32<4 * CHS4>(src); a1 = lds32<4 * CHS4 + 4>(src); a2 = lds32<4 * CHS4 + 8>(src); b0 = lds32<5 * CHS4>(src); b1 = lds32<5 * CHS4 + 4>(src); b2 = lds32<5 * CHS4 + 8>(src); break; default: a0 = lds32<6 * CHS4>(src); a1 = lds32<6 * CHS4 + 4>(src); a2 = lds32<6 * CHS4 + 8>(src); b0 = lds32<7 * CHS4>(src); b1 = lds32<7 * CHS4 + 4>(src); b2 = lds32<7 * CHS4 + 8>(src); break; } pk[0][J] = pack_h2(a0, b0); pk[1][J] = pack_h2(a1, b1); pk[2][J] = pack_h2(a2, b2); } // global col -1 (left zero pad) is real data of the previous row when the map shift > 0 if (__builtin_expect(tx == 0, 0) && zlane) { pk[0][0] = pk[0][1] = pk[0][2] = pk[0][3] = 0u; } } __syncwarp(); if (lane == 0) { mbar_arrive(&tempty[slot0]); mbar_arrive(&tempty[slot1]); } mbar_wait_x<(XV & 128)>(&cempty[cs], epar); if (act) { const uint32_t wa = wb + (uint32_t)(cs * U_CBYTES); sts128<0 * KXB>(wa, pk[0][0], pk[0][1], pk[0][2], pk[0][3]); sts128<1 * KXB>(wa, pk[1][0], pk[1][1], pk[1][2], pk[1][3]); sts128<2 * KXB>(wa, pk[2][0], pk[2][1], pk[2][2], pk[2][3]); } if (!(XV & XF_BIT)) asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); __syncwarp(); if (lane == 0) mbar_arrive(&cfull[cs]); if (++cs == NC) { cs = 0; epar ^= 1u; } slot0 += 2; if (slot0 >= NT) slot0 -= NT; if (ch) { txm += txstep; if (txm >= tilesX) txm -= tilesX; } } } }; // B8 PXS2 pair-load variant (wfused bit 64): per chunk ch, kx=1 col c = 2px + e(ch); the window c-1..c+1 is ONE // LDS.64 at the even col of the pair + ONE LDS.32 single per channel (e odd: pair (c-1,c), single c+1; e even: // pair (c,c+1), single c-1). The kx planes the pair/single feed are permuted per lane & chunk via precomputed // STS base registers. The stage loop is unrolled by chunk (S is even), so per-chunk offsets are compile-time // selected. Same values -> bit-identical. auto pxs2_loop = [&](auto c3c) { constexpr int CHS4 = (decltype(c3c)::value ? 3 : 2) * P_RW * 4; const int p = (rr + 3) & 3; const int rowoff = p * (TCK * 2 * P_RW) + (rr >> 2) * P_RW; const int px = 16 * g + m; uint32_t po[2], so[2], wx[2], wy[2], wsn[2]; bool oe[2]; const uint32_t wb = (uint32_t)__cvta_generic_to_shared(sc) + (rr & 1) * PY0 + (rr >> 1) * PROW + (px >> 3) * 256 + (m & 7) * 16 + q * 128; #pragma unroll for (int ch = 0; ch < 2; ch++) { const int sf = pm.sh[p * 4 + 2 * ch + q]; const int e = sf == 0 ? 4 : sf, c = rowoff + 2 * px + e; // rowoff even oe[ch] = (e & 1) != 0; po[ch] = (uint32_t)(oe[ch] ? c - 1 : c) * 4; so[ch] = (uint32_t)(oe[ch] ? c + 1 : c - 1) * 4; wx[ch] = wb + (oe[ch] ? 0u : 1u) * KXB; wy[ch] = wb + (oe[ch] ? 1u : 2u) * KXB; wsn[ch] = wb + (oe[ch] ? 2u : 0u) * KXB; } const bool zlane = px == 0; const int txh = (nfull + ((int)blockIdx.x >> 1)) % tilesX; int txm = (int)blockIdx.x % tilesX; const int txstep = (int)gridDim.x % tilesX; int slot0 = 0, cs = 0; uint32_t epar = 1u; for (int k = 0; 2 * k < S; k++) { const bool half = k >= myFull; const bool act = (!half || rr < U_HROWS) && !(nrwL && g == 1 && (half ? txh : txm) == tilesX - 1); // NRW const bool zl = zlane && (half ? txh : txm) == 0; #pragma unroll for (int ch = 0; ch < 2; ch++) { int slot1 = slot0 + 1; if (slot1 == NT) slot1 = 0; const int mys = q ? slot1 : slot0; const uint32_t sb = st_a + (uint32_t)(mys * TB); const uint32_t pa = sb + po[ch], sa = sb + so[ch]; mbar_wait_tf<XV>(&tfull[slot0], (tpar >> slot0) & 1u); tpar ^= 1u << slot0; mbar_wait_tf<XV>(&tfull[slot1], (tpar >> slot1) & 1u); tpar ^= 1u << slot1; uint32_t kX[4], kY[4], kS[4]; if (act) { #pragma unroll for (int J = 0; J < 4; J++) { float2 a, bq; float as, bs; switch (J) { case 0: a = lds64<0 * CHS4>(pa); bq = lds64<1 * CHS4>(pa); as = lds32<0 * CHS4>(sa); bs = lds32<1 * CHS4>(sa); break; case 1: a = lds64<2 * CHS4>(pa); bq = lds64<3 * CHS4>(pa); as = lds32<2 * CHS4>(sa); bs = lds32<3 * CHS4>(sa); break; case 2: a = lds64<4 * CHS4>(pa); bq = lds64<5 * CHS4>(pa); as = lds32<4 * CHS4>(sa); bs = lds32<5 * CHS4>(sa); break; default: a = lds64<6 * CHS4>(pa); bq = lds64<7 * CHS4>(pa); as = lds32<6 * CHS4>(sa); bs = lds32<7 * CHS4>(sa); break; } kX[J] = pack_h2(a.x, bq.x); kY[J] = pack_h2(a.y, bq.y); kS[J] = pack_h2(as, bs); } if (__builtin_expect(zl, 0)) { // global col -1 = left zero pad: kx 0 = P.x (e odd) or S (e even) #pragma unroll for (int J = 0; J < 4; J++) { if (oe[ch]) kX[J] = 0u; else kS[J] = 0u; } } } __syncwarp(); if (lane == 0) { mbar_arrive(&tempty[slot0]); mbar_arrive(&tempty[slot1]); } const int csx = (NC == 2) ? ch : cs; // NC == 2 -> converted slot = chunk (compile-time) mbar_wait_x<(XV & 128)>(&cempty[csx], epar); if (act) { const uint32_t co = (uint32_t)(csx * U_CBYTES); sts128<0>(wx[ch] + co, kX[0], kX[1], kX[2], kX[3]); sts128<0>(wy[ch] + co, kY[0], kY[1], kY[2], kY[3]); sts128<0>(wsn[ch] + co, kS[0], kS[1], kS[2], kS[3]); } if (!(XV & XF_BIT)) asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); __syncwarp(); if (lane == 0) mbar_arrive(&cfull[csx]); if (++cs == NC) { cs = 0; epar ^= 1u; } slot0 += 2; if (slot0 >= NT) slot0 -= NT; } txm += txstep; if (txm >= tilesX) txm -= tilesX; } }; if (wfused & 64) { if (((rr + 3) & 3) == 3) pxs2_loop(std::true_type{}); else pxs2_loop(std::false_type{}); } else if (((rr + 3) & 3) == 3) pxs_loop(std::true_type{}); else pxs_loop(std::false_type{}); } else if constexpr (PH) { // PHASE CONVERTER OUTER-LOOP DIET: the loop body is instantiated per (pair-load converter v2, 3-row // channel stride) so the CTA/warp-uniform converter selection leaves the loop; the half-tile column and // the shfl source lane are hoisted; the cempty parity is a toggled register; the item index k replaces // (s >> 1) (s = g + 2k, g in {0,1}). Same loads / stores / barrier sequence -> bit-identical output. auto ph_loop = [&](auto v2c, auto c3c) { constexpr bool V2 = decltype(v2c)::value; constexpr int CHS4 = (decltype(c3c)::value ? 3 : 2) * P_RW * 4; const int srch = (lane & 16) | ((lane - 1) & 15); // lane m-1 within the half-warp const bool nrwP = (XV & NRW_BIT) && (Wo - 32 * (tilesX - 1)) <= 16; // NRW const int txh = (nfull + ((int)blockIdx.x >> 1)) % tilesX; // tile column of the half item int slot0 = 2 * g; // TMA slot of sub-stage u = 2s uint32_t cpar = 0; // parity of the next cempty wait int txm = (int)blockIdx.x % tilesX; // incremental tile column const int txstep = (int)gridDim.x % tilesX; #pragma unroll ((XV & 16) ? 2 : 1) for (int s = g, k = 0; s < S; s += NG, k++) { int slot1 = slot0 + 1; if (slot1 == NT) slot1 = 0; const int mys = q ? slot1 : slot0; const bool half = k >= myFull; // half-tile item: 5-row TMA box const bool act = !half || rr < U_HROWS; // warp-uniform const int tx = half ? txh : txm; const bool nrw = nrwP && tx == tilesX - 1; // NRW (warp-uniform) const uint32_t sb = st_a + (uint32_t)(mys * TB); // formed before the tfull waits mbar_wait_tf<XV>(&tf[slot0], (tpar >> slot0) & 1u); tpar ^= 1u << slot0; mbar_wait_tf<XV>(&tf[slot1], (tpar >> slot1) & 1u); if (k == 0 && tid == 32 * WCV) PST(7); if (k == 0 && tid == 32 * WCV) GTS(5); tpar ^= 1u << slot1; uint32_t pk[2][3][4]; if (act) { // left pad (global col -1) is not OOB-filled when s > 0 -> zero it for tx == 0 // SEL HOIST: the per-pair left-pad select (zl ? 0: pack, 4 SEL per px-pair set per stage on // every lane) is removed from the conversion (zl = false is constant-folded); the zeroing is // instead applied only inside a WARP-UNIFORM tx == 0 branch, so stages of tile columns // tx > 0 run no select at all. Same values -> bit-identical output. if (__builtin_expect(nrw, 0)) { // NRW: px m only if (V2) conv_ld_ph2<CHS4, true>(sb + p2_off, sb + s2_off, false, false, pk); else conv_ld_ph<CHS4, false, true>(sb + rd_off, false, edge, srch, pk); } else { if (V2) conv_ld_ph2<CHS4>(sb + p2_off, sb + s2_off, false, false, pk); else conv_ld_ph<CHS4>(sb + rd_off, false, edge, srch, pk); } if (__builtin_expect(tx == 0, 0)) { // warp-uniform (tx is per stage) if (m == 0) { // left zero pad lane (global col -1) if (V2) { // pair-load converter: col -1 is S (even e) -> pk[0][2], or P.x (odd e) -> pk[0][0] #pragma unroll for (int jj = 0; jj < 4; jj++) { if (odd_e) pk[0][0][jj] = 0u; else pk[0][2][jj] = 0u; } } else { #pragma unroll for (int jj = 0; jj < 4; jj++) pk[0][0][jj] = 0u; // px m kx = 0 } } } } if (XV & 4096) { mbar_arrive(&tempty[slot0]); mbar_arrive(&tempty[slot1]); } else { __syncwarp(); if (lane == 0) { mbar_arrive(&tempty[slot0]); mbar_arrive(&tempty[slot1]); } } if (k > 0) { mbar_wait_x<(XV & 128)>(&cempty[g], cpar); cpar ^= 1u; } if (act) { if (V2) { // permuted per-lane planes sts128<0>(wa0, pk[0][0][0], pk[0][0][1], pk[0][0][2], pk[0][0][3]); if (!nrw) sts128<512>(wa0, pk[1][0][0], pk[1][0][1], pk[1][0][2], pk[1][0][3]); sts128<0>(wa1, pk[0][1][0], pk[0][1][1], pk[0][1][2], pk[0][1][3]); if (!nrw) sts128<512>(wa1, pk[1][1][0], pk[1][1][1], pk[1][1][2], pk[1][1][3]); sts128<0>(wa2, pk[0][2][0], pk[0][2][1], pk[0][2][2], pk[0][2][3]); if (!nrw) sts128<512>(wa2, pk[1][2][0], pk[1][2][1], pk[1][2][2], pk[1][2][3]); } else { sts128<0 * KXB>(wbase_a, pk[0][0][0], pk[0][0][1], pk[0][0][2], pk[0][0][3]); if (!nrw) sts128<0 * KXB + R2>(wbase_a, pk[1][0][0], pk[1][0][1], pk[1][0][2], pk[1][0][3]); sts128<1 * KXB>(wbase_a, pk[0][1][0], pk[0][1][1], pk[0][1][2], pk[0][1][3]); if (!nrw) sts128<1 * KXB + R2>(wbase_a, pk[1][1][0], pk[1][1][1], pk[1][1][2], pk[1][1][3]); sts128<2 * KXB>(wbase_a, pk[0][2][0], pk[0][2][1], pk[0][2][2], pk[0][2][3]); if (!nrw) sts128<2 * KXB + R2>(wbase_a, pk[1][2][0], pk[1][2][1], pk[1][2][2], pk[1][2][3]); } } if (!(XV & XF_BIT)) asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // STS -> async proxy if (XV & 8192) mbar_arrive(&cfull[g]); else { __syncwarp(); if (lane == 0) mbar_arrive(&cfull[g]); } slot0 += 2 * NG; if (slot0 >= NT) slot0 -= NT; txm += txstep; if (txm >= tilesX) txm -= tilesX; } }; if (v2) { if (pchs == 3 * P_RW) ph_loop(std::true_type{}, std::true_type{}); else ph_loop(std::true_type{}, std::false_type{}); } else { if (pchs == 3 * P_RW) ph_loop(std::false_type{}, std::true_type{}); else ph_loop(std::false_type{}, std::false_type{}); } } else { int slot0 = 2 * g; // TMA slot of sub-stage u = 2s // incremental tile column. Iteration k handles item k (s = g + 2k); full item k = tile // bid + k*grid, and tilesPer is a multiple of tilesX, so tx = tile % tilesX advances by grid % tilesX // per item -> replaces the two runtime-divisor mods per stage (item_tile + % tilesPer % tilesX). int txm = PH ? (int)blockIdx.x % tilesX : 0; const int txstep = PH ? (int)gridDim.x % tilesX : 0; int cwty = CW ? (cid * cwK) % tilesY : 0; // CW: tile row of item k (incremental) #pragma unroll ((XV & 16) ? 2 : 1) for (int s = g, k = 0; s < S; s += NG, k++) { int slot1 = slot0 + 1; if (slot1 == NT) slot1 = 0; const int mys = q ? slot1 : slot0, oth = q ? slot0 : slot1; const bool succ = CW && k > 0 && cwty > 0; // warp-uniform: window row 0 = previous tile's row 8 // own-slot source addresses formed before the tfull waits (first LDS right after the wait) const uint32_t mysb = st_a + (uint32_t)(mys * TB); const uint32_t asa = mysb + rd_off, aea = mysb + ed_off; mbar_wait_tf<XV>(&tf[slot0], (tpar >> slot0) & 1u); tpar ^= 1u << slot0; mbar_wait_tf<XV>(&tf[slot1], (tpar >> slot1) & 1u); if (k == 0 && tid == 32 * WCV) PST(7); tpar ^= 1u << slot1; const bool half = hfirst ? (k == 0) : (k >= myFull); // HF; item index k (= s >> 1) -> half-tile item: 5-row box const bool act = (!half || rr < U_HROWS) && !(succ && rr == 0); // warp-uniform uint32_t pk[2][3][4]; if (act) { if (PH) { // left pad (global col -1) is not OOB-filled when s > 0 -> zero it for tx == 0 const int tx = (k < myFull) ? txm : (nfull + ((int)blockIdx.x >> 1)) % tilesX; const uint32_t sa = st_a + (uint32_t)(mys * TB) + rd_off; const bool zl = (m == 0) && tx == 0; // left pad lane const int srch = (lane & 16) | ((lane - 1) & 15); // lane m-1 within the half-warp if (v2) { // pair-load converter (CTA-uniform flag) const uint32_t sb = st_a + (uint32_t)(mys * TB); const bool zS = zl && !odd_e, zP = zl && odd_e; if (pchs == 3 * P_RW) conv_ld_ph2<3 * P_RW * 4>(sb + p2_off, sb + s2_off, zS, zP, pk); else conv_ld_ph2<2 * P_RW * 4>(sb + p2_off, sb + s2_off, zS, zP, pk); } else { if (pchs == 3 * P_RW) conv_ld_ph<3 * P_RW * 4>(sa, zl, edge, srch, pk); // warp-uniform else conv_ld_ph<2 * P_RW * 4>(sa, zl, edge, srch, pk); } } else { if (XV & 1024) { // XA4: all LDS first, release the raw slots, then pack/shuffle float4 ra[8]; float rh[8]; if (CW && succ) { // rows 1..8 in the dense 8-row box (rr = 0 is copied, see below) conv_raw16<8 * A_MC, 8 * 4>(mysb + (uint32_t)(((rr - 1) * A_MC + 4 * m) * 4), mysb + (uint32_t)A_HOFF + (uint32_t)(((rr - 1) * 4 + 3) * 4), m == 0, ra, rh); // 8-row halo } else if constexpr (CLU) { // row rr in the local 8-row box or the shared-row region (warp-uniform) const int rk = (int)(blockIdx.x & 1); if (rr == (rk ? 0 : 8)) conv_raw16<A_MC, U_BOXR * 4>(mysb + 16384u + (uint32_t)(16 * m), aea, m == 0, ra, rh); else conv_raw16<8 * A_MC, U_BOXR * 4>(mysb + (uint32_t)(((rr - rk) * A_MC + 4 * m) * 4), aea, m == 0, ra, rh); } else if (!half) conv_raw16<U_BOXR * A_MC, U_BOXR * 4>(asa, aea, m == 0, ra, rh); else conv_raw16<U_HROWS * A_MC, U_BOXR * 4>(asa, aea, m == 0, ra, rh); __syncwarp(); if (XV & C70_TA2) { if (lane < 2) mbar_arrive(&tempty[lane ? slot1 : slot0]); } // C70 TA2: 2 lanes arrive in parallel else if (lane == 0) { mbar_arrive(&tempty[slot0]); mbar_arrive(&tempty[slot1]); } if (CLU && lane == 0 && (blockIdx.x & 1)) { mbar_arrive_remote(&tempty[slot0], 0u); mbar_arrive_remote(&tempty[slot1], 0u); } conv_pack16(ra, rh, m == 0, srcl, pk); } else if (!half) conv_ld16<U_BOXR * A_MC, U_BOXR * 4>(asa, aea, m == 0, srcl, pk); // own halo else conv_ld16<U_HROWS * A_MC, U_BOXR * 4>(asa, aea, m == 0, srcl, pk); } } if (XV & 1024) { if (!act) { __syncwarp(); if (lane == 0) { mbar_arrive(&tempty[slot0]); mbar_arrive(&tempty[slot1]); } } } else if (XV & 4096) { mbar_arrive(&tempty[slot0]); mbar_arrive(&tempty[slot1]); } else { __syncwarp(); if (lane == 0) { mbar_arrive(&tempty[slot0]); mbar_arrive(&tempty[slot1]); } } mbar_wait_x<(XV & 128)>(&cempty[g], (k & 1) ^ 1u); // k = 0 waits parity 1 = passes on a fresh barrier if (CW && succ) { if (rr == 0) { // copy the previous tile's converted window row 8 (py0 row 4, same slot g, same lane layout) // into window row 0 (py0 row 0). MMAs of the previous use of slot g are complete (cempty). constexpr int D = 4 * PROW; const float4 c0 = lds128<0 * KXB + D>(wbase_a), c1 = lds128<0 * KXB + R2 + D>(wbase_a); const float4 c2 = lds128<1 * KXB + D>(wbase_a), c3 = lds128<1 * KXB + R2 + D>(wbase_a); const float4 c4 = lds128<2 * KXB + D>(wbase_a), c5 = lds128<2 * KXB + R2 + D>(wbase_a); asm volatile("bar.arrive %0, 64;" :: "r"(2 + g) : "memory"); // reads done -> rr = 8 may overwrite sts128<0 * KXB>(wbase_a, __float_as_uint(c0.x), __float_as_uint(c0.y), __float_as_uint(c0.z), __float_as_uint(c0.w)); sts128<0 * KXB + R2>(wbase_a, __float_as_uint(c1.x), __float_as_uint(c1.y), __float_as_uint(c1.z), __float_as_uint(c1.w)); sts128<1 * KXB>(wbase_a, __float_as_uint(c2.x), __float_as_uint(c2.y), __float_as_uint(c2.z), __float_as_uint(c2.w)); sts128<1 * KXB + R2>(wbase_a, __float_as_uint(c3.x), __float_as_uint(c3.y), __float_as_uint(c3.z), __float_as_uint(c3.w)); sts128<2 * KXB>(wbase_a, __float_as_uint(c4.x), __float_as_uint(c4.y), __float_as_uint(c4.z), __float_as_uint(c4.w)); sts128<2 * KXB + R2>(wbase_a, __float_as_uint(c5.x), __float_as_uint(c5.y), __float_as_uint(c5.z), __float_as_uint(c5.w)); } else if (rr == 8) { asm volatile("bar.sync %0, 64;" :: "r"(2 + g) : "memory"); // wait for rr = 0's copy reads } } if (act && v2) { // permuted per-lane planes sts128<0>(wa0, pk[0][0][0], pk[0][0][1], pk[0][0][2], pk[0][0][3]); sts128<512>(wa0, pk[1][0][0], pk[1][0][1], pk[1][0][2], pk[1][0][3]); sts128<0>(wa1, pk[0][1][0], pk[0][1][1], pk[0][1][2], pk[0][1][3]); sts128<512>(wa1, pk[1][1][0], pk[1][1][1], pk[1][1][2], pk[1][1][3]); sts128<0>(wa2, pk[0][2][0], pk[0][2][1], pk[0][2][2], pk[0][2][3]); sts128<512>(wa2, pk[1][2][0], pk[1][2][1], pk[1][2][2], pk[1][2][3]); } else if (act) { // 6 STS.128 on one 32-bit base with immediate offsets (kx planes, M row +16 at +512 B) sts128<0 * KXB>(wbase_a, pk[0][0][0], pk[0][0][1], pk[0][0][2], pk[0][0][3]); sts128<0 * KXB + R2>(wbase_a, pk[1][0][0], pk[1][0][1], pk[1][0][2], pk[1][0][3]); sts128<1 * KXB>(wbase_a, pk[0][1][0], pk[0][1][1], pk[0][1][2], pk[0][1][3]); sts128<1 * KXB + R2>(wbase_a, pk[1][1][0], pk[1][1][1], pk[1][1][2], pk[1][1][3]); sts128<2 * KXB>(wbase_a, pk[0][2][0], pk[0][2][1], pk[0][2][2], pk[0][2][3]); sts128<2 * KXB + R2>(wbase_a, pk[1][2][0], pk[1][2][1], pk[1][2][2], pk[1][2][3]); } if (!(XV & XF_BIT)) asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // STS -> async proxy if (XV & 8192) mbar_arrive(&cfull[g]); else { __syncwarp(); if (lane == 0) mbar_arrive(&cfull[g]); } slot0 += 2 * NG; if (slot0 >= NT) slot0 -= NT; if (PH) { txm += txstep; if (txm >= tilesX) txm -= tilesX; } if (CW) { if (++cwty == tilesY) cwty = 0; } } } // !PH } // !spl } else if (warp >= WCV) { // ------------------------------ converters ------------------------------ const int cw = warp - WCV; const int rr = (TWC == 32) ? (cw >> 1) : cw; const int q = (TWC == 32) ? (cw & 1) : (lane >> 4); // channel octet const int px = (TWC == 32) ? lane : (lane & 15); const bool active = rr < BOXR; // GATHER: issue the first stage's global loads up front (1 stage = 16 ch in flight) float gv[8][3]; GatherCursor gc; gc.s = 0; gc.p = x; gc.ok0 = gc.ok1 = gc.ok2 = false; const size_t ghw = (size_t)H * W, gcs = ghw * CK; if (S > 0) gather_next<TWC>(gc, gv, x, rr, q, px, H, W, tilesX, tilesPer, ghw, gcs); for (int s = 0; s < S; s++) { const int cslot = s % NC; float nv[8][3]; if (s + 1 < S) gather_next<TWC>(gc, nv, x, rr, q, px, H, W, tilesX, tilesPer, ghw, gcs); const bool act = active; uint8_t* dst = sc + cslot * U_CBYTES; uint32_t pk[3][4]; // fp16x2 [kx][channel pair] #pragma unroll for (int j = 0; j < 4; j++) #pragma unroll for (int kx = 0; kx < 3; kx++) pk[kx][j] = pack_h2(gv[2 * j][kx], gv[2 * j + 1][kx]); if (s >= NC) mbar_wait(&cempty[cslot], ((s / NC) - 1) & 1); if (act) { const int py = rr & 1, r = rr >> 1; // pixel row (r*TWC + px) of plane py; SW32: 16B chunk ^= address bit 7 = (px>>2)&1 const uint32_t off = py * PY0 + (r * TWC + px) * 32 + (((q ^ (px >> 2)) & 1) << 4); #pragma unroll for (int kx = 0; kx < 3; kx++) *(uint4*)(dst + kx * KXB + off) = make_uint4(pk[kx][0], pk[kx][1], pk[kx][2], pk[kx][3]); } asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); // STS -> async proxy __syncwarp(); if (lane == 0) mbar_arrive(&cfull[cslot]); #pragma unroll for (int k = 0; k < 8; k++) #pragma unroll for (int kx = 0; kx < 3; kx++) gv[k][kx] = nv[k][kx]; } } else { // -------- epilogue: 8 warps. Warp e reads TMEM lane quadrant (e&3) (hardware restriction: // warp%4 selects lanes 32*(e&3)..+31 = M indices -> (row, px)) and cout half hf = e>>2 // (TMEM columns hf*32..hf*32+31): one tcgen05.ld 32x32b.x32 per tile, then +bias and // 32 coalesced 128 B row stores (direct st.global.cs) or one swizzled-smem TMA store. const int e = warp, qd = e & 3; const int mi = 32 * qd + lane; float* myo = (float*)(so + e * U_OBYTES); // bias prefetched before the first afull wait (latency overlaps the first tile's MMAs) // bias is folded into the MMA (bias slab MMA initializes each accumulator) -> no bias in the epilogue static_assert(!(XV & 512) && !(XV & C70_X16), "dormant XA1/X16 drains still add bias (removed in v184)"); // SMEM BIAS: each epilogue warp parks its 32 biases in a PRIVATE 128 B smem slot (barrier region // + 384 + 128*warp; region sized 1536 B) once; per 8-cout chunk the drain reads them with 2 broadcast // LDS.128 (immediate offsets) instead of 8 SHFLs. Same values -> bit-identical output. // +512 (was +384): with NC = 4 the barrier arrays + tmem_slot reach byte 388, so warp 0's bias slot // overlapped tmem_slot (read by every thread after the TMEM-alloc __syncthreads) -> race. 512 + 8*128 = 1536. const uint32_t bsm = (uint32_t)__cvta_generic_to_shared(tfull) + 512u + 128u * (uint32_t)e; for (int t = 0; ; t++) { int dtile = -1; if (t >= myTiles) { if (!(DYNc && dyn)) break; // DYN: wait for the MMA thread's publish of dynamic item t, then read its tile id (-1 = end) const int j = t - myTiles; mbar_wait_sleep(&dynb[j & 7], (j >> 3) & 1); dtile = ((volatile int*)itm)[t & 15]; if (dtile < 0) break; } const int a = t & (U_NACC - 1); // all per-tile address math (tile decode, oy/ox, inb, taddr, yp) is done BEFORE the afull wait // (pinned there by an empty asm consuming the results), so the first tcgen05.ld issues right after it. int hs; const int tile = (DYNc && t >= myTiles) ? (hs = -1, dtile) : item_tile(t, hs); const int n = tile / tilesPer; const int rem = tile - n * tilesPer; int ty, tx; if ((XV & 2) && !PH && !GATHER) { tx = rem / tilesY; ty = rem - tx * tilesY; } else { ty = rem / tilesX; tx = rem - ty * tilesX; } // half tile: only M rows 0..63 (out rows 4ty+2hs, +1) are valid const int oy = ROWS * ty + (hs < 0 ? 0 : 2 * hs) + mi / TWC, ox = TWC * tx + ((GATHER || (PH && !PSP)) ? (mi % TWC) : (2 * (lane & 15) + (lane >> 4))); // PSP: aligned px-pair map const bool inb = oy < Ho && ox < Wo && (hs < 0 || qd < 2); const size_t cs = (size_t)Ho * Wo; const bool v4ok = (Wo & 3) == 0 && ((((uintptr_t)y) & 15) == 0); // XB2: 16 B aligned px quads #pragma unroll 1 for (int hi = 0; hi < NHF; hi++) { const int hf = e >> 2; const uint32_t taddr = tmem_base + ((uint32_t)(32 * qd) << 16) + a * 64 + hf * (CSP ? 16 : 32); float* yp = y + ((size_t)n * COUT * Ho + (inb ? oy : 0)) * Wo + (inb ? ox : 0) + (CSP ? (32 * (int)blockIdx.y + 16 * hf) : hf * 32) * cs; asm volatile("" :: "l"(yp), "r"(taddr), "r"((int)inb)); // materialize before the wait if (hi == 0) { if constexpr (((XV & C70_EB2) || (XV & C70_EB4) || (XV & C70_EB6) || ((XV >> 44) & 7)) && !GATHER) { // C70 EB: burst the group's stores constexpr int BF = (int)((XV >> 44) & 7); // C70 EBN: explicit group size field (bits 44-46) constexpr int B0 = BF ? BF : ((XV & C70_EB6) ? 6 : ((XV & C70_EB4) ? 4 : 2)); int B = (XV & C70_EBA) ? (myTiles >= 12 ? (((XV & C70_EBA2) && myTiles >= 24) ? 4 : 5) : 4) : B0; // C70 EBA: adaptive group size { // D1 class override fields: bits 52-54 (myTiles < 12), 55-57 (12..23), 58-60 (>= 24); 0 = keep, 1 = 8, else B constexpr int FA = (int)((XV >> 52) & 7), FB = (int)((XV >> 55) & 7), FC = (int)((XV >> 58) & 7); const int fv = myTiles < 12 ? FA : (myTiles < 24 ? FB : FC); if (fv) B = fv == 1 ? 8 : fv; } { // runtime per-shape burst-size override (wfused bits 8-11, 1..8; 1 = no burst); 0 = keep const int bo = (wfused >> 8) & 15; if (bo) B = bo; } if ((t % B) == 0) { const int tl = (t + B - 1 < myTiles) ? t + B - 1 : myTiles - 1; const bool skip = (XV & C70_EBL) && tl >= myTiles - 1; // last group: no burst wait if (tl > t && !skip) mbar_wait_sleep(&afull[tl & (U_NACC - 1)], (tl >> 3) & 1); } } mbar_wait_sleep(&afull[a], (t >> 3) & 1); // suspend-hint wait if (e == 0 && lane == 0 && t == 0) GTS(7); #ifdef CONV_PROBE if (e == 0 && lane == 0 && t == 0) PST(12); if (e == 0 && lane == 0 && t == myTiles - 1) PST(14); #endif fence_after(); } if constexpr ((XV & 512) && !PH && !GATHER) { // XA1 16x256b DRAIN: the converter put px 2k / 2k+1 (k = 0..7 of each 16-px half lb) in TMEM lanes // 16lb + k / 16lb + 8 + k, so one 16x256b load gives each thread both px of a pair for 2 couts per // repetition -> float2 stores without shuffles. Chunk c = (lb = c>>1, cols 16(c&1)..+15). const int kq = lane >> 2, cp = lane & 3; const bool okr = oy < Ho && (hs < 0 || qd < 2); const int oxk = TWC * tx + 2 * kq; const bool ok0 = okr && oxk < Wo, ok1 = okr && oxk + 16 < Wo; float* yb = y + ((size_t)n * COUT * Ho + (okr ? oy : 0)) * Wo + oxk + (size_t)(hf * 32 + 2 * cp) * cs; const uint32_t ta = tmem_base + ((uint32_t)(32 * qd) << 16) + a * 64 + hf * 32; const uint32_t bs2 = bsm + 8u * (uint32_t)cp; float w0[8], w1[8], w2[8], w3[8]; auto st16 = [&](const float* vv, int lb, int cb, const float2 b0, const float2 b1) { if (lb ? ok1 : ok0) { float* p = yb + 16 * lb + (size_t)cb * cs; asm volatile("st.global.v2.f32 [%0], {%1, %2};" :: "l"(p), "f"(vv[0] + b0.x), "f"(vv[2] + b0.x) : "memory"); asm volatile("st.global.v2.f32 [%0], {%1, %2};" :: "l"(p + cs), "f"(vv[1] + b0.y), "f"(vv[3] + b0.y) : "memory"); p += 8 * cs; asm volatile("st.global.v2.f32 [%0], {%1, %2};" :: "l"(p), "f"(vv[4] + b1.x), "f"(vv[6] + b1.x) : "memory"); asm volatile("st.global.v2.f32 [%0], {%1, %2};" :: "l"(p + cs), "f"(vv[5] + b1.y), "f"(vv[7] + b1.y) : "memory"); } }; tmem_ld16x256(ta, w0); const float2 c00 = lds64<0>(bs2), c01 = lds64<32>(bs2), c10 = lds64<64>(bs2), c11 = lds64<96>(bs2); tmem_wait_ld8(w0); tmem_ld16x256(ta + 16, w1); st16(w0, 0, 0, c00, c01); tmem_wait_ld8(w1); tmem_ld16x256(ta + (16u << 16), w2); st16(w1, 0, 16, c10, c11); tmem_wait_ld8(w2); tmem_ld16x256(ta + (16u << 16) + 16, w3); st16(w2, 1, 0, c00, c01); tmem_wait_ld8(w3); fence_before(); __syncwarp(); if (lane == 0) mbar_arrive(&aempty[a]); st16(w3, 1, 16, c10, c11); continue; } if constexpr (TST) { // TST DRAIN: four 8-col TMEM loads; chunk c (couts hf*32+8c..+7) -> staging buffer c&1 of this warp // ([8 couts][32 px] fp32, 128 B rows; lane l holds px 2(l&15)+(l>>4): 8 conflict-free STS.32) -> one TMA // tensor store (box 32 px x 1 row x 8 couts) issued by lane 0. Before overwriting a buffer, lane 0 waits // until at most 1 bulk group (the other buffer's) is still reading smem. const uint32_t sbuf = (uint32_t)__cvta_generic_to_shared(so) + 2048u * (uint32_t)e + 4u * (uint32_t)(2 * (lane & 15) + (lane >> 4)); const uint32_t sbase0 = (uint32_t)__cvta_generic_to_shared(so) + 2048u * (uint32_t)e; const int oyr = ROWS * ty + qd; auto stc = [&](const float* vv, int c) { if (lane == 0) asm volatile("cp.async.bulk.wait_group.read 1;" ::: "memory"); __syncwarp(); const uint32_t ba = sbuf + 1024u * (uint32_t)(c & 1); asm volatile("st.shared.f32 [%0+0], %1;" :: "r"(ba), "f"(vv[0]) : "memory"); asm volatile("st.shared.f32 [%0+128], %1;" :: "r"(ba), "f"(vv[1]) : "memory"); asm volatile("st.shared.f32 [%0+256], %1;" :: "r"(ba), "f"(vv[2]) : "memory"); asm volatile("st.shared.f32 [%0+384], %1;" :: "r"(ba), "f"(vv[3]) : "memory"); asm volatile("st.shared.f32 [%0+512], %1;" :: "r"(ba), "f"(vv[4]) : "memory"); asm volatile("st.shared.f32 [%0+640], %1;" :: "r"(ba), "f"(vv[5]) : "memory"); asm volatile("st.shared.f32 [%0+768], %1;" :: "r"(ba), "f"(vv[6]) : "memory"); asm volatile("st.shared.f32 [%0+896], %1;" :: "r"(ba), "f"(vv[7]) : "memory"); asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); __syncwarp(); if (lane == 0) { asm volatile("cp.async.bulk.tensor.4d.global.shared::cta.tile.bulk_group [%0, {%1, %2, %3, %4}], [%5];" :: "l"((uint64_t)&omap), "r"(TWC * tx), "r"(oyr), "r"(hf * 32 + 8 * c), "r"(n), "r"(sbase0 + 1024u * (uint32_t)(c & 1)) : "memory"); bulk_commit(); } }; float v0[8], v1[8], v2[8], v3[8]; tmem_ld8(taddr, v0); tmem_wait_ld8(v0); tmem_ld8(taddr + 8, v1); stc(v0, 0); tmem_wait_ld8(v1); tmem_ld8(taddr + 16, v2); stc(v1, 1); tmem_wait_ld8(v2); tmem_ld8(taddr + 24, v3); stc(v2, 2); tmem_wait_ld8(v3); fence_before(); __syncwarp(); if (lane == 0) mbar_arrive(&aempty[a]); stc(v3, 3); (void)inb; (void)cs; (void)v4ok; continue; } if (!use_tstore) { // PIPELINED DRAIN (direct-store paths): two 16-column TMEM loads; the stores of chunk 0 // issue while chunk 1's tcgen05.ld is in flight. The second wait binds chunk 1's registers // ("+f") so no use of them can be scheduled before it. Same values/stores -> bit-identical. // DRAIN SHAPE: four 8-column TMEM loads (32x32b.x8), 3-stage software pipeline -- the stores of // chunk c issue while chunk c+1's tcgen05.ld is in flight; aempty arrives after the last chunk's wait. float v0[8], v1[8], v2[8], v3[8]; float* yq = yp; const bool hiL = (lane >> 4) != 0; // 8 couts of one chunk -> y. XV&4 (aligned path): lanes l / l+16 hold px 2m / 2m+1; one SHFL.xor 16 per // cout pair, then each lane stores a float2 (px 2m, 2m+1) of cout 2j (low lanes) / 2j+1 (high lanes). auto st8 = [&](float* yq0, const float* vv) { if ((XV & 16384) && !PH && !GATHER && v4ok) { // XB2: pair exchange (xor 16) then quad exchange (xor 1): lane holds px 4k..4k+3 of 2 couts -> // one st.global.v4 per cout (each instruction = 4 couts x 128 B full lines) const bool od = (lane & 1) != 0; float* yb = (hiL ? yq0 - 1 : yq0) - (od ? 2 : 0); float2 pr[4]; #pragma unroll for (int j = 0; j < 4; j++) { const float snd = hiL ? vv[2 * j] : vv[2 * j + 1]; const float r = __shfl_xor_sync(0xffffffffu, snd, 16); pr[j].x = hiL ? r : vv[2 * j]; pr[j].y = hiL ? vv[2 * j + 1] : r; } #pragma unroll for (int i = 0; i < 2; i++) { const float2 sd = od ? pr[2 * i] : pr[2 * i + 1]; float2 r; r.x = __shfl_xor_sync(0xffffffffu, sd.x, 1); r.y = __shfl_xor_sync(0xffffffffu, sd.y, 1); const float2 lo = od ? r : pr[2 * i], hi2 = od ? pr[2 * i + 1] : r; float* pp = yb + (size_t)(2 * (2 * i + (od ? 1 : 0)) + (hiL ? 1 : 0)) * cs; if (inb) asm volatile("st.global.v4.f32 [%0], {%1, %2, %3, %4};" :: "l"(pp), "f"(lo.x), "f"(lo.y), "f"(hi2.x), "f"(hi2.y) : "memory"); } } else if ((XV & 4) && !PH && !GATHER) { float* yb = hiL ? yq0 - 1 : yq0; #pragma unroll for (int j = 0; j < 4; j++) { const float snd = hiL ? vv[2 * j] : vv[2 * j + 1]; const float r = __shfl_xor_sync(0xffffffffu, snd, 16); const float a0 = hiL ? r : vv[2 * j], a1 = hiL ? vv[2 * j + 1] : r; float* pp = yb + (size_t)(2 * j + (hiL ? 1 : 0)) * cs; if (inb) { if (XV & YCS_BIT) asm volatile("st.global.cs.v2.f32 [%0], {%1, %2};" :: "l"(pp), "f"(a0), "f"(a1) : "memory"); else asm volatile("st.global.L1::no_allocate.v2.f32 [%0], {%1, %2};" :: "l"(pp), "f"(a0), "f"(a1) : "memory"); } } } else if (inb) { float* q = yq0; #pragma unroll for (int co = 0; co < 8; co++) { // NA3: odd-W phase/PXS scalar y stores also skip L1 allocation (y never re-read) if ((XV & 64) || PH) asm volatile("st.global.L1::no_allocate.f32 [%0], %1;" :: "l"(q), "f"(vv[co]) : "memory"); else st_out<true>(q, vv[co]); q += cs; } } }; // BIAS LDS HOIST: each chunk's 2 bias LDS.128 issue BEFORE its tcgen05.wait::ld (asm volatile // otherwise pins them after it), so their latency overlaps the TMEM load. Bit-identical. if constexpr ((XV & C70_X16) && !PH && !GATHER) { // C70 X16: two 16-column TMEM loads float u0[16], u1[16]; tmem_ld16(taddr, u0); const float4 c0 = lds128<0>(bsm), c1 = lds128<16>(bsm), c2 = lds128<32>(bsm), c3 = lds128<48>(bsm); tmem_wait_ld16(u0); tmem_ld16(taddr + 16, u1); u0[0] += c0.x; u0[1] += c0.y; u0[2] += c0.z; u0[3] += c0.w; u0[4] += c1.x; u0[5] += c1.y; u0[6] += c1.z; u0[7] += c1.w; u0[8] += c2.x; u0[9] += c2.y; u0[10] += c2.z; u0[11] += c2.w; u0[12] += c3.x; u0[13] += c3.y; u0[14] += c3.z; u0[15] += c3.w; st8(yq, u0); yq += 8 * cs; st8(yq, u0 + 8); yq += 8 * cs; const float4 d0 = lds128<64>(bsm), d1 = lds128<80>(bsm), d2 = lds128<96>(bsm), d3 = lds128<112>(bsm); tmem_wait_ld16(u1); fence_before(); if (XV & C70_AEL) mbar_arrive(&aempty[a]); else { __syncwarp(); if (lane == 0) mbar_arrive(&aempty[a]); } u1[0] += d0.x; u1[1] += d0.y; u1[2] += d0.z; u1[3] += d0.w; u1[4] += d1.x; u1[5] += d1.y; u1[6] += d1.z; u1[7] += d1.w; u1[8] += d2.x; u1[9] += d2.y; u1[10] += d2.z; u1[11] += d2.w; u1[12] += d3.x; u1[13] += d3.y; u1[14] += d3.z; u1[15] += d3.w; st8(yq, u1); yq += 8 * cs; st8(yq, u1 + 8); continue; } if constexpr (CSP) { // 16 couts per warp (TMEM columns 16hf..+15) tmem_ld8(taddr, v0); tmem_wait_ld8(v0); tmem_ld8(taddr + 8, v1); st8(yq, v0); yq += 8 * cs; tmem_wait_ld8(v1); fence_before(); __syncwarp(); if (lane == 0) mbar_arrive(&aempty[a]); st8(yq, v1); continue; } tmem_ld8(taddr, v0); tmem_wait_ld8(v0); tmem_ld8(taddr + 8, v1); st8(yq, v0); yq += 8 * cs; if (XV & C70_ESP) __nanosleep(64); tmem_wait_ld8(v1); tmem_ld8(taddr + 16, v2); st8(yq, v1); yq += 8 * cs; if (XV & C70_ESP) __nanosleep(64); tmem_wait_ld8(v2); tmem_ld8(taddr + 24, v3); st8(yq, v2); yq += 8 * cs; if (XV & C70_ESP) __nanosleep(64); tmem_wait_ld8(v3); if (hi == NHF - 1) { // accumulator slot free once all epilogue warps have read it fence_before(); if ((XV & C70_AEL) && !GATHER) mbar_arrive(&aempty[a]); // C70 AEL: per-lane arrive else { __syncwarp(); if (lane == 0) mbar_arrive(&aempty[a]); } } st8(yq, v3); yq += 8 * cs; continue; } float v[32]; tmem_ld32(taddr, v); asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); // accumulator slot can be reused by the MMA warp once all epilogue warps have read it if (hi == NHF - 1) { fence_before(); __syncwarp(); if (lane == 0) mbar_arrive(&aempty[a]); } if (use_tstore) { if (oy < Ho) { if (lane == 0) bulk_wait_read0(); __syncwarp(); #pragma unroll for (int co = 0; co < 32; co++) myo[co * 32 + ((((lane >> 2) ^ (co & 7))) << 2) + (lane & 3)] = v[co]; asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); __syncwarp(); if (lane == 0) { tma_store4(&omap, myo, TW * tx, oy, hf * 32, n); bulk_commit(); } } } else if (inb) { // direct NCHW stores: for each cout the warp writes TWC consecutive floats // (TWC=32: one full 128 B row segment), streaming (.cs) #pragma unroll for (int co = 0; co < 32; co++) st_cs(yp + co * cs, v[co]); } } // hi } if ((use_tstore || TST) && lane == 0) bulk_wait0(); __syncwarp(); if (e == 0 && lane == 0) PST(15); if (lane == 0) GTMAX(8); } // EARLY EXIT (non-cluster paths): only the TMEM allocator warp must wait for the epilogue's last tcgen05.ld // before the dealloc. The 8 epilogue warps arrive on named barrier 4 (288 = 8 epilogue + 1 allocator warp) and // exit; the allocator warp bar.syncs on it then deallocates; the MMA issuer / converter warps (all their work is // consumed by the epilogue's afull waits) exit right away instead of meeting at a CTA-wide __syncthreads. // Same stores -> bit-identical. CLU keeps the full CTA barrier + cluster sync. if constexpr (!CLU) { if (warp < NEPI) { fence_before(); asm volatile("bar.arrive 4, %0;" :: "n"(32 * (NEPI + 1)) : "memory"); return; } if (warp != WTMA) return; asm volatile("bar.sync 4, %0;" :: "n"(32 * (NEPI + 1)) : "memory"); fence_after(); asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, 512;" :: "r"(tmem_base) : "memory"); return; } fence_before(); __syncthreads(); if constexpr (CLU) cluster_sync_all(); // no CTA exits while its peer may still multicast / arrive into it if (tid == 0) GTS(9); #ifdef CONV_PROBE if (tid == 0) { PSR(8); g_probe[blockIdx.x * 64 + 0] = _pr[0]; for (int i = 1; i < 10; i++) if (i < 5 || i > 7) g_probe[blockIdx.x * 64 + i] = _pr[i]; } #endif if (warp == WTMA) { fence_after(); asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, 512;" :: "r"(tmem_base) : "memory"); } } // ===================================================================================== // TF32 TRANSFORM-FREE path: conv_s2_tf32_kernel -- tuner option for small shapes (any W, 16B-aligned x/w). // GEMM K order k = ci*9 + tap (288 total, tap = ky*3+kx), so the RAW fp32 weight tensor [64 co][288 k] // (row stride 1152 B) is already the K-major B operand: ONE 2D TMA tensor map (dims {288, 64}, box {32, 64}, // SWIZZLE_128B) loads it with 9 boxes (8 KB each = 32 k x 64 co) straight into the canonical SW128 K-major // layout -> no weight transform kernel and no per-CTA conversion of weights. // MMA: tcgen05.mma kind::tf32 (M128 x N64 x K8), 4 per 32-k chunk, 36 per tile, accumulator in TMEM (64 cols). // Item = one HALF tile (2 out rows x 32 out cols, M rows 0..63 valid) per CTA (non-persistent, grid = #items). // Raw input: bulk-row staging as in the mini path, natural channel order: [ci 32][rr 5][68 cols] fp32, one // 1D cp.async.bulk per (channel, input row), 4 barriers (8 channels each). // A operand: fp32 (rna-rounded to tf32) SW128 K-major chunks of 32 k: row p = M row (out row*32 + ox), // 128 B per row, 8-row atoms of 1 KB, 16 B chunk j stored at j ^ (p&7). Chunk stride is 8 KB (64 valid rows); // the M=128 MMA over-reads rows 64..127 from the next chunk / raw staging (inside the allocation, garbage // accumulator rows never stored). All 9 chunks resident (no A ring); MMA issues chunk c once cfull[c] fires. // Warps: 0,1 epilogue (TMEM quadrants 0,1 = out rows 0,1), 2 producer + TMEM alloc, 3 MMA issuer, // 4..11 converters: warp w builds 16 B group j = w (k = 32c+4w .. +3) of every chunk c for both out rows, // lane = ox (conflict-free STS.128 per 8-lane phase; the 4 k of a group are warp-uniform (ci,ky,kx)). // ===================================================================================== // re-added as a per-shape cold-L2 tuned option for small shapes. #ifndef BR_RB #define BR_RB (P_RW * 4) // 272 B per (channel,row) raw staging segment #endif #define F_THREADS 384 #define F_CHB 8192 // A / B chunk stride (B: 64 co x 128 B; A: 64 px x 128 B) #define F_SB 0 // B: 9 boxes = 73728 B #define F_SA (9 * F_CHB) // A: 9 chunks = 73728 B (+ over-read into raw staging) #define F_ST (F_SA + 9 * F_CHB) // raw staging [32][5][68] fp32 = 43520 B #define F_STB (CIN * U_HROWS * BR_RB) #define F_BAR (F_ST + F_STB) #define F_SMEM (F_BAR + 256 + 1024) // 192256 B (1 CTA/SM) __device__ __forceinline__ void tma_load2(void* dst, const CUtensorMap* map, uint64_t* bar, int c0, int c1) { asm volatile("cp.async.bulk.tensor.2d.shared::cluster.global.tile.mbarrier::complete_tx::bytes" " [%0], [%1, {%2, %3}], [%4];" :: "r"((uint32_t)__cvta_generic_to_shared(dst)), "l"((uint64_t)map), "r"(c0), "r"(c1), "r"((uint32_t)__cvta_generic_to_shared(bar)) : "memory"); } // K-major SWIZZLE_128B descriptor: SBO = 1024 B (8-row atom stride), LBO unused (1), layout type 2. __device__ __forceinline__ uint64_t make_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; } // kind::tf32 instruction descriptor: D=F32, A=B=TF32 (2), K-major both, N=64, M=128. __host__ __device__ constexpr uint32_t make_idesc_tf32() { return (1u << 4) | (2u << 7) | (2u << 10) | ((64u >> 3) << 17) | ((128u >> 4) << 24); } __device__ __forceinline__ void umma_tf32(uint32_t tmem_d, uint64_t da, uint64_t db, uint32_t acc) { asm volatile("{\n .reg .pred p;\n setp.ne.b32 p, %4, 0;\n" " tcgen05.mma.cta_group::1.kind::tf32 [%0], %1, %2, %3, p;\n}" :: "r"(tmem_d), "l"(da), "l"(db), "r"(make_idesc_tf32()), "r"(acc) : "memory"); } __device__ __forceinline__ uint32_t to_tf32(float f) { uint32_t r; asm("cvt.rna.tf32.f32 %0, %1;" : "=r"(r) : "f"(f)); return r; } __global__ void __launch_bounds__(F_THREADS, 1) conv_s2_tf32_kernel(const __grid_constant__ CUtensorMap wmap, const float* __restrict__ x, const float* __restrict__ b, float* __restrict__ y, int H, int W, int Ho, int Wo, int tilesX, int Hh) { extern __shared__ uint8_t smem_raw[]; uint8_t* smem = (uint8_t*)(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023); uint8_t* sB = smem + F_SB; uint8_t* sA = smem + F_SA; uint8_t* st = smem + F_ST; uint64_t* tfull = (uint64_t*)(smem + F_BAR); // 4: raw channel groups landed uint64_t* cfull = tfull + 4; // 9: A chunk c written by the 8 converter warps uint64_t* wbar = cfull + 9; // B (weights) landed uint64_t* afull = wbar + 1; // accumulator ready uint32_t* tmem_slot = (uint32_t*)(afull + 1); const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31; const int tx = blockIdx.x % tilesX; const int rest = blockIdx.x / tilesX; const int hy = rest % Hh, n = rest / Hh; const int r0 = 4 * hy - 1; // first input row of the half tile if (tid == 0) { for (int i = 0; i < 4; i++) mbar_init(&tfull[i], 1); for (int i = 0; i < 9; i++) mbar_init(&cfull[i], 8); mbar_init(wbar, 1); mbar_init(afull, 1); asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); asm volatile("prefetch.tensormap [%0];" :: "l"((uint64_t)&wmap) : "memory"); } if (warp == 2) { asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], 64;" :: "r"((uint32_t)__cvta_generic_to_shared(tmem_slot)) : "memory"); asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;" ::: "memory"); } fence_before(); __syncthreads(); fence_after(); const uint32_t tmem_base = *tmem_slot; if (tid == 0) asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); // after TMEM is owned asm volatile("griddepcontrol.wait;" ::: "memory"); // previous grid complete before any global access if (warp == 2) { // ---- producer: B = 9 TMA boxes (raw weights), then 4 raw-input channel groups (bulk rows) ---- if (lane == 0) { mbar_expect_tx(wbar, 9 * F_CHB); #pragma unroll for (int c = 0; c < 9; c++) tma_load2(sB + c * F_CHB, &wmap, wbar, 32 * c, 0); } const int cend = (64 * tx + 64 < W) ? 64 * tx + 64 : W; for (int g = 0; g < 4; g++) { uint32_t mytot = 0; for (int k = lane; k < TCK * U_HROWS; k += 32) { const int i = k / U_HROWS, rr = k - i * U_HROWS, iy = r0 + rr; if (iy < 0 || iy >= H) continue; const size_t R = ((size_t)(n * CIN + 8 * g + i) * H + iy) * W; long long A0 = ((long long)R + 64 * tx - 1) & ~3LL; const long long E = ((long long)R + cend + 3) & ~3LL; if (A0 < 0) A0 = 0; mytot += (uint32_t)((E - A0) * 4); } #pragma unroll for (int o = 16; o > 0; o >>= 1) mytot += __shfl_xor_sync(0xffffffffu, mytot, o); if (lane == 0) mbar_expect_tx(&tfull[g], mytot); __syncwarp(); for (int k = lane; k < TCK * U_HROWS; k += 32) { const int i = k / U_HROWS, rr = k - i * U_HROWS, iy = r0 + rr; if (iy < 0 || iy >= H) continue; const int ci = 8 * g + i; const size_t R = ((size_t)(n * CIN + ci) * H + iy) * W; long long A0 = ((long long)R + 64 * tx - 1) & ~3LL; // global col 64tx-1 -> smem col d const long long E = ((long long)R + cend + 3) & ~3LL; uint32_t dofs = 0; if (A0 < 0) { A0 = 0; dofs = 16; } bulk_g2s(st + (ci * U_HROWS + rr) * BR_RB + dofs, x + A0, (uint32_t)((E - A0) * 4), &tfull[g]); } __syncwarp(); } } else if (warp == 3) { // ---- single-thread MMA issuer: 9 chunks x 4 K=8 steps ---- if (lane == 0) { const uint32_t sA_a = (uint32_t)__cvta_generic_to_shared(sA); const uint32_t sB_a = (uint32_t)__cvta_generic_to_shared(sB); mbar_wait(wbar, 0); for (int c = 0; c < 9; c++) { mbar_wait(&cfull[c], 0); fence_after(); #pragma unroll for (int ks = 0; ks < 4; ks++) umma_tf32(tmem_base, make_desc_sw128(sA_a + c * F_CHB + 32 * ks), make_desc_sw128(sB_a + c * F_CHB + 32 * ks), (c | ks) != 0); } umma_commit(afull); } __syncwarp(); } else if (warp >= 4) { // ---- converters: warp w = 16 B group j of each chunk; lane = ox; both out rows ---- const int w = warp - 4, ox = lane; const uint32_t st_a = (uint32_t)__cvta_generic_to_shared(st); const uint32_t sA_a = (uint32_t)__cvta_generic_to_shared(sA); uint32_t cmask = 0; // bit kx: input col 64tx-1+2ox+kx inside [0, W) #pragma unroll for (int kx = 0; kx < 3; kx++) { const int gc = 64 * tx - 1 + 2 * ox + kx; if (gc >= 0 && gc < W) cmask |= 1u << kx; } int gdone = 0; #pragma unroll for (int c = 0; c < 9; c++) { const int need = ((32 * c + 31) / 9) >> 3; // last channel group chunk c touches while (gdone <= need) { mbar_wait(&tfull[gdone], 0); gdone++; } uint32_t v[2][4]; #pragma unroll for (int e = 0; e < 4; e++) { const int k = 32 * c + 4 * w + e; // warp-uniform const int ci = k / 9, tap = k - 9 * ci; const int ky = tap / 3, kx = tap - 3 * ky; const bool cok = (cmask >> kx) & 1u; #pragma unroll for (int orow = 0; orow < 2; orow++) { const int rr = 2 * orow + ky, iy = r0 + rr; const bool rok = iy >= 0 && iy < H; const uint32_t R = ((uint32_t)(n * CIN + ci) * (uint32_t)H + (uint32_t)iy) * (uint32_t)W; const uint32_t d = (R + 64u * tx - 1u) & 3u; // smem col of global col 64tx-1 const uint32_t a = st_a + (uint32_t)((ci * U_HROWS + rr) * BR_RB) + 4u * (d + 2 * ox + kx); v[orow][e] = to_tf32(lds32_pred(a, rok && cok)); } } #pragma unroll for (int orow = 0; orow < 2; orow++) { const int p = orow * 32 + ox; const uint32_t a = sA_a + c * F_CHB + (p >> 3) * 1024 + (p & 7) * 128 + ((w ^ (p & 7)) << 4); sts128<0>(a, v[orow][0], v[orow][1], v[orow][2], v[orow][3]); } asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); __syncwarp(); if (lane == 0) mbar_arrive(&cfull[c]); } } else { // ---- epilogue warps 0,1: TMEM quadrant qd = out row 2hy+qd, M row = qd*32 + ox ---- const int qd = warp; float bias_r[2]; bias_r[0] = __ldg(b + lane); bias_r[1] = __ldg(b + 32 + lane); mbar_wait(afull, 0); fence_after(); const int oy = 2 * hy + qd, ox = 32 * tx + lane; const bool inb = oy < Ho && ox < Wo; const size_t cs = (size_t)Ho * Wo; #pragma unroll 1 for (int hf = 0; hf < 2; hf++) { float v[32]; tmem_ld32(tmem_base + ((uint32_t)(32 * qd) << 16) + hf * 32, v); asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); #pragma unroll for (int co = 0; co < 32; co++) v[co] += __shfl_sync(0xffffffffu, bias_r[hf], co); if (inb) { float* yp = y + ((size_t)n * COUT + hf * 32) * cs + (size_t)oy * Wo + ox; #pragma unroll for (int co = 0; co < 32; co++) st_cs(yp + co * cs, v[co]); } } } fence_before(); __syncthreads(); if (warp == 2) { fence_after(); asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, 64;" :: "r"(tmem_base) : "memory"); } } // ===================================================================================== // SMALL-SMEM HIGH-OCCUPANCY path: conv_s2_small_kernel -- per-shape voted option for odd-W shapes. // Input: at kernel entry (after griddepcontrol.wait) both warps issue byte-granular 1D cp.async.bulk copies, // one per (channel, input row): staging [32 ch][5 rows][68 cols] fp32 (same bulk-row scheme as the tf32 path), // 4 mbarriers (8 channels each) so compute starts as soon as channels 0-7 land. // Compute: legacy mma.sync m16n8k16 (fp16 rn operands, fp32 accumulate) -- no TMEM, no converted stage. // GEMM M = 64 px (2 rows x 32), N = 64 couts, K = 288 in RAW weight order j = ci*9 + tap. K slot mapping per // 16-step s: lane slots (2t, 2t+1, 2t+8, 2t+9) <-> j = 16s + 4t + {0,1,2,3}, so a lane's B fragment of one n-tile // is ONE float4 LDG of the raw fp32 weights (L1/L2 resident), converted to fp16x2 in registers. // A fragments: 8 LDS.32 per (m-tile) from the fp32 staging, address = offT[orow][s][t][h] + 2*px, where the // per-CTA table offT (built at entry) folds (ci, ky, kx), the per-(ci,row) 16B-alignment shift and invalid rows // (-> a zero row). Pad columns -1 (tx == 0) and W (right edge) are zeroed in smem after each group lands. // Warp w = cout half (32 couts, 4 n-tiles) x all 4 m-tiles: 64 fp32 accumulators per lane. // Epilogue: + bias, direct NCHW stores (8 consecutive px per cout per lane quad). // ===================================================================================== #define SM_THREADS 64 #define SM_STB (CIN * U_HROWS * P_RW * 4) // 43520 B raw staging #define SM_ZROW SM_STB // 272 B zero row #define SM_OFFT (SM_ZROW + P_RW * 4) // offset table [2][18][4][4] int #define SM_BAR (SM_OFFT + 2 * 18 * 16 * 4) // 4 mbarriers #define SM_SMEM (SM_BAR + 64) // 46160 B -> 4 CTAs/SM __device__ __forceinline__ void mma_f16_16816(float (&c)[4], uint32_t a0, uint32_t a1, uint32_t a2, uint32_t a3, uint32_t b0, uint32_t b1) { asm("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};" : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1)); } __global__ void __launch_bounds__(SM_THREADS, 4) conv_s2_small_kernel(const float* __restrict__ x, const float* __restrict__ w, const float* __restrict__ b, float* __restrict__ y, int H, int W, int Ho, int Wo, int tilesX, int Hh) { extern __shared__ __align__(16) uint8_t smem_raw[]; float* sf = (float*)smem_raw; // staging (word-indexed), zero row at word 10880 int* offT = (int*)(smem_raw + SM_OFFT); uint64_t* tfull = (uint64_t*)(smem_raw + SM_BAR); const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31; const int tx = blockIdx.x % tilesX; const int rest = blockIdx.x / tilesX; const int hy = rest % Hh, n = rest / Hh; const int r0 = 4 * hy - 1; // first input row of the half tile const long long colb = 64LL * tx - 1; // global col of smem-relative col 0 (pad col) if (tid == 0) { for (int i = 0; i < 4; i++) mbar_init(&tfull[i], 1); asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); } // zero row + offset table (no global access: legal before the PDL wait) for (int i = tid; i < P_RW; i += SM_THREADS) sf[SM_ZROW / 4 + i] = 0.f; for (int e = tid; e < 576; e += SM_THREADS) { const int h = e & 3, t = (e >> 2) & 3, s = (e >> 4) % 18, o = (e >> 4) / 18; const int j = 16 * s + 4 * t + h, ci = j / 9, tap = j - 9 * ci, ky = tap / 3, kx = tap - 3 * ky; const int rr = 2 * o + ky, iy = r0 + rr; int v; if (iy < 0 || iy >= H) v = SM_ZROW / 4 + kx; else { const long long R = ((long long)(n * CIN + ci) * H + iy) * W; v = (ci * U_HROWS + rr) * P_RW + (int)((R + colb) & 3) + kx; } offT[e] = v; } asm volatile("griddepcontrol.wait;" ::: "memory"); // previous grid complete before any global access __syncthreads(); // ---- input: warp w issues channel groups w, w+2 (one 1D bulk copy per (channel, row)) ---- const int cend = (64 * tx + 64 < W) ? 64 * tx + 64 : W; for (int gi = 0; gi < 2; gi++) { const int g = warp + 2 * gi; uint32_t mytot = 0; for (int k = lane; k < TCK * U_HROWS; k += 32) { const int i = k / U_HROWS, rr = k - i * U_HROWS, iy = r0 + rr; if (iy < 0 || iy >= H) continue; const long long R = ((long long)(n * CIN + 8 * g + i) * H + iy) * W; long long A0 = (R + colb) & ~3LL; const long long E = (R + cend + 3) & ~3LL; if (A0 < 0) A0 = 0; mytot += (uint32_t)((E - A0) * 4); } #pragma unroll for (int o = 16; o > 0; o >>= 1) mytot += __shfl_xor_sync(0xffffffffu, mytot, o); if (lane == 0) mbar_expect_tx(&tfull[g], mytot); __syncwarp(); for (int k = lane; k < TCK * U_HROWS; k += 32) { const int i = k / U_HROWS, rr = k - i * U_HROWS, iy = r0 + rr; if (iy < 0 || iy >= H) continue; const int ci = 8 * g + i; const long long R = ((long long)(n * CIN + ci) * H + iy) * W; long long A0 = (R + colb) & ~3LL; const long long E = (R + cend + 3) & ~3LL; uint32_t dofs = 0; if (A0 < 0) { A0 = 0; dofs = 16; } bulk_g2s(smem_raw + (ci * U_HROWS + rr) * (P_RW * 4) + dofs, x + A0, (uint32_t)((E - A0) * 4), &tfull[g]); } } // ---- MMA main loop ---- const int gq = lane >> 2, tq = lane & 3, nh = warp; const bool fixL = tx == 0; // global col -1 = left zero pad const int rc = W - 64 * tx + 1; // smem-relative col of global col W const bool fixR = rc <= 64; // col W inside the window -> right zero pad const float* wl = w + (size_t)(nh * 32 + gq) * (CIN * 9) + 4 * tq; const int4* ot = (const int4*)offT + tq; // + (o*18+s)*4 const float* sl = sf + 2 * gq; float acc[4][4][4]; #pragma unroll for (int i = 0; i < 4; i++) #pragma unroll for (int j = 0; j < 4; j++) #pragma unroll for (int k = 0; k < 4; k++) acc[i][j][k] = 0.f; int gdone = 0; #pragma unroll for (int s = 0; s < 18; s++) { const int need = ((16 * s + 15) / 9) >> 3; // last channel group step s touches while (gdone <= need) { mbar_wait(&tfull[gdone], 0); if (fixL || fixR) { // CTA-uniform for (int k = tid; k < TCK * U_HROWS; k += SM_THREADS) { const int i = k / U_HROWS, rr = k - i * U_HROWS, iy = r0 + rr; if (iy < 0 || iy >= H) continue; const int ci = 8 * gdone + i; const long long R = ((long long)(n * CIN + ci) * H + iy) * W; const int seg = (ci * U_HROWS + rr) * P_RW + (int)((R + colb) & 3); if (fixL) sf[seg] = 0.f; if (fixR) sf[seg + rc] = 0.f; } asm volatile("bar.sync 1, %0;" :: "n"(SM_THREADS) : "memory"); } gdone++; } uint32_t bf[4][2]; #pragma unroll for (int nt = 0; nt < 4; nt++) { const float4 v = __ldg((const float4*)(wl + nt * 8 * (CIN * 9) + 16 * s)); bf[nt][0] = pack_h2(v.x, v.y); bf[nt][1] = pack_h2(v.z, v.w); } uint32_t af[4][4]; #pragma unroll for (int o = 0; o < 2; o++) { const int4 of = ot[(o * 18 + s) * 4]; const float* p0 = sl + of.x; const float* p1 = sl + of.y; const float* p2 = sl + of.z; const float* p3 = sl + of.w; #pragma unroll for (int hm = 0; hm < 2; hm++) { // m-tile 2o+hm = px 16hm + (g, g+8) const int q = 32 * hm; af[2 * o + hm][0] = pack_h2(p0[q], p1[q]); af[2 * o + hm][1] = pack_h2(p0[q + 16], p1[q + 16]); af[2 * o + hm][2] = pack_h2(p2[q], p3[q]); af[2 * o + hm][3] = pack_h2(p2[q + 16], p3[q + 16]); } } #pragma unroll for (int mt = 0; mt < 4; mt++) #pragma unroll for (int nt = 0; nt < 4; nt++) mma_f16_16816(acc[mt][nt], af[mt][0], af[mt][1], af[mt][2], af[mt][3], bf[nt][0], bf[nt][1]); } // ---- epilogue: c0 (row g, n 2t), c1 (row g, 2t+1), c2 (row g+8, 2t), c3 (row g+8, 2t+1) ---- const size_t cs = (size_t)Ho * Wo; #pragma unroll for (int nt = 0; nt < 4; nt++) { const int co = nh * 32 + 8 * nt + 2 * tq; const float b0 = __ldg(b + co), b1 = __ldg(b + co + 1); #pragma unroll for (int mt = 0; mt < 4; mt++) { const int oy = 2 * hy + (mt >> 1); #pragma unroll for (int rh = 0; rh < 2; rh++) { const int ox = 32 * tx + 16 * (mt & 1) + gq + 8 * rh; if (oy < Ho && ox < Wo) { float* yp = y + ((size_t)(n * COUT + co) * Ho + oy) * Wo + ox; yp[0] = acc[mt][nt][2 * rh] + b0; yp[cs] = acc[mt][nt][2 * rh + 1] + b1; } } } } } // ===================================================================================== // COUT-SPLIT TF32 path: conv_s2_tf32s_kernel -- same algorithm as conv_s2_tf32_kernel, but each half tile is // computed by TWO CTAs (blockIdx.x = 2*item + part), CTA `part` produces couts 32*part..+31 only: // * B = raw fp32 weights rows 32*part..+31, TMA'd (2D map box {32 k, 32 co}, SWIZZLE_128B) straight into the // K-major SW128 tf32 B layout: 9 boxes x 4 KB = 36 KB per CTA (half the weight bytes on the startup chain). // * MMA kind::tf32 M128 x N32 x K8, accumulator 32 TMEM columns. // * A operand: 3-slot ring of 8 KB SW128 chunks (cfull / cempty per slot; cempty = tcgen05.commit after the 4 // MMAs of a chunk) instead of 9 resident chunks, so smem = 106 KB -> 2 CTAs/SM (grid = 2x the items). // The M=128 MMA over-reads rows 64..127 of a slot from the next slot / the raw staging (inside the allocation; // those accumulator rows are never stored). // * Raw input staging / converters / epilogue as in conv_s2_tf32_kernel (epilogue: 32 couts per warp). // ===================================================================================== #define S_NP 32 // couts per CTA #define S_BCH (S_NP * 128) // 4096 B per B chunk (32 co x 32 k fp32) #define S_NA 3 // A ring slots #define S_SB 0 #define S_SA (9 * S_BCH) // 36864 #define S_ST (S_SA + S_NA * F_CHB) // 61440 #define S_BAR (S_ST + F_STB) // 104960 #define S_SMEM (S_BAR + 256 + 1024) // 106240 B -> 2 CTAs/SM static_assert(S_SA % 1024 == 0 && S_ST % 1024 == 0, "SW128 alignment"); static_assert(S_SA + (S_NA - 1) * F_CHB + 2 * F_CHB <= S_BAR, "M=128 over-read stays inside the allocation"); __host__ __device__ constexpr uint32_t make_idesc_tf32_n32() { return (1u << 4) | (2u << 7) | (2u << 10) | ((32u >> 3) << 17) | ((128u >> 4) << 24); } __global__ void __launch_bounds__(F_THREADS, 2) conv_s2_tf32s_kernel(const __grid_constant__ CUtensorMap wmap, const float* __restrict__ x, const float* __restrict__ b, float* __restrict__ y, int H, int W, int Ho, int Wo, int tilesX, int Hh) { extern __shared__ uint8_t smem_raw[]; uint8_t* smem = (uint8_t*)(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023); uint8_t* sB = smem + S_SB; uint8_t* sA = smem + S_SA; uint8_t* st = smem + S_ST; uint64_t* tfull = (uint64_t*)(smem + S_BAR); // 4: raw channel groups landed uint64_t* cfull = tfull + 4; // S_NA: A slot written by the 8 converter warps uint64_t* cempty = cfull + S_NA; // S_NA: A slot consumed by the MMAs uint64_t* wbar = cempty + S_NA; // B (weights) landed uint64_t* afull = wbar + 1; // accumulator ready uint32_t* tmem_slot = (uint32_t*)(afull + 1); const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31; const int part = blockIdx.x & 1; // cout half const int item = blockIdx.x >> 1; const int tx = item % tilesX; const int rest = item / tilesX; const int hy = rest % Hh, n = rest / Hh; const int r0 = 4 * hy - 1; // first input row of the half tile if (tid == 0) { for (int i = 0; i < 4; i++) mbar_init(&tfull[i], 1); for (int i = 0; i < S_NA; i++) { mbar_init(&cfull[i], 8); mbar_init(&cempty[i], 1); } mbar_init(wbar, 1); mbar_init(afull, 1); asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); asm volatile("prefetch.tensormap [%0];" :: "l"((uint64_t)&wmap) : "memory"); } if (warp == 2) { asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], 32;" :: "r"((uint32_t)__cvta_generic_to_shared(tmem_slot)) : "memory"); asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;" ::: "memory"); } fence_before(); __syncthreads(); fence_after(); const uint32_t tmem_base = *tmem_slot; if (tid == 0) asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); // after TMEM is owned asm volatile("griddepcontrol.wait;" ::: "memory"); // previous grid complete before any global access if (warp == 2) { // ---- producer: B = 9 TMA boxes (this CTA's 32 couts of the raw weights), then 4 raw-input groups ---- if (lane == 0) { mbar_expect_tx(wbar, 9 * S_BCH); #pragma unroll for (int c = 0; c < 9; c++) tma_load2(sB + c * S_BCH, &wmap, wbar, 32 * c, S_NP * part); } const int cend = (64 * tx + 64 < W) ? 64 * tx + 64 : W; for (int g = 0; g < 4; g++) { uint32_t mytot = 0; for (int k = lane; k < TCK * U_HROWS; k += 32) { const int i = k / U_HROWS, rr = k - i * U_HROWS, iy = r0 + rr; if (iy < 0 || iy >= H) continue; const size_t R = ((size_t)(n * CIN + 8 * g + i) * H + iy) * W; long long A0 = ((long long)R + 64 * tx - 1) & ~3LL; const long long E = ((long long)R + cend + 3) & ~3LL; if (A0 < 0) A0 = 0; mytot += (uint32_t)((E - A0) * 4); } #pragma unroll for (int o = 16; o > 0; o >>= 1) mytot += __shfl_xor_sync(0xffffffffu, mytot, o); if (lane == 0) mbar_expect_tx(&tfull[g], mytot); __syncwarp(); for (int k = lane; k < TCK * U_HROWS; k += 32) { const int i = k / U_HROWS, rr = k - i * U_HROWS, iy = r0 + rr; if (iy < 0 || iy >= H) continue; const int ci = 8 * g + i; const size_t R = ((size_t)(n * CIN + ci) * H + iy) * W; long long A0 = ((long long)R + 64 * tx - 1) & ~3LL; const long long E = ((long long)R + cend + 3) & ~3LL; uint32_t dofs = 0; if (A0 < 0) { A0 = 0; dofs = 16; } bulk_g2s(st + (ci * U_HROWS + rr) * BR_RB + dofs, x + A0, (uint32_t)((E - A0) * 4), &tfull[g]); } __syncwarp(); } } else if (warp == 3) { // ---- single-thread MMA issuer: 9 chunks (ring slot c % 3) x 4 K=8 steps, N = 32 ---- if (lane == 0) { const uint32_t sA_a = (uint32_t)__cvta_generic_to_shared(sA); const uint32_t sB_a = (uint32_t)__cvta_generic_to_shared(sB); mbar_wait(wbar, 0); #pragma unroll for (int c = 0; c < 9; c++) { const int sl = c % S_NA; mbar_wait(&cfull[sl], (c / S_NA) & 1); fence_after(); #pragma unroll for (int ks = 0; ks < 4; ks++) asm volatile("{\n .reg .pred p;\n setp.ne.b32 p, %4, 0;\n" " tcgen05.mma.cta_group::1.kind::tf32 [%0], %1, %2, %3, p;\n}" :: "r"(tmem_base), "l"(make_desc_sw128(sA_a + sl * F_CHB + 32 * ks)), "l"(make_desc_sw128(sB_a + c * S_BCH + 32 * ks)), "r"(make_idesc_tf32_n32()), "r"((uint32_t)((c | ks) != 0)) : "memory"); if (c == 8) umma_commit(afull); else umma_commit(&cempty[sl]); // slot reusable once these MMAs have read it } } __syncwarp(); } else if (warp >= 4) { // ---- converters: warp w = 16 B group j of each chunk; lane = ox; both out rows ---- const int w = warp - 4, ox = lane; const uint32_t st_a = (uint32_t)__cvta_generic_to_shared(st); const uint32_t sA_a = (uint32_t)__cvta_generic_to_shared(sA); uint32_t cmask = 0; // bit kx: input col 64tx-1+2ox+kx inside [0, W) #pragma unroll for (int kx = 0; kx < 3; kx++) { const int gc = 64 * tx - 1 + 2 * ox + kx; if (gc >= 0 && gc < W) cmask |= 1u << kx; } int gdone = 0; #pragma unroll for (int c = 0; c < 9; c++) { const int need = ((32 * c + 31) / 9) >> 3; // last channel group chunk c touches while (gdone <= need) { mbar_wait(&tfull[gdone], 0); gdone++; } uint32_t v[2][4]; #pragma unroll for (int e = 0; e < 4; e++) { const int k = 32 * c + 4 * w + e; // warp-uniform const int ci = k / 9, tap = k - 9 * ci; const int ky = tap / 3, kx = tap - 3 * ky; const bool cok = (cmask >> kx) & 1u; #pragma unroll for (int orow = 0; orow < 2; orow++) { const int rr = 2 * orow + ky, iy = r0 + rr; const bool rok = iy >= 0 && iy < H; const uint32_t R = ((uint32_t)(n * CIN + ci) * (uint32_t)H + (uint32_t)iy) * (uint32_t)W; const uint32_t d = (R + 64u * tx - 1u) & 3u; // smem col of global col 64tx-1 const uint32_t a = st_a + (uint32_t)((ci * U_HROWS + rr) * BR_RB) + 4u * (d + 2 * ox + kx); v[orow][e] = to_tf32(lds32_pred(a, rok && cok)); } } const int sl = c % S_NA; if (c >= S_NA) mbar_wait(&cempty[sl], ((c / S_NA) - 1) & 1); // MMAs of chunk c-3 done with the slot #pragma unroll for (int orow = 0; orow < 2; orow++) { const int p = orow * 32 + ox; const uint32_t a = sA_a + sl * F_CHB + (p >> 3) * 1024 + (p & 7) * 128 + ((w ^ (p & 7)) << 4); sts128<0>(a, v[orow][0], v[orow][1], v[orow][2], v[orow][3]); } asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); __syncwarp(); if (lane == 0) mbar_arrive(&cfull[sl]); } } else { // ---- epilogue warps 0,1: TMEM quadrant qd = out row 2hy+qd, M row = qd*32 + ox; 32 couts ---- const int qd = warp; const float bias_r = __ldg(b + S_NP * part + lane); mbar_wait(afull, 0); fence_after(); const int oy = 2 * hy + qd, ox = 32 * tx + lane; const bool inb = oy < Ho && ox < Wo; const size_t cs = (size_t)Ho * Wo; float v[32]; tmem_ld32(tmem_base + ((uint32_t)(32 * qd) << 16), v); asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); #pragma unroll for (int co = 0; co < 32; co++) v[co] += __shfl_sync(0xffffffffu, bias_r, co); if (inb) { float* yp = y + ((size_t)n * COUT + S_NP * part) * cs + (size_t)oy * Wo + ox; #pragma unroll for (int co = 0; co < 32; co++) st_cs(yp + co * cs, v[co]); } } fence_before(); __syncthreads(); if (warp == 2) { fence_after(); asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, 32;" :: "r"(tmem_base) : "memory"); } } typedef CUresult (*EncodeTiledFn)(CUtensorMap*, CUtensorMapDataType, cuuint32_t, void*, const cuuint64_t*, const cuuint64_t*, const cuuint32_t*, const cuuint32_t*, CUtensorMapInterleave, CUtensorMapSwizzle, CUtensorMapL2promotion, CUtensorMapFloatOOBfill); // Tiny host-side cache of encoded tensor maps keyed by (ptr, d0, d1, N). Plain POD statics. struct MapEntry { const void* p; int a, b, n; int ok; CUtensorMap m; }; #define MAPC 8 static MapEntry g_xmap9[MAPC]; static int g_x9next = 0; static MapEntry g_ymap[MAPC]; static MapEntry g_ymap8[MAPC]; // TST: y store map, box {32 px, 1 row, 8 couts, 1}, no swizzle static int g_y8next = 0; static void* g_enc = nullptr; // cuTensorMapEncodeTiled (for the fast-path y-map refresh) static int g_ynext = 0; static MapEntry g_xmap5[MAPC]; // 5-row box (half tiles) static int g_x5next = 0; static MapEntry g_xmap9p[MAPC]; // 64x9 main box with L2_256B promotion (tuner option 3) static int g_x9pnext = 0; static MapEntry g_xmap9n[MAPC]; // XA5: 64x9 main box, L2 promotion NONE static int g_x9nnext = 0; static MapEntry g_xmaph[MAPC]; // 4-col halo box (9 rows) static MapEntry g_xmap8[MAPC]; // CLU: 64x8 local-row main box static int g_x8next = 0; static MapEntry g_xmap1[MAPC]; // CLU: 64x1 shared-row (multicast) box static int g_x1next = 0; static int g_xhnext = 0; static MapEntry* find_map(MapEntry* tab, const void* p, int a, int b2, int n) { for (int i = 0; i < MAPC; i++) if (tab[i].p == p && tab[i].a == a && tab[i].b == b2 && tab[i].n == n) return &tab[i]; return nullptr; } // input map on NCHW x: dims (W,H,C,N), box (68, rows, 8, 1), no swizzle, OOB zero fill static MapEntry* get_xmap(EncodeTiledFn encode, MapEntry* tab, int* next, const float* x, int N, int H, int W, int rows, int cols, CUtensorMapL2promotion promo = CU_TENSOR_MAP_L2_PROMOTION_L2_128B) { MapEntry* xe = find_map(tab, x, W, H, N); if (!xe) { xe = &tab[*next]; *next = (*next + 1) % MAPC; cuuint64_t gdim[4] = {(cuuint64_t)W, (cuuint64_t)H, (cuuint64_t)CIN, (cuuint64_t)N}; cuuint64_t gstr[3] = {(cuuint64_t)W * 4, (cuuint64_t)H * W * 4, (cuuint64_t)CIN * H * W * 4}; cuuint32_t box[4] = {(cuuint32_t)cols, (cuuint32_t)rows, TCK, 1}; cuuint32_t est[4] = {1, 1, 1, 1}; CUresult r = encode(&xe->m, CU_TENSOR_MAP_DATA_TYPE_FLOAT32, 4, (void*)x, gdim, gstr, box, est, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, promo, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); xe->ok = (r == CUDA_SUCCESS); xe->p = x; xe->a = W; xe->b = H; xe->n = N; } return xe; } // output store map on NCHW y: dims (Wo,Ho,64,N), box (32 cols, 1 row, 32 couts, 1), SWIZZLE_128B static MapEntry* get_ymap(EncodeTiledFn encode, const float* y, int N, int Ho, int Wo) { MapEntry* ye = find_map(g_ymap, y, Wo, Ho, N); if (!ye) { ye = &g_ymap[g_ynext]; g_ynext = (g_ynext + 1) % MAPC; cuuint64_t odim[4] = {(cuuint64_t)Wo, (cuuint64_t)Ho, (cuuint64_t)COUT, (cuuint64_t)N}; cuuint64_t ostr[3] = {(cuuint64_t)Wo * 4, (cuuint64_t)Ho * Wo * 4, (cuuint64_t)COUT * Ho * Wo * 4}; cuuint32_t obox[4] = {TW, 1, 32, 1}; cuuint32_t est[4] = {1, 1, 1, 1}; CUresult r = encode(&ye->m, CU_TENSOR_MAP_DATA_TYPE_FLOAT32, 4, (void*)y, odim, ostr, obox, est, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); ye->ok = (r == CUDA_SUCCESS); ye->p = y; ye->a = Wo; ye->b = Ho; ye->n = N; } return ye; } // TST: y store map for the TMA-store epilogue (needs 16 B aligned y and Wo % 4 == 0); cached keyed by y static MapEntry* get_ymap8(EncodeTiledFn encode, const float* y, int N, int Ho, int Wo) { MapEntry* ye = find_map(g_ymap8, y, Wo, Ho, N); if (!ye) { ye = &g_ymap8[g_y8next]; g_y8next = (g_y8next + 1) % MAPC; cuuint64_t odim[4] = {(cuuint64_t)Wo, (cuuint64_t)Ho, (cuuint64_t)COUT, (cuuint64_t)N}; cuuint64_t ostr[3] = {(cuuint64_t)Wo * 4, (cuuint64_t)Ho * Wo * 4, (cuuint64_t)COUT * Ho * Wo * 4}; cuuint32_t obox[4] = {TW, 1, 8, 1}; cuuint32_t est[4] = {1, 1, 1, 1}; CUresult r = (encode && (Wo % 4) == 0 && (((uintptr_t)y) & 15) == 0) ? encode(&ye->m, CU_TENSOR_MAP_DATA_TYPE_FLOAT32, 4, (void*)y, odim, ostr, obox, est, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE) : CUDA_ERROR_INVALID_VALUE; ye->ok = (r == CUDA_SUCCESS); ye->p = y; ye->a = Wo; ye->b = Ho; ye->n = N; } return ye; } // Launch the conv kernel with Programmatic Dependent Launch after wprep_kernel. // 16 phase maps for odd/unaligned W (see P_* defines). Cached keyed by (x, W, H, N); nullptr if unusable. struct PMapEntry { const void* p; int a, b, n, pr; int ok; PhaseMaps<16> pm; }; static PMapEntry g_pmaps[4]; static int g_pnext = 0; static const PhaseMaps<16>* get_pmaps(EncodeTiledFn encode, const float* x, int N, int H, int W, CUtensorMapL2promotion promo = CU_TENSOR_MAP_L2_PROMOTION_L2_128B) { if (!encode || H < 4 || (((uintptr_t)x) & 15) != 0) return nullptr; for (int i = 0; i < 4; i++) if (g_pmaps[i].p == x && g_pmaps[i].a == W && g_pmaps[i].b == H && g_pmaps[i].n == N && g_pmaps[i].pr == (int)promo) return g_pmaps[i].ok ? &g_pmaps[i].pm : nullptr; PMapEntry* e = &g_pmaps[g_pnext]; g_pnext = (g_pnext + 1) % 4; e->p = x; e->a = W; e->b = H; e->n = N; e->pr = (int)promo; e->ok = 1; const size_t hw = (size_t)H * W; for (int p = 0; p < 4; p++) for (int j = 0; j < 4; j++) { const size_t off = j * hw + (size_t)p * W; // element offset of (c=j, row=p, col 0) const int sft = (int)(off & 3); // dropped elements -> column shift cuuint64_t gdim[4] = {(cuuint64_t)(W + sft), (cuuint64_t)((H - p + 3) / 4), 8, (cuuint64_t)N}; cuuint64_t gstr[3] = {(cuuint64_t)W * 16, (cuuint64_t)hw * 16, (cuuint64_t)hw * 128}; cuuint32_t box[4] = {P_RW, (cuuint32_t)(p == 3 ? 3 : 2), TCK, 1}; cuuint32_t est[4] = {1, 1, 1, 1}; CUresult r = encode(&e->pm.m[p * 4 + j], CU_TENSOR_MAP_DATA_TYPE_FLOAT32, 4, (void*)(x + off - sft), gdim, gstr, box, est, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, promo, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); if (r != CUDA_SUCCESS) e->ok = 0; e->pm.sh[p * 4 + j] = sft; } return e->ok ? &e->pm : nullptr; } #ifdef CONV_PROBE #include <stdexcept> #include <string> static int g_probe_calls = 0; static void probe_report(int grid, int N, int H, int W) { if (++g_probe_calls != 2) return; cudaDeviceSynchronize(); static long long hb[1024 * 64]; cudaMemcpyFromSymbol(hb, g_probe, sizeof(long long) * 64 * grid); double acc[64] = {0}; double mx[64] = {0}; for (int b = 0; b < grid; b++) for (int i = 1; i < 60; i++) { double d = (double)(hb[b * 64 + i] - hb[b * 64]); acc[i] += d; if (d > mx[i]) mx[i] = d; } char buf[2048]; int o = snprintf(buf, sizeof buf, "PROBE N=%d H=%d W=%d grid=%d cyc mean/max:", N, H, W, grid); for (int i = 1; i < 60; i++) if (i < 22 || i > 31) o += snprintf(buf + o, sizeof buf - o, " %d:%.0f", i, acc[i] / grid); throw std::runtime_error(buf); } #define PROBE_REPORT(g) probe_report(g, N, H, W) #else #define PROBE_REPORT(g) #endif #ifdef XPROBE static int g_xv = 0; #ifdef XPGRID // grid-shape A/B (1x373): v1 balanced odd grid, v2 3-tile grid, v3 identical control #define XV1 (XV_DEF | (1LL << 22)) #define XV2 (XV_DEF | (1LL << 62)) #define XV3 XV_DEF #endif #ifdef XPPFX // A/B: v1 = seed (no pre-wait prefetch), v2 = identical control, v3 = + halo prefetch #define XV1 XV_DEF #define XV2 (XV_DEF | PFX_BIT) #define XV3 (XV_DEF | PFX_BIT | PFH_BIT) #endif #ifdef XPEFL // A/B: v1 = seed (no startup ring fill), v2 = identical control #define XV1 (XV_DEF & ~EFL_BIT) #define XV2 (XV_DEF | EF4_BIT) #define XV3 XV_DEF #endif #ifdef XPPOL // A/B: v1 = per-issue createpolicy (seed), v2 = identical control #define XV1 (XV_DEF & ~PPOL_BIT) #define XV2 XV_DEF #endif #ifdef XPNRW // A/B: v1 = without the narrow-column skip, v2 = identical control #define XV1 (XV_DEF & ~NRW_BIT) #define XV2 XV_DEF #endif #ifndef XV1 #define XV1 (1 << 20) #endif #ifndef XV2 #define XV2 1 #endif #ifndef XV3 #define XV3 2 #endif #ifndef XV4 #define XV4 4 #endif #ifndef XV5 #define XV5 8 #endif #ifndef XV6 #define XV6 16 #endif #ifndef XV7 #define XV7 32 #endif #ifndef XV8 #define XV8 64 #endif #ifndef XV9 #define XV9 128 #endif #ifndef XNV #define XNV 10 #endif #ifndef XPR #define XPR 41 #endif #endif #ifdef XPROBE static int g_tchoice = 0; static long long xv_host_bits() { const long long b[10] = {0, XV1, XV2, XV3, XV4, XV5, XV6, XV7, XV8, XV9}; return b[g_xv < 10 ? g_xv : 9] & ~(PPOL_BIT | CW_BIT | PFX_BIT | PFH_BIT); } // kernel-only bits overlap the host option field #endif #ifdef XSTRESS static int g_sv = 0; #endif // 2D SW128 tensor map on the raw fp32 weights [64][288] (tf32 path), cached by pointer (POD statics) struct WMapEntry { const void* p; int ok; CUtensorMap m; }; static WMapEntry g_wmaps[4]; static int g_wnext = 0; static WMapEntry g_wmaps_s[4]; // box {32, 32} (cout-split tf32 path) static int g_wnext_s = 0; static const CUtensorMap* get_wmap(EncodeTiledFn encode, const float* w, bool split = false) { if (!encode || (((uintptr_t)w) & 15) != 0) return nullptr; WMapEntry* tab = split ? g_wmaps_s : g_wmaps; int& nx = split ? g_wnext_s : g_wnext; for (int i = 0; i < 4; i++) if (tab[i].p == w) return tab[i].ok ? &tab[i].m : nullptr; WMapEntry* e = &tab[nx]; nx = (nx + 1) % 4; e->p = w; cuuint64_t gdim[2] = {(cuuint64_t)(CIN * 9), (cuuint64_t)COUT}; cuuint64_t gstr[1] = {(cuuint64_t)(CIN * 9 * 4)}; cuuint32_t box[2] = {32, (cuuint32_t)(split ? S_NP : 64)}; cuuint32_t est[2] = {1, 1}; CUresult r = encode(&e->m, CU_TENSOR_MAP_DATA_TYPE_FLOAT32, 2, (void*)w, gdim, gstr, box, est, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, CU_TENSOR_MAP_L2_PROMOTION_L2_128B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); e->ok = (r == CUDA_SUCCESS); return e->ok ? &e->m : nullptr; } static PhaseMaps<1> g_pm_dummy; static PhaseMaps<1> g_pm_cw; // CW: m[0] = 8-row halo map (rows 8ty..8ty+7) static MapEntry g_xmaph8[MAPC]; // CW: 4-col halo box, 8 rows static int g_xh8next = 0; static constexpr size_t smem_ph6_c = (size_t)U_NC_TMA * U_CBYTES + U_WBYTES + P_TRING_N(6) + 2048 + COUT * CIN * 9 + 1024; // POD placeholder for the non-phase instantiations // HOST FAST PATH: the steady-state call (same x/w/b pointers, shape, stream as the previous call; tuned // TMA/phase path) skips the whole host decision chain (tensor-map cache lookups, tune-cache scan, grid/tail // split math, template dispatch) and replays the recorded launch with only y replaced, via cudaLaunchKernelExC // on a pre-built config (PDL attribute) and a pre-built kernel-argument array. Same kernel, same arguments // (all of them are functions of the key) -> bit-identical output. Plain POD static (no CUDA object destructs). struct FastLaunch { bool valid; const void *kx, *kw, *kb; int kN, kH, kW; cudaStream_t ks; // key const void* func; unsigned grid; size_t smem; CUtensorMap m0, m1, m2; alignas(64) unsigned char pm[sizeof(PhaseMaps<16>)]; const float* xp; const uint16_t* wimg; const float* bp; float* y; int iv[10]; const float* wraw; int wf; int dyn; // DYN: wfused bits 16-25 = pool-counter slot, advanced on every replay int ytm; // TST: m1 = y store map (must be re-pointed at the new y on replay) void* args[20]; cudaLaunchAttribute attr[2]; // PDL (+ cluster dims for the CLU option) cudaLaunchConfig_t cfg; }; #define NFL 16 static FastLaunch g_flc[NFL] = {}; static unsigned g_flstamp[NFL] = {}; static unsigned g_flclk = 0; static int g_flmru = 0; static FastLaunch* g_flp = &g_flc[0]; #define g_fl (*g_flp) static bool g_rec_on = false; static int g_dynslot = 0; // DYN: next pool-counter slot (one per call) // record the next launch_umma into g_fl // TF32 TRANSFORM-FREE OPTION for small shapes: conv_s2_tf32_kernel (raw fp32 weights TMA'd straight into the // K-major SW128 B operand, kind::tf32 MMA, no weight transform), one half tile per CTA. Same fast-path record. static void launch_tf32(cudaStream_t s, const CUtensorMap& wm, const float* x, const float* b, float* y, int N, int H, int W, int Ho, int Wo, int tilesX, bool split = false) { const int Hh = (Ho + 1) / 2; const int nit = N * Hh * tilesX * (split ? 2 : 1); // split = 2 CTAs (cout halves) per half tile const size_t sm = split ? (size_t)S_SMEM : (size_t)F_SMEM; auto kfn = split ? conv_s2_tf32s_kernel : conv_s2_tf32_kernel; cudaLaunchConfig_t cfg = {}; cfg.gridDim = dim3((unsigned)nit); cfg.blockDim = dim3(F_THREADS); cfg.dynamicSmemBytes = sm; cfg.stream = s; cudaLaunchAttribute attr[1]; attr[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; attr[0].val.programmaticStreamSerializationAllowed = 1; cfg.attrs = attr; cfg.numAttrs = 1; if (g_rec_on) { g_rec_on = false; FastLaunch& f = g_fl; f.func = (const void*)kfn; f.grid = (unsigned)nit; f.smem = sm; f.m0 = wm; f.xp = x; f.bp = b; f.y = y; const int iv[6] = {H, W, Ho, Wo, tilesX, Hh}; for (int i = 0; i < 6; i++) f.iv[i] = iv[i]; f.args[0] = &f.m0; f.args[1] = &f.xp; f.args[2] = &f.bp; f.args[3] = &f.y; for (int i = 0; i < 6; i++) f.args[4 + i] = &f.iv[i]; f.attr[0] = attr[0]; f.cfg = cfg; f.cfg.attrs = f.attr; f.cfg.numAttrs = 1; f.ytm = 0; f.dyn = 0; f.valid = true; } cudaLaunchKernelEx(&cfg, kfn, wm, x, b, y, H, W, Ho, Wo, tilesX, Hh); } // small-smem high-occupancy mma.sync option (odd-W shapes, voted per shape); same fast-path record static void launch_small(cudaStream_t s, const float* x, const float* w, const float* b, float* y, int N, int H, int W, int Ho, int Wo, int tilesX) { const int Hh = (Ho + 1) / 2; const int nit = N * Hh * tilesX; cudaLaunchConfig_t cfg = {}; cfg.gridDim = dim3((unsigned)nit); cfg.blockDim = dim3(SM_THREADS); cfg.dynamicSmemBytes = SM_SMEM; cfg.stream = s; cudaLaunchAttribute attr[1]; attr[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; attr[0].val.programmaticStreamSerializationAllowed = 1; cfg.attrs = attr; cfg.numAttrs = 1; if (g_rec_on) { g_rec_on = false; FastLaunch& f = g_fl; f.func = (const void*)conv_s2_small_kernel; f.grid = (unsigned)nit; f.smem = SM_SMEM; f.xp = x; f.wraw = w; f.bp = b; f.y = y; const int iv[6] = {H, W, Ho, Wo, tilesX, Hh}; for (int i = 0; i < 6; i++) f.iv[i] = iv[i]; f.args[0] = &f.xp; f.args[1] = &f.wraw; f.args[2] = &f.bp; f.args[3] = &f.y; for (int i = 0; i < 6; i++) f.args[4 + i] = &f.iv[i]; f.attr[0] = attr[0]; f.cfg = cfg; f.cfg.attrs = f.attr; f.cfg.numAttrs = 1; f.ytm = 0; f.dyn = 0; f.valid = true; } cudaLaunchKernelEx(&cfg, conv_s2_small_kernel, x, w, b, y, H, W, Ho, Wo, tilesX, Hh); } template <bool G, int TWC, int NPM = 1, int PNT = 6, int ANC = 2, long long XVK = XV_DEF> static void launch_umma(int grid, size_t smem, cudaStream_t s, const CUtensorMap& m, const CUtensorMap& om, const CUtensorMap& hm, const PhaseMaps<NPM>& pm, const float* x, const uint16_t* wimg, const float* b, float* y, int H, int W, int Ho, int Wo, int tilesX, int tilesY, int nt, int use_tstore, int nfull, int nhalf, const float* wraw = nullptr, int wfused = 0) { cudaLaunchConfig_t cfg = {}; cfg.gridDim = dim3(grid, (XVK & CSP_BIT) ? 2 : 1); cfg.blockDim = dim3(U_THREADS); // CSP: y = cout half cfg.dynamicSmemBytes = smem; cfg.stream = s; constexpr bool CLUh = (XVK & CLU_BIT) != 0; cudaLaunchAttribute attr[2]; attr[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; attr[0].val.programmaticStreamSerializationAllowed = 1; attr[1].id = cudaLaunchAttributeClusterDimension; // CLU: 2-CTA clusters attr[1].val.clusterDim.x = 2; attr[1].val.clusterDim.y = 1; attr[1].val.clusterDim.z = 1; cfg.attrs = attr; cfg.numAttrs = CLUh ? 2 : 1; auto kern = conv_s2_umma_kernel<G, TWC, NPM, PNT, ANC, XVK>; // per-launch copy of the phase-map block with the stage-0 coordinate table (same decode as the kernel's // fallback path, see PhaseMaps::s0) static PhaseMaps<NPM> pmc; // POD static (no CUDA object), rebuilt every slow-path launch memcpy(&pmc, &pm, sizeof(PhaseMaps<NPM>)); { constexpr bool PHh = (NPM == 16); const int tp = tilesX * tilesY; bool hfh = !G && NPM == 1 && (XV_DEF & HF_BIT) != 0; // HF (must match the launched kernel's XV) #ifdef XPROBE if (g_xv > 0) hfh = !G && NPM == 1 && (xv_host_bits() & HF_BIT) != 0; #endif if (CLUh) hfh = false; constexpr bool CWh = (XVK & CW_BIT) != 0; for (int bid = 0; bid < grid && bid < S0MAX; bid++) { if (CWh) { // item 0 of CTA bid = column-major tile L = bid*K (never a successor -> full 9-row box) const int K = (wfused >> 16) & 0xFFF, L = bid * K; const int ty0 = L % tilesY, qq = L / tilesY, tx0 = qq % tilesX, n0 = qq / tilesX; pmc.s0[bid] = make_int4(n0, 64 * tx0, 8 * ty0 - 1, (L < nt ? 1 : 0) | 2 | ((wfused & 4) ? 4 : 0)); continue; } if (CLUh) { // pair p = bid/2 (nfull = #pairs), tile ty = 2*typ + rank const int p = bid >> 1, pp = tilesX * (tilesY >> 1); const int n0 = p / pp, rem = p - n0 * pp, typ = rem / tilesX, tx0 = rem - typ * tilesX; const int ty0 = 2 * typ + (bid & 1); pmc.s0[bid] = make_int4(n0, 64 * tx0, 8 * ty0 - 1, (p < nfull ? 1 : 0) | 2 | ((wfused & 4) ? 4 : 0)); continue; } const bool f0 = bid < nfull && !(hfh && bid < nhalf); const int any = (f0 || bid < nhalf) ? 1 : 0; const int hs0 = f0 ? -1 : (bid & 1); const int tile0 = f0 ? bid : nfull + (bid >> 1); const int n0 = tile0 / tp, rem = tile0 - n0 * tp; const int ty0 = rem / tilesX, tx0 = rem - ty0 * tilesX; const int rc = PHh ? 2 * ty0 + (hs0 < 0 ? 0 : hs0) : 8 * ty0 - 1 + (hs0 < 0 ? 0 : 4 * hs0); pmc.s0[bid] = make_int4(n0, 64 * tx0, rc, any | (f0 ? 2 : 0) | ((wfused & 4) ? 4 : 0)); } } #ifdef XSTRESS if constexpr (!G) { // stress build: g_sv == 1 -> per-thread converter fence version (XF off) if (g_sv == 1) { kern = conv_s2_umma_kernel<G, TWC, NPM, PNT, ANC, (XV_DEF & ~XF_BIT)>; static bool set = false; if (!set) { set = true; cudaFuncSetAttribute(kern, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem); } } } #endif #ifdef XPROBE #ifdef XPODD if constexpr (!G && NPM == 16) { // phase path ring 6 AND 7 get the variants #else if constexpr (!G && ((NPM == 1 && (ANC == 2 || ANC == 3 || ANC == 4)) || (NPM == 16 && ANC == 2))) { // B8: ph6 too; C70: NC4 #endif static bool attr_set[16] = {}; if (g_xv > 0) { switch (g_xv) { case 1: kern = conv_s2_umma_kernel<G, TWC, NPM, PNT, ANC, XV1>; break; case 2: kern = conv_s2_umma_kernel<G, TWC, NPM, PNT, ANC, XV2>; break; case 3: kern = conv_s2_umma_kernel<G, TWC, NPM, PNT, ANC, XV3>; break; case 4: kern = conv_s2_umma_kernel<G, TWC, NPM, PNT, ANC, XV4>; break; case 5: kern = conv_s2_umma_kernel<G, TWC, NPM, PNT, ANC, XV5>; break; case 6: kern = conv_s2_umma_kernel<G, TWC, NPM, PNT, ANC, XV6>; break; case 7: kern = conv_s2_umma_kernel<G, TWC, NPM, PNT, ANC, XV7>; break; case 8: kern = conv_s2_umma_kernel<G, TWC, NPM, PNT, ANC, XV8>; break; default: kern = conv_s2_umma_kernel<G, TWC, NPM, PNT, ANC, XV9>; break; } if (!attr_set[g_xv]) { attr_set[g_xv] = true; cudaFuncSetAttribute(kern, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem); } } } #endif #ifdef XPROBE cudaLaunchAttribute attr2[2]; cudaLaunchAttribute attr3[2]; if (xv_host_bits() & C70_MSD) { // C70 MSD: remote memory-sync domain attr3[0] = attr[0]; attr3[1].id = cudaLaunchAttributeMemSyncDomain; attr3[1].val.memSyncDomain = cudaLaunchMemSyncDomainRemote; cfg.attrs = attr3; cfg.numAttrs = 2; } if (xv_host_bits() & (1 << 27)) cfg.numAttrs = 0; // XA2: no PDL if (xv_host_bits() & (1 << 28)) { // XA3: + greatest launch priority int lo = 0, hi = 0; cudaDeviceGetStreamPriorityRange(&lo, &hi); attr2[0] = attr[0]; attr2[1].id = cudaLaunchAttributePriority; attr2[1].val.priority = hi; cfg.attrs = attr2; cfg.numAttrs = 2; } #endif if (g_rec_on) { // capture this launch for the host fast path g_rec_on = false; FastLaunch& f = g_fl; f.func = (const void*)kern; f.grid = (unsigned)grid; f.smem = smem; f.m0 = m; f.m1 = om; f.m2 = hm; memcpy(f.pm, &pmc, sizeof(PhaseMaps<NPM>)); f.xp = x; f.wimg = wimg; f.bp = b; f.y = y; const int iv[10] = {H, W, Ho, Wo, tilesX, tilesY, nt, use_tstore, nfull, nhalf}; for (int i = 0; i < 10; i++) f.iv[i] = iv[i]; f.wraw = wraw; f.wf = wfused; f.args[0] = &f.m0; f.args[1] = &f.m1; f.args[2] = &f.m2; f.args[3] = f.pm; f.args[4] = &f.xp; f.args[5] = &f.wimg; f.args[6] = &f.bp; f.args[7] = &f.y; for (int i = 0; i < 10; i++) f.args[8 + i] = &f.iv[i]; f.args[18] = &f.wraw; f.args[19] = &f.wf; f.attr[0] = attr[0]; f.attr[1] = attr[1]; f.cfg = cfg; f.cfg.attrs = f.attr; f.cfg.numAttrs = CLUh ? 2 : 1; f.ytm = (XVK & TST_BIT) ? 1 : 0; f.dyn = (XVK & DYN_BIT) ? 1 : 0; f.valid = true; } cudaLaunchKernelEx(&cfg, kern, m, om, hm, pmc, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY, nt, use_tstore, nfull, nhalf, wraw, wfused); } // per-shape autotune cache for the non-TMA shapes (plain POD statics) struct TuneEntry { int n, h, w, c; }; #define TUNEC 16 struct KnownTune { int n, h, w, c, b = 0, g = 0; }; // g = 1 -> EXD exact-divisor grid (see run_tma) // b = epilogue burst-size override (0 = class default) static const KnownTune g_known_tma[] = {{2,512,512,5,5,5},{1,1024,1024,0,8,8},{1,512,512,5,2,4},{8,256,256,5,5,20},{4,512,512,4,8,5}, {2,1024,1024,4,0,7},{16,384,384,4,0,9},{4,256,256,5,2,21},{16,256,256,4,8,20},{64,128,128,4,8,23},{1,384,384,5,2,20},{2,256,256,5,2,19}}; // 1x384 g 11 = PF0 pre-wait octet-0 stage-0 L2 prefetch // 2-tile shapes -> pair-unrolled split NC2 (option 5) + B=2 burst static const KnownTune g_known_odd[] = {{2,449,449,2},{1,373,373,8},{2,211,211,5},{1,131,131,9}}; // 1x131 -> option 9 (CSP cout split + per-piece half weights, PXS ring 6) template <int NK> static int known_choice(const KnownTune (&t)[NK], int N, int H, int W) { for (int i = 0; i < NK; i++) if (t[i].n == N && t[i].h == H && t[i].w == W) return t[i].c; return -1; } template <int NK> static int known_burst(const KnownTune (&t)[NK], int N, int H, int W) { for (int i = 0; i < NK; i++) if (t[i].n == N && t[i].h == H && t[i].w == W) return t[i].b; return 0; } static int g_force = -1; static int g_bov = 0; // burst-size override for the next launches (wfused bits 8-11) static int g_gov = 0; // EXD: grid override for the next aligned launches (1 = exact-divisor grid) template <int NK> static int known_grid(const KnownTune (&t)[NK], int N, int H, int W) { for (int i = 0; i < NK; i++) if (t[i].n == N && t[i].h == H && t[i].w == W) return t[i].g; return 0; } float g_last_tune[16] = {0}; // last aligned tune scores (us), for probes int g_last_best[4] = {0}; int g_force_tma = -1; // probe hook: force an aligned option (-1 = tuned) void conv_force_mode(int m) { g_force = m; } void launch_conv(const float* x, const float* w, const float* b, float* y, int N, int H, int W, int Ho, int Wo, cudaStream_t s) { #if !defined(XPROBE) && !defined(CONV_PROBE) if (g_force < 0 && g_force_tma < 0) { int hit = -1; { // MRU REPLAY SHORTCUT: an MRU hit replays immediately (no stamp/clock update: the MRU // slot always holds the max stamp, so the LRU victim choice is unchanged; the key includes the stream). FastLaunch& f = g_flc[g_flmru]; // most recent first if (f.valid && f.kx == x && f.kw == w && f.kb == b && f.kN == N && f.kH == H && f.kW == W && f.ks == s) { bool okm = true; if (f.ytm) { MapEntry* ye = get_ymap8((EncodeTiledFn)g_enc, y, N, Ho, Wo); okm = ye->ok; if (okm) f.m1 = ye->m; } if (okm) { f.y = y; if (f.dyn) { f.wf = (f.wf & ~((DYN_SLOTS - 1) << 16)) | (g_dynslot << 16); g_dynslot = (g_dynslot + 1) & (DYN_SLOTS - 1); } cudaLaunchKernelExC(&f.cfg, f.func, f.args); return; } f.valid = false; // y unusable for the TMA store -> slow path re-decides } } if (hit < 0) for (int i = 0; i < NFL; i++) { const FastLaunch& f = g_flc[i]; if (f.valid && f.kx == x && f.kw == w && f.kb == b && f.kN == N && f.kH == H && f.kW == W && f.ks == s) { hit = i; break; } } if (hit >= 0 && g_flc[hit].ytm) { MapEntry* ye = get_ymap8((EncodeTiledFn)g_enc, y, N, Ho, Wo); if (ye->ok) g_flc[hit].m1 = ye->m; else { g_flc[hit].valid = false; hit = -1; } } if (hit >= 0) { FastLaunch& f = g_flc[hit]; g_flmru = hit; g_flstamp[hit] = ++g_flclk; f.y = y; if (f.dyn) { f.wf = (f.wf & ~((DYN_SLOTS - 1) << 16)) | (g_dynslot << 16); g_dynslot = (g_dynslot + 1) & (DYN_SLOTS - 1); } f.cfg.stream = s; cudaLaunchKernelExC(&f.cfg, f.func, f.args); return; } // miss: record into the least recently used slot int v = 0; for (int i = 0; i < NFL; i++) { if (!g_flc[i].valid) { v = i; break; } if (g_flstamp[i] < g_flstamp[v]) v = i; } g_flp = &g_flc[v]; g_flmru = v; g_flstamp[v] = ++g_flclk; } #endif static int nsm = 0; static EncodeTiledFn encode = nullptr; static CUtensorMap dummy_map; // POD, placeholder for unused map params static uint16_t* wimg = nullptr; // raw device workspace (36864 B), intentionally never freed // TMA path: NC*27648 + 36864 + TRING + 512 (barriers) + 1024 (align slack); no output staging const size_t smem_umma = (size_t)U_NC_TMA * U_CBYTES + U_WBYTES + U_TRING + 2048 + 1024; static_assert(SmemLayout<false, 32, 1, 6, 2>::TOT == (size_t)U_NC_TMA * U_CBYTES + U_WBYTES + U_TRING + 2048 + 1024, "host smem size != layout table"); const size_t smem_umma3 = (size_t)3 * U_CBYTES + U_WBYTES + U_TRING_N(U_NT3) + 2048 + 1024; // 219648 static_assert(SmemLayout<false, 32, 1, 6, 3>::TOT == (size_t)3 * U_CBYTES + U_WBYTES + U_TRING_N(U_NT3) + 2048 + 1024, "host smem size != layout table"); const size_t smem_umma4 = (size_t)4 * U_CBYTES + U_WBYTES + U_TRING_N(U_NT4) + 2048 + 1024; // 227840 static_assert(SmemLayout<false, 32, 1, 6, 4>::TOT == (size_t)4 * U_CBYTES + U_WBYTES + U_TRING_N(U_NT4) + 2048 + 1024, "host smem size != layout table"); const size_t smem_ph6 = (size_t)U_NC_TMA * U_CBYTES + U_WBYTES + P_TRING_N(6) + 2048 + COUT * CIN * 9 + 1024; // + raw piece 3 static_assert(SmemLayout<false, 32, 16, 6, 2>::TOT == smem_ph6_c, "host smem size != layout table"); const size_t smem_ph5x = (size_t)3 * U_CBYTES + U_WBYTES + P_TRING_N(5) + 2048 + 1024; // B8 PXS static_assert(SmemLayout<false, 32, 16, 5, 3>::TOT == (size_t)3 * U_CBYTES + U_WBYTES + P_TRING_N(5) + 2048 + 1024, "host smem size != layout table"); const size_t smem_ph7 = (size_t)U_NC_TMA * U_CBYTES + U_WBYTES + P_TRING_N(7) + 2048 + 1024; // 230912 static_assert(SmemLayout<false, 32, 16, 7, 2>::TOT == (size_t)U_NC_TMA * U_CBYTES + U_WBYTES + P_TRING_N(7) + 2048 + 1024, "host smem size != layout table"); const size_t smem_umma_g = (size_t)U_NC_G * U_CBYTES + U_WBYTES + U_NEPI * U_OBYTES + 2048 + 1024; static_assert(SmemLayout<true, 32, 1, 6, 2>::TOT == (size_t)U_NC_G * U_CBYTES + U_WBYTES + U_NEPI * U_OBYTES + 2048 + 1024, "host smem size != layout table"); if (!nsm) { cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 1, 6>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_umma); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 1, 6, 2, (XV_DEF | PFX_BIT)>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_umma); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 1, 6, 2, (XV_DEF | PFX_BIT | PF0_BIT)>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_umma); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 1, 6, 2, (XV_DEF | PFX_BIT | PF0_BIT | PFH_BIT)>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_umma); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 1, 6, 2, (XV_DEF | YCS_BIT)>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_umma); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 1, 6, 2, (XV_DEF | YCS_BIT | MS0_BIT)>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_umma); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 1, 6, 2, (XV_DEF | PFX_BIT | PF0_BIT | PFH_BIT | WPN_BIT | MS0_BIT)>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_umma); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 1, 6, 2, (XV_DEF | WPN_BIT | MS0_BIT)>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_umma); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 1, 6, 2, (XV_DEF | PFX_BIT | YCS_BIT)>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_umma); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 1, 6, 2, (XV_DEF | CLU_BIT)>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_umma); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 1, 6, 2, (XV_DEF | CW_BIT)>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_umma); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 1, 6, 3>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_umma3); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 1, 6, 4>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_umma4); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 16, 6>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_ph6); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 16, 7, 3>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_ph7); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 16, 6, 3>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_ph6); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 16, 6, 3, (XV_DEF | CSP_BIT | MS0_BIT)>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_ph6); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 16, 7, 2, (XV_DEF | MS0_BIT)>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_ph7); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 16, 6, 3, (XV_DEF | MS0_BIT)>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_ph6); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 1, 6, 2, (XV_DEF | MS0_BIT)>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_umma); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 16, 5, 3>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_ph5x); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 16, 7>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_ph7); cudaFuncSetAttribute(conv_s2_umma_kernel<true, 32, 1, 6>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_umma_g); static_assert(SmemLayout<true, 16, 1, 6, 2>::TOT == SmemLayout<true, 32, 1, 6, 2>::TOT, "gather sizes"); static_assert(SmemLayout<false, 32, 16, 6, 3>::TOT == SmemLayout<false, 32, 16, 6, 2>::TOT && SmemLayout<false, 32, 16, 7, 3>::TOT == SmemLayout<false, 32, 16, 7, 2>::TOT, "PXS sizes"); cudaFuncSetAttribute(conv_s2_umma_kernel<true, 16, 1, 6>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_umma_g); cudaFuncSetAttribute(conv_s2_tf32_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)F_SMEM); cudaFuncSetAttribute(conv_s2_small_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)SM_SMEM); cudaFuncSetAttribute(conv_s2_small_kernel, cudaFuncAttributePreferredSharedMemoryCarveout, 86); // 196 KB smem: 4 CTAs/SM, rest L1 (weights) cudaFuncSetAttribute(conv_s2_tf32s_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)S_SMEM); cudaFuncSetAttribute(conv_s2_tf32s_kernel, cudaFuncAttributePreferredSharedMemoryCarveout, 100); int dev; cudaGetDevice(&dev); cudaDeviceGetAttribute(&nsm, cudaDevAttrMultiProcessorCount, dev); cudaMalloc((void**)&wimg, U_WBYTES); void* fn = nullptr; cudaDriverEntryPointQueryResult q; if (cudaGetDriverEntryPointByVersion("cuTensorMapEncodeTiled", &fn, 12000, cudaEnableDefault, &q) == cudaSuccess && q == cudaDriverEntryPointSuccess) encode = (EncodeTiledFn)fn; g_enc = (void*)encode; cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 1, 6, 2, (XV_DEF | PFX_BIT | TST_BIT)>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)SmemLayout<false, 32, 1, 6, 2, TST_SB>::TOT); cudaFuncSetAttribute(conv_s2_umma_kernel<false, 32, 1, 6, 2, (XV_DEF | PFX_BIT | TST_BIT | DYN_BIT)>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)SmemLayout<false, 32, 1, 6, 2, TST_SB>::TOT); } #ifdef XOCC { char buf[256]; int o = 0; for (int cs = 1; cs <= 8; cs *= 2) { cudaLaunchConfig_t cfg = {}; cfg.gridDim = dim3(148); cfg.blockDim = dim3(U_THREADS); cfg.dynamicSmemBytes = smem_umma; cfg.stream = s; cudaLaunchAttribute at[1]; at[0].id = cudaLaunchAttributeClusterDimension; at[0].val.clusterDim.x = cs; at[0].val.clusterDim.y = 1; at[0].val.clusterDim.z = 1; cfg.attrs = at; cfg.numAttrs = 1; int nc = -1; cudaError_t e = cudaOccupancyMaxActiveClusters(&nc, conv_s2_umma_kernel<false, 32, 1, 6>, &cfg); o += snprintf(buf + o, sizeof buf - o, " cs%d:%d(%d)", cs, nc, (int)e); } throw std::runtime_error(std::string("XOCC") + buf); } #endif const int tilesX = (Wo + TW - 1) / TW, tilesY4 = (Ho + 3) / 4; const int nt4 = tilesX * tilesY4 * N; if (nt4 <= 0) return; const int g4 = nt4 < nsm ? nt4 : nsm; // per-call weight pre-transform (fp32 -> swizzled fp16 smem image) -- gather fallback only auto launch_wprep = [&]() { // PDL launch: pre-scheduled behind the previous call's conv (see wprep_kernel) cudaLaunchConfig_t cfg = {}; cfg.gridDim = dim3((COUT * CIN * 9 + 255) / 256); cfg.blockDim = dim3(256); cfg.dynamicSmemBytes = 0; cfg.stream = s; cudaLaunchAttribute attr[1]; attr[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; attr[0].val.programmaticStreamSerializationAllowed = 1; cfg.attrs = attr; cfg.numAttrs = 1; cudaLaunchKernelEx(&cfg, wprep_kernel, w, wimg); }; const int wf_raw = (((uintptr_t)w) & 15) == 0 ? 1 : 0; // raw fp32 weight bulk copy needs a 16B-aligned w // tf32 option: needs 16B-aligned x (bulk-row copies) and w (2D weight tensor map); small outputs only bool use_tma = g_force < 0 && encode != nullptr && (W % 4) == 0 && (((uintptr_t)x) & 15) == 0; if (use_tma) { MapEntry* xe = get_xmap(encode, g_xmap9, &g_x9next, x, N, H, W, U_BOXR, A_MC); // the 16 B halo box (col 64tx-1 of each row) is the tail of the left neighbour tile's main-box line, // which a concurrently running CTA fetches; no L2 promotion -> a halo miss fills one 32 B sector instead of // a speculative 128 B line (fewer DRAM bytes when the halo races ahead of the neighbour; same data). MapEntry* xh = get_xmap(encode, g_xmaph, &g_xhnext, x, N, H, W, U_BOXR, 4, CU_TENSOR_MAP_L2_PROMOTION_NONE); if (xe->ok && xh->ok) { MapEntry* xp = get_xmap(encode, g_xmap9p, &g_x9pnext, x, N, H, W, U_BOXR, A_MC, CU_TENSOR_MAP_L2_PROMOTION_L2_256B); // CLU option 10 eligibility: even tile-row count (every tile has its vertical pair partner) MapEntry* x8 = get_xmap(encode, g_xmap8, &g_x8next, x, N, H, W, 8, A_MC); MapEntry* x1 = get_xmap(encode, g_xmap1, &g_x1next, x, N, H, W, 1, A_MC); const bool cl_ok = (tilesY4 % 2) == 0 && nt4 >= 2 && x8->ok && x1->ok; // CW option 11: K = ceil(nt4 / nsm) tiles per CTA (balanced: grid = ceil(nt4 / K) <= nsm <= S0MAX) const int cwK = (nt4 + nsm - 1) / nsm; MapEntry* xh8 = get_xmap(encode, g_xmaph8, &g_xh8next, x, N, H, W, 8, 4, CU_TENSOR_MAP_L2_PROMOTION_NONE); if (xh8->ok) g_pm_cw.m[0] = xh8->m; const bool cw_ok = x8->ok && xh8->ok && cwK >= 2 && cwK <= 0xFFF && ((nt4 + cwK - 1) / cwK) <= S0MAX && tilesY4 >= 2; auto run_tma = [&](int mode) { if (mode == 11) { const int g = (nt4 + cwK - 1) / cwK; launch_umma<false, 32, 1, 6, 2, (XV_DEF | CW_BIT)>(g, smem_umma, s, xe->m, x8->m, xh->m, g_pm_cw, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nt4, 0, w, wf_raw | 32 | (cwK << 16) | (g_bov << 8)); return; } if (mode == 10) { // CLU: 2-CTA clusters over vertical tile pairs, balanced persistent grid const int np = nt4 / 2; int ncl = np < nsm / 2 ? np : nsm / 2; const int waves = (np + ncl - 1) / ncl; ncl = (np + waves - 1) / waves; launch_umma<false, 32, 1, 6, 2, (XV_DEF | CLU_BIT)>(2 * ncl, smem_umma, s, x8->m, x1->m, xh->m, g_pm_dummy, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, np, 0, w, wf_raw | 32 | (g_bov << 8)); return; } // 4 = split-stage converters, 5 = split + evict_first + early flood // 6 = split + 3-deep converted ring (TMA ring 5), 7 = that + evict_first + early flood // ALWAYS-EARLY FLOOD (aligned; mirrors on odd W): every aligned option sets wfused bit 32 -- the // producer issues sub-stages >= 2 right away instead of holding the input flood behind the 73 KB raw // weight copy (already first in the TMA queue; ring slots do not overlap its smem region), so DRAM is // busy from CTA start and the ring absorbs the weight-transform startup. Option 2 (was ef+early, now // identical to 1) becomes plain + early flood (no evict_first). Output bit-identical. const int ef = 32 | (mode == 1 ? 4 : (mode == 2 ? 0 : (mode == 4 || mode == 6 || mode == 8 ? 128 : (mode == 5 || mode == 7 || mode == 9 ? (4 | 128) : 0)))); const CUtensorMap* mm = (mode == 3 && xp->ok) ? &xp->m : &xe->m; // MPN384: 16x384 (table g 9, >L2 DRAM-bound) full-tile main boxes use a tensor map with L2 promotion // NONE (each box row = one 256B-aligned fully consumed 256 B run); same TMAs/bytes -> bit-identical. if (g_gov == 9 || g_gov == 19 || g_gov == 23) { // MPN256: 2x256 (g 19) too; MPNY: 64x128 (g 23 YCS+MS0) too MapEntry* xn = get_xmap(encode, g_xmap9n, &g_x9nnext, x, N, H, W, U_BOXR, A_MC, CU_TENSOR_MAP_L2_PROMOTION_NONE); if (xn->ok) mm = &xn->m; } #ifdef XPROBE if (xv_host_bits() & (1 << 29)) { MapEntry* xn = get_xmap(encode, g_xmap9n, &g_x9nnext, x, N, H, W, U_BOXR, A_MC, CU_TENSOR_MAP_L2_PROMOTION_NONE); if (xn->ok && mode != 3) mm = &xn->m; } #endif int g = g4; #ifdef XPROBE if ((xv_host_bits() & C70_GRD) && nt4 > 2 * nsm) g = nsm - 4; // C70 GRD #endif int nfull = nt4, nhalf = 0; const CUtensorMap* hm = &dummy_map; // EXD EXACT-DIVISOR GRID (per-shape table flag g_gov): a multi-wave shape whose tile count has a divisor d in // [nsm-8, nsm) runs on d CTAs with exactly nt4/d full tiles each -- no half-tile tail items (5-row boxes, extra // map, HF reordering) and every CTA ends at the same tile count (16x384: 4608 = 144 x 32 instead of 148 x 31 + // 40 halves). 4 SMs idle, 4 fewer raw-weight copies/transforms. Schedule is grid-agnostic -> bit-identical. bool exd = false; if ((g_gov == 1 || g_gov == 2 || g_gov == 4 || g_gov == 6 || g_gov == 7 || g_gov == 9 || g_gov == 21) && nt4 > 2 * g) { // WIDE EXD (g 4 / 6): accept any exact divisor down to 3/4 of the SM count const int dmin = (g_gov >= 4) ? (3 * g) / 4 : g - 8; // g 7 = wide EXD + YCS for (int d = g - 1; d >= dmin && d > 0; d--) if (nt4 % d == 0) { g = d; exd = true; break; } } const int R = nt4 % g; if (exd) { } else if (nt4 > g && R > 0 && 2 * R <= g) { MapEntry* he = get_xmap(encode, g_xmap5, &g_x5next, x, N, H, W, U_HROWS, A_MC); if (he->ok) { nfull = nt4 - R; nhalf = 2 * R; hm = &he->m; } } else if (2 * nt4 <= nsm) { // SMALL-SHAPE SPLIT: < half a wave of tiles -> every tile becomes 2 half tiles MapEntry* he = get_xmap(encode, g_xmap5, &g_x5next, x, N, H, W, U_HROWS, A_MC); if (he->ok) { nfull = 0; nhalf = 2 * nt4; g = nhalf; hm = &he->m; } } // BALANCED GRID: no half-tile split applies and the last wave is partial (e.g. 2x256: 256 tiles on // 148 SMs = 108 CTAs x 2 + 40 x 1) -> grid = ceil(nt4 / waves): every CTA gets the same tile count // (2x256: 128 x 2, 1x384: 144 x 2), same per-CTA maximum, fewer redundant raw-weight copies/transforms. // The persistent schedule (tile = bid + k*grid) is grid-agnostic. bool bal = nhalf == 0 && nt4 > g && R > 0; #ifdef XPROBE if (xv_host_bits() & (1 << 21)) bal = false; // probe host bit: seed behaviour #endif if (bal) { const int waves = (nt4 + g - 1) / g; g = (nt4 + waves - 1) / waves; } if (mode >= 8) // NC = 4, TMA ring 4 launch_umma<false, 32, 1, 6, 4>(g, smem_umma4, s, *mm, *hm, xh->m, g_pm_dummy, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | ef | (g_bov << 8)); else if (mode >= 6) launch_umma<false, 32, 1, 6, 3>(g, smem_umma3, s, *mm, *hm, xh->m, g_pm_dummy, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | ef | (g_bov << 8)); else if (g_gov == 9 && exd && nhalf == 0 && (mode == 4 || mode == 5) && get_ymap8(encode, y, N, Ho, Wo)->ok) // TST (16x384): TMA tensor-store epilogue, y store map passed as omap (no half tiles on the EXD grid) { // DYN: the last 2 tiles of every CTA become the dynamically claimed pool (needs >= 10 tiles per CTA) const bool dy = (nt4 % g) == 0 && nt4 / g >= 10; const int nfs = dy ? nt4 - 2 * g : nfull; const int dsl = g_dynslot; g_dynslot = (g_dynslot + 1) & (DYN_SLOTS - 1); if (dy) launch_umma<false, 32, 1, 6, 2, (XV_DEF | PFX_BIT | TST_BIT | DYN_BIT)>(g, (size_t)SmemLayout<false, 32, 1, 6, 2, TST_SB>::TOT, s, *mm, get_ymap8(encode, y, N, Ho, Wo)->m, xh->m, g_pm_dummy, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 1, nfs, nhalf, w, wf_raw | ef | (g_bov << 8) | (dsl << 16)); else launch_umma<false, 32, 1, 6, 2, (XV_DEF | PFX_BIT | TST_BIT)>(g, (size_t)SmemLayout<false, 32, 1, 6, 2, TST_SB>::TOT, s, *mm, get_ymap8(encode, y, N, Ho, Wo)->m, xh->m, g_pm_dummy, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | ef | (g_bov << 8)); } else if (g_gov == 9 && exd) launch_umma<false, 32, 1, 6, 2, (XV_DEF | PFX_BIT | YCS_BIT)>(g, smem_umma, s, *mm, *hm, xh->m, g_pm_dummy, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | ef | (g_bov << 8)); else if (g_gov == 16) // best-of merge: 4x512 = YCS + PFX pre-wait prefetch, balanced grid launch_umma<false, 32, 1, 6, 2, (XV_DEF | PFX_BIT | YCS_BIT)>(g, smem_umma, s, *mm, *hm, xh->m, g_pm_dummy, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | ef | (g_bov << 8)); else if (g_gov == 23) // MS0Y (64x128): YCS streaming y stores + MS0 first-tile cfull spin wait launch_umma<false, 32, 1, 6, 2, (XV_DEF | YCS_BIT | MS0_BIT)>(g, smem_umma, s, *mm, *hm, xh->m, g_pm_dummy, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | ef | (g_bov << 8)); else if (g_gov == 7 || g_gov == 8 || g_gov == 9) // YCS: streaming y stores (2x1024); g 8 = YCS only (1x1024/4x512/64x128) launch_umma<false, 32, 1, 6, 2, (XV_DEF | YCS_BIT)>(g, smem_umma, s, *mm, *hm, xh->m, g_pm_dummy, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | ef | (g_bov << 8)); else if (g_gov == 19 || g_gov == 21) // g 21 = wide EXD grid + WPN (4x256); WPN (2x256): per-piece raw-weight barriers + early chunk-1 B-image stores launch_umma<false, 32, 1, 6, 2, (XV_DEF | WPN_BIT | MS0_BIT)>(g, smem_umma, s, *mm, *hm, xh->m, g_pm_dummy, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | ef | (g_bov << 8)); else if (g_gov == 20) // PF0H+WPN (8x256): PF0H + per-piece raw-weight barriers / early chunk-1 B-image stores launch_umma<false, 32, 1, 6, 2, (XV_DEF | PFX_BIT | PF0_BIT | PFH_BIT | WPN_BIT | MS0_BIT)>(g, smem_umma, s, *mm, *hm, xh->m, g_pm_dummy, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | ef | (g_bov << 8)); else if (g_gov == 14) // PF0H (8x256): PF0 + pre-wait L2 prefetch of the octet-0 stage-0 HALO box (scattered 16 B sectors) launch_umma<false, 32, 1, 6, 2, (XV_DEF | PFX_BIT | PF0_BIT | PFH_BIT)>(g, smem_umma, s, *mm, *hm, xh->m, g_pm_dummy, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | ef | (g_bov << 8)); else if (g_gov == 11) // PF0 (8x256): octet-0-only pre-wait stage-0 L2 prefetch, balanced grid launch_umma<false, 32, 1, 6, 2, (XV_DEF | PFX_BIT | PF0_BIT)>(g, smem_umma, s, *mm, *hm, xh->m, g_pm_dummy, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | ef | (g_bov << 8)); else if ((g_gov == 2 && exd) || g_gov == 5 || (g_gov == 6 && exd)) launch_umma<false, 32, 1, 6, 2, (XV_DEF | PFX_BIT)>(g, smem_umma, s, *mm, *hm, xh->m, g_pm_dummy, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | ef | (g_bov << 8)); else if (g_gov == 4) // MS0 on 1x512 (wide EXD grid): first-tile cfull spin wait launch_umma<false, 32, 1, 6, 2, (XV_DEF | MS0_BIT)>(g, smem_umma, s, *mm, *hm, xh->m, g_pm_dummy, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | ef | (g_bov << 8)); else launch_umma<false, 32>(g, smem_umma, s, *mm, *hm, xh->m, g_pm_dummy, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | ef | (g_bov << 8)); }; // per-shape voted cold-L2 autotune (cached by (N,H,W)); captured stream -> option 0 int choice = g_force_tma; if ((choice == 10 && !cl_ok) || (choice == 11 && !cw_ok)) choice = 0; if (choice < 0) choice = known_choice(g_known_tma, N, H, W); if (choice < 0) choice = 0; #ifdef XPROBE { const int ob = (xv_host_bits() >> 23) & 15; if (ob == 15) choice = g_tchoice; else if (ob) choice = ob - 1; } #endif { g_fl.valid = false; { cudaStreamCaptureStatus cs_ = cudaStreamCaptureStatusNone; cudaStreamIsCapturing(s, &cs_); g_rec_on = (g_force < 0 && g_force_tma < 0 && cs_ == cudaStreamCaptureStatusNone); } // captured: choice 0 untuned -> do not freeze it // fixed f16 path for every aligned shape (the removed tf32/tf32s vote picked f16 on all 16 eval shapes) g_bov = g_force_tma < 0 ? known_burst(g_known_tma, N, H, W) : g_bov; if (g_force_tma < 0) g_gov = known_grid(g_known_tma, N, H, W); run_tma(choice); g_bov = 0; g_gov = 0; g_rec_on = false; if (g_fl.valid) { g_fl.kx = x; g_fl.kw = w; g_fl.kb = b; g_fl.kN = N; g_fl.kH = H; g_fl.kW = W; g_fl.ks = s; } } PROBE_REPORT(2 * nt4 <= nsm ? 2 * nt4 : g4); return; } } // ---- non-TMA-aligned shapes: phase-map TMA kernel (ring 7 / 6, tail half-tiles), gather fallback ---- // phase path: 16 tensor maps (row phase p x channel phase j), needs 16B-aligned x and H >= 4 // BEST-OF MERGE: 2x449 phase maps with L2_256B promotion; // host-only, same TMAs/bytes -> bit-identical. All other shapes keep L2_128B. const PhaseMaps<16>* pmp = get_pmaps(encode, x, N, H, W, (N == 2 && H == 449 && W == 449) ? CU_TENSOR_MAP_L2_PROMOTION_L2_256B : CU_TENSOR_MAP_L2_PROMOTION_L2_128B); auto run_phase = [&](int nt, int v2, bool csp = false) { int nfull = nt4, nhalf = 0; if (csp) { // CSP: item grid <= nsm/2 (2 CTAs per item, 1 CTA/SM); half split / balanced grid as below const int g2 = nsm / 2; int gc = nt4 < g2 ? nt4 : g2; const int Rc = nt4 % gc; if (nt4 > gc && Rc > 0 && 2 * Rc <= gc) { nfull = nt4 - Rc; nhalf = 2 * Rc; } else if (nt4 > gc && Rc > 0) { const int wv = (nt4 + gc - 1) / gc; gc = (nt4 + wv - 1) / wv; } launch_umma<false, 32, 16, 6, 3, (XV_DEF | CSP_BIT | MS0_BIT)>(gc, smem_ph6, s, dummy_map, dummy_map, dummy_map, *pmp, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | 32 | (g_bov << 8)); return; } const int R = nt4 % g4; int gg = g4; if (nt4 > g4 && R > 0 && 2 * R <= g4) { nfull = nt4 - R; nhalf = 2 * R; } else if (2 * nt4 <= nsm) { nfull = 0; nhalf = 2 * nt4; gg = nhalf; } // small-shape split if (nhalf == 0 && nt4 > g4 && R > 0) { const int waves = (nt4 + g4 - 1) / g4; gg = (nt4 + waves - 1) / waves; } #ifdef XPROBE if ((xv_host_bits() & (1LL << 62)) && nhalf == 0 && nt4 > g4 && R > 0) gg = (nt4 + 2) / 3; // probe: 3-tile grid #endif if (nt == 17 || nt == 16) { // B8 PXS with NC = 2, ring 7 / 6 if (nt == 17) launch_umma<false, 32, 16, 7, 3>(gg, smem_ph7, s, dummy_map, dummy_map, dummy_map, *pmp, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | (v2 ? 64 : 0) | 32 | (g_bov << 8)); else launch_umma<false, 32, 16, 6, 3, (XV_DEF | MS0_BIT)>(gg, smem_ph6, s, dummy_map, dummy_map, dummy_map, *pmp, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | (v2 ? 64 : 0) | 32 | (g_bov << 8)); } else if (nt == 5) // B8 PXS: px-split converters + 3-deep converted ring, TMA ring 5 launch_umma<false, 32, 16, 5, 3>(gg, smem_ph5x, s, dummy_map, dummy_map, dummy_map, *pmp, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | 32 | (g_bov << 8)); else if (nt == 7) launch_umma<false, 32, 16, 7, 2, (XV_DEF | MS0_BIT)>(gg, smem_ph7, s, dummy_map, dummy_map, dummy_map, *pmp, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | (v2 ? 64 : 0) | 32 | (g_bov << 8)); else launch_umma<false, 32, 16, 6>(gg, smem_ph6, s, dummy_map, dummy_map, dummy_map, *pmp, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, 0, nfull, nhalf, w, wf_raw | (v2 ? 64 : 0) | 32 | (g_bov << 8)); }; const CUtensorMap* om = &dummy_map; int use_tstore = 0; if (encode != nullptr && (Wo % 4) == 0 && (((uintptr_t)y) & 15) == 0) { MapEntry* ye = get_ymap(encode, y, N, Ho, Wo); if (ye->ok) { om = &ye->m; use_tstore = 1; } } const int tilesX16 = (Wo + 15) / 16, tilesY8 = (Ho + 7) / 8; const int nt8 = tilesX16 * tilesY8 * N; const int waves4 = (nt4 + nsm - 1) / nsm, waves8 = (nt8 + nsm - 1) / nsm; auto run_gather = [&]() { launch_wprep(); if (waves8 < waves4) { const int g8 = nt8 < nsm ? nt8 : nsm; launch_umma<true, 16>(g8, smem_umma_g, s, dummy_map, dummy_map, dummy_map, g_pm_dummy, x, wimg, b, y, H, W, Ho, Wo, tilesX16, tilesY8, nt8, 0, nt8, 0); } else { launch_umma<true, 32>(g4, smem_umma_g, s, dummy_map, *om, dummy_map, g_pm_dummy, x, wimg, b, y, H, W, Ho, Wo, tilesX, tilesY4, nt4, use_tstore, nt4, 0); } }; // options: 0 = phase ring7 + halves, 1 = phase ring6 + halves // 2 = ring7 + halves + pair-load converter, 3 = ring6 + halves + pair-load converter auto run_opt = [&](int o) { if (o == 9) run_phase(16, 0, true); else if (o == 4) run_phase(5, 0); else if (o == 5) run_phase(17, 0); else if (o == 6) run_phase(16, 0); else if (o == 7) run_phase(17, 1); else if (o == 8) run_phase(16, 1); else run_phase((o & 1) == 0 ? 7 : 6, o >= 2); }; if (pmp == nullptr || g_force == 0) { run_gather(); return; } // no usable phase maps -> gather (any shape) if (g_force > 0) { run_opt(g_force - 1); return; } int choice = known_choice(g_known_odd, N, H, W); if (choice < 0) choice = 0; // unknown odd-W shapes -> phase ring7 + halves (deterministic, no timing) #ifdef XPROBE { const int hb = xv_host_bits(); if (hb & (1 << 26)) choice = (hb & (1 << 19)) ? 8 : 7; else if (hb & (1 << 30)) choice = (hb & (1 << 19)) ? 6 : 4; else if (hb & (1 << 19)) choice = 5; } // B8 probe: force PXS #endif { g_fl.valid = false; { cudaStreamCaptureStatus cs_ = cudaStreamCaptureStatusNone; cudaStreamIsCapturing(s, &cs_); g_rec_on = (g_force < 0 && g_force_tma < 0 && cs_ == cudaStreamCaptureStatusNone); } // captured: choice 0 untuned -> do not freeze it // fixed phase f16 path (the removed tf32/tf32s/small votes picked it on all 4 odd eval shapes) g_bov = known_burst(g_known_odd, N, H, W); run_opt(choice); g_bov = 0; g_rec_on = false; if (g_fl.valid) { g_fl.kx = x; g_fl.kw = w; g_fl.kb = b; g_fl.kN = N; g_fl.kH = H; g_fl.kW = W; g_fl.ks = s; } } PROBE_REPORT(2 * nt4 <= nsm ? 2 * nt4 : g4); }
// (1) conv_s2_umma_kernel<false,32> -- W % 4 == 0 (16B aligned x): tcgen05.mma kind::f16
// (M128 px x N64 cout x K16, accumulators in TMEM) fed by a TMA ring and a smem K-major
// conversion stage. Tile = 4 out rows x 32 out cols. One MMA "stage" = 16 input channels
// (2 per tile). TMA ring = U_NT sub-stages of 8 input channels (box 68 cols x 9 rows x 8 ch =
// 19584 B each) = U_NT/4 tiles of raw input in flight per SM; every stage consumes two
// sub-stages (one per channel octet), each released by the 9 converter warps of its octet.
// Converted ring = U_NC_TMA stages. To make room for the deeper TMA ring, this path has NO
// output smem staging: the epilogue writes y directly from TMEM regs with streaming
// st.global.cs (each warp store = one 128 B row segment of one cout).
// (3) conv_s2_band_kernel -- odd/unaligned W with Wo <= 256: full-width 1-row bands fed by one 1D
// bulk copy per channel (see its header); autotuned per shape against (2).
// PDL: the conv prologue overlaps wprep; thread 0 issues only stage 0's input TMAs at startup; after
// setup the MMA thread (griddepcontrol.wait, then 1D bulk copies of the pre-swizzled weights, one 18 KB
// copy per 16-channel K-chunk with its own mbarrier wbar[c]) and the producer (rest of the input ring)
// run concurrently, so the L2-hot weights are not queued behind the cold-DRAM input flood. Grid = min(#tiles, #SM).
// (4) PHASE path, conv_s2_umma_kernel<false,32,16> -- W % 4 != 0 (16B-aligned x, H >= 4): the TMA
// pipeline of (1) fed through 16 (row phase x channel phase) tensor maps, 4 TMAs per 8-channel
// sub-stage, converters undo the per-map column shift (see P_* defines). Autotuned per shape
// (cudaEvent timing, cached by (N,H,W)) against gather (2) and band (3).
// (5) DUAL, conv_s2_umma_kernel<false,32,1,true> -- the (1) pipeline at 2 CTAs/SM (480 thr, 105.7 KB smem,
// see D_* defines); per-shape cold-L2 autotune single vs DUAL for aligned shapes.
// (7) aligned converter shuffles the packed fp16x2 kx=0 column (half the SHFLs, 4 fewer F2FP).
// (8) aligned converter uses explicit 32-bit ld/st.shared with immediate offsets (no generic 64-bit LD/ST).
// (9) phase-path converter: packed kx=0 SHFL + 32-bit ld.shared with immediate offsets.
// (10) phase converter lane -> px (m, m+16): bank-conflict-free stride-2 LDS.32, templated channel stride.
// (11) phase path box 72->68 cols, ring depth 6/7 (template) x tail halves on/off, cold-L2 autotuned.
// (12) fused weight transform remapped (cout per lane, per-lane element rotation): conflict-free LDS/STS.
// (13) BULK-ROW path, conv_s2_umma_kernel<false,32,2,false,PNT> -- W % 4 != 0, 16B-aligned x: same pipeline
// and converter as the phase path, but the producer WARP loads each 8-channel sub-stage (channel phase j:
// ci = 4i+j) with plain 1D cp.async.bulk copies, one per (channel, input row): the contiguous segment from the
// 16B-aligned element at/below col 64tx-1 (col 0 for tx = 0) to min(64tx+64, W), rounded up to 16 B (<= 68
// cols), into a dense [8 ch][9 rows][68] slot. The column shift is uniform over the 8 channels of a phase
// (4*H*W = 0 mod 4), so it is uniform per converter half-warp; pad rows are zeroed by the converter, col W
// (odd W) is masked. Autotuned against phase/gather/band.
// (14) bulk-row producer = one warp-reduced arrive.expect_tx (lane 0) then the copies; bulk-row ring 6
// or 7 x tail halves on/off, all cold-L2 autotuned per shape.
// (15) shapes with 2*tiles <= #SM run as ALL half tiles (2 out rows x 32, grid = 2*tiles): shorter
// per-CTA critical path for tiny shapes (e.g. 1x131: 51 tiles -> 102 CTAs). Autotuned (odd W) via 'halves'.
// (16) MINI: conv_s2_mini_kernel -- non-persistent half-tile CTAs, 75 KB smem, 3 CTAs/SM (see its header);
// cold-L2 autotuned per shape against every other path (aligned and odd W).
// (17) mini path template ring depth MNT (2 or 4 slots); MNT = 4 issues the CTA's whole input up front
// (roofline calibration: tiny shapes were furthest from a streaming kernel). Autotuned as another option.
// (18) mini path with 2-CTA clusters splitting the weight transform (DSMEM stores), autotuned option.
// (19) parity-alias guard in the 2-group TMA converter loop (latent intermittent hang fix).
// (20) the guard is replaced by per-converter-group full barriers tfull[slot][group] (alias-free by
// construction, no extra wait in steady state).
// (21) PDL audit: every PDL kernel triggers launch_dependents only AFTER its TMEM alloc (no
// secondary-holds-TMEM / primary-blocked-in-alloc deadlock); every thread griddepcontrol.waits before
// its first global access (band/gather paths included).
// (22) autotune score = trimmed mean of 11 cold-L2 reps.
// (24) per-shape choice = majority over 3 independent tune passes (tune_select_vote).
// (25) tuner options 14/15 (odd W) = phase ring7/6 + halves with wfused = 3: same raw smem weight copy,
// but the converters build the fp16 B image with one (cout, 4-chunk) item per thread from 8 LDS.128
// (phase K order makes 4 consecutive chunks = the components of aligned float4s) instead of 4 rotated
// chunks from 32 LDS.32 + barrel shifts. (An epilogue-warp transform from global w was probed: no gain.)
// (26) aligned tuner option 6 = single TMA path with a vectorized natural-order B-image transform
// (wfused = 3 on the aligned path: (co, octet, half) items, 9 LDS.128 + 9 STS.64 per thread).
// (27) the vectorized transforms (natural order: aligned single/DUAL; phase order: phase/bulk-row/mini)
// are the ONLY in-CTA weight transforms (old scalar/barrel-shift ones removed); options 6/14/15 retired.
// (28) tuner options (aligned 6/7, odd 14/15) = mini / mini4 launched with a ~100 KB smem carveout preference.
// (29) aligned tuner option 8 = converter-free tf32 direct kernel (raw fp32 TMA planes as MN-major A,
// kx folded into N=192, stride-2 in the epilogue, in-CTA vectorized tf32 B image); voted cold-L2 tune.
// (31) aligned tuner options 10/11 = option 9 + producer TMA L2 prefetches (cp.async.bulk.prefetch.tensor)
// of the input boxes 2 / 4 MMA stages beyond the smem ring (more DRAM bytes in flight, no extra smem).
// (32) aligned tuner options 12/13 = option 10 / 9 with the producer NOT waiting for the raw weight copy
// before issuing the rest of the input ring (cuts the startup DRAM-idle gap on mid shapes, e.g. 2x512).
// (6) aligned TMA path fetches each input row as a 128B-line-aligned 64-col main box + a 4-col halo box.
// (35) odd-W tuner options 2/3 = phase ring7/6 + halves with the PAIR-LOAD converter (ph2_pair: LDS.64 +
// LDS.32 per channel and px, no SHFL, destination planes permuted per lane).
// (37) natural-order (aligned) weight-transform item map permuted: STS.64 2-way -> conflict-free, LDS.128 stays clean.
// (36) phase-order weight-transform item map rotated (co = it%64, rb = (it/64 + co)%9): STS conflicts 8 -> <=2-way.
// (38) aligned tuner options 6/7 = split-stage converters with a 3-deep converted ring (ANC = 3,
// TMA ring 7 -> 5 sub-stages to fit smem): converting stages s+1, s+2 overlaps the MMAs of stage s; each
// converted slot is released per 16-channel K-chunk (umma_commit -> cempty). Plain / +ef+early flood.
// (39) aligned tuner options 8/9 = split-stage with a 4-deep converted ring (ANC = 4, TMA ring 4 sub-stages,
// 227840 B smem), plain / +ef+early flood. (NC = 3 + TMA ring 6 does not fit: 239104 B.)
// (41) odd-W phase path input TMA loads always use the L2 evict_first cache hint (replacement, no new option).
// (42) direct-store epilogue drains TMEM as two x16 loads, chunk-0 stores overlap chunk-1's tcgen05.ld.
// (44) aligned-path halo tensor map encoded with L2 promotion NONE (bit-identical).
// (45) DEAD-CODE PRUNE: removed the never-instantiated bulk-row (NPM==2) producer/converter, the DUAL template
// parameter (2 CTAs/SM variant, never launched) and the legacy non-gather branch of the gather converter loop.
// Same kernel instantiations / tuner options; output bit-identical.
// (47) direct-store epilogue walks one running output pointer (+Ho*Wo per cout); bit-identical.
// (46) phase converter tracks the tile column incrementally (no per-stage div/mod); bit-identical.
// (49) phase converter outer loop specialised per (v2, channel stride), hoisted half-tile column,
// toggled cempty parity; bit-identical.
// (48) MMA-issuer loop diet (precomputed descriptor bases + immediate offsets, incremental slot/parity,
// unrolled K-chunk loop, hoisted weight wait); bit-identical.
// (51) raw fp32 weight copy split into 4 parallel 18 KB bulk copies on one barrier; bit-identical.
// (52) direct-store epilogue drains TMEM as four pipelined 32x32b.x8 loads; bit-identical.
// (53) ROBUSTNESS AUDIT (no kernel change): in-process stress of every tuner option (aligned 0-9, odd-W gather +
// phase 1-4) on 8x256, 2x512, 16x384, 2x449, 1x131: ~84k launches, back-to-back PDL chains + cold-L2 memsets,
// fresh inputs, NaN-prefilled rotated outputs -> 0 hangs, 0 bit mismatches, 0 tolerance failures. Barrier audit:
// every ring (tfull per group, tempty, cfull/cempty, afull/aempty) waits phases in order and the producer of
// phase k+1 is gated on the consumer of phase k, so parity bits cannot alias; 1 CTA/SM (>116 KB smem) means a
// PDL secondary never shares an SM (TMEM) with its primary; launch_dependents follows the TMEM alloc.
// (54) phase converter left-pad zeroing moved out of the per-pair conversion into a warp-uniform tx == 0
// branch (no per-pair SEL on tx > 0 stages); bit-identical.
// (55) aligned converters (conv_ld16 / split conv_ld8) drop the per-pair halo select before the SHFL; lane m = 0
// loads its own octet's halo column in one m == 0 branch after the shuffles; bit-identical.