Download kernels/Quant/020_nvfp4_linear_layer/src/kernel.cu from QianQu/CompoundingKernel-Explorer: direct link, hf CLI and curl.
- Browser
- Download file 167 kB
-
https://huggingface.co/spaces/QianQu/CompoundingKernel-Explorer/resolve/main/kernels/Quant/020_nvfp4_linear_layer/src/kernel.cu
- Command line
-
hf download hf://spaces/QianQu/CompoundingKernel-Explorer/kernels/Quant/020_nvfp4_linear_layer/src/kernel.cu
-
curl -L -o kernel.cu https://huggingface.co/spaces/QianQu/CompoundingKernel-Explorer/resolve/main/kernels/Quant/020_nvfp4_linear_layer/src/kernel.cu
167 kB
// NVFP4 linear layer: fused custom quantization pipeline feeding either
// (a) the custom swap-AB split-K tcgen05 NVFP4 GEMM (Mp 128 pin), or
// (b) a CUTLASS sm100 block-scaled NVFP4 GEMM (cutlass_gemm_{b,h}.cu, Mp >= 256), PDL-launched.
//
// ---------------------------------------------------------------------------------------------
// QUANT (grid-barrier kernels, sized to be fully co-resident).
// Work unit = one 16-element block of x ("item": 32 B of bf16 -> 8 B packed E2M1 + 1 B E4M3).
// One launch, one lightweight grid barrier between the global-amax phase and quantization:
// grid_arrive()/grid_wait(): thread 0 of each CTA reads the epoch e = ctr / G (ctr = monotone u64
// arrival counter, never reset; all launches on one counter use the same G), red.max's its
// block max (float bits as u32) into amax slot e&1, release-adds the counter, acquire-spins
// until ctr >= (e+1)*G, then reads the slot. Block 0 zeroes slot (e+1)&1 for the next launch.
// fused_quant_res_kernel<IPT> (small/medium M): each thread owns IPT items kept in registers
// (x read exactly once), block amax, grid barrier, quantize straight from registers.
// fused_quant_hyb_kernel (medium M): register tier + a bulk-copied shared-memory tier.
// fused_quant_kernel (large M, persistent grid): Phase A chunk amax, barrier, Phase B re-reads
// its chunk in reverse order (L2 hits) and quantizes.
//
// GEMM (custom swap-AB nvfp4_swapab_gemm): see its section header below.
// ---------------------------------------------------------------------------------------------
#include "kernel.h"
#include <cuda.h>
#include <cuda_bf16.h>
#include <cuda_fp8.h>
#include <cfloat>
#include <algorithm>
static constexpr int kThreads = 256;
// ---- TLPROBE (dormant, probe builds only): per-CTA globaltimer stamps of the quant kernels ----
#ifdef NVFP4_TLPROBE
__device__ unsigned long long g_hp[1024 * 16];
// stamps kept in registers (tl_[s]) and written once at TL(15) -> no store traffic mid-kernel
#define TL(s) do { if (threadIdx.x == 0) { unsigned long long t_; \
asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t_) :: "memory"); tl_[s] = t_; \
if ((s) == 15 && blockIdx.x < 1024) { for (int i_ = 0; i_ < 16; ++i_) g_hp[blockIdx.x * 16 + i_] = tl_[i_]; } } } while (0)
#define TL_DECL unsigned long long tl_[16] = {0};
#define TLD(s, dep) do { if (threadIdx.x == 0) { unsigned long long t_; \
asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t_) : "r"(dep) : "memory"); tl_[s] = t_; } } while (0)
void hyb_probe_reset() { void* p = nullptr; cudaGetSymbolAddress(&p, g_hp); cudaMemset(p, 0, sizeof(unsigned long long) * 1024 * 16); }
void hyb_probe_read(unsigned long long* o) { cudaMemcpyFromSymbol(o, g_hp, sizeof(unsigned long long) * 1024 * 16); }
#else
#define TL(s)
#define TLD(s, dep)
#define TL_DECL
#endif
__device__ __forceinline__ float bf16lo(uint32_t v) { return __uint_as_float(v << 16); }
__device__ __forceinline__ float bf16hi(uint32_t v) { return __uint_as_float(v & 0xffff0000u); }
// blocked layout offset of scale (r, c) in a rows x cols scale matrix (cols % 4 == 0):
// 128x4 tiles ordered (row_block, col_block); inside a tile: [r%32][(r%128)/32][c%4]
__device__ __forceinline__ uint32_t blk_off(int r, int c, int ncb) {
int rb = r >> 7, ri = r & 127, cb = c >> 2, c0 = c & 3;
return ((uint32_t)rb * ncb + cb) * 512u + (ri & 31) * 16 + (ri >> 5) * 4 + c0;
}
__device__ __forceinline__ uint32_t bmx_xa(uint32_t a, uint32_t b) {
uint32_t r;
asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(r) : "r"(a), "r"(b));
return r;
}
__device__ __forceinline__ uint32_t absmax2x8(uint4 v) {
return bmx_xa(bmx_xa(v.x, v.y), bmx_xa(v.z, v.w)) & 0x7fff7fffu;
}
__device__ __forceinline__ uint32_t fold2(uint32_t m) { return max(m & 0xffffu, m >> 16); }
// Item (16 bf16) block max |x| as fp32, low-op form for the issue-bound quant pass 2:
// 7 max.xorsign.abs.bf16x2 over the RAW words (magnitude of each lane = max |.| of its 8 values,
// sign garbage) then ONE fp32 FMNMX with |.| operand modifiers on the two lanes widened exactly
// (lo << 16, hi & 0xffff0000) -> 10 ops instead of 13 (2 masks + vmaxu2 + 3-op fold2 + shl).
// Bit-identical to fold2(vmaxu2(absmax2x8,absmax2x8)) << 16 for non-NaN inputs: both yield the
// exact fp32 value of the largest-magnitude bf16 with a + sign (fabs on +-0 gives +0, same bits).
__device__ __forceinline__ float item_bm(const uint4& a, const uint4& b) {
const uint32_t m = bmx_xa(bmx_xa(bmx_xa(a.x, a.y), bmx_xa(a.z, a.w)),
bmx_xa(bmx_xa(b.x, b.y), bmx_xa(b.z, b.w)));
return fmaxf(fabsf(__uint_as_float(m << 16)), fabsf(__uint_as_float(m & 0xffff0000u)));
}
// ALL-PACKED item block max (M >= 1024 paths: IPT 7 register quant, hybrid quant, persistent
// quant pass 2): the 7-op max.xorsign.abs.bf16x2 tree, then ONE more packed max against the
// half-swapped word (prmt) instead of the two fp32 widens + fp32 FMNMX: both lanes then hold the
// largest magnitude (sign garbage), and masking with 0x7fff0000 yields exactly the fp32 bits of
// +max|x| (bf16 hi lane = top half of an fp32). Same value as item_bm for non-NaN inputs
// (+0 for all-zero items) -> bit-identical; no fp32-pipe op in the block max.
__device__ __forceinline__ float item_bm_p(const uint4& a, const uint4& b) {
const uint32_t m = bmx_xa(bmx_xa(bmx_xa(a.x, a.y), bmx_xa(a.z, a.w)),
bmx_xa(bmx_xa(b.x, b.y), bmx_xa(b.z, b.w)));
return __uint_as_float(bmx_xa(m, __byte_perm(m, 0, 0x1032)) & 0x7fff0000u);
}
// Packed amax accumulation over RAW words (sign garbage, magnitude exact): m = running packed
// max.xorsign.abs accumulator (init 0); amax_fin() masks the signs once and folds the two lanes.
// Bit-identical to the former mask + __vmaxu2 accumulation + fold2 << 16 for non-NaN inputs.
__device__ __forceinline__ uint32_t acc_item(uint32_t m, const uint4& a, const uint4& b) {
return bmx_xa(m, bmx_xa(bmx_xa(bmx_xa(a.x, a.y), bmx_xa(a.z, a.w)),
bmx_xa(bmx_xa(b.x, b.y), bmx_xa(b.z, b.w))));
}
__device__ __forceinline__ uint32_t acc_u4(uint32_t m, const uint4& a) {
return bmx_xa(m, bmx_xa(bmx_xa(a.x, a.y), bmx_xa(a.z, a.w)));
}
__device__ __forceinline__ uint32_t amax_fin(uint32_t m) { return fold2(m & 0x7fff7fffu) << 16; }
// (scalar cvt_e2m1x4 / enc8 encoder removed: every quant path uses the packed enc8x2 below)
// ---- 256-bit global loads (sm_100: ld.global.v8.b32), one 16-element item per instruction ----
// L1::no_allocate (pure streaming, no L1 reuse); L2 policy: evict_last (amax pass, the bytes the
// quantize pass re-reads soon), evict_first (quantize pass: last use of x). Non-volatile asm so the
// compiler can batch several independent loads before their use. x must be 32-byte aligned
// (checked on the host -> `al32`; otherwise two 16-byte loads are used).
#define LD_V8(HINT) \
asm("ld.global.nc.L1::no_allocate." HINT ".v8.b32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];" \
: "=r"(a.x), "=r"(a.y), "=r"(a.z), "=r"(a.w), "=r"(b.x), "=r"(b.y), "=r"(b.z), "=r"(b.w) \
: "l"(p))
__device__ __forceinline__ void ld_item_last(const uint4* x, int t, bool al32, uint4& a, uint4& b) {
const uint4* p = x + 2 * (size_t)t;
if (al32) { LD_V8("L2::evict_last"); }
else { a = __ldg(p); b = __ldg(p + 1); }
}
__device__ __forceinline__ void ld_item_norm(const uint4* x, int t, bool al32, uint4& a, uint4& b) {
const uint4* p = x + 2 * (size_t)t;
if (al32) { LD_V8("L2::evict_normal"); }
else { a = __ldg(p); b = __ldg(p + 1); }
}
__device__ __forceinline__ void ld_item_first(const uint4* x, int t, bool al32, uint4& a, uint4& b) {
const uint4* p = x + 2 * (size_t)t;
if (al32) { LD_V8("L2::evict_first"); }
else { a = __ldcs(p); b = __ldcs(p + 1); }
}
// volatile variant (evict_first): not reordered across the grid-barrier spin (volatile asm)
__device__ __forceinline__ void ld_item_first_v(const uint4* x, int t, bool al32, uint4& a, uint4& b) {
const uint4* p = x + 2 * (size_t)t;
if (al32) {
asm volatile("ld.global.nc.L1::no_allocate.L2::evict_first.v8.b32 {%0,%1,%2,%3,%4,%5,%6,%7}, [%8];"
: "=r"(a.x), "=r"(a.y), "=r"(a.z), "=r"(a.w), "=r"(b.x), "=r"(b.y), "=r"(b.z), "=r"(b.w)
: "l"(p));
} else {
asm volatile("ld.global.nc.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(a.x), "=r"(a.y), "=r"(a.z), "=r"(a.w) : "l"(p));
asm volatile("ld.global.nc.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(b.x), "=r"(b.y), "=r"(b.z), "=r"(b.w) : "l"(p + 1));
}
}
static long long g_evict_last_bytes = 40ll << 20;
void set_evict_last_mb(int mb) { g_evict_last_bytes = (long long)mb << 20; }
__device__ __forceinline__ uint32_t enc8x2(uint32_t w0, uint32_t w1, uint32_t w2, uint32_t w3,
float es) {
uint32_t r;
asm("{\n .reg .b64 s, p;\n .reg .b32 l, h;\n .reg .b8 c0, c1, c2, c3;\n"
" mov.b64 s, {%5, %5};\n"
" shl.b32 l, %1, 16; and.b32 h, %1, 0xffff0000; mov.b64 p, {l, h}; mul.rn.f32x2 p, p, s;"
" mov.b64 {l, h}, p; cvt.rn.satfinite.e2m1x2.f32 c0, h, l;\n"
" shl.b32 l, %2, 16; and.b32 h, %2, 0xffff0000; mov.b64 p, {l, h}; mul.rn.f32x2 p, p, s;"
" mov.b64 {l, h}, p; cvt.rn.satfinite.e2m1x2.f32 c1, h, l;\n"
" shl.b32 l, %3, 16; and.b32 h, %3, 0xffff0000; mov.b64 p, {l, h}; mul.rn.f32x2 p, p, s;"
" mov.b64 {l, h}, p; cvt.rn.satfinite.e2m1x2.f32 c2, h, l;\n"
" shl.b32 l, %4, 16; and.b32 h, %4, 0xffff0000; mov.b64 p, {l, h}; mul.rn.f32x2 p, p, s;"
" mov.b64 {l, h}, p; cvt.rn.satfinite.e2m1x2.f32 c3, h, l;\n"
" mov.b32 %0, {c0, c1, c2, c3};\n}"
: "=r"(r) : "r"(w0), "r"(w1), "r"(w2), "r"(w3), "f"(es));
return r;
}
#define ENC16_STEP(W, C) \
" shl.b32 l, " W ", 16; and.b32 h, " W ", 0xffff0000; mov.b64 p, {l, h}; mul.rn.f32x2 p, p, s;" \
" mov.b64 {l, h}, p; cvt.rn.satfinite.e2m1x2.f32 " C ", h, l;\n"
__device__ __forceinline__ uint2 enc16(const uint4& a, const uint4& b, float es) {
uint32_t r0, r1;
asm("{\n .reg .b64 s, p;\n .reg .b32 l, h;\n .reg .b8 c0, c1, c2, c3, c4, c5, c6, c7;\n"
" .reg .b16 q0, q1, q2, q3;\n"
" mov.b64 s, {%10, %10};\n"
ENC16_STEP("%2", "c0") ENC16_STEP("%3", "c1") ENC16_STEP("%4", "c2") ENC16_STEP("%5", "c3")
ENC16_STEP("%6", "c4") ENC16_STEP("%7", "c5") ENC16_STEP("%8", "c6") ENC16_STEP("%9", "c7")
" mov.b16 q0, {c0, c1};\n mov.b16 q1, {c2, c3};\n mov.b16 q2, {c4, c5};\n mov.b16 q3, {c6, c7};\n"
" mov.b32 %0, {q0, q1};\n mov.b32 %1, {q2, q3};\n}"
: "=r"(r0), "=r"(r1)
: "r"(a.x), "r"(a.y), "r"(a.z), "r"(a.w), "r"(b.x), "r"(b.y), "r"(b.z), "r"(b.w), "f"(es));
return make_uint2(r0, r1);
}
// quantize one 16-element item (v0,v1) and store payload + blocked scale.
// Instruction-count tuned (the quantize pass is issue-bound when x is L2-resident):
// * row/col of the scale via shift when sfk = K/16 is a power of two (uniform branch, hoisted);
// * es = rcp.rn(dsf * gd): the correctly rounded reciprocal == div.rn(1, y) bit for bit;
// * packed f32x2 multiplies in enc8x2.
// SL = true: payload + scale stores carry an L2 evict_last cache-policy (pol, createpolicy) so the
// quantized x of a chunk quantized while the previous chunk's GEMM runs stays L2-resident for its
// own GEMM (chunked large-M schedule, mode 8).
template <bool SL = false>
__device__ __forceinline__ void quant_item(int t, uint4 v0, uint4 v1, int sfk, int ncb, float ge,
float gd, uint8_t* __restrict__ xq,
uint8_t* __restrict__ xsf_blk, uint64_t pol = 0) {
const float bm = item_bm(v0, v1);
float ds = __fmul_rn(__fmul_rn(bm, 1.0f / 6.0f), ge);
// no explicit clamp: ds >= 0 and the SATFINITE E4M3 conversion below saturates to 448
// (incl. +inf) exactly like clamp-then-convert -> bit-identical, 2 fewer ops per item
__nv_fp8_storage_t s8 = __nv_cvt_float_to_fp8(ds, __NV_SATFINITE, __NV_E4M3);
__half_raw hr = __nv_cvt_fp8_to_halfraw(s8, __NV_E4M3);
const float dsf = __half2float(__half(hr));
const float es = fminf(__frcp_rn(__fmul_rn(dsf, gd)), FLT_MAX);
const uint32_t lo = enc8x2(v0.x, v0.y, v0.z, v0.w, es);
const uint32_t hi = enc8x2(v1.x, v1.y, v1.z, v1.w, es);
const bool p2 = (sfk & (sfk - 1)) == 0;
const int r = p2 ? (t >> (__ffs(sfk) - 1)) : t / sfk;
const int c = t - r * sfk;
if constexpr (SL) {
asm volatile("st.global.L2::cache_hint.v2.b32 [%0], {%1, %2}, %3;" ::"l"(
reinterpret_cast<uint2*>(xq) + t), "r"(lo), "r"(hi), "l"(pol) : "memory");
asm volatile("st.global.L2::cache_hint.b8 [%0], %1, %2;" ::"l"(xsf_blk + blk_off(r, c, ncb)),
"h"((unsigned short)s8), "l"(pol) : "memory");
} else {
reinterpret_cast<uint2*>(xq)[t] = make_uint2(lo, hi);
xsf_blk[blk_off(r, c, ncb)] = (uint8_t)s8;
}
}
// Split form of quant_item for the register-resident kernels: quant_pre() computes everything
// that does NOT depend on the global amax (item block max |x| as fp32 and the blocked scale byte
// offset) -- run inside the grid-barrier latency window -- and quant_post() does the remaining
// scale computation + multiply/convert/store after the barrier. Bit-identical to quant_item.
__device__ __forceinline__ void quant_pre(int t, uint4 v0, uint4 v1, int sfk, int ncb, float& bm,
uint32_t& soff) {
bm = item_bm(v0, v1);
const bool p2 = (sfk & (sfk - 1)) == 0;
const int r = p2 ? (t >> (__ffs(sfk) - 1)) : t / sfk;
const int c = t - r * sfk;
soff = blk_off(r, c, ncb);
}
// SL = true: xq / scale stores with L2 cache-policy pol (evict_last, see quant_item).
template <bool SL = false>
__device__ __forceinline__ void quant_post(int t, uint4 v0, uint4 v1, float bm, uint32_t soff,
float ge, float gd, uint8_t* __restrict__ xq,
uint8_t* __restrict__ xsf_blk, uint64_t pol = 0) {
float ds = __fmul_rn(__fmul_rn(bm, 1.0f / 6.0f), ge);
// no explicit clamp: ds >= 0 and the SATFINITE E4M3 conversion below saturates to 448
// (incl. +inf) exactly like clamp-then-convert -> bit-identical, 2 fewer ops per item
__nv_fp8_storage_t s8 = __nv_cvt_float_to_fp8(ds, __NV_SATFINITE, __NV_E4M3);
__half_raw hr = __nv_cvt_fp8_to_halfraw(s8, __NV_E4M3);
const float dsf = __half2float(__half(hr));
const float es = fminf(__frcp_rn(__fmul_rn(dsf, gd)), FLT_MAX);
const uint32_t lo = enc8x2(v0.x, v0.y, v0.z, v0.w, es);
const uint32_t hi = enc8x2(v1.x, v1.y, v1.z, v1.w, es);
if constexpr (SL) {
asm volatile("st.global.L2::cache_hint.v2.b32 [%0], {%1, %2}, %3;" ::"l"(
reinterpret_cast<uint2*>(xq) + t), "r"(lo), "r"(hi), "l"(pol) : "memory");
asm volatile("st.global.L2::cache_hint.b8 [%0], %1, %2;" ::"l"(xsf_blk + soff),
"h"((unsigned short)s8), "l"(pol) : "memory");
} else {
reinterpret_cast<uint2*>(xq)[t] = make_uint2(lo, hi);
xsf_blk[soff] = (uint8_t)s8;
}
}
// SL = true: xq / scale stores with L2 cache-policy pol (as quant_post<true>).
template <bool SL = false>
__device__ __forceinline__ void quant_post_pair(int t0, int t1, uint4 a0, uint4 a1, uint4 b0, uint4 b1,
float bm0, float bm1, uint32_t so0, uint32_t so1,
bool ok0, bool ok1, float ge, float gd,
uint8_t* __restrict__ xq, uint8_t* __restrict__ xsf_blk,
uint64_t pol = 0) {
// packed f32x2 scale chain: (bm * (1/6)) * ge for both items with two mul.rn.f32x2 (same IEEE RN
// product per lane as the scalar __fmul_rn chain -> bit-identical)
float ds0, ds1;
asm("{\n .reg .b64 v, c;\n mov.b64 v, {%2, %3};\n mov.b64 c, {%4, %4};\n mul.rn.f32x2 v, v, c;\n"
" mov.b64 c, {%5, %5};\n mul.rn.f32x2 v, v, c;\n mov.b64 {%0, %1}, v;\n}"
: "=f"(ds0), "=f"(ds1) : "f"(bm0), "f"(bm1), "f"(1.0f / 6.0f), "f"(ge));
uint32_t h2;
unsigned short q;
// e4m3x2: first source -> upper byte, second -> lower byte (lower = item 0)
asm("{\n .reg .b16 qq;\n cvt.rn.satfinite.e4m3x2.f32 qq, %2, %3;\n"
" cvt.rn.f16x2.e4m3x2 %0, qq;\n mov.b16 %1, qq;\n}"
: "=r"(h2), "=h"(q) : "f"(ds1), "f"(ds0));
const float dsf0 = __half2float(__ushort_as_half((unsigned short)(h2 & 0xffffu)));
const float dsf1 = __half2float(__ushort_as_half((unsigned short)(h2 >> 16)));
float p0, p1; // dsf * gd for both items, one packed mul.rn.f32x2 (bit-identical to scalar)
asm("{\n .reg .b64 v, c;\n mov.b64 v, {%2, %3};\n mov.b64 c, {%4, %4};\n mul.rn.f32x2 v, v, c;\n"
" mov.b64 {%0, %1}, v;\n}"
: "=f"(p0), "=f"(p1) : "f"(dsf0), "f"(dsf1), "f"(gd));
const float es0 = fminf(__frcp_rn(p0), FLT_MAX);
const float es1 = fminf(__frcp_rn(p1), FLT_MAX);
auto st = [&](int t, uint32_t so, uint32_t lo, uint32_t hi, unsigned short sb) {
if constexpr (SL) {
asm volatile("st.global.L2::cache_hint.v2.b32 [%0], {%1, %2}, %3;" ::"l"(
reinterpret_cast<uint2*>(xq) + t), "r"(lo), "r"(hi), "l"(pol) : "memory");
asm volatile("st.global.L2::cache_hint.b8 [%0], %1, %2;" ::"l"(xsf_blk + so), "h"(sb), "l"(pol)
: "memory");
} else {
reinterpret_cast<uint2*>(xq)[t] = make_uint2(lo, hi);
xsf_blk[so] = (uint8_t)sb;
}
};
if (ok0) { const uint2 e = enc16(a0, a1, es0); st(t0, so0, e.x, e.y, (unsigned short)(q & 0xffu)); }
if (ok1) { const uint2 e = enc16(b0, b1, es1); st(t1, so1, e.x, e.y, (unsigned short)(q >> 8)); }
}
// block max of per-thread u32 values (float bits >= 0): warp redux + one smem round.
// Result valid in thread 0 only.
template <int NT = kThreads>
__device__ __forceinline__ uint32_t block_max_u32(uint32_t v, uint32_t* sm) {
v = __reduce_max_sync(0xffffffffu, v);
if ((threadIdx.x & 31) == 0) sm[threadIdx.x >> 5] = v;
__syncthreads();
if (threadIdx.x == 0) {
#pragma unroll
for (int w = 1; w < NT / 32; ++w) v = max(v, sm[w]);
}
return v;
}
// grid barrier fused with the global amax reduction (see file header). Called by ALL threads
// (thread 0 holds the block max `bmax`); returns the global amax bits in every thread.
// sync_ws layout: [0..1] = u64 arrival counter, [2], [3] = u32 amax slots (epoch parity),
// [6], [7] = u32 pass-2 tile counters of fused_quant_kernel (epoch parity; [4] = amax_out).
// Epoch of this launch, read by thread 0 at KERNEL ENTRY (its latency hides under the x loads):
// the previous launch on this counter is complete (stream order) and no CTA of this launch can
// pass the barrier before all G CTAs arrived, so ctr / G is this launch's epoch at any time
// before this CTA's own arrival.
__device__ __forceinline__ unsigned long long grid_epoch(const float* sync_ws) {
unsigned long long c0 = 0;
if (threadIdx.x == 0)
asm volatile("ld.relaxed.gpu.global.u64 %0, [%1];" : "=l"(c0) : "l"(sync_ws) : "memory");
return c0 / gridDim.x;
}
// Arrival is fire-and-forget: red.relaxed max into the amax slot, then red.release add on the
// counter (release orders the max before the arrival; no returned values -> the last arriver's
// critical path is no longer 3 dependent L2 round trips + membar). Waiters ld.acquire-spin.
__device__ __forceinline__ uint32_t grid_amax(uint32_t bmax, float* sync_ws, uint32_t* sm,
unsigned long long e) {
unsigned long long* ctr = reinterpret_cast<unsigned long long*>(sync_ws);
unsigned int* slots = reinterpret_cast<unsigned int*>(sync_ws) + 2;
if (threadIdx.x == 0) {
const unsigned long long G = gridDim.x;
asm volatile("red.relaxed.gpu.global.max.u32 [%0], %1;" ::"l"(slots + (e & 1)), "r"(bmax)
: "memory");
asm volatile("red.release.gpu.global.add.u64 [%0], %1;" ::"l"(ctr), "l"(1ull) : "memory");
const unsigned long long target = (e + 1) * G;
unsigned long long c;
do {
asm volatile("ld.acquire.gpu.global.u64 %0, [%1];" : "=l"(c) : "l"(ctr) : "memory");
} while (c < target);
uint32_t a;
asm volatile("ld.relaxed.gpu.global.u32 %0, [%1];" : "=r"(a) : "l"(slots + (e & 1)) : "memory");
sm[0] = a;
// nobody uses slot (e+1)&1 during this launch: reset it for the next launch
if (blockIdx.x == 0) slots[(e + 1) & 1] = 0u;
}
__syncthreads();
return sm[0];
}
// Split form of grid_amax (same protocol / counters): grid_arrive() = thread 0's fire-and-forget
// amax red + release arrival; grid_wait() = thread 0's acquire-spin + slot read + reset, then a CTA
// barrier; returns the global amax bits in every thread. Independent work (the weight-scale
// re-layout) can run between the two calls, i.e. inside the barrier latency window.
__device__ __forceinline__ void grid_arrive(uint32_t bmax, float* sync_ws, unsigned long long e) {
unsigned long long* ctr = reinterpret_cast<unsigned long long*>(sync_ws);
unsigned int* slots = reinterpret_cast<unsigned int*>(sync_ws) + 2;
if (threadIdx.x == 0) {
asm volatile("red.relaxed.gpu.global.max.u32 [%0], %1;" ::"l"(slots + (e & 1)), "r"(bmax)
: "memory");
asm volatile("red.release.gpu.global.add.u64 [%0], %1;" ::"l"(ctr), "l"(1ull) : "memory");
}
}
__device__ __forceinline__ uint32_t grid_wait(float* sync_ws, uint32_t* sm, unsigned long long e) {
unsigned long long* ctr = reinterpret_cast<unsigned long long*>(sync_ws);
unsigned int* slots = reinterpret_cast<unsigned int*>(sync_ws) + 2;
if (threadIdx.x == 0) {
const unsigned long long target = (e + 1) * (unsigned long long)gridDim.x;
// ONE-ROUND-TRIP exit: the u64 counter (bytes 0..7) and both u32 amax slots (bytes 8..15)
// share one naturally aligned 16-byte word (every sync_ws block is 16 B aligned) inside one
// L2 sector, so each poll is a single 16 B acquire vector load returning counter + slots
// together. The arrivers' red.max on the slot is ordered before their red.release.add on the
// counter at the same L2 sector, so the load that observes the final count also carries the
// final max -> the former dependent slot load after the spin (one extra loaded L2 round trip
// on every CTA's barrier exit) is gone. Same values, deterministic.
unsigned long long c, sv;
do {
asm volatile("ld.acquire.gpu.global.v2.u64 {%0, %1}, [%2];" : "=l"(c), "=l"(sv) : "l"(ctr) : "memory");
} while (c < target);
const uint32_t a = (e & 1) ? (uint32_t)(sv >> 32) : (uint32_t)(sv & 0xffffffffull);
sm[0] = a;
if (blockIdx.x == 0) slots[(e + 1) & 1] = 0u;
}
__syncthreads();
return sm[0];
}
__device__ __forceinline__ uint32_t grid_wait_bo(float* sync_ws, uint32_t* sm, unsigned long long e) {
unsigned long long* ctr = reinterpret_cast<unsigned long long*>(sync_ws);
unsigned int* slots = reinterpret_cast<unsigned int*>(sync_ws) + 2;
if (threadIdx.x == 0) {
const unsigned long long target = (e + 1) * (unsigned long long)gridDim.x;
unsigned long long c, sv;
for (;;) {
asm volatile("ld.acquire.gpu.global.v2.u64 {%0, %1}, [%2];" : "=l"(c), "=l"(sv) : "l"(ctr) : "memory");
if (c >= target) break;
__nanosleep(64);
}
const uint32_t a = (e & 1) ? (uint32_t)(sv >> 32) : (uint32_t)(sv & 0xffffffffull);
sm[0] = a;
if (blockIdx.x == 0) slots[(e + 1) & 1] = 0u;
}
__syncthreads();
return sm[0];
}
__device__ __forceinline__ uint32_t grid_wait_dbo(float* sync_ws, uint32_t* sm, unsigned long long e) {
unsigned long long* ctr = reinterpret_cast<unsigned long long*>(sync_ws);
unsigned int* slots = reinterpret_cast<unsigned int*>(sync_ws) + 2;
if (threadIdx.x == 0) {
const unsigned long long target = (e + 1) * (unsigned long long)gridDim.x;
unsigned long long c, sv;
const long long t0 = clock64();
bool slow = false;
for (;;) {
asm volatile("ld.acquire.gpu.global.v2.u64 {%0, %1}, [%2];" : "=l"(c), "=l"(sv) : "l"(ctr) : "memory");
if (c >= target) break;
if (!slow) slow = (clock64() - t0) > 1900;
if (slow) __nanosleep(32);
}
const uint32_t a = (e & 1) ? (uint32_t)(sv >> 32) : (uint32_t)(sv & 0xffffffffull);
sm[0] = a;
if (blockIdx.x == 0) slots[(e + 1) & 1] = 0u;
}
__syncthreads();
return sm[0];
}
// weight-scale re-layout (row-major N x sfk bytes -> blocked), only for the cuBLASLt path.
// One unit = (128-row tile rb, row r32, 4-col group cb): 4 coalesced u32 loads -> one 16 B store.
// N == 0 -> no work (custom GEMM path reads the raw layout directly).
__device__ __forceinline__ void swizzle_wsf(const uint32_t* __restrict__ wsf,
uint8_t* __restrict__ wsf_blk, int N, int ncb) {
const int units = (N >> 2) * ncb; // (N/128) * 32 * ncb
const int G = gridDim.x;
for (int u = blockIdx.x * kThreads + threadIdx.x; u < units; u += G * kThreads) {
const int cb = u % ncb;
const int rr = u / ncb; // rb*32 + r32
const int rb = rr >> 5, r32 = rr & 31;
const int row0 = rb * 128 + r32;
uint4 o;
o.x = __ldg(wsf + (row0)*ncb + cb);
o.y = __ldg(wsf + (row0 + 32) * ncb + cb);
o.z = __ldg(wsf + (row0 + 64) * ncb + cb);
o.w = __ldg(wsf + (row0 + 96) * ncb + cb);
*reinterpret_cast<uint4*>(wsf_blk + ((uint32_t)rb * ncb + cb) * 512u + r32 * 16) = o;
}
}
// Latency-hidden variant of swizzle_wsf: the first U units of this thread are LOADED into
// registers at kernel start (together with the x loads, so the weight-scale DRAM latency
// overlaps the amax loads instead of sitting serially between the amax pass and the grid
// barrier); wsf_store<U>() later stores them and handles any remaining units with the plain
// grid-stride loop. Same mapping / output bytes as swizzle_wsf.
template <int U>
struct WsfPre { uint4 v[U]; };
__device__ __forceinline__ void wsf_unit(int u, int ncb, int& row0, int& cb, uint32_t& dst) {
cb = u % ncb;
const int rr = u / ncb;
const int rb = rr >> 5, r32 = rr & 31;
row0 = rb * 128 + r32;
dst = ((uint32_t)rb * ncb + cb) * 512u + r32 * 16;
}
template <int U, int NT = kThreads>
__device__ __forceinline__ void wsf_load(const uint32_t* __restrict__ wsf, int N, int ncb,
WsfPre<U>& p) {
const int units = (N >> 2) * ncb;
const int S = gridDim.x * NT;
const int u0 = blockIdx.x * NT + threadIdx.x;
#pragma unroll
for (int j = 0; j < U; ++j) {
const int u = u0 + j * S;
if (u < units) {
int row0, cb; uint32_t dst;
wsf_unit(u, ncb, row0, cb, dst);
p.v[j].x = __ldg(wsf + (row0)*ncb + cb);
p.v[j].y = __ldg(wsf + (row0 + 32) * ncb + cb);
p.v[j].z = __ldg(wsf + (row0 + 64) * ncb + cb);
p.v[j].w = __ldg(wsf + (row0 + 96) * ncb + cb);
}
}
}
template <int U, int NT = kThreads>
__device__ __forceinline__ void wsf_store(const uint32_t* __restrict__ wsf,
uint8_t* __restrict__ wsf_blk, int N, int ncb,
const WsfPre<U>& p) {
const int units = (N >> 2) * ncb;
const int S = gridDim.x * NT;
const int u0 = blockIdx.x * NT + threadIdx.x;
#pragma unroll
for (int j = 0; j < U; ++j) {
const int u = u0 + j * S;
if (u < units) {
int row0, cb; uint32_t dst;
wsf_unit(u, ncb, row0, cb, dst);
*reinterpret_cast<uint4*>(wsf_blk + dst) = p.v[j];
}
}
for (int u = u0 + U * S; u < units; u += S) { // leftover units (small grids only)
int row0, cb; uint32_t dst;
wsf_unit(u, ncb, row0, cb, dst);
uint4 o;
o.x = __ldg(wsf + (row0)*ncb + cb);
o.y = __ldg(wsf + (row0 + 32) * ncb + cb);
o.z = __ldg(wsf + (row0 + 64) * ncb + cb);
o.w = __ldg(wsf + (row0 + 96) * ncb + cb);
*reinterpret_cast<uint4*>(wsf_blk + dst) = o;
}
}
__device__ __forceinline__ uint32_t u4cw(const uint4& v, int k) {
return k == 0 ? v.x : (k == 1 ? v.y : (k == 2 ? v.z : v.w));
}
// Coalesced weight-scale re-layout (same output bytes as swizzle_wsf / wsf_store): one thread unit
// = (128-row tile rb, row r32 = lane, group of 4 scale-column groups cb4). The lane loads 16 B
// from each of its 4 rows r32 + 32j, then writes 4 blocked 16 B words;
// for each word the 32 lanes of a warp store one CONTIGUOUS 512 B tile (fully coalesced; the
// old mapping wrote 16 B per lane at a 512 B stride = 32 half-filled sectors per instruction).
// (ncb % 4 == 0 always: K % 64 == 0.) One unit per thread at the mid-M grids (65536 units).
template <int NT = kThreads>
__device__ __forceinline__ void wsf_relayout_c(const uint32_t* __restrict__ wsf,
uint8_t* __restrict__ wsf_blk, int N, int ncb) {
const int units = (N >> 7) * ncb * 8; // (rb, cb4, r32): N/128 * ncb/4 * 32
const uint8_t* src = reinterpret_cast<const uint8_t*>(wsf);
const int sfk = ncb * 4; // bytes per weight-scale row
const int ng = ncb >> 2; // 4-group columns per row
for (int u = blockIdx.x * NT + threadIdx.x; u < units; u += gridDim.x * NT) {
const int r32 = u & 31, w = u >> 5;
const int cb4 = w % ng, rb = w / ng;
uint4 v[4];
#pragma unroll
for (int j = 0; j < 4; ++j)
v[j] = __ldg(reinterpret_cast<const uint4*>(src + (size_t)(rb * 128 + r32 + 32 * j) * sfk + cb4 * 16));
uint8_t* dbase = wsf_blk + ((size_t)rb * ncb + cb4 * 4) * 512 + r32 * 16;
#pragma unroll
for (int c = 0; c < 4; ++c)
*reinterpret_cast<uint4*>(dbase + (size_t)c * 512) =
make_uint4(u4cw(v[0], c), u4cw(v[1], c), u4cw(v[2], c), u4cw(v[3], c));
}
}
template <int NT = kThreads, int Q = 1>
__device__ __forceinline__ void wsf_relayout_lo(const uint32_t* __restrict__ wsf,
uint8_t* __restrict__ wsf_blk, int N, int ncb) {
constexpr int CH = Q * NT;
const int units = (N >> 7) * ncb * 8;
const uint8_t* src = reinterpret_cast<const uint8_t*>(wsf);
const int sfk = ncb * 4, ng = ncb >> 2;
for (int c0 = blockIdx.x * CH; c0 < units; c0 += gridDim.x * CH) {
uint4 v[Q][4];
#pragma unroll
for (int q = 0; q < Q; ++q) {
const int u = c0 + q * NT + threadIdx.x;
if (u < units) {
const int r32 = u & 31, w = u >> 5;
const int cb4 = w % ng, rb = w / ng;
#pragma unroll
for (int j = 0; j < 4; ++j)
v[q][j] = __ldg(reinterpret_cast<const uint4*>(src + (size_t)(rb * 128 + r32 + 32 * j) * sfk + cb4 * 16));
}
}
#pragma unroll
for (int q = 0; q < Q; ++q) {
const int u = c0 + q * NT + threadIdx.x;
if (u < units) {
const int r32 = u & 31, w = u >> 5;
const int cb4 = w % ng, rb = w / ng;
uint8_t* dbase = wsf_blk + ((size_t)rb * ncb + cb4 * 4) * 512 + r32 * 16;
#pragma unroll
for (int c = 0; c < 4; ++c)
*reinterpret_cast<uint4*>(dbase + (size_t)c * 512) =
make_uint4(u4cw(v[q][0], c), u4cw(v[q][1], c), u4cw(v[q][2], c), u4cw(v[q][3], c));
}
}
}
}
template <int NT = kThreads>
__device__ __forceinline__ void wsf_relayout_w(const uint32_t* __restrict__ wsf,
uint8_t* __restrict__ wsf_blk, int N, int ncb) {
if (ncb & 7) { wsf_relayout_c<NT>(wsf, wsf_blk, N, ncb); return; }
const int ng8 = ncb >> 3;
const int nwu = (N >> 7) * ng8;
const uint8_t* src = reinterpret_cast<const uint8_t*>(wsf);
const int sfk = ncb * 4;
const int warp = threadIdx.x >> 5, r32 = threadIdx.x & 31;
const int G = gridDim.x;
for (int wu = warp * G + blockIdx.x; wu < nwu; wu += (NT / 32) * G) {
const int rb = wu / ng8, cb8 = wu - rb * ng8;
uint4 v[4][2];
#pragma unroll
for (int j = 0; j < 4; ++j) {
const uint4* q = reinterpret_cast<const uint4*>(src + (size_t)(rb * 128 + r32 + 32 * j) * sfk + cb8 * 32);
v[j][0] = __ldg(q);
v[j][1] = __ldg(q + 1);
}
uint8_t* dbase = wsf_blk + ((size_t)rb * ncb + cb8 * 8) * 512 + r32 * 16;
#pragma unroll
for (int c = 0; c < 8; ++c)
*reinterpret_cast<uint4*>(dbase + (size_t)c * 512) =
make_uint4(u4cw(v[0][c >> 2], c & 3), u4cw(v[1][c >> 2], c & 3),
u4cw(v[2][c >> 2], c & 3), u4cw(v[3][c >> 2], c & 3));
}
}
// LOW-INDEX warp-spread variant of wsf_relayout_w (same unit code / output bytes): warp unit
// wu = blockIdx.x * (NT/32) + warp, i.e. only the lowest nwu/(NT/32) CTAs carry re-layout work;
// the high-index CTAs (latest grid-barrier arrivals) go straight from their arrival to the wait.
template <int NT = kThreads>
__device__ __forceinline__ void wsf_relayout_wlo(const uint32_t* __restrict__ wsf,
uint8_t* __restrict__ wsf_blk, int N, int ncb) {
if (ncb & 7) { wsf_relayout_c<NT>(wsf, wsf_blk, N, ncb); return; }
const int ng8 = ncb >> 3;
const int nwu = (N >> 7) * ng8;
const uint8_t* src = reinterpret_cast<const uint8_t*>(wsf);
const int sfk = ncb * 4;
const int warp = threadIdx.x >> 5, r32 = threadIdx.x & 31;
for (int wu = blockIdx.x * (NT / 32) + warp; wu < nwu; wu += (NT / 32) * gridDim.x) {
const int rb = wu / ng8, cb8 = wu - rb * ng8;
uint4 v[4][2];
#pragma unroll
for (int j = 0; j < 4; ++j) {
const uint4* q = reinterpret_cast<const uint4*>(src + (size_t)(rb * 128 + r32 + 32 * j) * sfk + cb8 * 32);
v[j][0] = __ldg(q);
v[j][1] = __ldg(q + 1);
}
uint8_t* dbase = wsf_blk + ((size_t)rb * ncb + cb8 * 8) * 512 + r32 * 16;
#pragma unroll
for (int c = 0; c < 8; ++c)
*reinterpret_cast<uint4*>(dbase + (size_t)c * 512) =
make_uint4(u4cw(v[0][c >> 2], c & 3), u4cw(v[1][c >> 2], c & 3),
u4cw(v[2][c >> 2], c & 3), u4cw(v[3][c >> 2], c & 3));
}
}
// PADDED weight-scale re-layout for the CUTLASS 256x224 tile configs (cutlass_gemm_h.cu): same
// 128x4 blocked format, but over a VIRTUAL row space where N-tile t (224 weight rows) occupies
// virtual rows [256t, 256t + 224): virtual 128-row block vb = 2t + h holds real rows
// 224t + 128h + r for r < (h ? 96 : 128) (and < N). The 32 padding rows per tile are never written
// (the buffer is zero-initialised once -> finite zero scales). Unit = (vb, cb4, r32) as in
// wsf_relayout_c: 4 x 16 B loads (rows r32 + 32j), 4 coalesced 16 B blocked stores.
template <int NT = kThreads>
__device__ __forceinline__ void wsf_relayout_pad(const uint32_t* __restrict__ wsf,
uint8_t* __restrict__ wsf_blk, int N, int ncb) {
if (N & (1 << 29)) {
// 256x112 tile variant (flag bit 29): N-tile t (112 weight rows) occupies virtual 128-row
// block t (virtual rows [128t, 128t+112)); rows 112..127 of each block stay zero (never
// written, buffer zero-initialised once). Unit = (tile t, cb4, r32) as wsf_relayout_c.
N &= ~(1 << 29);
const int T112 = (N + 111) / 112;
const int ng2 = ncb >> 2;
const int units2 = T112 * ng2 * 32;
const uint8_t* src2 = reinterpret_cast<const uint8_t*>(wsf);
const int sfk2 = ncb * 4;
for (int u = blockIdx.x * NT + threadIdx.x; u < units2; u += gridDim.x * NT) {
const int r32 = u & 31, w = u >> 5;
const int t = w / ng2, cb4 = w - t * ng2;
const int n0 = 112 * t;
const int lim = min(112, N - n0);
const uint8_t* p = src2 + (size_t)(n0 + r32) * sfk2 + cb4 * 16;
uint4 v[4];
#pragma unroll
for (int j = 0; j < 4; ++j) {
v[j] = make_uint4(0, 0, 0, 0);
if (r32 + 32 * j < lim) v[j] = __ldg(reinterpret_cast<const uint4*>(p + (size_t)j * 32 * sfk2));
}
uint4* d = reinterpret_cast<uint4*>(wsf_blk + ((size_t)t * ncb + cb4 * 4) * 512 + r32 * 16);
d[0] = make_uint4(v[0].x, v[1].x, v[2].x, v[3].x);
d[32] = make_uint4(v[0].y, v[1].y, v[2].y, v[3].y);
d[64] = make_uint4(v[0].z, v[1].z, v[2].z, v[3].z);
d[96] = make_uint4(v[0].w, v[1].w, v[2].w, v[3].w);
}
return;
}
// LIVE virtual blocks only: when the last N-tile has <= 128 real rows, its second virtual
// 128-row block (h = 1) lies entirely beyond N -> its units would load nothing and store only
// zeros over bytes that are already zero (buffer zero-initialised once, padding never written
// nonzero). Those trailing dead units are dropped from the grid-stride range (same output bytes).
const int T224 = (N + 223) / 224;
const int VB = 2 * T224 - ((N - 224 * (T224 - 1)) <= 128 ? 1 : 0);
const int ng = ncb >> 2;
const int units = VB * ng * 32;
const uint8_t* src = reinterpret_cast<const uint8_t*>(wsf);
const int sfk = ncb * 4;
// DIET (same unit mapping, same per-row guarded loads issued in the same order, same 16 B stores
// -> bit-identical): ng = ncb/4 power of two (K = 8192: 32) -> cb4 / vb by mask / shift (uniform
// branch); row guard folded into ONE per-unit limit lim = min(nrow, N - n0); source pointer
// strength-reduced (+32 rows per group). The blocked 16 B word c of lane r32 is
// {row r32 word c, row r32+32 word c, ...}: a 4x4 transpose at 32-bit granularity (each source
// word already holds the 4 consecutive scale bytes of one 4-column group), i.e. register
// renaming only -- no byte permutes are needed for this layout.
const bool ngp2 = (ng & (ng - 1)) == 0;
const int ngs = __ffs(ng) - 1;
const size_t rstride32 = (size_t)32 * sfk;
for (int u = blockIdx.x * NT + threadIdx.x; u < units; u += gridDim.x * NT) {
const int r32 = u & 31, w = u >> 5;
const int vb = ngp2 ? (w >> ngs) : w / ng;
const int cb4 = w - vb * ng;
const int h = vb & 1;
const int n0 = 224 * (vb >> 1) + 128 * h;
const int lim = min(h ? 96 : 128, N - n0);
const uint8_t* p = src + (size_t)(n0 + r32) * sfk + cb4 * 16;
uint4 v[4];
#pragma unroll
for (int j = 0; j < 4; ++j) {
v[j] = make_uint4(0, 0, 0, 0);
if (r32 + 32 * j < lim) v[j] = __ldg(reinterpret_cast<const uint4*>(p + j * rstride32));
}
// a 32-row group j is either fully inside the tile or fully padding (96 = 3 x 32)
uint4* d = reinterpret_cast<uint4*>(wsf_blk + ((size_t)vb * ncb + cb4 * 4) * 512 + r32 * 16);
d[0] = make_uint4(v[0].x, v[1].x, v[2].x, v[3].x);
d[32] = make_uint4(v[0].y, v[1].y, v[2].y, v[3].y);
d[64] = make_uint4(v[0].z, v[1].z, v[2].z, v[3].z);
d[96] = make_uint4(v[0].w, v[1].w, v[2].w, v[3].w);
}
}
// BATCHED form of wsf_relayout_pad (224 tiles, no bit 29): each thread issues the guarded loads of
// its units u0 and u0 + S together, then stores both (one DRAM round trip instead of two when the
// grid has fewer threads than units). Same unit mapping / bytes -> bit-identical.
template <int NT = kThreads>
__device__ __forceinline__ void wsf_relayout_pad2(const uint32_t* __restrict__ wsf,
uint8_t* __restrict__ wsf_blk, int N, int ncb) {
if (N & (1 << 29)) { wsf_relayout_pad<NT>(wsf, wsf_blk, N, ncb); return; }
const int T224 = (N + 223) / 224;
const int VB = 2 * T224 - ((N - 224 * (T224 - 1)) <= 128 ? 1 : 0);
const int ng = ncb >> 2;
const int units = VB * ng * 32;
const uint8_t* src = reinterpret_cast<const uint8_t*>(wsf);
const int sfk = ncb * 4;
const size_t rstride32 = (size_t)32 * sfk;
auto unit_ld = [&](int u, uint4 (&v)[4], uint4*& d) {
const int r32 = u & 31, w = u >> 5;
const int vb = w / ng;
const int cb4 = w - vb * ng;
const int h = vb & 1;
const int n0 = 224 * (vb >> 1) + 128 * h;
const int lim = min(h ? 96 : 128, N - n0);
const uint8_t* p = src + (size_t)(n0 + r32) * sfk + cb4 * 16;
#pragma unroll
for (int j = 0; j < 4; ++j) {
v[j] = make_uint4(0, 0, 0, 0);
if (r32 + 32 * j < lim) v[j] = __ldg(reinterpret_cast<const uint4*>(p + j * rstride32));
}
d = reinterpret_cast<uint4*>(wsf_blk + ((size_t)vb * ncb + cb4 * 4) * 512 + r32 * 16);
};
auto unit_st = [&](const uint4 (&v)[4], uint4* d) {
d[0] = make_uint4(v[0].x, v[1].x, v[2].x, v[3].x);
d[32] = make_uint4(v[0].y, v[1].y, v[2].y, v[3].y);
d[64] = make_uint4(v[0].z, v[1].z, v[2].z, v[3].z);
d[96] = make_uint4(v[0].w, v[1].w, v[2].w, v[3].w);
};
const int S = gridDim.x * NT;
for (int u = blockIdx.x * NT + threadIdx.x; u < units; u += 2 * S) {
uint4 a[4], b[4];
uint4 *da = nullptr, *db = nullptr;
unit_ld(u, a, da);
const bool two = u + S < units;
if (two) unit_ld(u + S, b, db);
unit_st(a, da);
if (two) unit_st(b, db);
}
}
template <int NT, class F>
__device__ __forceinline__ void wsf_relayout_pad_ovl(const uint32_t* __restrict__ wsf,
uint8_t* __restrict__ wsf_blk, int N, int ncb,
F&& mid) {
const int T224 = (N + 223) / 224;
const int VB = 2 * T224 - ((N - 224 * (T224 - 1)) <= 128 ? 1 : 0);
const int ng = ncb >> 2;
const int units = VB * ng * 32;
const uint8_t* src = reinterpret_cast<const uint8_t*>(wsf);
const int sfk = ncb * 4;
const bool ngp2 = (ng & (ng - 1)) == 0;
const int ngs = __ffs(ng) - 1;
const size_t rstride32 = (size_t)32 * sfk;
auto unit_ld = [&](int u, uint4 (&v)[4], uint4*& d) {
const int r32 = u & 31, w = u >> 5;
const int vb = ngp2 ? (w >> ngs) : w / ng;
const int cb4 = w - vb * ng;
const int h = vb & 1;
const int n0 = 224 * (vb >> 1) + 128 * h;
const int lim = min(h ? 96 : 128, N - n0);
const uint8_t* p = src + (size_t)(n0 + r32) * sfk + cb4 * 16;
#pragma unroll
for (int j = 0; j < 4; ++j) {
v[j] = make_uint4(0, 0, 0, 0);
if (r32 + 32 * j < lim) v[j] = __ldg(reinterpret_cast<const uint4*>(p + j * rstride32));
}
d = reinterpret_cast<uint4*>(wsf_blk + ((size_t)vb * ncb + cb4 * 4) * 512 + r32 * 16);
};
auto unit_st = [&](const uint4 (&v)[4], uint4* d) {
d[0] = make_uint4(v[0].x, v[1].x, v[2].x, v[3].x);
d[32] = make_uint4(v[0].y, v[1].y, v[2].y, v[3].y);
d[64] = make_uint4(v[0].z, v[1].z, v[2].z, v[3].z);
d[96] = make_uint4(v[0].w, v[1].w, v[2].w, v[3].w);
};
const int u0 = blockIdx.x * NT + threadIdx.x;
uint4 v[4];
uint4* d = nullptr;
if (u0 < units) unit_ld(u0, v, d);
mid();
if (u0 < units) unit_st(v, d);
for (int u = u0 + gridDim.x * NT; u < units; u += gridDim.x * NT) {
uint4 w4[4];
uint4* d2;
unit_ld(u, w4, d2);
unit_st(w4, d2);
}
}
// Late PDL trigger, used when the dependent GEMM is CUTLASS: its epilogue warps read alpha (ab[0])
// WITHOUT executing griddepcontrol.wait themselves, so the dependent grid must not launch before
// ab[0] is written. Block 0 thread 0 wrote ab[0] (global_scales) -> gpu-scope fence, then every
// CTA triggers after the grid barrier; the dependent launches only once ALL CTAs triggered.
// xq / scales are still read only after the CUTLASS producer's griddepcontrol.wait.
__device__ __forceinline__ void pdl_late_trigger() {
// (no __threadfence: every consumer of ab[0] / xq / scales -- CUTLASS producer + LazyAlpha leaf --
// executes griddepcontrol.wait, which waits for this grid's COMPLETION and makes all of its
// memory operations visible; the trigger itself carries no visibility guarantee, so a gpu-scope
// fence before it orders nothing any consumer relies on)
__syncthreads();
asm volatile("griddepcontrol.launch_dependents;" ::: "memory");
}
__device__ __forceinline__ void global_scales_nw(float amax, float& ge, float& gd) {
ge = __fdiv_rn(2688.0f, amax); // 448 * 6 / amax (inf -> clamp)
ge = fminf(ge, FLT_MAX);
if (ge == 0.0f) ge = 1.0f;
gd = __fdiv_rn(1.0f, ge);
}
__device__ __forceinline__ void global_scales(float amax, float w_gd, float* __restrict__ ab,
float& ge, float& gd) {
global_scales_nw(amax, ge, gd);
if (blockIdx.x == 0 && threadIdx.x == 0) { ab[0] = gd * w_gd; ab[1] = 0.0f; }
}
// cuBLASLt alpha vector (ALPHA_DEVICE_VECTOR_BETA_ZERO pointer mode, see main.cpp): n copies of
// alpha = gd * w_gd (same fp32 product as ab[0]); grid-stride over the whole quant grid.
// beta == 0 is then known to cuBLASLt at launch -> the epilogue never reads the C (= out) operand.
__device__ __forceinline__ void write_avec(float* avec, int n, float gd, float w_gd) {
if (avec == nullptr) return;
const float a = gd * w_gd;
for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) avec[i] = a;
}
// ---------------- FENCE-FREE SLOT grid barrier (register-resident quant, SP bit 64) ----------------
// sync block layout (this barrier's private block, >= 4 + 2*G floats): u32 launch tag counter at
// [0], u64 per-CTA arrival slots at [4 + 2b]. Arrival = ONE relaxed 64-bit store of
// (tag << 32 | CTA amax bits) into the CTA's own slot: the payload travels in the same
// single-copy-atomic word as the arrival flag, so NO release fence / ordered second atomic is
// needed (the former red.max + red.release.add pair made thread 0 wait for the SM's outstanding
// memory traffic before arriving). Waiters: every thread polls G/NT slots (ld.relaxed.gpu), the CTA
// agrees (__syncthreads_and) that every slot carries this launch's tag, and the max over the slot
// payloads is the global amax (max is order-independent -> bit-identical to the red.max slot).
// tag = counter + 1, read at entry by thread 0 (before this CTA's arrival); block 0 advances the
// counter after its barrier exit (every CTA read it before arriving); stream order guarantees the
// next launch starts after this one completes. Slots start zeroed (tag 0 never matches).
__device__ __forceinline__ uint32_t slot_tag_read(const float* sb) {
uint32_t c;
asm volatile("ld.relaxed.gpu.global.u32 %0, [%1];" : "=r"(c) : "l"(sb) : "memory");
return c + 1u;
}
__device__ __forceinline__ void slot_arrive(float* sb, uint32_t tag, uint32_t bmax) {
unsigned long long* sl = reinterpret_cast<unsigned long long*>(sb + 4);
const unsigned long long v = ((unsigned long long)tag << 32) | bmax;
asm volatile("st.relaxed.gpu.global.u64 [%0], %1;" ::"l"(sl + blockIdx.x), "l"(v) : "memory");
}
template <int NT>
__device__ __forceinline__ uint32_t slot_wait(float* sb, uint32_t tag, uint32_t* sm) {
const unsigned long long* sl = reinterpret_cast<const unsigned long long*>(sb + 4);
const int G = gridDim.x;
uint32_t mm;
for (;;) {
bool ok = true;
mm = 0;
for (int i = threadIdx.x; i < G; i += NT) {
unsigned long long v;
asm volatile("ld.relaxed.gpu.global.u64 %0, [%1];" : "=l"(v) : "l"(sl + i) : "memory");
ok = ok && (uint32_t)(v >> 32) == tag;
mm = max(mm, (uint32_t)v);
}
if (__syncthreads_and(ok)) break;
}
mm = __reduce_max_sync(0xffffffffu, mm);
if ((threadIdx.x & 31) == 0) sm[20 + (threadIdx.x >> 5)] = mm;
__syncthreads();
#pragma unroll
for (int w = 0; w < NT / 32; ++w) mm = max(mm, sm[20 + w]);
if (blockIdx.x == 0 && threadIdx.x == 0)
asm volatile("st.relaxed.gpu.global.u32 [%0], %1;" ::"l"(sb), "r"(tag) : "memory");
return mm;
}
// ---------------- register-resident variant (small/medium M) ----------------
// CTA b owns items [b*IPT*256, (b+1)*IPT*256); thread item j = base + j*256 + tid (coalesced).
// CV: carveout variant tag (separate instantiation; CV=1 is configured with the MAX shared-memory
// carveout so a PDL-launched GEMM CTA (~200 KB smem) can co-reside with quant CTAs and run its
// prologue + weight prefetch during the quant; CV=0 keeps the driver-default L1/smem split).
// NT: threads per CTA (256 default; 128 for the IPT 8 / 128-thread variant). Min CTAs/SM:
// IPT <= 4 or IPT == 6 -> 3 (IPT 6 = 3-CTA/SM variant), NT 128 -> 4, else 2.
// SP: compile-time PIN of the runtime plan knobs (-1 = all runtime). SP >= 0: bits 0-1 = the
// `late` bits (bit 0 late PDL trigger, bit 1 barrier poll backoff), bits 2-3 = weight-scale
// re-layout mode (0 none / N == 0, 1 padded N < 0, 3 plain N > 0), bit 4 = weight-prefix L2
// prefetch on (pf_ops > 0), bit 5 = no alpha vector (avec == nullptr). The host launches an SP
// instantiation only when the runtime values equal its constants -> same code path, bit-identical.
template <int IPT, int CV, int NT = kThreads, int SP = -1>
__global__ void __launch_bounds__(NT, (NT < kThreads) ? 4 : ((NT > kThreads) ? 2 : ((IPT <= 4 || IPT == 6) ? 3 : 2)))
fused_quant_res_kernel(const uint4* __restrict__ x, int M, int Mp, int K,
const uint32_t* __restrict__ wsf, uint8_t* __restrict__ wsf_blk, int N,
float w_gd, uint8_t* __restrict__ xq, uint8_t* __restrict__ xsf_blk,
float* __restrict__ sync_ws, float* __restrict__ ab, int late,
float* __restrict__ avec, const uint8_t* __restrict__ pf, long long pfb,
const __grid_constant__ CUtensorMap tmPF, int pf_ops, int pf_ci, int pf_bi,
int pf_bo) {
__shared__ uint32_t sm[32];
if constexpr (SP >= 0) late = SP & 3; // pinned late bits (host-verified equal)
constexpr int kNM = SP >= 0 ? ((SP >> 2) & 3) : -1;
const bool n_neg = kNM >= 0 ? (kNM == 1) : (N < 0);
const bool n_pos = kNM >= 0 ? (kNM == 3) : (N > 0);
const bool pf_on = SP >= 0 ? ((SP & 16) != 0) : (pf_ops > 0);
// PDL: early trigger (late == 0): let the dependent custom GEMM grid launch now (its prologue
// + weight prefetch overlap this kernel; it calls griddepcontrol.wait before touching xq /
// scales / alpha). late != 0: trigger after alpha is published (see pdl_late_trigger).
// late bit 2 (probe): PDL trigger right after the grid-barrier arrival instead of at entry
TL_DECL
TL(0);
if (!(late & 5)) asm volatile("griddepcontrol.launch_dependents;" ::: "memory");
const int sfk = K >> 4, ncb = sfk >> 2;
const int n_items = Mp * sfk;
const int n_real = M * sfk;
const int base = blockIdx.x * (IPT * NT) + threadIdx.x;
// x loads are issued FIRST (entry-latency critical path); the epoch read (volatile asm with a
// memory clobber = compiler barrier) follows them. Still before this CTA's arrival -> valid.
uint4 v0[IPT], v1[IPT];
uint32_t m2 = 0;
#pragma unroll
for (int j = 0; j < IPT; ++j) {
const int t = base + j * NT;
v0[j] = make_uint4(0, 0, 0, 0);
v1[j] = make_uint4(0, 0, 0, 0);
if (t < n_real) { v0[j] = __ldcs(x + 2 * t); v1[j] = __ldcs(x + 2 * t + 1); }
}
constexpr bool SLOT = SP >= 0 && (SP & 64) != 0; // fence-free slot barrier (see slot_wait)
static_assert(!SLOT || NT <= 640, "slot barrier smem scratch sm[20 + NT/32]");
const unsigned long long ep = SLOT ? 0ull : grid_epoch(sync_ws);
if constexpr (SLOT) { if (threadIdx.x == 0) sm[16] = slot_tag_read(sync_ws); }
// PER-ITEM block maxima computed once, BEFORE the arrival, and kept in registers: they feed
// both the CTA amax (max over items == the former packed fold, exact integer max) and pass 2
// (quant_post), so no 16-value re-fold sits in the barrier window / post-barrier path.
float pbm[IPT];
#pragma unroll
for (int j = 0; j < IPT; ++j) {
// packed bf16x2 abs-max over the raw words (max.xorsign.abs.bf16x2), ONE fp32 widen+fmax of
// the two lanes (item_bm): bit-identical to fold2(vmaxu2(absmax2x8, absmax2x8)) << 16
const float bmj = (IPT == 7) ? item_bm_p(v0[j], v1[j]) : item_bm(v0[j], v1[j]);
m2 = max(m2, __float_as_uint(bmj));
pbm[j] = bmj;
}
TLD(3, m2);
const uint32_t bmax = block_max_u32<NT>(m2, sm);
TL(1);
// arrive on the grid barrier FIRST, then do the weight-scale re-layout (N == 0: no-op) inside
// the barrier latency window: the x load phase no longer shares DRAM with the
// 4 MB weight-scale read, and the re-layout's loads + stores overlap the barrier wait.
uint32_t stag = 0;
if constexpr (SLOT) {
stag = sm[16]; // published by block_max_u32's CTA barrier
if (threadIdx.x == 0) slot_arrive(sync_ws, stag, bmax);
} else {
grid_arrive(bmax, sync_ws, ep);
}
TL(6);
if (late & 4) asm volatile("griddepcontrol.launch_dependents;" ::: "memory");
// coalesced re-layout in the barrier window (IPT 7 = Mp~1024 pin: sector-full warp-spread variant)
if (n_neg) {
// late bit 3 (probe): two relayout units per thread with batched loads
if (late & 8) wsf_relayout_pad2<NT>(wsf, wsf_blk, -N, ncb);
else wsf_relayout_pad<NT>(wsf, wsf_blk, -N, ncb); // padded layout for the 256x224 CUTLASS tiles
} else if (n_pos) {
if constexpr (IPT == 7 || IPT == 6 || NT != kThreads) wsf_relayout_w<NT>(wsf, wsf_blk, N, ncb);
else wsf_relayout_c<NT>(wsf, wsf_blk, N, ncb);
}
TL(4);
// amax-independent scale offsets of pass 2, inside the window (block maxima: see above)
uint32_t psoff[IPT];
#pragma unroll
for (int j = 0; j < IPT; ++j) {
const int t = base + j * NT;
const bool p2 = (sfk & (sfk - 1)) == 0;
const int r = p2 ? (t >> (__ffs(sfk) - 1)) : t / sfk;
psoff[j] = blk_off(r, t - r * sfk, ncb);
}
float amax;
if constexpr (SLOT) amax = __uint_as_float(slot_wait<NT>(sync_ws, stag, sm));
else if constexpr (SP >= 0 && (SP & 128) != 0) amax = __uint_as_float(grid_wait_dbo(sync_ws, sm, ep));
else amax = __uint_as_float((late & 2) ? grid_wait_bo(sync_ws, sm, ep) : grid_wait(sync_ws, sm, ep));
TL(2);
float ge, gd;
global_scales(amax, w_gd, ab, ge, gd);
TLD(7, __float_as_uint(gd));
if constexpr (SP < 0 || !(SP & 32)) write_avec(avec, N, gd, w_gd);
if (late & 1) pdl_late_trigger();
// pass 2: items processed in PAIRS (one e4m3x2 scale encode + one e4m3x2->f16x2 decode per pair)
#pragma unroll
for (int j = 0; j + 1 < IPT; j += 2) {
const int t = base + j * NT, t1 = t + NT;
quant_post_pair(t, t1, v0[j], v1[j], v0[j + 1], v1[j + 1], pbm[j], pbm[j + 1], psoff[j],
psoff[j + 1], t < n_items, t1 < n_items, ge, gd, xq, xsf_blk);
}
if constexpr (IPT & 1) {
const int t = base + (IPT - 1) * NT;
if (t < n_items) quant_post(t, v0[IPT - 1], v1[IPT - 1], pbm[IPT - 1], psoff[IPT - 1], ge, gd, xq, xsf_blk);
}
TL(5);
if (pf_on && threadIdx.x == 0) {
for (int o = blockIdx.x; o < pf_ops; o += gridDim.x) {
const int ci = o % pf_ci, ro = o / pf_ci;
asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile [%0, {%1, %2}];"
::"l"((uint64_t)&tmPF), "r"(ci * pf_bi), "r"(ro * pf_bo) : "memory");
}
}
TL(15);
}
#define QOPT true
static constexpr int kGran = 1024; // items per CTA granule (8 warps x 4 x 32 lanes), LPT = 4
// PIN = true: compile-time production configuration of the large-M pins (Mp >= 4096): pass-1
// non-tail loads evict_first (bit 2), no pre-barrier pass-2 granule loads / PFJ prefetch (bit 4096),
// no hot/cold interleave (bit 1024 or Mp < 8192), poll backoff (bit 512). The host selects it only
// when exactly those runtime bits would be set -> same code path, bit-identical, fewer registers /
// branches (the pre-barrier pa[] buffer and its quant_pre / prefetch code are compiled out).
template <int CV, int LPT = 4, bool PIN = false>
__global__ void __launch_bounds__(kThreads, (LPT <= 4) ? 4 : 2)
fused_quant_kernel(const uint4* __restrict__ x, int M, int Mp, int K,
const uint32_t* __restrict__ wsf, uint8_t* __restrict__ wsf_blk, int N,
float w_gd, uint8_t* __restrict__ xq, uint8_t* __restrict__ xsf_blk,
float* __restrict__ sync_ws, float* __restrict__ ab, float* amax_out,
int tail, int al32i, int late, float* __restrict__ avec,
const __grid_constant__ CUtensorMap tmPF, int pf_ops, int pf_ci, int pf_bi,
int pf_bo, const uint8_t* __restrict__ dmp, long long dmb) {
constexpr int GRN = kThreads * LPT; // items per granule
__shared__ uint32_t sm[32];
__shared__ int sq[2]; // claim broadcast (double-buffered)
// PDL trigger: early (late == 0) or after alpha is published (late != 0)
if (!late) asm volatile("griddepcontrol.launch_dependents;" ::: "memory");
const bool al32 = (al32i & 1) != 0;
const bool p1f = PIN || (al32i & 2) != 0; // pass-1 non-tail loads with L2 evict_first
const int sfk = K >> 4, ncb = sfk >> 2;
const int G = gridDim.x;
const int n_items = Mp * sfk;
const int n_real = M * sfk;
const int tid = threadIdx.x, lane = tid & 31, wo = (tid >> 5) * (32 * LPT) + lane;
const int ngA = (n_real + GRN - 1) / GRN; // pass-1 granules (real rows only)
const int ngB = (n_items + GRN - 1) / GRN; // pass-2 granules (incl. zero padding rows)
const int k0A = (int)(((long long)ngA * 7) / (10ll * G));
const int k0B = (int)(((long long)ngB * 7) / (10ll * G));
const long long tl_tot = (long long)tail * G;
const int elast = (int)max(0ll, (long long)n_real - tl_tot); // items >= elast: evict_last
unsigned int* cnt = reinterpret_cast<unsigned int*>(sync_ws) + 200;
int par = 0;
auto bcast = [&](unsigned int v) -> int {
if (tid == 0) sq[par] = (int)v;
__syncthreads();
const int r = sq[par];
par ^= 1;
return r;
};
uint32_t m2 = 0;
// weight-scale re-layout: done between grid_arrive and grid_wait (below)
constexpr int WU = (LPT > 4) ? 4 : 2; // wsf units per thread per register batch
// ---- pass 1: amax ----
auto granA_ld = [&](int g, uint4 (&a)[LPT], uint4 (&b)[LPT]) {
const int i0 = g * GRN + wo;
if (g * GRN + GRN <= n_real) {
if (g * GRN + GRN > elast) {
#pragma unroll
for (int k = 0; k < LPT; ++k) ld_item_last(x, i0 + k * 32, al32, a[k], b[k]);
} else {
#pragma unroll
for (int k = 0; k < LPT; ++k) { if (p1f) ld_item_first(x, i0 + k * 32, al32, a[k], b[k]); else ld_item_norm(x, i0 + k * 32, al32, a[k], b[k]); }
}
} else {
#pragma unroll
for (int k = 0; k < LPT; ++k) {
a[k] = make_uint4(0, 0, 0, 0); b[k] = a[k];
if (i0 + k * 32 < n_real) ld_item_last(x, i0 + k * 32, al32, a[k], b[k]);
}
}
};
auto granA_fold = [&](const uint4 (&a)[LPT], const uint4 (&b)[LPT]) {
#pragma unroll
for (int k = 0; k < LPT; ++k) m2 = acc_item(m2, a[k], b[k]);
};
auto granA = [&](int g) {
uint4 a[LPT], b[LPT];
granA_ld(g, a, b);
granA_fold(a, b);
};
// Entry latency: the loads of this CTA's FIRST static granule are issued before the epoch read
// and the first claim (both volatile asm / atomics = compiler barriers). The epoch read is
// still before this CTA's grid-barrier arrival -> valid (see grid_epoch).
uint4 fa[LPT], fb[LPT];
if (k0A > 0) granA_ld((int)blockIdx.x, fa, fb);
extern __shared__ __align__(16) uint4 keep_s[]; // [LPT * 2 * kThreads] when bit 2 is set
const bool keep = (LPT <= 4) && (al32i & 4) != 0 && amax_out == nullptr && Mp >= 4096 && k0A > 0 &&
(long long)G * GRN <= (long long)n_real &&
(long long)(k0B + 1) * G <= (long long)ngB;
const unsigned long long ep = grid_epoch(sync_ws); // valid in thread 0
unsigned int* cA = cnt + 2 * (int)(ep & 1); // thread 0 only
// Mp >= 4096 (every persistent-quant shape): the previous call's xq / blocked-scale lines (stored
// with L2 evict_last: 18 MB at Mp 4096, ~34 MB at 8192, ~40 MB pinned at 16384) are dead (pass 2 of THIS launch rewrites every byte before the stream-ordered GEMM reads them)
// -> discard.global.L2 them now: frees that L2 capacity for the x stream (more pass-2 re-read
// hits) and drops their dirty writeback. Issued long before the grid barrier (release/acquire)
// that orders every pass-2 store after it.
if (Mp >= 4096 && amax_out == nullptr && ((((uintptr_t)xq) | ((uintptr_t)xsf_blk)) & 127) == 0) {
const long long nlq = (long long)Mp * (K >> 1) / 128, nls = (long long)n_items / 128;
for (long long l = (long long)blockIdx.x * kThreads + tid; l < nlq + nls; l += (long long)G * kThreads) {
uint8_t* a = l < nlq ? xq + l * 128 : xsf_blk + (l - nlq) * 128;
asm volatile("discard.global.L2 [%0], 128;" ::"l"(a) : "memory");
}
}
// L2 WEIGHT DEMOTION (al32i bit 65536, Mp 16384 pin): the dependent GEMM's fp4 weight (32 MB,
// left L2 evict_last by the previous call's CUTLASS B loads) is demoted to evict_normal at entry,
// so it no longer holds L2 capacity against this pass's evict_last x tail (pass-2 re-read hits).
// The GEMM re-pins it with its own B evict_last loads. Cache-priority hint only: data unchanged.
if ((al32i & 65536) && dmp != nullptr && amax_out == nullptr) {
const long long nl = dmb >> 7;
for (long long l = (long long)blockIdx.x * kThreads + tid; l < nl; l += (long long)G * kThreads)
asm volatile("applypriority.global.L2::evict_normal [%0], 128;" ::"l"(dmp + l * 128) : "memory");
}
{
unsigned int pend = 0;
const int baseA = k0A * G;
if (baseA < ngA && tid == 0) pend = atomicAdd(cA, 1u); // first claim, overlaps static part
if (k0A > 0) granA_fold(fa, fb);
if (keep) {
#pragma unroll
for (int k = 0; k < LPT; ++k) {
keep_s[(2 * k) * kThreads + tid] = fa[k];
keep_s[(2 * k + 1) * kThreads + tid] = fb[k];
}
}
// ROTATING-SLOT STATIC PASS-1 STREAM: instead of load-granule / fold-granule (all LPT loads
// drain to zero outstanding before the next granule's loads issue), slot k of the next static
// granule is re-loaded as soon as slot k of the current one has been folded, so each thread
// keeps ~LPT 32-byte loads (8 x 16 B) continuously in flight with the SAME register footprint
// (one LPT-slot buffer). Same granules, same per-granule L2 policy (ldA_k), max is order-
// independent -> bit-identical amax.
if (k0A > 1) {
auto ldA_k = [&](int g, int k, uint4& a, uint4& b) {
const int t = g * GRN + wo + k * 32;
if (g * GRN + GRN <= n_real) {
if (g * GRN + GRN > elast) ld_item_last(x, t, al32, a, b);
else if (p1f) ld_item_first(x, t, al32, a, b);
else ld_item_norm(x, t, al32, a, b);
} else {
a = make_uint4(0, 0, 0, 0); b = a;
if (t < n_real) ld_item_last(x, t, al32, a, b);
}
};
uint4 ra[LPT], rb[LPT];
#pragma unroll
for (int k = 0; k < LPT; ++k) ldA_k((int)blockIdx.x + G, k, ra[k], rb[k]);
#pragma unroll 1
for (int j = 1; j < k0A; ++j) {
const bool more = j + 1 < k0A;
const int gn = (int)blockIdx.x + (j + 1) * G;
#pragma unroll
for (int k = 0; k < LPT; ++k) {
m2 = acc_item(m2, ra[k], rb[k]);
if (more) ldA_k(gn, k, ra[k], rb[k]);
}
}
}
if (baseA < ngA) {
int g = baseA + bcast(pend);
while (g < ngA) {
if (tid == 0) pend = atomicAdd(cA, 1u); // next claim, one granule ahead
granA(g);
g = baseA + bcast(pend);
}
}
}
// Barrier-latency hiding: the loads of this CTA's FIRST pass-2 granule (static id blockIdx.x =
// the L2-hot, evict_last top of x) are issued BEFORE the grid barrier (x is read-only; volatile
// asm keeps them ahead of the barrier spin), consumed right after it.
const uint4 z = make_uint4(0, 0, 0, 0);
const int k0B_ = (int)(((long long)ngB * 7) / (10ll * G));
// al32i bit 4096: no pre-barrier first pass-2 granule loads (and no PFJ prefetch)
const bool pre = !PIN && QOPT && amax_out == nullptr && k0B_ > 0 && (al32i & 4096) == 0;
uint4 pa[LPT][2];
const bool ilv = !PIN && Mp >= 8192 && (al32i & 1024) == 0;
const int n2 = keep ? ngB - G : ngB; // permuted pool = all non-kept granules
const int s8 = max(1, G / 8);
auto pmap = [&](int c) -> int {
if (!ilv || c >= n2) return ngB - 1 - c;
const int q = c >> 1;
int r = c;
if (2 * q + 1 < n2) r = 2 * q + ((c & 1) ^ ((q / s8) & 1));
const int cc = (r & 1) ? n2 - 1 - (r >> 1) : (r >> 1);
return ngB - 1 - cc;
};
const int pi0 = pmap((int)blockIdx.x) * GRN + GRN - 1 - wo;
auto prefetch2 = [&]() {
if (pre) {
#pragma unroll
for (int k = 0; k < LPT; ++k) {
const int tk = pi0 - k * 32;
pa[k][0] = z; pa[k][1] = z;
if (tk < n_real) ld_item_first_v(x, tk, al32, pa[k][0], pa[k][1]);
}
}
};
const uint32_t bmax = block_max_u32(amax_fin(m2), sm);
// split grid barrier: arrive first, then the weight-scale re-layout (4 MB ld + st, N == 0 ->
// no-op) inside the barrier latency window instead of competing with the x amax stream.
grid_arrive(bmax, sync_ws, ep);
prefetch2(); // first pass-2 granule loads, issued AFTER the arrival (see prefetch2)
if (N < 0) wsf_relayout_pad(wsf, wsf_blk, -N, ncb); // padded layout (256x224 CUTLASS tiles)
if (N > 0) {
WsfPre<WU> wp;
wsf_load<WU>(wsf, N, ncb, wp);
wsf_store<WU>(wsf, wsf_blk, N, ncb, wp);
}
{
const int pfj = (al32i >> 6) & 3;
if (pre && pfj > 0 && tid == 0) {
for (int j = 1; j <= pfj && j < k0B; ++j) {
const int g = pmap((int)blockIdx.x + j * G);
if ((long long)g * GRN + GRN <= (long long)n_real)
asm volatile("cp.async.bulk.prefetch.L2.global [%0], %1;" ::"l"(x + 2 * (size_t)g * GRN),
"r"((uint32_t)(GRN * 32)) : "memory");
}
}
}
// amax-independent part of the first pass-2 granule (block maxima, scale offsets), also inside
// the barrier window (operands from the pre-barrier prefetch)
// SMEM-KEPT GRANULE block maxima, also in the barrier window: per-item max|x| of this thread's
// kept items -> float slot behind keep_s (thread-private slots, no CTA barrier). The final
// kept-granule quantize then uses quant_post with it instead of re-folding 16 values.
float* keep_bm = reinterpret_cast<float*>(keep_s + LPT * 2 * kThreads);
if (keep) {
#pragma unroll
for (int k = 0; k < LPT; ++k)
keep_bm[k * kThreads + tid] = item_bm_p(keep_s[(2 * k) * kThreads + tid],
keep_s[(2 * k + 1) * kThreads + tid]);
}
float pbm[LPT];
uint32_t psoff[LPT];
if (pre) {
#pragma unroll
for (int k = 0; k < LPT; ++k)
quant_pre(pi0 - k * 32, pa[k][0], pa[k][1], sfk, ncb, pbm[k], psoff[k]);
}
const float amax = __uint_as_float((PIN || (al32i & 512)) ? grid_wait_bo(sync_ws, sm, ep) : grid_wait(sync_ws, sm, ep));
// the other parity's counters were last used by launch e-1 (complete) -> reset for launch e+1
if (blockIdx.x == 0 && tid == 0) {
cnt[2 * (int)((ep + 1) & 1)] = 0u;
cnt[2 * (int)((ep + 1) & 1) + 1] = 0u;
}
float ge, gd;
global_scales(amax, w_gd, ab, ge, gd);
write_avec(avec, N, gd, w_gd);
if (late) pdl_late_trigger();
if (amax_out != nullptr) { // amax-only mode: chunked quant kernels do the rest
if (blockIdx.x == 0 && threadIdx.x == 0) *amax_out = amax;
return;
}
const bool sl2 = true;
uint64_t pol2;
if (al32i & 8)
asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 0.5;" : "=l"(pol2));
else if (al32i & 16)
asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 0.25;" : "=l"(pol2));
else if (al32i & 32)
asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol2));
else if (Mp <= 8192)
asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol2));
else
asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 0.5;" : "=l"(pol2)); // ENERGY pass: 0.5 (~32 MB pinned) leaves more L2 for pass-2 x re-read hits -> fewer DRAM bytes/call
if (pre) {
#pragma unroll
for (int k = 0; k < LPT; ++k) {
const int tk = pi0 - k * 32;
if (tk < n_items) quant_post(tk, pa[k][0], pa[k][1], pbm[k], psoff[k], ge, gd, xq, xsf_blk);
}
}
// granB fast path condition (grid-uniform): sfk multiple of 32*LPT (see granB)
const bool rowfast = sl2 && (sfk % (32 * LPT)) == 0;
const bool p2s = (sfk & (sfk - 1)) == 0;
const int sh = __ffs(sfk) - 1;
auto granB = [&](int c) {
const int i0 = pmap(c) * GRN + GRN - 1 - wo;
uint4 a[LPT][2];
#pragma unroll
for (int k = 0; k < LPT; ++k) {
const int tk = i0 - k * 32;
a[k][0] = z; a[k][1] = z;
if (tk < n_real) ld_item_first(x, tk, al32, a[k][0], a[k][1]);
}
if (rowfast) {
// PER-GRANULE SCALE OFFSET: the LPT items of this thread (i0 - 32k) lie in one 32*LPT-aligned
// window that never crosses a row (sfk % (32*LPT) == 0), so they share row r and have
// columns c0 - 32k -> blocked offset blk_off(r, c0) - 4096k (8 col-blocks of 512 B each).
// One row/col/blk_off computation per thread per granule instead of per item; same bytes.
const int r = p2s ? (i0 >> sh) : i0 / sfk;
const uint32_t so0 = blk_off(r, i0 - r * sfk, ncb);
// items in PAIRS: one e4m3x2 scale encode + one e4m3x2->f16x2 decode per pair (LPT even)
#pragma unroll
for (int k = 0; k < LPT; k += 2) {
const int tk = i0 - k * 32, tk1 = tk - 32;
const float bm0 = item_bm_p(a[k][0], a[k][1]); // 10-op block max (see item_bm)
const float bm1 = item_bm_p(a[k + 1][0], a[k + 1][1]);
quant_post_pair<true>(tk, tk1, a[k][0], a[k][1], a[k + 1][0], a[k + 1][1], bm0, bm1,
so0 - 4096u * (uint32_t)k, so0 - 4096u * (uint32_t)(k + 1),
tk < n_items, tk1 < n_items, ge, gd, xq, xsf_blk, pol2);
}
} else {
#pragma unroll
for (int k = 0; k < LPT; ++k) {
const int tk = i0 - k * 32;
if (tk < n_items) {
if (sl2) quant_item<true>(tk, a[k][0], a[k][1], sfk, ncb, ge, gd, xq, xsf_blk, pol2);
else quant_item<false>(tk, a[k][0], a[k][1], sfk, ncb, ge, gd, xq, xsf_blk);
}
}
}
};
{
unsigned int pend = 0;
const int baseB = k0B * G;
const int ngBd = keep ? ngB - G : ngB; // dynamic pool end (kept granules excluded)
if (baseB < ngBd && tid == 0) pend = atomicAdd(cA + 1, 1u);
#pragma unroll 1
for (int j = pre ? 1 : 0; j < k0B; ++j) granB(blockIdx.x + j * G);
if (baseB < ngBd) {
int c = baseB + bcast(pend);
while (c < ngBd) {
if (tid == 0) pend = atomicAdd(cA + 1, 1u);
granB(c);
c = baseB + bcast(pend);
}
}
}
if (keep) { // smem-kept granule blockIdx.x (all items real: G*GRN <= n_real)
const int i0 = (int)blockIdx.x * GRN + wo;
#pragma unroll
for (int k = 0; k < LPT; ++k) {
const int t = i0 + k * 32;
const bool p2 = (sfk & (sfk - 1)) == 0;
const int r = p2 ? (t >> (__ffs(sfk) - 1)) : t / sfk;
quant_post<true>(t, keep_s[(2 * k) * kThreads + tid], keep_s[(2 * k + 1) * kThreads + tid],
keep_bm[k * kThreads + tid], blk_off(r, t - r * sfk, ncb), ge, gd, xq,
xsf_blk, pol2);
}
}
// COLD-L2 WEIGHT PREFIX PREFETCH (pf_ops > 0: Mp = 4096 / 8192 CUTLASS pins), same 2D TMA tensor
// prefetch form as fused_quant_res_kernel / the hybrid quant: after this CTA's last pass-2 xq /
// scale store, thread 0 issues its share of pf_ops boxes {pf_bi B, pf_bo rows} covering the first
// K-prefix (<= 1 KB) of every fp4 weight row (fire-and-forget L2 fill, output unaffected).
if (pf_ops > 0 && tid == 0) {
for (int o = blockIdx.x; o < pf_ops; o += G) {
const int ci = o % pf_ci, ro = o / pf_ci;
asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile [%0, {%1, %2}];"
::"l"((uint64_t)&tmPF), "r"(ci * pf_bi), "r"(ro * pf_bo) : "memory");
}
}
}
template <typename F>
static int max_coresident(F kern, int nt = kThreads) {
int dev, sms, per = 0;
cudaGetDevice(&dev);
cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev);
cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per, kern, nt, 0);
if (per < 1) per = 1;
int g = sms * per;
return g < kMaxPartials ? g : kMaxPartials;
}
template <typename F>
static void coop_launch(F kern, int grid, void** args, cudaStream_t s, size_t dsm = 0,
int nt = kThreads) {
cudaLaunchKernel((const void*)kern, dim3(grid), dim3(nt), args, dsm, s);
}
static bool make_tmap_u8(CUtensorMap* tm, const void* ptr, uint64_t inner, uint64_t outer,
uint32_t box_inner, uint32_t box_outer, CUtensorMapSwizzle swz);
static const uint8_t* g_qpf_ptr = nullptr; // register-resident quant L2 weight prefetch (launch time)
static long long g_qpf_bytes = 0;
// bytes of every fp4 weight row covered by the quant-side cold-L2 prefix prefetch (default 1 KB)
static int g_qpf_prefix = 1024;
void set_quant_pf_prefix(int b) { g_qpf_prefix = b < 256 ? 256 : b; }
void set_quant_l2_prefetch(const void* p, long long bytes) {
g_qpf_ptr = (const uint8_t*)p; g_qpf_bytes = p ? (bytes & ~15ll) : 0;
}
static const uint8_t* g_demote_ptr = nullptr; // L2 weight demotion range (persistent quant, bit 65536)
static long long g_demote_bytes = 0;
void set_quant_l2_demote(const void* p, long long bytes) {
g_demote_ptr = (const uint8_t*)p; g_demote_bytes = p ? bytes : 0;
}
static bool g_res_slot = false; // register-resident quant: fence-free slot grid barrier (SP bit 64)
void set_res_slot(bool on) { g_res_slot = on; }
static bool g_res_dbo = false; // register-resident quant: delayed-backoff epoch barrier (SP bit 128)
void set_res_dbo(bool on) { g_res_dbo = on; }
static bool g_res_bo = false; // register-resident quant: grid-barrier poll backoff
void set_res_bo(bool on) { g_res_bo = on; }
// probe-only late bits of the register-resident quant: 4 = PDL trigger after arrival, 8 = batched relayout
static int g_res_xbits = 0;
void set_res_xbits(int b) { g_res_xbits = b & 12; }
static int g_wsf_pad = 0; // padded weight-scale re-layout: 0 off, 1 = 256x224 tiles, 2 = 256x112 tiles
void set_wsf_pad(int mode) { g_wsf_pad = mode; }
static bool launch_hyb_quant(const void* x, int M, int Mp, int K, const uint32_t* wsf,
uint8_t* wsf_blk, int N, float w_gd, uint8_t* xq, uint8_t* xsf_blk,
float* sync_ws, float* ab, int late, float* avec, cudaStream_t s,
const CUtensorMap& tmPF, int pf_ops, int pf_ci, int pf_bi, int pf_bo);
static int g4 = 0, g8 = 0, gp = 0, g7 = 0, g2h = 0;
static constexpr int kKeepSmem = 4 * 2 * kThreads * 16 + 4 * kThreads * 4; // 32 KB keep_s + 4 KB block maxima (fused_quant_kernel<0, 4>)
static bool g_keep_ok = false;
static bool g_pin_ok = false; // fused_quant_kernel<0, 4, true> co-resident like <0>
static void init_grids() {
if (!gp) {
// CV=0 register-resident instantiations (no dynamic smem, 128 B static): explicit MINIMUM
// shared-memory carveout (0 -> max L1). Set before the occupancy queries below (co-residency).
cudaFuncSetAttribute(fused_quant_res_kernel<4, 0>, cudaFuncAttributePreferredSharedMemoryCarveout, 0);
cudaFuncSetAttribute(fused_quant_res_kernel<8, 0>, cudaFuncAttributePreferredSharedMemoryCarveout, 0);
cudaFuncSetAttribute(fused_quant_res_kernel<7, 0>, cudaFuncAttributePreferredSharedMemoryCarveout, 0);
cudaFuncSetAttribute(fused_quant_res_kernel<2, 0>, cudaFuncAttributePreferredSharedMemoryCarveout, 0);
// CV=1 instantiations: max shared-memory carveout so a dependent (PDL) GEMM CTA can co-reside
cudaFuncSetAttribute(fused_quant_res_kernel<4, 1>, cudaFuncAttributePreferredSharedMemoryCarveout, 100);
cudaFuncSetAttribute(fused_quant_res_kernel<8, 1>, cudaFuncAttributePreferredSharedMemoryCarveout, 100);
cudaFuncSetAttribute(fused_quant_kernel<1>, cudaFuncAttributePreferredSharedMemoryCarveout, 100);
// grid sizes must be identical for both variants (shared epoch counter) and co-resident for
// both -> min over the two instantiations
g4 = std::min(max_coresident(fused_quant_res_kernel<4, 0>), max_coresident(fused_quant_res_kernel<4, 1>));
g8 = std::min(max_coresident(fused_quant_res_kernel<8, 0>), max_coresident(fused_quant_res_kernel<8, 1>));
gp = std::min(max_coresident(fused_quant_kernel<0>), max_coresident(fused_quant_kernel<1>));
// smem-kept granule (32 KB dynamic smem, Mp >= 4096): enabled only if the default-carveout
// instantiation still fits the SAME number of CTAs per SM with it (grid barrier co-residency)
{
int per0 = 0, per1 = 0;
if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per0, fused_quant_kernel<0>, kThreads, 0) == cudaSuccess &&
cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per1, fused_quant_kernel<0>, kThreads, kKeepSmem) == cudaSuccess)
g_keep_ok = per1 >= per0 && per1 >= 1;
int pp0 = 0, pp1 = 0;
if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&pp0, fused_quant_kernel<0, 4, true>, kThreads, 0) == cudaSuccess &&
cudaOccupancyMaxActiveBlocksPerMultiprocessor(&pp1, fused_quant_kernel<0, 4, true>, kThreads, kKeepSmem) == cudaSuccess)
g_pin_ok = pp0 >= per0 && (!g_keep_ok || pp1 >= per1);
cudaGetLastError();
}
// IPT = 7 SM-balance variant (see launch_fused_quant, ipt == 7)
cudaFuncSetAttribute(fused_quant_res_kernel<7, 1>, cudaFuncAttributePreferredSharedMemoryCarveout, 100);
g7 = std::min(max_coresident(fused_quant_res_kernel<7, 0>), max_coresident(fused_quant_res_kernel<7, 1>));
// IPT 2 x 128-thread variant (ipt 21)
cudaFuncSetAttribute(fused_quant_res_kernel<2, 0, 128>, cudaFuncAttributePreferredSharedMemoryCarveout, 0);
cudaFuncSetAttribute(fused_quant_res_kernel<2, 1, 128>, cudaFuncAttributePreferredSharedMemoryCarveout, 100);
g2h = std::min(max_coresident(fused_quant_res_kernel<2, 0, 128>, 128),
max_coresident(fused_quant_res_kernel<2, 1, 128>, 128));
}
}
int quant_full_grid() { init_grids(); return gp; }
static int g_p2frac = 0; // probe: persistent-quant pass-2 store policy override bits (8/16/32), 0 = default
void set_p2frac(int b) { g_p2frac = b; }
static bool g_p1_first = false; // pass-1 evict_first (non-tail loads)
void set_p1_first(bool on) { g_p1_first = on; }
static int g_tail_force_mb = -1; // probe override of the pass-1 evict_last budget
void set_tail_force_mb(int mb) { g_tail_force_mb = mb; }
static int evict_tail(int Mp, int K, int G) {
if (g_tail_force_mb >= 0) {
long long per = ((long long)g_tail_force_mb << 20) / 32 / (G > 0 ? G : 1);
long long chunk = ((long long)Mp * (K / 16) + G - 1) / G;
// ROUND-ALIGNED TAIL (Mp >= 8192 pins): pass 2 processes granules in descending rounds of G
// (round j = granules [ngB-(j+1)G, ngB-jG), static strided, then dynamic claims, kept lowest
// granules last). A per-CTA tail of r*kGran items makes the pass-1 evict_last x tail EXACTLY
// the top r rounds = the granules pass 2 quantizes first (no partially-pinned round whose
// untouched evict_last lines outlive their use). r = nearest whole round of the MB budget.
// Cache-priority hint boundary only -> bit-identical outputs.
if (Mp >= 8192) {
long long r = (per + kGran / 2) / kGran;
per = r * kGran;
}
return (int)(per < chunk ? per : chunk);
}
if (Mp >= 4096) return 0;
long long per = g_evict_last_bytes / 32 / (G > 0 ? G : 1);
long long chunk = ((long long)Mp * (K / 16) + G - 1) / G;
return (int)(per < chunk ? per : chunk);
}
template <int IPT, int NT, int SP>
static bool res_spec_ok() {
static int ok = -1;
if (ok < 0) {
cudaFuncSetAttribute(fused_quant_res_kernel<IPT, 0, NT, SP>, cudaFuncAttributePreferredSharedMemoryCarveout, 0);
int a = 0, b = 0;
if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&a, fused_quant_res_kernel<IPT, 0, NT>, NT, 0) != cudaSuccess) a = 0;
if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&b, fused_quant_res_kernel<IPT, 0, NT, SP>, NT, 0) != cudaSuccess) b = 0;
cudaGetLastError();
ok = (a >= 1 && b >= a) ? 1 : 0;
}
return ok == 1;
}
void launch_fused_quant(const void* x, int M, int Mp, int K, const uint8_t* wsf, uint8_t* wsf_blk,
int N, float w_gd, uint8_t* xq, uint8_t* xsf_blk, float* sync_ws,
float* ab, bool do_wsf, bool late_pdl, int carve, cudaStream_t s,
float* avec, int ipt) {
init_grids();
if (!do_wsf) avec = nullptr;
const uint4* xp = (const uint4*)x;
const uint32_t* wp = (const uint32_t*)wsf;
// 0 -> skip the weight-scale re-layout; negative -> padded layout (register-resident / hybrid
// quant variants only; the persistent large-M quant never runs with it, see main.cpp)
int Nw = do_wsf ? (g_wsf_pad == 1 ? -N : (g_wsf_pad == 2 ? -(N | (1 << 29)) : N)) : 0;
float* no_amax = nullptr;
const uint8_t* pfp = g_qpf_ptr;
long long pfb = g_qpf_bytes;
// tensor map of the prefix prefetch (weight viewed as [N rows, K/2 bytes] u8, box {bi, bo}),
// cached per (pointer, N, K); prefetch disabled if the encode fails
static CUtensorMap& tmPF = *new CUtensorMap();
static const void* pf_key_p = nullptr;
static int pf_key_n = -1, pf_key_k = -1;
static bool pf_key_ok = false;
int pf_ops = 0, pf_ci = 1, pf_bi = 16, pf_bo = 1;
if (pfp != nullptr && pfb > 0 && N > 0) {
const int rb = K / 2;
const long long nrows = std::min<long long>(N, pfb / rb);
pf_bi = std::min(256, rb);
pf_bo = (int)std::min<long long>(256, nrows);
if (pf_key_p != pfp || pf_key_n != N || pf_key_k != K) {
pf_key_ok = make_tmap_u8(&tmPF, pfp, (uint64_t)rb, (uint64_t)N, (uint32_t)pf_bi, (uint32_t)pf_bo,
CU_TENSOR_MAP_SWIZZLE_NONE);
pf_key_p = pfp; pf_key_n = N; pf_key_k = K;
}
if (pf_key_ok) {
pf_ci = (std::min(g_qpf_prefix, rb) + pf_bi - 1) / pf_bi;
pf_ops = (int)(((nrows + pf_bo - 1) / pf_bo) * pf_ci);
}
}
int al32 = ((((uintptr_t)x) & 31) == 0 ? 1 : 0) | (g_p1_first ? 2 : 0) | g_p2frac;
const uint8_t* dmp = g_demote_ptr;
long long dmb = g_demote_bytes;
if ((g_p2frac & 192) == 0) al32 |= 64;
int tail = evict_tail(Mp, K, gp);
int late = late_pdl ? 1 : 0;
int rlate = late | (g_res_bo ? 2 : 0) | g_res_xbits; // register-resident variants: bit 1 = barrier poll backoff
// runtime knob code in the SP encoding of fused_quant_res_kernel (selects pinned instantiations)
const int rspc = ((rlate & 12) << 4) | (rlate & 3) | (Nw == 0 ? 0 : (Nw < 0 ? 4 : 12)) | (pf_ops > 0 ? 16 : 0) |
(avec == nullptr ? 32 : 0);
void* args[] = {(void*)&xp, (void*)&M, (void*)&Mp, (void*)&K, (void*)&wp, (void*)&wsf_blk,
(void*)&Nw, (void*)&w_gd, (void*)&xq, (void*)&xsf_blk, (void*)&sync_ws,
(void*)&ab, (void*)&no_amax, (void*)&tail, (void*)&al32, (void*)&late,
(void*)&avec, (void*)&tmPF, (void*)&pf_ops, (void*)&pf_ci, (void*)&pf_bi,
(void*)&pf_bo, (void*)&dmp, (void*)&dmb};
void* rargs[] = {(void*)&xp, (void*)&M, (void*)&Mp, (void*)&K, (void*)&wp, (void*)&wsf_blk,
(void*)&Nw, (void*)&w_gd, (void*)&xq, (void*)&xsf_blk, (void*)&sync_ws,
(void*)&ab, (void*)&rlate, (void*)&avec, (void*)&pfp, (void*)&pfb,
(void*)&tmPF, (void*)&pf_ops, (void*)&pf_ci, (void*)&pf_bi, (void*)&pf_bo};
// NOTE: the grid size depends only on (Mp, K) -> constant per plan (required by grid_amax's
// epoch arithmetic on the plan's persistent counter)
const long long n_items = (long long)Mp * (K / 16);
const int need4 = (int)((n_items + 4 * kThreads - 1) / (4 * kThreads));
const int need8 = (int)((n_items + 8 * kThreads - 1) / (8 * kThreads));
// ipt == 7: SM-balanced register-resident variant. The default choice (IPT 4 / 8) yields 256
// CTAs at Mp = 512 / 1024 -> 108 SMs run 2 CTAs, 40 SMs run 1 (critical SM = 2 x IPT*256
// items). IPT 7 -> 147 / 293 CTAs = ~1 / ~2 CTAs on EVERY SM.
// Private barrier counter block sync_ws[800..] (different grid size than the default variant
// on the same plan -> separate epoch counter). Falls back to the default if not co-resident.
const int need7 = (int)((n_items + 7 * kThreads - 1) / (7 * kThreads));
if (ipt == 7 && need7 <= g7) {
float* sw7 = sync_ws + 800;
void* r7[] = {(void*)&xp, (void*)&M, (void*)&Mp, (void*)&K, (void*)&wp, (void*)&wsf_blk,
(void*)&Nw, (void*)&w_gd, (void*)&xq, (void*)&xsf_blk, (void*)&sw7,
(void*)&ab, (void*)&rlate, (void*)&avec, (void*)&pfp, (void*)&pfb,
(void*)&tmPF, (void*)&pf_ops, (void*)&pf_ci, (void*)&pf_bi, (void*)&pf_bo};
if (carve != 0) coop_launch(fused_quant_res_kernel<7, 1>, need7, r7, s);
// Mp 1024 pin: delayed-backoff epoch barrier (SP bit 128, same protocol / values as SP 54)
else if (g_res_dbo && rspc == 54 && res_spec_ok<7, kThreads, 54 | 128>()) coop_launch(fused_quant_res_kernel<7, 0, kThreads, 54 | 128>, need7, r7, s);
else if (rspc == 54 && res_spec_ok<7, kThreads, 54>()) coop_launch(fused_quant_res_kernel<7, 0, kThreads, 54>, need7, r7, s);
else coop_launch(fused_quant_res_kernel<7, 0>, need7, r7, s);
return;
}
// ipt == 25: IPT 2 x 512-thread CTAs (Mp 128 pin candidate: same 64 CTAs / SMs as IPT 4 x 256,
// half the per-thread load / encode chain, twice the warps per scheduler for latency hiding in the
// post-barrier encode). Private barrier counter block sync_ws[1040..]; falls through to the
// default if not co-resident.
if (ipt == 25 && carve == 0) {
static int g25 = -1;
if (g25 < 0) {
cudaFuncSetAttribute(fused_quant_res_kernel<2, 0, 512>, cudaFuncAttributePreferredSharedMemoryCarveout, 0);
g25 = max_coresident(fused_quant_res_kernel<2, 0, 512>, 512);
}
const int need25 = (int)((n_items + 2 * 512 - 1) / (2 * 512));
if (need25 <= g25) {
float* sw = sync_ws + 1040;
void* rx[] = {(void*)&xp, (void*)&M, (void*)&Mp, (void*)&K, (void*)&wp, (void*)&wsf_blk,
(void*)&Nw, (void*)&w_gd, (void*)&xq, (void*)&xsf_blk, (void*)&sw,
(void*)&ab, (void*)&rlate, (void*)&avec, (void*)&pfp, (void*)&pfb,
(void*)&tmPF, (void*)&pf_ops, (void*)&pf_ci, (void*)&pf_bi, (void*)&pf_bo};
if (rspc == 34 && res_spec_ok<2, 512, 34>())
coop_launch(fused_quant_res_kernel<2, 0, 512, 34>, need25, rx, s, 0, 512);
else
coop_launch(fused_quant_res_kernel<2, 0, 512>, need25, rx, s, 0, 512);
return;
}
}
// ipt == 33 / 35: IPT 3 x 384 / 512-thread CTAs (probe variants; private counter blocks
// sync_ws[960..] / [1000..]); fall through to the default if not co-resident
if (ipt == 33 || ipt == 35) {
static int g384 = -1, g512 = -1;
if (g384 < 0) {
cudaFuncSetAttribute(fused_quant_res_kernel<3, 0, 384>, cudaFuncAttributePreferredSharedMemoryCarveout, 0);
cudaFuncSetAttribute(fused_quant_res_kernel<3, 0, 512>, cudaFuncAttributePreferredSharedMemoryCarveout, 0);
g384 = max_coresident(fused_quant_res_kernel<3, 0, 384>, 384);
g512 = max_coresident(fused_quant_res_kernel<3, 0, 512>, 512);
}
const int nt = ipt == 33 ? 384 : 512;
const int needx = (int)((n_items + 3 * nt - 1) / (3 * nt));
if (carve == 0 && needx <= (ipt == 33 ? g384 : g512)) {
float* sw = sync_ws + (ipt == 33 ? 960 : 1000);
void* rx[] = {(void*)&xp, (void*)&M, (void*)&Mp, (void*)&K, (void*)&wp, (void*)&wsf_blk,
(void*)&Nw, (void*)&w_gd, (void*)&xq, (void*)&xsf_blk, (void*)&sw,
(void*)&ab, (void*)&rlate, (void*)&avec, (void*)&pfp, (void*)&pfb,
(void*)&tmPF, (void*)&pf_ops, (void*)&pf_ci, (void*)&pf_bi, (void*)&pf_bo};
if (ipt == 33) coop_launch(fused_quant_res_kernel<3, 0, 384>, needx, rx, s, 0, 384);
else coop_launch(fused_quant_res_kernel<3, 0, 512>, needx, rx, s, 0, 512);
return;
}
}
{
static int g3 = -1;
if (g3 < 0) {
cudaFuncSetAttribute(fused_quant_res_kernel<3, 0>, cudaFuncAttributePreferredSharedMemoryCarveout, 0);
g3 = max_coresident(fused_quant_res_kernel<3, 0>);
}
const int need3 = (int)((n_items + 3 * kThreads - 1) / (3 * kThreads));
if (ipt == 3 && carve == 0 && need3 <= g3) {
float* sw = sync_ws + 920;
void* r3[] = {(void*)&xp, (void*)&M, (void*)&Mp, (void*)&K, (void*)&wp, (void*)&wsf_blk,
(void*)&Nw, (void*)&w_gd, (void*)&xq, (void*)&xsf_blk, (void*)&sw,
(void*)&ab, (void*)&rlate, (void*)&avec, (void*)&pfp, (void*)&pfb,
(void*)&tmPF, (void*)&pf_ops, (void*)&pf_ci, (void*)&pf_bi, (void*)&pf_bo};
// fence-free slot barrier (SP bit 64): private block sync_ws[2048..] (4 + 2*G floats)
float* swl3 = sync_ws + 2048;
void* r3l[] = {(void*)&xp, (void*)&M, (void*)&Mp, (void*)&K, (void*)&wp, (void*)&wsf_blk,
(void*)&Nw, (void*)&w_gd, (void*)&xq, (void*)&xsf_blk, (void*)&swl3,
(void*)&ab, (void*)&rlate, (void*)&avec, (void*)&pfp, (void*)&pfb,
(void*)&tmPF, (void*)&pf_ops, (void*)&pf_ci, (void*)&pf_bi, (void*)&pf_bo};
if (g_res_dbo && rspc == 52 && res_spec_ok<3, kThreads, 52 | 128>())
coop_launch(fused_quant_res_kernel<3, 0, kThreads, 52 | 128>, need3, r3, s);
else if (g_res_slot && rspc == 52 && 4 + 2 * need3 <= kMaxPartials - 2048 && res_spec_ok<3, kThreads, 52 | 64>())
coop_launch(fused_quant_res_kernel<3, 0, kThreads, 52 | 64>, need3, r3l, s);
else if (rspc == 52 && res_spec_ok<3, kThreads, 52>()) coop_launch(fused_quant_res_kernel<3, 0, kThreads, 52>, need3, r3, s);
else coop_launch(fused_quant_res_kernel<3, 0>, need3, r3, s);
return;
}
}
// ipt == 21: IPT 2 x 128-thread CTAs (Mp 256 / 512 pins; private barrier counter block
// sync_ws[880..]). Falls back to the default variant if not co-resident.
{
const int need2h = (int)((n_items + 2 * 128 - 1) / (2 * 128));
if (ipt == 21 && need2h <= g2h) {
float* sw = sync_ws + 880;
void* r[] = {(void*)&xp, (void*)&M, (void*)&Mp, (void*)&K, (void*)&wp, (void*)&wsf_blk,
(void*)&Nw, (void*)&w_gd, (void*)&xq, (void*)&xsf_blk, (void*)&sw,
(void*)&ab, (void*)&rlate, (void*)&avec, (void*)&pfp, (void*)&pfb,
(void*)&tmPF, (void*)&pf_ops, (void*)&pf_ci, (void*)&pf_bi, (void*)&pf_bo};
// slot barrier: private block sync_ws[2048..] (tag counter + 2 floats per CTA, <= 4096)
float* swl = sync_ws + 2048;
void* rl[] = {(void*)&xp, (void*)&M, (void*)&Mp, (void*)&K, (void*)&wp, (void*)&wsf_blk,
(void*)&Nw, (void*)&w_gd, (void*)&xq, (void*)&xsf_blk, (void*)&swl,
(void*)&ab, (void*)&rlate, (void*)&avec, (void*)&pfp, (void*)&pfb,
(void*)&tmPF, (void*)&pf_ops, (void*)&pf_ci, (void*)&pf_bi, (void*)&pf_bo};
if (carve != 0) coop_launch(fused_quant_res_kernel<2, 1, 128>, need2h, r, s, 0, 128);
else if (g_res_dbo && rspc == 52 && res_spec_ok<2, 128, 52 | 128>())
coop_launch(fused_quant_res_kernel<2, 0, 128, 52 | 128>, need2h, r, s, 0, 128);
else if (g_res_slot && rspc == 52 && 4 + 2 * need2h <= kMaxPartials - 2048 &&
res_spec_ok<2, 128, 52 | 64>())
coop_launch(fused_quant_res_kernel<2, 0, 128, 52 | 64>, need2h, rl, s, 0, 128);
else if (rspc == 52 && res_spec_ok<2, 128, 52>()) coop_launch(fused_quant_res_kernel<2, 0, 128, 52>, need2h, r, s, 0, 128);
else coop_launch(fused_quant_res_kernel<2, 0, 128>, need2h, r, s, 0, 128);
return;
}
}
// carve < 0: default per variant (register-resident: max carveout, persistent: default split)
if (need4 <= g4) {
if (carve != 0) coop_launch(fused_quant_res_kernel<4, 1>, need4, rargs, s);
else if (g_res_slot && rspc == 34 && 4 + 2 * need4 <= kMaxPartials - 2048 && res_spec_ok<4, kThreads, 34 | 64>()) {
// fence-free slot barrier (SP bit 64, Mp 128 pin): private block sync_ws[2048..]
float* swl4 = sync_ws + 2048;
void* r4l[] = {(void*)&xp, (void*)&M, (void*)&Mp, (void*)&K, (void*)&wp, (void*)&wsf_blk,
(void*)&Nw, (void*)&w_gd, (void*)&xq, (void*)&xsf_blk, (void*)&swl4,
(void*)&ab, (void*)&rlate, (void*)&avec, (void*)&pfp, (void*)&pfb,
(void*)&tmPF, (void*)&pf_ops, (void*)&pf_ci, (void*)&pf_bi, (void*)&pf_bo};
coop_launch(fused_quant_res_kernel<4, 0, kThreads, 34 | 64>, need4, r4l, s);
}
else if (rspc == 34 && res_spec_ok<4, kThreads, 34>()) coop_launch(fused_quant_res_kernel<4, 0, kThreads, 34>, need4, rargs, s);
else if (rspc == 52 && res_spec_ok<4, kThreads, 52>()) coop_launch(fused_quant_res_kernel<4, 0, kThreads, 52>, need4, rargs, s);
else coop_launch(fused_quant_res_kernel<4, 0>, need4, rargs, s);
} else if (need8 <= g8) {
if (carve != 0) coop_launch(fused_quant_res_kernel<8, 1>, need8, rargs, s);
else coop_launch(fused_quant_res_kernel<8, 0>, need8, rargs, s);
} else if (launch_hyb_quant(x, M, Mp, K, wp, wsf_blk, Nw, w_gd, xq, xsf_blk, sync_ws, ab, late,
avec, s, tmPF, pf_ops, pf_ci, pf_bi, pf_bo)) {
// hybrid register + smem resident variant (x read once)
} else {
// compile-time pin variant when the runtime bits equal its constants (see fused_quant_kernel)
const bool pin = g_pin_ok && Mp >= 4096 && (al32 & (2 | 4096 | 512)) == (2 | 4096 | 512) &&
(Mp < 8192 || (al32 & 1024));
if (carve > 0) coop_launch(fused_quant_kernel<1>, gp, args, s);
else if (g_keep_ok && Mp >= 4096) {
// smem-kept first granule (al32 bit 2) with its 32 KB of dynamic smem
int alk = al32 | 4;
args[14] = (void*)&alk;
if (pin) coop_launch(fused_quant_kernel<0, 4, true>, gp, args, s, kKeepSmem);
else coop_launch(fused_quant_kernel<0>, gp, args, s, kKeepSmem);
} else if (pin) {
coop_launch(fused_quant_kernel<0, 4, true>, gp, args, s);
} else {
coop_launch(fused_quant_kernel<0>, gp, args, s);
}
}
}
__device__ __forceinline__ uint32_t smem_u32(const void* p) {
return (uint32_t)__cvta_generic_to_shared(p);
}
__device__ __forceinline__ void mbar_init(uint32_t bar, uint32_t cnt) {
asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(bar), "r"(cnt) : "memory");
}
__device__ __forceinline__ void mbar_expect_tx(uint32_t bar, uint32_t bytes) {
asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(bar), "r"(bytes)
: "memory");
}
__device__ __forceinline__ void mbar_wait(uint32_t bar, uint32_t parity) {
uint32_t ok = 0;
do {
asm volatile(
"{\n .reg .pred p;\n mbarrier.try_wait.parity.shared::cta.b64 p, [%1], %2, %3;\n"
" selp.u32 %0, 1, 0, p;\n}\n"
: "=r"(ok)
: "r"(bar), "r"(parity), "r"(0x989680u)
: "memory");
} while (!ok);
}
__device__ __forceinline__ void tma_load_2d(uint32_t dst, const CUtensorMap* tm, int c0, int c1,
uint32_t bar) {
asm volatile(
"cp.async.bulk.tensor.2d.shared::cluster.global.tile.mbarrier::complete_tx::bytes"
" [%0], [%1, {%2, %3}], [%4];" ::"r"(dst),
"l"((uint64_t)tm), "r"(c0), "r"(c1), "r"(bar)
: "memory");
}
__device__ __forceinline__ void tma_load_2d_wl(uint32_t dst, const CUtensorMap* tm, int c0, int c1,
uint32_t bar) {
uint64_t pol;
asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol));
asm volatile(
"cp.async.bulk.tensor.2d.shared::cluster.global.tile.mbarrier::complete_tx::bytes.L2::cache_hint"
" [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(dst),
"l"((uint64_t)tm), "r"(c0), "r"(c1), "r"(bar), "l"(pol)
: "memory");
}
// Weight-operand TMA load with an L2 evict_first policy (swap-AB GEMM, Mp = 128 pin): at small M
// the weight is streamed exactly once per call, so it should not displace other L2 lines.
__device__ __forceinline__ void tma_load_2d_wf(uint32_t dst, const CUtensorMap* tm, int c0, int c1,
uint32_t bar) {
uint64_t pol;
asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol));
asm volatile(
"cp.async.bulk.tensor.2d.shared::cluster.global.tile.mbarrier::complete_tx::bytes.L2::cache_hint"
" [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(dst),
"l"((uint64_t)tm), "r"(c0), "r"(c1), "r"(bar), "l"(pol)
: "memory");
}
__device__ __forceinline__ void bulk_load(uint32_t dst, const void* src, uint32_t bytes,
uint32_t bar) {
asm volatile(
"cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1], %2, [%3];" ::"r"(
dst),
"l"((uint64_t)src), "r"(bytes), "r"(bar)
: "memory");
}
// 1D bulk copy with an L2 evict_first cache policy (last use of the source bytes: the hybrid
// quant reads x exactly once, so x must not displace the L2-resident weight / xq / output lines).
__device__ __forceinline__ void bulk_load_ef(uint32_t dst, const void* src, uint32_t bytes,
uint32_t bar, uint64_t pol) {
asm volatile(
"cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint"
" [%0], [%1], %2, [%3], %4;" ::"r"(dst),
"l"((uint64_t)src), "r"(bytes), "r"(bar), "l"(pol)
: "memory");
}
static constexpr int kHybIR = 10, kHybISMax = 12;
// IR_ = register-tier items per thread, MINB = CTAs per SM (launch bounds): <kHybIR, 2>.
// SP: compile-time PIN (-1 = runtime): bit 0 = late PDL trigger, bits 2-3 = weight-scale
// re-layout mode (0 none, 1 padded-224 N < 0 without bit 29, 2 padded-112, 3 plain N > 0),
// bit 4 = prefix prefetch on, bit 5 = avec == nullptr. Host-verified equal -> bit-identical.
template <int IR_, int MINB, int SP = -1>
__global__ void __launch_bounds__(kThreads, MINB)
fused_quant_hyb_kernel(const uint4* __restrict__ x, int M, int Mp, int K, int IS,
const uint32_t* __restrict__ wsf, uint8_t* __restrict__ wsf_blk, int N,
float w_gd, uint8_t* __restrict__ xq, uint8_t* __restrict__ xsf_blk,
float* __restrict__ hyb_ws, float* __restrict__ ab, int late,
float* __restrict__ avec, const __grid_constant__ CUtensorMap tmPF,
int pf_ops, int pf_ci, int pf_bi, int pf_bo) {
constexpr int IR = IR_;
extern __shared__ __align__(128) uint8_t hsm[];
__shared__ uint32_t sm[32];
// one mbarrier per 16 KB bulk chunk (IS <= 12 -> <= 96 KB -> <= 6 chunks): the amax fold of
// chunk c starts as soon as chunk c landed instead of after the whole smem range landed
constexpr int kHybCh = (kHybISMax * kThreads * 32 + 16383) / 16384;
__shared__ __align__(8) unsigned long long hbar[kHybCh];
if constexpr (SP >= 0) late = SP & 1;
constexpr int kNM = SP >= 0 ? ((SP >> 2) & 3) : -1;
const bool pf_on = SP >= 0 ? ((SP & 16) != 0) : (pf_ops > 0);
if (!late) asm volatile("griddepcontrol.launch_dependents;" ::: "memory");
const int tid = threadIdx.x;
const int sfk = K >> 4, ncb = sfk >> 2;
const int n_items = Mp * sfk;
const int n_real = M * sfk;
const int cbase = blockIdx.x * ((IR + IS) * kThreads);
const int base = cbase + tid;
// SMEM-TIER BULK COPIES ISSUED FIRST: thread 0 initialises the per-chunk mbarriers and issues
// the cp.async.bulk copies of this CTA's contiguous smem-resident x range at kernel ENTRY,
// before any register-tier load (bulk copies need no registers; the smem tier is the part of
// x that lands last). The other threads issue their register-tier loads meanwhile; the CTA
// barrier below (before any thread waits on an mbarrier) publishes the initialised barriers.
// Same data, same fold order per chunk -> bit-identical results.
const int s0 = cbase + IR * kThreads; // first smem-resident item
const int s1 = min(s0 + IS * kThreads, n_real); // end of the real (loaded) part
const uint32_t bar = smem_u32(&hbar[0]); // chunk c barrier at bar + 8*c
const bool have_s = s1 > s0;
if (tid == 0) {
for (int ch = 0; ch < kHybCh; ++ch) mbar_init(bar + 8 * ch, 1);
asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory");
asm volatile("fence.proxy.async.shared::cta;" ::: "memory");
if (have_s) {
const uint32_t bytes = (uint32_t)(s1 - s0) * 32u;
const uint8_t* src = reinterpret_cast<const uint8_t*>(x) + (size_t)s0 * 32;
uint64_t pol;
asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol));
for (uint32_t off = 0; off < bytes; off += 16384u) {
const uint32_t cb = bar + 8u * (off >> 14), n = min(16384u, bytes - off);
mbar_expect_tx(cb, n);
bulk_load_ef(smem_u32(hsm) + off, src + off, n, cb, pol);
}
}
}
// register-resident items (coalesced, evict_first streaming loads)
uint4 v0[IR], v1[IR];
uint32_t m2 = 0;
#pragma unroll
for (int j = 0; j < IR; ++j) {
const int t = base + j * kThreads;
v0[j] = make_uint4(0, 0, 0, 0);
v1[j] = make_uint4(0, 0, 0, 0);
if (t < n_real) { v0[j] = __ldcs(x + 2 * t); v1[j] = __ldcs(x + 2 * t + 1); }
}
const unsigned long long ep = grid_epoch(hyb_ws);
__syncthreads(); // mbarrier inits visible before any thread waits on them
float pbm[IR];
uint32_t mreg = 0;
#pragma unroll
for (int j = 0; j < IR; ++j) {
pbm[j] = item_bm_p(v0[j], v1[j]);
mreg = max(mreg, __float_as_uint(pbm[j]));
}
// smem-resident items (amax only here; quantized after the barrier)
const uint4* hs = reinterpret_cast<const uint4*>(hsm);
if (have_s) {
const int n4 = (s1 - s0) * 2; // 16 B chunks of real (loaded) items
for (int ch = 0; ch * 1024 < n4; ++ch) {
mbar_wait(bar + 8 * ch, 0);
const int fe = min(n4, (ch + 1) * 1024);
#pragma unroll 4
for (int f = ch * 1024 + tid; f < fe; f += kThreads) m2 = acc_u4(m2, hs[f]);
}
}
const uint32_t bmax = block_max_u32(max(mreg, amax_fin(m2)), sm); // m2: smem tier only
grid_arrive(bmax, hyb_ws, ep);
const uint4* hs2 = reinterpret_cast<const uint4*>(hsm);
float* hbm = reinterpret_cast<float*>(hsm + (size_t)IS * kThreads * 32);
// SMEM-ITEM BLOCK MAXIMA in the barrier window: per-item max|x| of this thread's smem-resident
// items (amax-independent) is written to a per-item float slot behind the item data
// (hbm[l], l = item index inside the smem range; each thread only touches its own slots ->
// no CTA barrier). Pass 2 then reads one float instead of re-folding 16 values. Bit-identical.
auto smem_bm = [&]() {
#pragma unroll 2
for (int j = 0; j < IS; ++j) {
const int t = s0 + j * kThreads + tid;
if (t < s1) {
const int l = t - s0;
hbm[l] = item_bm_p(hs2[2 * l], hs2[2 * l + 1]);
}
}
};
// padded layout (256x224 CUTLASS tiles): smem-item block maxima run while the relayout's
// weight-scale loads are in flight (see wsf_relayout_pad_ovl)
if (kNM >= 0 ? kNM == 2 : (N < 0 && ((-N) & (1 << 29)))) { wsf_relayout_pad<kThreads>(wsf, wsf_blk, -N, ncb); smem_bm(); }
else if (kNM >= 0 ? kNM == 1 : N < 0) wsf_relayout_pad_ovl<kThreads>(wsf, wsf_blk, -N, ncb, smem_bm);
else {
if (kNM >= 0 ? kNM == 3 : N > 0) wsf_relayout_lo(wsf, wsf_blk, N, ncb); // low-index CTAs only, in the barrier window
smem_bm();
}
// amax-independent scale offsets of the register tier (block maxima: computed above)
uint32_t psoff[IR];
#pragma unroll
for (int j = 0; j < IR; ++j) {
const int t = base + j * kThreads;
const bool p2 = (sfk & (sfk - 1)) == 0;
const int r = p2 ? (t >> (__ffs(sfk) - 1)) : t / sfk;
psoff[j] = blk_off(r, t - r * sfk, ncb);
}
const float amax = __uint_as_float(grid_wait_bo(hyb_ws, sm, ep));
float ge, gd;
global_scales(amax, w_gd, ab, ge, gd);
if constexpr (SP < 0 || !(SP & 32)) write_avec(avec, N, gd, w_gd);
if (late) pdl_late_trigger();
// xq / scale stores with an L2 evict_last policy: the quantized x stays L2-resident for the
// dependent GEMM instead of competing with other traffic. Bit-identical values.
uint64_t pol;
asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol));
#pragma unroll
for (int j = 0; j + 1 < IR; j += 2) {
const int t = base + j * kThreads, t1 = t + kThreads;
quant_post_pair<true>(t, t1, v0[j], v1[j], v0[j + 1], v1[j + 1], pbm[j], pbm[j + 1], psoff[j],
psoff[j + 1], t < n_items, t1 < n_items, ge, gd, xq, xsf_blk, pol);
}
if constexpr (IR & 1) {
const int t = base + (IR - 1) * kThreads;
if (t < n_items) quant_post<true>(t, v0[IR - 1], v1[IR - 1], pbm[IR - 1], psoff[IR - 1], ge, gd, xq, xsf_blk, pol);
}
const uint4 z = make_uint4(0, 0, 0, 0);
// smem tier in PAIRS (j, j+1); odd IS: last item alone (ok1 = false)
auto sitem = [&](int t, uint4& a, uint4& b, float& bm, uint32_t& so) {
a = z; b = z; bm = 0.f;
if (t < s1) { const int l = t - s0; a = hs[2 * l]; b = hs[2 * l + 1]; bm = hbm[l]; }
const bool p2 = (sfk & (sfk - 1)) == 0;
const int r = p2 ? (t >> (__ffs(sfk) - 1)) : t / sfk;
so = blk_off(r, t - r * sfk, ncb);
};
#pragma unroll 1
for (int j = 0; j < IS; j += 2) {
const int t = s0 + j * kThreads + tid, t1 = t + kThreads;
const bool ok0 = t < n_items, ok1 = (j + 1 < IS) && t1 < n_items;
if (!ok0) continue;
uint4 a0, a1, b0, b1;
float bm0, bm1;
uint32_t so0, so1 = 0;
sitem(t, a0, a1, bm0, so0);
if (ok1) sitem(t1, b0, b1, bm1, so1);
else { b0 = z; b1 = z; bm1 = 0.f; }
quant_post_pair<true>(t, t1, a0, a1, b0, b1, bm0, bm1, so0, so1, ok0, ok1, ge, gd, xq, xsf_blk, pol);
}
// COLD-L2 WEIGHT PREFIX PREFETCH (pf_ops > 0: Mp = 2048 CUTLASS k6 pin), same 2D TMA tensor
// prefetch form as fused_quant_res_kernel: after this CTA's last xq / scale store, thread 0
// issues the CTA's share of pf_ops boxes {pf_bi B, pf_bo rows} covering the first K-prefix of
// every fp4 weight row (fire-and-forget L2 fill, no smem, output unaffected).
if (pf_on && tid == 0) {
for (int o = blockIdx.x; o < pf_ops; o += gridDim.x) {
const int ci = o % pf_ci, ro = o / pf_ci;
asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile [%0, {%1, %2}];"
::"l"((uint64_t)&tmPF), "r"(ci * pf_bi), "r"(ro * pf_bo) : "memory");
}
}
}
// Host launcher; returns false (nothing launched) if not applicable.
// Variant 3x<4>: 3 CTAs/SM, 4 register items + IS smem items per thread, used when its smem tier
// fits 3 CTAs per SM; otherwise the 2x<8> variant (as before).
// compile-time pin of the Mp 2048 plan (late 0, padded-224 re-layout, prefix prefetch, no avec)
static constexpr int kHybSP = 4 | 16 | 32;
static bool launch_hyb_quant(const void* x, int M, int Mp, int K, const uint32_t* wsf,
uint8_t* wsf_blk, int N, float w_gd, uint8_t* xq, uint8_t* xsf_blk,
float* sync_ws, float* ab, int late, float* avec, cudaStream_t s,
const CUtensorMap& tmPF, int pf_ops, int pf_ci, int pf_bi, int pf_bo) {
static int gh = -1, sms = 0;
static bool sp_ok = false; // pinned instantiation verified co-resident like the generic one
const void* kg = (const void*)fused_quant_hyb_kernel<kHybIR, 2>;
const void* kp = (const void*)fused_quant_hyb_kernel<kHybIR, 2, kHybSP>;
const int smax = kHybISMax * kThreads * 36; // item data + per-item block-max float
if (gh < 0) {
for (const void* k : {kg, kp}) {
cudaFuncSetAttribute(k, cudaFuncAttributeMaxDynamicSharedMemorySize, smax);
cudaFuncSetAttribute(k, cudaFuncAttributePreferredSharedMemoryCarveout, 100);
}
int dev, per = 0, perp = 0;
cudaGetDevice(&dev);
cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev);
if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per, kg, kThreads, smax) != cudaSuccess) per = 0;
if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&perp, kp, kThreads, smax) != cudaSuccess) perp = 0;
cudaGetLastError();
gh = per >= 1 ? std::min(sms * per, kMaxPartials) : 0;
sp_ok = perp >= per && per >= 1;
}
if (gh <= 0 || (((uintptr_t)x) & 15) != 0) return false;
const long long n_items = (long long)Mp * (K / 16);
float* hws = sync_ws + 600; // private barrier counter block (u64 ctr + 2 amax slots)
const long long per_thr = (n_items + (long long)gh * kThreads - 1) / ((long long)gh * kThreads);
int IS = (int)per_thr - kHybIR;
if (IS < 1) IS = 1;
if (IS > kHybISMax) return false;
const long long ipc = (long long)(kHybIR + IS) * kThreads;
const int grid = (int)((n_items + ipc - 1) / ipc);
if (grid > gh) return false;
{
static int is_set = 0;
if (IS > is_set) {
int dev = 0, smsm = 0;
cudaGetDevice(&dev);
cudaDeviceGetAttribute(&smsm, cudaDevAttrMaxSharedMemoryPerMultiprocessor, dev);
for (int v = 0; v < 2; ++v) {
const void* k = v ? kp : kg;
cudaFuncAttributes fa{};
cudaFuncGetAttributes(&fa, k);
const long long need = 2ll * ((long long)IS * kThreads * 36 + (long long)fa.sharedSizeBytes + 1024);
int pct = smsm > 0 ? (int)((need * 100 + smsm - 1) / smsm) + 1 : 100;
if (pct > 100) pct = 100;
cudaFuncSetAttribute(k, cudaFuncAttributePreferredSharedMemoryCarveout, pct);
int per = 0;
if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per, k, kThreads, IS * kThreads * 36) != cudaSuccess ||
(long long)per * sms < grid || per < 2) {
cudaFuncSetAttribute(k, cudaFuncAttributePreferredSharedMemoryCarveout, 100);
if (v) sp_ok = false;
}
}
cudaGetLastError();
is_set = IS;
}
}
const int spc = (late & 1) | (N == 0 ? 0 : (N > 0 ? 12 : (((-N) & (1 << 29)) ? 8 : 4))) |
(pf_ops > 0 ? 16 : 0) | (avec == nullptr ? 32 : 0);
if (sp_ok && spc == kHybSP)
fused_quant_hyb_kernel<kHybIR, 2, kHybSP><<<grid, kThreads, IS * kThreads * 36, s>>>(
(const uint4*)x, M, Mp, K, IS, wsf, wsf_blk, N, w_gd, xq, xsf_blk, hws, ab, late, avec, tmPF, pf_ops,
pf_ci, pf_bi, pf_bo);
else
fused_quant_hyb_kernel<kHybIR, 2><<<grid, kThreads, IS * kThreads * 36, s>>>(
(const uint4*)x, M, Mp, K, IS, wsf, wsf_blk, N, w_gd, xq, xsf_blk, hws, ab, late, avec, tmPF, pf_ops,
pf_ci, pf_bi, pf_bo);
return cudaPeekAtLastError() == cudaSuccess;
}
// tcgen05 shared-memory matrix descriptor
// [0,14) start>>4 | [16,30) LBO>>4 | [32,46) SBO>>4 | [46,49)=0b001 | [61,64) swizzle
__device__ __forceinline__ uint64_t make_desc(uint32_t saddr, uint32_t lbo, uint32_t sbo,
uint32_t swz) {
uint64_t d = 0;
d |= (uint64_t)((saddr >> 4) & 0x3FFF);
d |= (uint64_t)((lbo >> 4) & 0x3FFF) << 16;
d |= (uint64_t)((sbo >> 4) & 0x3FFF) << 32;
d |= (uint64_t)1 << 46;
d |= (uint64_t)swz << 61;
return d;
}
__device__ __forceinline__ void epi_bar() { asm volatile("bar.sync 1, 128;" ::: "memory"); }
__device__ __forceinline__ void cluster_sync_all() {
asm volatile("barrier.cluster.arrive.release;\n barrier.cluster.wait.acquire;" ::: "memory");
}
__device__ __forceinline__ uint32_t cluster_rank() {
uint32_t r;
asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(r));
return r;
}
__device__ __forceinline__ void tmem_ld32(uint32_t taddr, uint32_t* r) {
asm volatile(
"tcgen05.ld.sync.aligned.32x32b.x32.b32 {%0,%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11,%12,%13,"
"%14,%15,%16,%17,%18,%19,%20,%21,%22,%23,%24,%25,%26,%27,%28,%29,%30,%31}, [%32];"
: "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]), "=r"(r[4]), "=r"(r[5]), "=r"(r[6]),
"=r"(r[7]), "=r"(r[8]), "=r"(r[9]), "=r"(r[10]), "=r"(r[11]), "=r"(r[12]),
"=r"(r[13]), "=r"(r[14]), "=r"(r[15]), "=r"(r[16]), "=r"(r[17]), "=r"(r[18]),
"=r"(r[19]), "=r"(r[20]), "=r"(r[21]), "=r"(r[22]), "=r"(r[23]), "=r"(r[24]),
"=r"(r[25]), "=r"(r[26]), "=r"(r[27]), "=r"(r[28]), "=r"(r[29]), "=r"(r[30]),
"=r"(r[31])
: "r"(taddr));
asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory");
}
__device__ __forceinline__ uint32_t u4c(const uint4& v, int k) {
return k == 0 ? v.x : (k == 1 ? v.y : (k == 2 ? v.z : v.w));
}
static bool make_tmap_u8(CUtensorMap* tm, const void* ptr, uint64_t inner, uint64_t outer,
uint32_t box_inner, uint32_t box_outer, CUtensorMapSwizzle swz) {
cuuint64_t dims[2] = {inner, outer};
cuuint64_t strides[1] = {inner};
cuuint32_t box[2] = {box_inner, box_outer};
cuuint32_t es[2] = {1, 1};
return cuTensorMapEncodeTiled(tm, CU_TENSOR_MAP_DATA_TYPE_UINT8, 2, const_cast<void*>(ptr), dims,
strides, box, es, CU_TENSOR_MAP_INTERLEAVE_NONE, swz,
CU_TENSOR_MAP_L2_PROMOTION_L2_256B,
CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE) == CUDA_SUCCESS;
}
// =============================================================================================
// SWAP-AB tcgen05 NVFP4 GEMM (small M): D^T[N, Mp] = (wq * sfw) @ (xq * sfx)^T * alpha
// The weight is the MMA M operand (128-row tiles over N -> N/128 = 64 tiles), the tokens are the
// MMA N operand (BX = 128 or 256 tokens per tile) -> full 128-lane MMAs, weight streamed exactly
// once per token tile. Grid (N/128, Mp/BX, S); S > 1 = (1,1,S) cluster split-K over L2 workspace
// (same deterministic owner-sum scheme as nvfp4_splitk_gemm, owner slices = token columns).
// Warp roles identical to nvfp4_splitk_gemm:
// warp 0: TMA producer. Weight (A: 128 rows x 128 B SW128 + raw row-major scales box {16,128})
// is issued for the first ring BEFORE griddepcontrol.wait (independent of the quant
// kernel); x (B: BX rows x 128 B SW128 + H = BX/128 blocked 2 KB scale chunks) after.
// warp 1: MMA issuer: 4*KS x tcgen05.mma kind::mxf4nvf4 scale_vec::4X 128xBXx64 per stage
// (KS = 1 or 2 K=256 sub-steps per stage, autotuned; KS=2 halves barrier round trips).
// warps 2-5: scale writer (waits only the per-stage scale barrier bar_sf, runs up to ST stages
// ahead of the MMA into the ST-slot TMEM scale ring; smem -> tcgen05.st), then epilogue: TMEM lane = weight row n,
// TMEM column = token m -> transposed bf16 stores (warp writes 64 contiguous bytes of
// one output row per instruction).
// TMEM: [0, BX) accumulator, then per stage SF_COLS = 16 (SFA: weight, col kc*4+j = row 32j+l)
// + 16H (SFB: x, col 16 + kc*4H + h*4 + j = blocked chunk (h, kc) word j) columns.
// =============================================================================================
static constexpr int kSwNT = 256;
template <int BX, int KS = 1>
struct SWC {
static constexpr int H = BX / 128;
static constexpr int ST = ((BX == 128) ? 6 : 4) / KS;
static constexpr int SUB_A = 128 * 128; // weight sub-tile 128 rows x 128 B (256 fp4)
static constexpr int SUB_B = BX * 128; // x sub-tile BX rows x 128 B
static constexpr int SUB_SFA = 2048; // raw weight scales 128 rows x 16 B
static constexpr int SUB_SFB = H * 2048; // blocked x scales, H chunks of 2 KB
static constexpr int SF_SUB = 16 + 16 * H; // TMEM scale columns per sub-step
static constexpr int A_BYTES = KS * SUB_A;
static constexpr int B_BYTES = KS * SUB_B;
static constexpr int SFA_BYTES = KS * SUB_SFA;
static constexpr int SFB_BYTES = KS * SUB_SFB;
static constexpr int A_OFF = 0;
static constexpr int B_OFF = A_OFF + ST * A_BYTES;
static constexpr int SFA_OFF = B_OFF + ST * B_BYTES;
static constexpr int SFB_OFF = SFA_OFF + ST * SFA_BYTES;
static constexpr int BAR_OFF = SFB_OFF + ST * SFB_BYTES;
static constexpr int SMEM = BAR_OFF + 256 + 1024;
static constexpr int STAGE_TX = A_BYTES + B_BYTES + SFA_BYTES + SFB_BYTES;
static constexpr int SF_COLS = KS * SF_SUB;
static_assert(BX + ST * SF_COLS <= 512, "TMEM");
};
// 32 fp32 accumulators of one weight row n, tokens m0..m0+31 -> out[m][n] (transposed store)
__device__ __forceinline__ void store_bf16x32_T(const float* f, float gs, __nv_bfloat16* p,
int N) {
#pragma unroll
for (int j = 0; j < 32; ++j) {
p[(size_t)j * N] = __float2bfloat16_rn(__fmul_rn(f[j], gs)); // single rounding bf16_rn(alpha*acc)
}
}
// tcgen05.ld 32x32b.x32 WITHOUT the wait (caller batches several loads, then one wait::ld)
__device__ __forceinline__ void tmem_ld32_nw(uint32_t taddr, uint32_t* r) {
asm volatile(
"tcgen05.ld.sync.aligned.32x32b.x32.b32 {%0,%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11,%12,%13,"
"%14,%15,%16,%17,%18,%19,%20,%21,%22,%23,%24,%25,%26,%27,%28,%29,%30,%31}, [%32];"
: "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]), "=r"(r[4]), "=r"(r[5]), "=r"(r[6]),
"=r"(r[7]), "=r"(r[8]), "=r"(r[9]), "=r"(r[10]), "=r"(r[11]), "=r"(r[12]),
"=r"(r[13]), "=r"(r[14]), "=r"(r[15]), "=r"(r[16]), "=r"(r[17]), "=r"(r[18]),
"=r"(r[19]), "=r"(r[20]), "=r"(r[21]), "=r"(r[22]), "=r"(r[23]), "=r"(r[24]),
"=r"(r[25]), "=r"(r[26]), "=r"(r[27]), "=r"(r[28]), "=r"(r[29]), "=r"(r[30]),
"=r"(r[31])
: "r"(taddr));
}
// 64 fp32 accumulators (raw bits) of one weight row n, tokens m0..m0+63 -> out[m][n].
// Same rounding as store_bf16x32_T: single bf16_rn(acc * gs) (like the CUTLASS epilogues),
// computed pairwise: mul.rn.f32x2 + cvt.rn.bf16x2.f32.
template <int NC>
__device__ __forceinline__ void store_bf16xN_T(const uint32_t* u, float gs, __nv_bfloat16* p,
int N) {
#pragma unroll
for (int j = 0; j < NC; j += 2) {
uint32_t o; // single rounding: one mul.rn.f32x2 + one cvt.rn.bf16x2.f32 per pair
asm("{\n .reg .b64 s, v;\n .reg .b32 l, h;\n mov.b64 s, {%3, %3};\n mov.b64 v, {%1, %2};\n"
" mul.rn.f32x2 v, v, s;\n mov.b64 {l, h}, v;\n cvt.rn.bf16x2.f32 %0, h, l;\n}"
: "=r"(o) : "f"(__uint_as_float(u[j])), "f"(__uint_as_float(u[j + 1])), "f"(gs));
p[(size_t)j * N] = __ushort_as_bfloat16((unsigned short)(o & 0xffffu));
p[(size_t)(j + 1) * N] = __ushort_as_bfloat16((unsigned short)(o >> 16));
}
}
__device__ __forceinline__ void store_bf16x64_T(const uint32_t* u, float gs, __nv_bfloat16* p,
int N) {
store_bf16xN_T<64>(u, gs, p, N);
}
// PIN = 1: compile-time pin of the Mp 128 plan's runtime knobs (S = 2 split-K, no cold-L2 weight
// prefetch, no token-fastest raster, N = K = 8192). The host launches it only when the runtime
// values equal these constants -> same code path / values, bit-identical; the constants fold the
// S == 1 / generic split-K branches, the prefetch loop and the K-dependent stage arithmetic.
template <int BX, bool FUSED, int KS, int PIN = 0>
__global__ void __launch_bounds__(kSwNT, 1)
nvfp4_swapab_gemm(const __grid_constant__ CUtensorMap tmW, const __grid_constant__ CUtensorMap tmX,
const __grid_constant__ CUtensorMap tmWS, const uint8_t* sfx,
const float* __restrict__ ab, __nv_bfloat16* __restrict__ out, int N, int K,
int S, float* __restrict__ red_ws,
// FUSED only: bf16 x, real/padded rows, w_gd, writable xq / x scales, barrier ws
const uint4* __restrict__ xin, int M, int Mp, float w_gd, uint8_t* xq_w,
uint8_t* xsf_w, float* fsync, int pf_end, int mfast) {
if constexpr (PIN == 1) { S = 2; pf_end = 0; mfast = 0; N = 8192; K = 8192; }
using C = SWC<BX, KS>;
constexpr int ST = C::ST, H = C::H;
// weight ring stages issued before griddepcontrol.wait: BX=128/KS=2 (Mp 128 pin) issues only 2
// of its 3 stages up front so the first x tile does not queue behind the whole weight ring.
constexpr int NPRE = (!FUSED && BX == 128 && KS == 2) ? 2 : ST;
extern __shared__ uint8_t smem_raw[];
uint8_t* smem = (uint8_t*)(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023);
const uint32_t sbase = smem_u32(smem);
const uint32_t bar_full = sbase + C::BAR_OFF;
const uint32_t bar_empty = bar_full + ST * 8;
const uint32_t bar_sfr = bar_empty + ST * 8;
const uint32_t bar_done = bar_sfr + ST * 8;
// bar_sf: scale bytes (SFA + SFB) of the stage landed -- separate from bar_full (A/B tiles) so
// the scale writers fill the TMEM scale ring slot while the big operand tiles are in flight
const uint32_t bar_sf = bar_done + 8;
uint32_t* tmem_slot = reinterpret_cast<uint32_t*>(smem + C::BAR_OFF + 4 * ST * 8 + 8);
const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
// mfast (non-fused S == 1 only): grid (Mp/BX, N/128) with the token tile fastest, so the
// Mp/BX CTAs sharing one weight tile get ADJACENT blockIdx -> launched together on neighbouring
// SMs: their identical weight-tile TMA requests coincide in time (one DRAM/L2 fetch serves both)
// instead of being Mp/BX * 64 CTAs apart in launch order.
const int n_tile = mfast ? blockIdx.y : blockIdx.x, m_tile = mfast ? blockIdx.x : blockIdx.y,
split = blockIdx.z;
const int n_mt = mfast ? (int)gridDim.x : (int)gridDim.y; // token tiles
const int nk = (K / 256) / S / KS; // pipeline stages of this split (KS sub-steps each)
const int k0 = split * nk; // first stage; sub-step kt = (k0 + it) * KS + ks
const int ncb = K / 64;
// EARLY WEIGHT ISSUE: warp 2 lane 0 (the weight-ring prefetch thread) prefetches the weight
// descriptors, initialises the mbarriers and issues the first NPRE weight stages right here at
// kernel entry, BEFORE the TMEM allocation + CTA barrier (and long before the producer's
// griddepcontrol.wait). The weights do not depend on the quant kernel. Thread 0 prefetches the
// x descriptor. The CTA barrier below still publishes the initialised barriers to every waiter.
if (threadIdx.x == 0) asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tmX) : "memory");
if (threadIdx.x == 64) {
asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tmW) : "memory");
asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tmWS) : "memory");
for (int s = 0; s < ST; ++s) {
// full: producer expect_tx arrival + TMA bytes + 4 scale-writer warp arrivals (scales in
// TMEM) -> the MMA warp does ONE wait per stage
mbar_init(bar_full + 8 * s, 5);
mbar_init(bar_empty + 8 * s, 1);
mbar_init(bar_sf + 8 * s, 1);
}
mbar_init(bar_done, 1);
asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory");
asm volatile("fence.proxy.async.shared::cta;" ::: "memory");
// first ST stages of weight tiles + raw weight scales (independent of x -> overlap the
// quant / PDL wait).
const int npre0 = nk < NPRE ? nk : NPRE;
for (int it = 0; it < npre0; ++it) {
const uint32_t fb = bar_full + 8 * it, sb = bar_sf + 8 * it;
mbar_expect_tx(fb, C::A_BYTES + C::B_BYTES);
mbar_expect_tx(sb, C::SFA_BYTES + C::SFB_BYTES);
#pragma unroll
for (int ks = 0; ks < KS; ++ks) {
const int kt = (k0 + it) * KS + ks;
tma_load_2d_wf(sbase + C::SFA_OFF + it * C::SFA_BYTES + ks * C::SUB_SFA, &tmWS, kt * 16, n_tile * 128, sb);
tma_load_2d_wf(sbase + C::A_OFF + it * C::A_BYTES + ks * C::SUB_A, &tmW, kt * 128, n_tile * 128, fb);
}
}
// COLD-L2 weight prefetch (pf_end > 0, host-selected per plan): stages [npre0, pf_end) of this
// split's weight tiles + raw weight scales are pulled into L2 (evict_last, no smem) BEFORE the
// quant dependency resolves, so a flushed-L2 call streams them from DRAM while the quant runs
// instead of on the mainloop's critical path. The gridDim.y token-tile CTAs sharing the weight
// tile split the stages round robin (each byte prefetched once). Warm L2: prefetches hit L2.
if (pf_end > npre0) {
uint64_t pol;
asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol));
for (int it = npre0; it < pf_end && it < nk; ++it) {
if ((it % n_mt) != m_tile) continue;
#pragma unroll
for (int ks = 0; ks < KS; ++ks) {
const int kt = (k0 + it) * KS + ks;
asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile.L2::cache_hint [%0, {%1, %2}], %3;"
::"l"((uint64_t)&tmW), "r"(kt * 128), "r"(n_tile * 128), "l"(pol) : "memory");
asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile.L2::cache_hint [%0, {%1, %2}], %3;"
::"l"((uint64_t)&tmWS), "r"(kt * 16), "r"(n_tile * 128), "l"(pol) : "memory");
}
}
}
}
if (warp == 1) {
asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(
smem_u32(tmem_slot)), "r"(512) : "memory");
asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;" ::: "memory");
}
asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory");
__syncthreads();
asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory");
const uint32_t tmem = *tmem_slot;
const int npre = nk < NPRE ? nk : NPRE;
float gs_f = 0.f;
static_assert(!FUSED, "fused quant phase removed (only the PDL two-kernel pipeline is built)");
if (warp == 0) {
// ---------------- TMA producer ----------------
if (lane == 0) {
const uint8_t* sfx_tile = sfx + (size_t)(m_tile * H) * ncb * 512;
if constexpr (FUSED) {
asm volatile("fence.proxy.async.global;" ::: "memory"); // after the grid barrier
} else {
asm volatile("griddepcontrol.wait;" ::: "memory"); // xq / x scales now valid
}
for (int it = 0; it < nk; ++it) {
const int s = it % ST;
const uint32_t fb = bar_full + 8 * s, sb = bar_sf + 8 * s;
// X-FIRST (NPRE < ST, i.e. the Mp 128 pin, first ring pass only): for the weight stages
// NOT issued before griddepcontrol.wait (it in [npre, ST)), this stage's x tile + x scales
// are issued BEFORE its weight tile, so the x bytes the early MMAs need are not queued
// behind 16-32 KB of weight. complete_tx before expect_tx is legal (see above). Same data.
const bool xfirst = (NPRE < ST) && it >= npre && it < ST;
auto ld_w = [&]() {
#pragma unroll
for (int ks = 0; ks < KS; ++ks) {
const int kt = (k0 + it) * KS + ks;
tma_load_2d_wf(sbase + C::SFA_OFF + s * C::SFA_BYTES + ks * C::SUB_SFA, &tmWS, kt * 16, n_tile * 128, sb);
tma_load_2d_wf(sbase + C::A_OFF + s * C::A_BYTES + ks * C::SUB_A, &tmW, kt * 128, n_tile * 128, fb);
}
};
if (it >= npre) {
// slot reuse guard: MMAs of stage it-ST retired (commit -> empty) -> both the smem
// stage and its TMEM scale-ring slot are free (bar_sf(it) thus implies empty(it-ST))
if (it >= ST) mbar_wait(bar_empty + 8 * s, ((it / ST) - 1) & 1);
mbar_expect_tx(fb, C::A_BYTES + C::B_BYTES);
mbar_expect_tx(sb, C::SFA_BYTES + C::SFB_BYTES);
if (!xfirst) ld_w();
}
#pragma unroll
for (int ks = 0; ks < KS; ++ks) {
const int kt = (k0 + it) * KS + ks;
#pragma unroll
for (int h = 0; h < H; ++h) // small scale chunks first: writers start earlier
bulk_load(sbase + C::SFB_OFF + s * C::SFB_BYTES + ks * C::SUB_SFB + h * 2048,
sfx_tile + (size_t)h * ncb * 512 + (size_t)kt * 4 * 512, 2048, sb);
tma_load_2d(sbase + C::B_OFF + s * C::B_BYTES + ks * C::SUB_B, &tmX, kt * 128, m_tile * BX, fb);
}
if (xfirst) ld_w();
}
}
} else if (warp == 1) {
// ---------------- MMA issuer ----------------
// The WHOLE warp runs the loop and waits (converged); lane 0 alone issues MMAs + commit.
{
const uint32_t idesc = (1u << 7) | (1u << 10) | ((uint32_t)(BX >> 3) << 17) |
((uint32_t)(128 >> 4) << 24);
// hoisted operand descriptors (fewer per-MMA issue ops in the MMA warp)
const uint64_t ad0 = make_desc(sbase + C::A_OFF, 16, 1024, 2);
const uint64_t bd0 = make_desc(sbase + C::B_OFF, 16, 1024, 2);
for (int it = 0; it < nk; ++it) {
const int s = it % ST;
// ONE wait: operand tiles landed AND the 4 writer warps stored this stage's scales
mbar_wait(bar_full + 8 * s, (it / ST) & 1);
asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory");
if (lane == 0) {
#pragma unroll
for (int ks = 0; ks < KS; ++ks)
#pragma unroll
for (int kc = 0; kc < 4; ++kc) {
const uint32_t sf_col = tmem + BX + s * C::SF_COLS + ks * C::SF_SUB;
// descriptors = hoisted stage-0 base + (byte offset >> 4) in the 14-bit start field
// (smem < 256 KB -> no carry out of the field; same bits as make_desc per call)
const uint64_t ad = ad0 + (uint64_t)((uint32_t)(s * C::A_BYTES + ks * C::SUB_A + kc * 32) >> 4);
const uint64_t bd = bd0 + (uint64_t)((uint32_t)(s * C::B_BYTES + ks * C::SUB_B + kc * 32) >> 4);
uint32_t accum = (it | ks | kc) ? 1u : 0u;
asm volatile(
"{\n .reg .pred p;\n setp.ne.b32 p, %4, 0;\n"
" tcgen05.mma.cta_group::1.kind::mxf4nvf4.block_scale.scale_vec::4X"
" [%0], %1, %2, %3, [%5], [%6], p;\n}\n" ::"r"(tmem),
"l"(ad), "l"(bd), "r"(idesc), "r"(accum), "r"(sf_col + kc * 4),
"r"(sf_col + 16 + kc * 4 * H)
: "memory");
}
asm volatile(
"tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(
bar_empty + 8 * s) : "memory");
} // lane 0 (warp reconverges here)
}
if (lane == 0) {
asm volatile(
"tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(
bar_done) : "memory");
}
}
__syncwarp();
} else if (warp < 6) {
// ---------------- scale writer (+ split-K epilogue) (warps 2..5) ----------------
const int q = warp & 3;
const uint32_t tl = tmem + ((uint32_t)(q * 32) << 16);
for (int it = 0; it < nk; ++it) {
const int s = it % ST;
mbar_wait(bar_sf + 8 * s, (it / ST) & 1); // scale bytes only (not the A/B tiles)
#pragma unroll
for (int ks = 0; ks < KS; ++ks) {
const uint8_t* sfa_s = smem + C::SFA_OFF + s * C::SFA_BYTES + ks * C::SUB_SFA; // raw: row r at r*16
const uint8_t* sfb_s = smem + C::SFB_OFF + s * C::SFB_BYTES + ks * C::SUB_SFB + lane * 16;
uint4 a[4], b[H][4];
#pragma unroll
for (int j = 0; j < 4; ++j) a[j] = *reinterpret_cast<const uint4*>(sfa_s + (32 * j + lane) * 16);
#pragma unroll
for (int h = 0; h < H; ++h)
#pragma unroll
for (int kc = 0; kc < 4; ++kc)
b[h][kc] = *reinterpret_cast<const uint4*>(sfb_s + h * 2048 + kc * 512);
uint32_t w[C::SF_SUB];
#pragma unroll
for (int kc = 0; kc < 4; ++kc) {
#pragma unroll
for (int j = 0; j < 4; ++j) w[kc * 4 + j] = u4c(a[j], kc); // weight row 32j+l, word kc
#pragma unroll
for (int h = 0; h < H; ++h)
#pragma unroll
for (int j = 0; j < 4; ++j) w[16 + kc * 4 * H + h * 4 + j] = u4c(b[h][kc], j);
}
const uint32_t ta = tl + BX + s * C::SF_COLS + ks * C::SF_SUB;
#pragma unroll
for (int c3 = 0; c3 < C::SF_SUB / 16; ++c3) {
const uint32_t* v = w + c3 * 16;
asm volatile(
"tcgen05.st.sync.aligned.32x32b.x16.b32 [%0], {%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11,"
"%12,%13,%14,%15,%16};" ::"r"(ta + c3 * 16),
"r"(v[0]), "r"(v[1]), "r"(v[2]), "r"(v[3]), "r"(v[4]), "r"(v[5]), "r"(v[6]),
"r"(v[7]), "r"(v[8]), "r"(v[9]), "r"(v[10]), "r"(v[11]), "r"(v[12]), "r"(v[13]),
"r"(v[14]), "r"(v[15])
: "memory");
}
} // ks
asm volatile("tcgen05.wait::st.sync.aligned;" ::: "memory");
asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory");
__syncwarp();
// scales of stage s in TMEM: arrive on the stage's FULL barrier (count 5)
if (lane == 0) asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(bar_full + 8 * s) : "memory");
}
}
// warps 6, 7: no mainloop role (S == 1 epilogue helpers for lane quarters 2, 3)
if (S == 1) {
// ---------------- S == 1 epilogue: ALL 8 warps ----------------
// The epilogue is instruction-issue bound (one warp per TMEM lane quarter left the schedulers
// mostly idle): every lane quarter q = warp % 4 now has TWO warps, {2..5} take token columns
// [0, BX/2), {0, 1, 6, 7} take [BX/2, BX). Warps 0/1 join after their producer / MMA loops.
__syncwarp();
// ALPHA LOAD HOISTED off the tail critical path: griddepcontrol.wait (returns at once: the
// producer already waited for the quant grid before its x loads) + the L2 load of alpha are
// issued BEFORE the accumulator wait, so the load latency overlaps the last MMAs instead of
// sitting between bar_done and the first bf16 store. Same value -> bit-identical.
if constexpr (!FUSED) asm volatile("griddepcontrol.wait;" ::: "memory"); // alpha ready
const float gs = FUSED ? gs_f : __ldcg(ab);
mbar_wait(bar_done, 0);
asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory");
const int q = warp & 3;
const uint32_t tl = tmem + ((uint32_t)(q * 32) << 16);
const int h0 = (warp >= 2 && warp < 6) ? 0 : BX / 2;
const int n = n_tile * 128 + q * 32 + lane;
__nv_bfloat16* ocol = out + (size_t)(m_tile * BX) * N + n;
// 64 token columns per round: two tcgen05.ld x32 in flight, ONE wait::ld
#pragma unroll 1
for (int c0 = h0; c0 < h0 + BX / 2; c0 += 64) {
uint32_t u[64];
tmem_ld32_nw(tl + c0, u);
tmem_ld32_nw(tl + c0 + 32, u + 32);
asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory");
store_bf16x64_T(u, gs, ocol + (size_t)c0 * N, N);
}
}
if (S > 1) {
if (warp >= 2 && warp < 6) {
mbar_wait(bar_done, 0);
asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory");
if constexpr (!FUSED) asm volatile("griddepcontrol.wait;" ::: "memory"); // alpha ready
}
// split-K reduction (owner rank owns token columns [rank*SW, (rank+1)*SW))
const int rank = (int)cluster_rank();
const int SW = BX / S;
const size_t tile = (size_t)blockIdx.y * gridDim.x + blockIdx.x;
float4* W = reinterpret_cast<float4*>(red_ws) + tile * (size_t)S * (BX / 4) * 128;
const size_t slot = (size_t)(SW / 4) * 128;
// FAST PATH S == 2, SW == 64 (BX = 128, the Mp = 128 pin): both phases batched so each pays
// ONE latency: write = 2 tcgen05.ld + 1 wait + 16 stores; read = 16 L2 loads issued first,
// own 64 TMEM columns loaded meanwhile, one sum pass, one 64-column store. Same fp32 sum
// order (0 + part[0]) + part[1] and the same bf16 rounding as the generic path.
const bool fast2 = (S == 2 && SW == 64);
// 8-warp split: TMEM lane quarter q = warp % 4 is served by TWO warps; warps 2..5 take column
// half [0, 32) of each 64-column slice, warps {0, 1, 6, 7} take [32, 64) (halves the per-warp
// TMEM-load / L2-store / transposed-store issue chain of the reduction). Helper warps first
// wait for the accumulator (bar_done) and the PDL dependency (alpha), like warps 2..5 above.
const bool helper = (warp < 2 || warp >= 6);
if (fast2 && helper) {
__syncwarp();
mbar_wait(bar_done, 0);
asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory");
if constexpr (!FUSED) asm volatile("griddepcontrol.wait;" ::: "memory");
}
const int fh = helper ? 32 : 0; // column half of this warp
if (fast2) {
const int q = warp & 3;
const int r = q * 32 + lane;
const uint32_t tl = tmem + ((uint32_t)(q * 32) << 16);
const int o = 1 - rank;
uint32_t u[32];
tmem_ld32_nw(tl + o * 64 + fh, u);
asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory");
float4* dst = W + ((size_t)o * 2 + rank) * slot + (size_t)(fh >> 2) * 128 + r;
#pragma unroll
for (int j = 0; j < 8; ++j)
__stcg(dst + j * 128, make_float4(__uint_as_float(u[4 * j]), __uint_as_float(u[4 * j + 1]),
__uint_as_float(u[4 * j + 2]), __uint_as_float(u[4 * j + 3])));
}
if (!fast2 && warp >= 2 && warp < 6) {
const int q = warp & 3;
const int r = q * 32 + lane;
const uint32_t tl = tmem + ((uint32_t)(q * 32) << 16);
#pragma unroll 1
for (int c0 = 0; c0 < BX; c0 += 32) {
const int o = c0 / SW;
if (o == rank) continue;
uint32_t u[32];
tmem_ld32(tl + c0, u);
float4* dst = W + ((size_t)o * S + rank) * slot + (size_t)((c0 % SW) >> 2) * 128 + r;
#pragma unroll
for (int j = 0; j < 8; ++j)
__stcg(dst + j * 128, make_float4(__uint_as_float(u[4 * j]), __uint_as_float(u[4 * j + 1]),
__uint_as_float(u[4 * j + 2]), __uint_as_float(u[4 * j + 3])));
}
}
cluster_sync_all();
if (fast2) {
const int q = warp & 3;
const int r = q * 32 + lane;
const uint32_t tl = tmem + ((uint32_t)(q * 32) << 16);
const int p = 1 - rank; // partner split
const float4* src = W + ((size_t)rank * 2 + p) * slot + (size_t)(fh >> 2) * 128 + r;
float4 v[8];
#pragma unroll
for (int j = 0; j < 8; ++j) v[j] = __ldcg(src + j * 128);
uint32_t own[32];
tmem_ld32_nw(tl + rank * 64 + fh, own);
asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory");
const float gs = FUSED ? gs_f : __ldcg(ab);
const uint32_t* vu = reinterpret_cast<const uint32_t*>(v);
const int n = n_tile * 128 + r;
__nv_bfloat16* op = out + (size_t)(m_tile * BX + rank * SW + fh) * N + n;
#pragma unroll
for (int j = 0; j < 32; j += 2) {
const uint32_t a0 = rank == 0 ? own[j] : vu[j], a1 = rank == 0 ? own[j + 1] : vu[j + 1];
const uint32_t b0 = rank == 0 ? vu[j] : own[j], b1 = rank == 0 ? vu[j + 1] : own[j + 1];
uint32_t o;
asm("{\n .reg .b64 z, pa, pb, s, w;\n .reg .b32 l, h, q;\n"
" mov.b64 z, {%5, %5};\n mov.b64 pa, {%1, %2};\n mov.b64 pb, {%3, %4};\n"
" add.rn.f32x2 pa, z, pa;\n add.rn.f32x2 pa, pa, pb;\n"
" mov.b64 s, {%6, %6};\n mul.rn.f32x2 w, pa, s;\n mov.b64 {l, h}, w;\n"
" cvt.rn.bf16x2.f32 %0, h, l;\n}"
: "=r"(o) : "r"(a0), "r"(a1), "r"(b0), "r"(b1), "r"(0u), "f"(gs));
op[(size_t)j * N] = __ushort_as_bfloat16((unsigned short)(o & 0xffffu));
op[(size_t)(j + 1) * N] = __ushort_as_bfloat16((unsigned short)(o >> 16));
}
}
if (!fast2 && warp >= 2 && warp < 6) {
const int q = warp & 3;
const int r = q * 32 + lane;
const uint32_t tl = tmem + ((uint32_t)(q * 32) << 16);
const float gs = FUSED ? gs_f : __ldcg(ab);
const int n = n_tile * 128 + r;
__nv_bfloat16* ocol = out + (size_t)(m_tile * BX + rank * SW) * N + n;
#pragma unroll 1
for (int g0 = 0; g0 < SW / 4; g0 += 8) {
uint32_t own[32];
tmem_ld32(tl + rank * SW + g0 * 4, own);
float f[32];
#pragma unroll
for (int j = 0; j < 32; ++j) f[j] = 0.f;
#pragma unroll 1
for (int p = 0; p < S; ++p) {
if (p == rank) {
#pragma unroll
for (int j = 0; j < 32; ++j) f[j] += __uint_as_float(own[j]);
} else {
const float4* src = W + ((size_t)rank * S + p) * slot + (size_t)g0 * 128 + r;
float4 v[8];
#pragma unroll
for (int j = 0; j < 8; ++j) v[j] = __ldcg(src + j * 128);
#pragma unroll
for (int j = 0; j < 8; ++j) {
f[4 * j] += v[j].x; f[4 * j + 1] += v[j].y; f[4 * j + 2] += v[j].z; f[4 * j + 3] += v[j].w;
}
}
}
store_bf16x32_T(f, gs, ocol + (size_t)(g0 * 4) * N, N);
}
}
}
// Exit tail: only the deallocating warp 1 waits (bar.sync) for every warp's TMEM reads; all
// other warps signal with a non-blocking bar.arrive and retire immediately (their final global
// stores drain while warp 1 deallocates). Named barrier 3, all kSwNT threads participate.
asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory");
if (warp != 1) {
asm volatile("bar.arrive 3, %0;" ::"n"(kSwNT) : "memory");
} else {
asm volatile("bar.sync 3, %0;" ::"n"(kSwNT) : "memory");
}
if (warp == 1) {
asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory");
asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tmem), "r"(512)
: "memory");
}
}
static int g_swap_pf_pct = 0; // swap-AB cold-L2 weight prefetch (% of K), set per enqueue
void set_swap_l2_prefetch(int pct) { g_swap_pf_pct = pct < 0 ? 0 : (pct > 100 ? 100 : pct); }
template <int BX, bool FUSED, int KS = 1, int PIN = 0>
static void swap_attr() {
static bool attr = false;
if (!attr) {
auto kf = nvfp4_swapab_gemm<BX, FUSED, KS, PIN>;
cudaFuncSetAttribute(kf, cudaFuncAttributeMaxDynamicSharedMemorySize, SWC<BX, KS>::SMEM);
// Explicit MINIMAL smem carveout that fits exactly 1 CTA/SM (dynamic SWC::SMEM = ring + barriers
{
int dev = 0, smsm = 0;
cudaGetDevice(&dev);
cudaDeviceGetAttribute(&smsm, cudaDevAttrMaxSharedMemoryPerMultiprocessor, dev);
cudaFuncAttributes fa{};
cudaFuncGetAttributes(&fa, kf);
const long long need = (long long)SWC<BX, KS>::SMEM + (long long)fa.sharedSizeBytes + 1024;
int pct = smsm > 0 ? (int)((need * 100 + smsm - 1) / smsm) : 100;
if (pct > 100) pct = 100;
cudaFuncSetAttribute(kf, cudaFuncAttributePreferredSharedMemoryCarveout, pct);
int per = 0;
if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per, kf, kSwNT, SWC<BX, KS>::SMEM) != cudaSuccess || per < 1)
cudaFuncSetAttribute(kf, cudaFuncAttributePreferredSharedMemoryCarveout, 100);
cudaGetLastError();
}
attr = true;
}
}
template <int BX, bool FUSED, int KS = 1>
static bool launch_swap_t(const void* xq, const void* xsf_blk, const void* wq, const void* wsf_raw,
const float* ab, void* out, float* red_ws, int Mp, int N, int K, int S,
cudaStream_t s, const void* x = nullptr, int M = 0, float w_gd = 0.f,
float* fsync = nullptr) {
using C = SWC<BX, KS>;
// Tensor-map cache (per template instantiation): the direct-launch fast path (main.cpp) calls
// this every run(); re-encoding 3 tensor maps per call costs host time. Keyed on every input of
// the encode (pointers, dims) -> identical maps whenever the key matches.
struct TmCache { const void *w, *x, *s; int Mp, N, K; bool valid; CUtensorMap tW, tX, tS; };
static TmCache& tc = *new TmCache();
CUtensorMap tW, tX, tS;
if (tc.valid && tc.w == wq && tc.x == xq && tc.s == wsf_raw && tc.Mp == Mp && tc.N == N &&
tc.K == K) {
tW = tc.tW; tX = tc.tX; tS = tc.tS;
} else {
bool ok = make_tmap_u8(&tW, wq, K / 2, N, 128, 128, CU_TENSOR_MAP_SWIZZLE_128B) &&
make_tmap_u8(&tX, xq, K / 2, Mp, 128, BX, CU_TENSOR_MAP_SWIZZLE_128B) &&
make_tmap_u8(&tS, wsf_raw, K / 16, N, 16, 128, CU_TENSOR_MAP_SWIZZLE_NONE);
if (!ok) return false;
tc.w = wq; tc.x = xq; tc.s = wsf_raw; tc.Mp = Mp; tc.N = N; tc.K = K;
tc.tW = tW; tc.tX = tX; tc.tS = tS; tc.valid = true;
}
swap_attr<BX, FUSED, KS>();
cudaLaunchConfig_t cfg = {};
const int mfast = (!FUSED && S == 1 && Mp / BX > 1) ? 1 : 0; // token-tile-fastest raster
cfg.gridDim = mfast ? dim3(Mp / BX, N / 128, 1) : dim3(N / 128, Mp / BX, S);
cfg.blockDim = dim3(kSwNT);
cfg.dynamicSmemBytes = C::SMEM;
cfg.stream = s;
cudaLaunchAttribute at[2];
at[0].id = cudaLaunchAttributeClusterDimension;
at[0].val.clusterDim.x = 1;
at[0].val.clusterDim.y = 1;
at[0].val.clusterDim.z = S;
at[1].id = cudaLaunchAttributeProgrammaticStreamSerialization;
at[1].val.programmaticStreamSerializationAllowed = 1;
cfg.attrs = at;
cfg.numAttrs = FUSED ? 1 : 2; // fused: plain stream order (no PDL; it is the only kernel)
// non-fused S == 1: no split-K cluster -> plain (non-cluster) launch with the PDL attribute
// only: the cluster-launch path adds CTA scheduling latency to every call.
if (!FUSED && S == 1) { cfg.attrs = at + 1; cfg.numAttrs = 1; }
const uint8_t* sfa = (const uint8_t*)xsf_blk;
__nv_bfloat16* o = (__nv_bfloat16*)out;
const uint4* xin = (const uint4*)x;
uint8_t* xqw = (uint8_t*)const_cast<void*>(xq);
uint8_t* xsfw = (uint8_t*)const_cast<void*>(xsf_blk);
// cold-L2 weight prefetch range (non-fused only): first g_swap_pf_pct % of this split's stages
const int nk_split = (K / 256) / S / KS;
int pf_end = FUSED ? 0 : (nk_split * g_swap_pf_pct) / 100;
// pinned instantiation (see nvfp4_swapab_gemm PIN) when every pinned knob matches at runtime
if constexpr (!FUSED && BX == 128 && KS == 2) {
if (S == 2 && pf_end == 0 && mfast == 0 && N == 8192 && K == 8192) {
swap_attr<BX, FUSED, KS, 1>();
if (cudaLaunchKernelEx(&cfg, nvfp4_swapab_gemm<BX, FUSED, KS, 1>, tW, tX, tS, sfa, ab, o, N, K,
S, red_ws, xin, M, Mp, w_gd, xqw, xsfw, fsync, pf_end, mfast) != cudaSuccess)
return false;
return cudaPeekAtLastError() == cudaSuccess;
}
}
if (cudaLaunchKernelEx(&cfg, nvfp4_swapab_gemm<BX, FUSED, KS>, tW, tX, tS, sfa, ab, o, N, K, S,
red_ws, xin, M, Mp, w_gd, xqw, xsfw, fsync, pf_end, mfast) != cudaSuccess)
return false;
return cudaPeekAtLastError() == cudaSuccess;
}
bool launch_nvfp4_gemm_swap(const void* xq, const void* xsf_blk, const void* wq,
const void* wsf_raw, const float* ab, void* out, float* red_ws, int Mp,
int N, int K, int S, int BX, int KS, cudaStream_t s) {
// only the Mp 128 pin configuration (BX 128, KS 2) is built
if (KS != 2 || BX != 128) return false;
if ((K / 256) % (2 * S)) return false; // whole BK=512 stages per split required
return launch_swap_t<128, false, 2>(xq, xsf_blk, wq, wsf_raw, ab, out, red_ws, Mp, N, K, S, s);
}
// =============================================================================================
// WEIGHT-STATIONARY small-M tcgen05 NVFP4 GEMM (Mp 128 pin): out[Mp, N] = alpha * (xq*sfx) @ (wq*sfw)^T
// Each CTA owns a slice of WS_ROWS = 64 consecutive weight rows over the FULL K (no split-K, no
// partial exchange): 8192 / 64 = 128 CTAs (exact N64, no padding). MMA shape M = 128 tokens (x = A
// operand, SW128 K-major) x N = 64 weight rows (B operand: the 56-row slice plus 8 rows of the next
// slice / TMA zero-fill beyond N; their output columns are never stored) x K = 64 per instruction,
// kind::mxf4nvf4 scale_vec::4X. The weight slice (229 KB) streams through a ST-stage smem ring (read
// once, L2 evict_first); x (4 MB, L2-resident, shared by all CTAs) is re-read per CTA.
// Warp roles: 0 TMA producer (x tiles + blocked x scales after griddepcontrol.wait; weight stages
// beyond the first ring), 1 MMA issuer, 2-5 scale writers (smem -> TMEM, SFA = x blocked chunk,
// SFB = raw weight scale rows; same 4X column format: column kc*4+j at lane l = 4 scale bytes of row
// 32j+l), all 8 warps epilogue. Thread 64 issues the first ring of weight stages at kernel entry.
// TMEM: [0, 64) accumulator (lane = token, column = weight row), then ST * KS * 32 scale columns.
// Epilogue: TMEM -> regs -> bf16_rn(alpha * acc) -> 16 B row-contiguous stores (112 B per token).
// =============================================================================================
static constexpr int WS_ROWS = 64; // 128 CTAs x 64 rows: exact MMA N64, no padded rows
struct WSC {
static constexpr int KS = 2, ST = 4;
static constexpr int SUB_A = 128 * 128; // x sub-tile: 128 tokens x 128 B (256 fp4)
static constexpr int SUB_B = 64 * 128; // weight sub-tile: 64 rows x 128 B
static constexpr int SUB_SFA = 2048; // blocked x scales, one 128x4 chunk
static constexpr int SUB_SFB = 64 * 16; // raw weight scales, 64 rows x 16 B
static constexpr int A_BYTES = KS * SUB_A, B_BYTES = KS * SUB_B;
static constexpr int SFA_BYTES = KS * SUB_SFA, SFB_BYTES = KS * SUB_SFB;
static constexpr int A_OFF = 0;
static constexpr int B_OFF = A_OFF + ST * A_BYTES;
static constexpr int SFA_OFF = B_OFF + ST * B_BYTES;
static constexpr int SFB_OFF = SFA_OFF + ST * SFA_BYTES;
static constexpr int BAR_OFF = SFB_OFF + ST * SFB_BYTES;
static constexpr int SMEM = BAR_OFF + 256 + 1024;
static constexpr int SF_SUB = 32; // TMEM scale columns per K=256 sub-step: SFA 16 + SFB 16
static constexpr int SF_COLS = KS * SF_SUB;
static constexpr int ACC = 64;
static_assert(ACC + ST * SF_COLS <= 512, "TMEM");
};
__global__ void __launch_bounds__(256, 1)
nvfp4_ws_gemm(const __grid_constant__ CUtensorMap tmW, const __grid_constant__ CUtensorMap tmX,
const __grid_constant__ CUtensorMap tmWS, const uint8_t* __restrict__ sfx,
const float* __restrict__ ab, __nv_bfloat16* __restrict__ out, int N, int K) {
using C = WSC;
constexpr int ST = C::ST, KS = C::KS;
extern __shared__ uint8_t smem_raw[];
uint8_t* smem = (uint8_t*)(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023);
const uint32_t sbase = smem_u32(smem);
const uint32_t bar_full = sbase + C::BAR_OFF;
const uint32_t bar_empty = bar_full + ST * 8;
const uint32_t bar_sf = bar_empty + ST * 8;
const uint32_t bar_done = bar_sf + ST * 8;
uint32_t* tmem_slot = reinterpret_cast<uint32_t*>(smem + C::BAR_OFF + 3 * ST * 8 + 8);
const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
const int n0 = blockIdx.x * WS_ROWS; // first weight row of this CTA's slice
const int m_tile = blockIdx.y;
const int nk = (K / 256) / KS; // pipeline stages (full K)
const int ncb = K / 64;
const int npre = nk < ST ? nk : ST;
if (threadIdx.x == 0) asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tmX) : "memory");
if (threadIdx.x == 64) {
asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tmW) : "memory");
asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tmWS) : "memory");
for (int s = 0; s < ST; ++s) {
mbar_init(bar_full + 8 * s, 5); // producer expect_tx + 4 scale-writer warps
mbar_init(bar_empty + 8 * s, 1);
mbar_init(bar_sf + 8 * s, 1);
}
mbar_init(bar_done, 1);
asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory");
asm volatile("fence.proxy.async.shared::cta;" ::: "memory");
// first ring of weight stages (independent of the quant kernel -> before the PDL wait)
for (int it = 0; it < npre; ++it) {
const uint32_t fb = bar_full + 8 * it, sb = bar_sf + 8 * it;
mbar_expect_tx(fb, C::A_BYTES + C::B_BYTES);
mbar_expect_tx(sb, C::SFA_BYTES + C::SFB_BYTES);
#pragma unroll
for (int ks = 0; ks < KS; ++ks) {
const int kt = it * KS + ks;
tma_load_2d_wf(sbase + C::SFB_OFF + it * C::SFB_BYTES + ks * C::SUB_SFB, &tmWS, kt * 16, n0, sb);
tma_load_2d_wf(sbase + C::B_OFF + it * C::B_BYTES + ks * C::SUB_B, &tmW, kt * 128, n0, fb);
}
}
}
if (warp == 1) {
asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(
smem_u32(tmem_slot)), "r"(512) : "memory");
asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;" ::: "memory");
}
asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory");
__syncthreads();
asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory");
const uint32_t tmem = *tmem_slot;
if (warp == 0) {
// ---------------- TMA producer ----------------
if (lane == 0) {
const uint8_t* sfx_tile = sfx + (size_t)m_tile * ncb * 512;
asm volatile("griddepcontrol.wait;" ::: "memory"); // xq / x scales valid
uint64_t pol_x;
asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol_x));
for (int it = 0; it < nk; ++it) {
const int s = it % ST;
const uint32_t fb = bar_full + 8 * s, sb = bar_sf + 8 * s;
if (it >= npre) {
mbar_wait(bar_empty + 8 * s, ((it / ST) - 1) & 1);
mbar_expect_tx(fb, C::A_BYTES + C::B_BYTES);
mbar_expect_tx(sb, C::SFA_BYTES + C::SFB_BYTES);
#pragma unroll
for (int ks = 0; ks < KS; ++ks) {
const int kt = it * KS + ks;
tma_load_2d_wf(sbase + C::SFB_OFF + s * C::SFB_BYTES + ks * C::SUB_SFB, &tmWS, kt * 16, n0, sb);
tma_load_2d_wf(sbase + C::B_OFF + s * C::B_BYTES + ks * C::SUB_B, &tmW, kt * 128, n0, fb);
}
}
#pragma unroll
for (int ks = 0; ks < KS; ++ks) {
const int kt = it * KS + ks;
// x (xq + blocked x scales, ~1 MB) is re-read by all 128 CTAs -> L2 evict_last
// (the weight / weight scales stream once -> evict_first, see tma_load_2d_wf)
bulk_load_ef(sbase + C::SFA_OFF + s * C::SFA_BYTES + ks * C::SUB_SFA,
sfx_tile + (size_t)kt * 4 * 512, 2048, sb, pol_x);
tma_load_2d_wl(sbase + C::A_OFF + s * C::A_BYTES + ks * C::SUB_A, &tmX, kt * 128, m_tile * 128, fb);
}
}
}
} else if (warp == 1) {
// ---------------- MMA issuer (M = 128 tokens, N = 64 weight rows) ----------------
const uint32_t idesc = (1u << 7) | (1u << 10) | ((uint32_t)(64 >> 3) << 17) |
((uint32_t)(128 >> 4) << 24);
const uint64_t ad0 = make_desc(sbase + C::A_OFF, 16, 1024, 2);
const uint64_t bd0 = make_desc(sbase + C::B_OFF, 16, 1024, 2);
for (int it = 0; it < nk; ++it) {
const int s = it % ST;
mbar_wait(bar_full + 8 * s, (it / ST) & 1);
asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory");
if (lane == 0) {
#pragma unroll
for (int ks = 0; ks < KS; ++ks)
#pragma unroll
for (int kc = 0; kc < 4; ++kc) {
const uint32_t sf_col = tmem + C::ACC + s * C::SF_COLS + ks * C::SF_SUB;
const uint64_t ad = ad0 + (uint64_t)((uint32_t)(s * C::A_BYTES + ks * C::SUB_A + kc * 32) >> 4);
const uint64_t bd = bd0 + (uint64_t)((uint32_t)(s * C::B_BYTES + ks * C::SUB_B + kc * 32) >> 4);
const uint32_t accum = (it | ks | kc) ? 1u : 0u;
asm volatile(
"{\n .reg .pred p;\n setp.ne.b32 p, %4, 0;\n"
" tcgen05.mma.cta_group::1.kind::mxf4nvf4.block_scale.scale_vec::4X"
" [%0], %1, %2, %3, [%5], [%6], p;\n}\n" ::"r"(tmem),
"l"(ad), "l"(bd), "r"(idesc), "r"(accum), "r"(sf_col + kc * 4),
"r"(sf_col + 16 + kc * 4)
: "memory");
}
asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(
bar_empty + 8 * s) : "memory");
}
__syncwarp();
}
if (lane == 0)
asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(
bar_done) : "memory");
__syncwarp();
} else if (warp < 6) {
// ---------------- scale writers (warps 2..5, TMEM lane quarter q) ----------------
const int q = warp & 3;
const uint32_t tl = tmem + ((uint32_t)(q * 32) << 16);
for (int it = 0; it < nk; ++it) {
const int s = it % ST;
mbar_wait(bar_sf + 8 * s, (it / ST) & 1);
#pragma unroll
for (int ks = 0; ks < KS; ++ks) {
const uint8_t* sfa_s = smem + C::SFA_OFF + s * C::SFA_BYTES + ks * C::SUB_SFA + lane * 16;
const uint8_t* sfb_s = smem + C::SFB_OFF + s * C::SFB_BYTES + ks * C::SUB_SFB;
uint4 xa[4], wb[2];
#pragma unroll
for (int kc = 0; kc < 4; ++kc) xa[kc] = *reinterpret_cast<const uint4*>(sfa_s + kc * 512);
#pragma unroll
for (int j = 0; j < 2; ++j) wb[j] = *reinterpret_cast<const uint4*>(sfb_s + (32 * j + lane) * 16);
uint32_t w[C::SF_SUB];
#pragma unroll
for (int kc = 0; kc < 4; ++kc) {
#pragma unroll
for (int j = 0; j < 4; ++j) w[kc * 4 + j] = u4c(xa[kc], j); // x row 32j+l, k-group kc
#pragma unroll
for (int j = 0; j < 4; ++j) w[16 + kc * 4 + j] = j < 2 ? u4c(wb[j], kc) : 0u; // weight row 32j+l
}
const uint32_t ta = tl + C::ACC + s * C::SF_COLS + ks * C::SF_SUB;
#pragma unroll
for (int c3 = 0; c3 < 2; ++c3) {
const uint32_t* v = w + c3 * 16;
asm volatile(
"tcgen05.st.sync.aligned.32x32b.x16.b32 [%0], {%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11,"
"%12,%13,%14,%15,%16};" ::"r"(ta + c3 * 16),
"r"(v[0]), "r"(v[1]), "r"(v[2]), "r"(v[3]), "r"(v[4]), "r"(v[5]), "r"(v[6]),
"r"(v[7]), "r"(v[8]), "r"(v[9]), "r"(v[10]), "r"(v[11]), "r"(v[12]), "r"(v[13]),
"r"(v[14]), "r"(v[15])
: "memory");
}
}
asm volatile("tcgen05.wait::st.sync.aligned;" ::: "memory");
asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory");
__syncwarp();
if (lane == 0) asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(bar_full + 8 * s) : "memory");
}
}
// ---------------- epilogue: all 8 warps ----------------
// lane quarter q = warp % 4; warps 2..5 take weight columns [0, 32), warps {0,1,6,7} [32, 64)
__syncwarp();
asm volatile("griddepcontrol.wait;" ::: "memory"); // alpha ready (quant grid complete)
const float gs = __ldcg(ab);
mbar_wait(bar_done, 0);
asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory");
{
const int q = warp & 3;
const uint32_t tl = tmem + ((uint32_t)(q * 32) << 16);
const int c0 = (warp >= 2 && warp < 6) ? 0 : 32;
const int nchk = 4; // 16 B chunks (8 columns) of this 32-column half of the 64-row slice
uint32_t u[32];
tmem_ld32_nw(tl + c0, u);
asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory");
const int m = m_tile * 128 + q * 32 + lane;
__nv_bfloat16* orow = out + (size_t)m * N + n0 + c0;
#pragma unroll
for (int c = 0; c < 4; ++c) {
if (c < nchk && n0 + c0 + 8 * c + 8 <= N) {
uint32_t o[4];
#pragma unroll
for (int p = 0; p < 4; ++p) {
asm("{\n .reg .b64 s, v;\n .reg .b32 l, h;\n mov.b64 s, {%3, %3};\n mov.b64 v, {%1, %2};\n"
" mul.rn.f32x2 v, v, s;\n mov.b64 {l, h}, v;\n cvt.rn.bf16x2.f32 %0, h, l;\n}"
: "=r"(o[p]) : "f"(__uint_as_float(u[8 * c + 2 * p])), "f"(__uint_as_float(u[8 * c + 2 * p + 1])), "f"(gs));
}
*reinterpret_cast<uint4*>(orow + 8 * c) = make_uint4(o[0], o[1], o[2], o[3]);
}
}
}
asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory");
if (warp != 1) {
asm volatile("bar.arrive 3, %0;" ::"n"(256) : "memory");
} else {
asm volatile("bar.sync 3, %0;" ::"n"(256) : "memory");
asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory");
asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tmem), "r"(512)
: "memory");
}
}
bool launch_nvfp4_gemm_ws(const void* xq, const void* xsf_blk, const void* wq, const void* wsf_raw,
const float* ab, void* out, int Mp, int N, int K, cudaStream_t s) {
using C = WSC;
if (K % 512 || Mp % 128 || N % 64) return false;
struct TmCache { const void *w, *x, *s; int Mp, N, K; bool valid; CUtensorMap tW, tX, tS; };
static TmCache& tc = *new TmCache();
if (!(tc.valid && tc.w == wq && tc.x == xq && tc.s == wsf_raw && tc.Mp == Mp && tc.N == N && tc.K == K)) {
bool ok = make_tmap_u8(&tc.tW, wq, K / 2, N, 128, 64, CU_TENSOR_MAP_SWIZZLE_128B) &&
make_tmap_u8(&tc.tX, xq, K / 2, Mp, 128, 128, CU_TENSOR_MAP_SWIZZLE_128B) &&
make_tmap_u8(&tc.tS, wsf_raw, K / 16, N, 16, 64, CU_TENSOR_MAP_SWIZZLE_NONE);
if (!ok) { tc.valid = false; return false; }
tc.w = wq; tc.x = xq; tc.s = wsf_raw; tc.Mp = Mp; tc.N = N; tc.K = K; tc.valid = true;
}
static bool attr = false;
if (!attr) {
cudaFuncSetAttribute(nvfp4_ws_gemm, cudaFuncAttributeMaxDynamicSharedMemorySize, C::SMEM);
attr = true;
}
cudaLaunchConfig_t cfg = {};
cfg.gridDim = dim3((N + WS_ROWS - 1) / WS_ROWS, Mp / 128, 1);
cfg.blockDim = dim3(256);
cfg.dynamicSmemBytes = C::SMEM;
cfg.stream = s;
cudaLaunchAttribute at[1];
at[0].id = cudaLaunchAttributeProgrammaticStreamSerialization;
at[0].val.programmaticStreamSerializationAllowed = 1;
cfg.attrs = at;
cfg.numAttrs = 1;
if (cudaLaunchKernelEx(&cfg, nvfp4_ws_gemm, tc.tW, tc.tX, tc.tS, (const uint8_t*)xsf_blk, ab,
(__nv_bfloat16*)out, N, K) != cudaSuccess)
return false;
return cudaPeekAtLastError() == cudaSuccess;
}
// =============================================================================================
// CHUNKED LARGE-M PIPELINE (quant overlapped with the GEMM), see main.cpp enqueue_chunked:
// 1) launch_quant_amax: the persistent quant kernel in amax-only mode (pass 1 + grid barrier +
// padded weight-scale re-layout in the barrier window), publishes alpha (ab[0]) and the global
// amax (amax_out) -- no quantization.
// 2) quant_rows_kernel per row chunk [r0, r1): reads the published amax, derives ge / gd with the
// same fp32 op sequence (global_scales_nw), quantizes the chunk's items with quant_item (same
// bytes as the fused pass 2), xq / scale stores L2 evict_last (consumed by the chunk GEMM).
// Small grid (2 CTAs / SM, 4 x 256-bit loads per thread in flight) so it can co-reside with the
// persistent CUTLASS GEMM of the previous chunk, which runs concurrently on the main stream.
// =============================================================================================
__global__ void __launch_bounds__(kThreads)
quant_rows_kernel(const uint4* __restrict__ x, int t0, int t1, int n_real, int K,
const float* __restrict__ amax_p, uint8_t* __restrict__ xq,
uint8_t* __restrict__ xsf_blk) {
const int sfk = K >> 4, ncb = sfk >> 2;
const float amax = __ldcg(amax_p);
float ge, gd;
global_scales_nw(amax, ge, gd);
uint64_t pol;
asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol));
const bool al32 = (((uintptr_t)x) & 31) == 0;
const uint4 z = make_uint4(0, 0, 0, 0);
for (long long b = (long long)t0 + (long long)blockIdx.x * (4 * kThreads); b < t1;
b += (long long)gridDim.x * (4 * kThreads)) {
uint4 a[4][2];
#pragma unroll
for (int k = 0; k < 4; ++k) {
const int t = (int)b + k * kThreads + threadIdx.x;
a[k][0] = z; a[k][1] = z;
if (t < t1 && t < n_real) ld_item_first(x, t, al32, a[k][0], a[k][1]);
}
#pragma unroll
for (int k = 0; k < 4; ++k) {
const int t = (int)b + k * kThreads + threadIdx.x;
if (t < t1) quant_item<true>(t, a[k][0], a[k][1], sfk, ncb, ge, gd, xq, xsf_blk, pol);
}
}
}
void launch_quant_amax(const void* x, int M, int Mp, int K, const uint8_t* wsf, uint8_t* wsf_blk,
int N, float w_gd, uint8_t* xq, uint8_t* xsf_blk, float* sync_ws, float* ab,
float* amax_out, cudaStream_t s) {
init_grids();
const uint4* xp = (const uint4*)x;
const uint32_t* wp = (const uint32_t*)wsf;
int Nw = g_wsf_pad == 1 ? -N : (g_wsf_pad == 2 ? -(N | (1 << 29)) : N);
static CUtensorMap& tmz = *new CUtensorMap();
int pf_ops = 0, pf_ci = 1, pf_bi = 16, pf_bo = 1;
int al32 = ((((uintptr_t)x) & 31) == 0 ? 1 : 0) | (g_p1_first ? 2 : 0) | 512;
int tail = evict_tail(Mp, K, gp);
int late = 0;
float* avec = nullptr;
const uint8_t* dmp = nullptr;
long long dmb = 0;
void* args[] = {(void*)&xp, (void*)&M, (void*)&Mp, (void*)&K, (void*)&wp, (void*)&wsf_blk,
(void*)&Nw, (void*)&w_gd, (void*)&xq, (void*)&xsf_blk, (void*)&sync_ws,
(void*)&ab, (void*)&amax_out, (void*)&tail, (void*)&al32, (void*)&late,
(void*)&avec, (void*)&tmz, (void*)&pf_ops, (void*)&pf_ci, (void*)&pf_bi,
(void*)&pf_bo, (void*)&dmp, (void*)&dmb};
coop_launch(fused_quant_kernel<0>, gp, args, s);
}
void launch_quant_rows(const void* x, int M, int r0, int r1, int K, const float* amax_p,
uint8_t* xq, uint8_t* xsf_blk, cudaStream_t s, int cps) {
static int grid = 0, sms = 0;
if (!grid) {
// max smem carveout: never forces an L1-heavy SM config that would block GEMM CTAs
cudaFuncSetAttribute(quant_rows_kernel, cudaFuncAttributePreferredSharedMemoryCarveout, 100);
int dev = 0;
cudaGetDevice(&dev);
cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev);
grid = 2 * sms;
}
if (cps > 0) {
const int sfk0 = K / 16;
const int need0 = ((r1 - r0) * sfk0 + 4 * kThreads - 1) / (4 * kThreads);
quant_rows_kernel<<<std::min(cps * sms, need0), kThreads, 0, s>>>((const uint4*)x, r0 * sfk0, r1 * sfk0,
M * sfk0, K, amax_p, xq, xsf_blk);
return;
}
const int sfk = K / 16;
const int t0 = r0 * sfk, t1 = r1 * sfk;
const int need = (t1 - t0 + 4 * kThreads - 1) / (4 * kThreads);
quant_rows_kernel<<<std::min(grid, need), kThreads, 0, s>>>((const uint4*)x, t0, t1, M * sfk, K,
amax_p, xq, xsf_blk);
}
#ifdef NVFP4_AUDITPROBE // never defined in production builds
// ---- DORMANT AUDIT PROBE: per-variant occupancy / regs / spec-pin co-residency report ----
#include <string>
template <typename F>
static std::string occ_str(const char* nm, F k, int nt, size_t dsm = 0) {
int per = -1; cudaFuncAttributes fa{};
cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per, k, nt, dsm);
cudaFuncGetAttributes(&fa, (const void*)k);
cudaGetLastError();
char b[256];
snprintf(b, sizeof b, "%s:per%d,regs%d,ssm%zu,lmem%zu | ", nm, per, fa.numRegs, (size_t)fa.sharedSizeBytes, (size_t)fa.localSizeBytes);
return b;
}
std::string quant_audit() {
init_grids();
std::string s;
char b[512];
snprintf(b, sizeof b, "g4=%d g8=%d gp=%d g7=%d g2h=%d keep=%d pin=%d | ", g4, g8, gp, g7, g2h, (int)g_keep_ok, (int)g_pin_ok);
s += b;
s += occ_str("r4_0", fused_quant_res_kernel<4, 0>, 256);
s += occ_str("r4_34", fused_quant_res_kernel<4, 0, 256, 34>, 256);
s += occ_str("r4_52", fused_quant_res_kernel<4, 0, 256, 52>, 256);
s += occ_str("r3_0", fused_quant_res_kernel<3, 0>, 256);
s += occ_str("r3_52", fused_quant_res_kernel<3, 0, 256, 52>, 256);
s += occ_str("r7_0", fused_quant_res_kernel<7, 0>, 256);
s += occ_str("r7_54", fused_quant_res_kernel<7, 0, 256, 54>, 256);
s += occ_str("r8_0", fused_quant_res_kernel<8, 0>, 256);
s += occ_str("r2h_0", fused_quant_res_kernel<2, 0, 128>, 128);
s += occ_str("hyb", fused_quant_hyb_kernel<kHybIR, 2>, 256, 4 * 256 * 36);
s += occ_str("hybSP", fused_quant_hyb_kernel<kHybIR, 2, kHybSP>, 256, 4 * 256 * 36);
s += occ_str("pq0", fused_quant_kernel<0>, 256);
s += occ_str("pq0k", fused_quant_kernel<0>, 256, kKeepSmem);
s += occ_str("pqpin", fused_quant_kernel<0, 4, true>, 256);
s += occ_str("pqpink", fused_quant_kernel<0, 4, true>, 256, kKeepSmem);
snprintf(b, sizeof b, "spec34=%d spec52_4=%d spec52_3=%d spec54=%d",
(int)res_spec_ok<4, kThreads, 34>(), (int)res_spec_ok<4, kThreads, 52>(),
(int)res_spec_ok<3, kThreads, 52>(), (int)res_spec_ok<7, kThreads, 54>());
s += b;
snprintf(b, sizeof b, " spec52_2h=%d hybsp=%d", (int)res_spec_ok<2, 128, 52>(), (int)g_hyb_sp_ok); s += b;
return s;
}
#endif // NVFP4_AUDITPROBE
// NVFP4 linear layer: fused custom quantization pipeline feeding either
// (a) the custom swap-AB split-K tcgen05 NVFP4 GEMM (Mp 128 pin), or
// (b) a CUTLASS sm100 block-scaled NVFP4 GEMM (cutlass_gemm_{b,h}.cu, Mp >= 256), PDL-launched.
//
// ---------------------------------------------------------------------------------------------
// QUANT (grid-barrier kernels, sized to be fully co-resident).
// Work unit = one 16-element block of x ("item": 32 B of bf16 -> 8 B packed E2M1 + 1 B E4M3).
// One launch, one lightweight grid barrier between the global-amax phase and quantization:
// grid_arrive()/grid_wait(): thread 0 of each CTA reads the epoch e = ctr / G (ctr = monotone u64
// arrival counter, never reset; all launches on one counter use the same G), red.max's its
// block max (float bits as u32) into amax slot e&1, release-adds the counter, acquire-spins
// until ctr >= (e+1)*G, then reads the slot. Block 0 zeroes slot (e+1)&1 for the next launch.
// fused_quant_res_kernel<IPT> (small/medium M): each thread owns IPT items kept in registers
// (x read exactly once), block amax, grid barrier, quantize straight from registers.
// fused_quant_hyb_kernel (medium M): register tier + a bulk-copied shared-memory tier.
// fused_quant_kernel (large M, persistent grid): Phase A chunk amax, barrier, Phase B re-reads
// its chunk in reverse order (L2 hits) and quantizes.
//
// GEMM (custom swap-AB nvfp4_swapab_gemm): see its section header below.
// ---------------------------------------------------------------------------------------------
static constexpr int kThreads = 256;
// ---- TLPROBE (dormant, probe builds only): per-CTA globaltimer stamps of the quant kernels ----
__device__ unsigned long long g_hp[1024 * 16];
// stamps kept in registers (tl_[s]) and written once at TL(15) -> no store traffic mid-kernel
void hyb_probe_reset() { void* p = nullptr; cudaGetSymbolAddress(&p, g_hp); cudaMemset(p, 0, sizeof(unsigned long long) * 1024 * 16); }
void hyb_probe_read(unsigned long long* o) { cudaMemcpyFromSymbol(o, g_hp, sizeof(unsigned long long) * 1024 * 16); }
__device__ __forceinline__ float bf16lo(uint32_t v) { return __uint_as_float(v << 16); }
__device__ __forceinline__ float bf16hi(uint32_t v) { return __uint_as_float(v & 0xffff0000u); }
// blocked layout offset of scale (r, c) in a rows x cols scale matrix (cols % 4 == 0):
// 128x4 tiles ordered (row_block, col_block); inside a tile: [r%32][(r%128)/32][c%4]
__device__ __forceinline__ uint32_t blk_off(int r, int c, int ncb) {
int rb = r >> 7, ri = r & 127, cb = c >> 2, c0 = c & 3;
return ((uint32_t)rb * ncb + cb) * 512u + (ri & 31) * 16 + (ri >> 5) * 4 + c0;
}
__device__ __forceinline__ uint32_t bmx_xa(uint32_t a, uint32_t b) {
uint32_t r;
asm("max.xorsign.abs.bf16x2 %0, %1, %2;" : "=r"(r) : "r"(a), "r"(b));
return r;
}
__device__ __forceinline__ uint32_t absmax2x8(uint4 v) {
return bmx_xa(bmx_xa(v.x, v.y), bmx_xa(v.z, v.w)) & 0x7fff7fffu;
}
__device__ __forceinline__ uint32_t fold2(uint32_t m) { return max(m & 0xffffu, m >> 16); }
// Item (16 bf16) block max |x| as fp32, low-op form for the issue-bound quant pass 2:
// 7 max.xorsign.abs.bf16x2 over the RAW words (magnitude of each lane = max |.| of its 8 values,
// sign garbage) then ONE fp32 FMNMX with |.| operand modifiers on the two lanes widened exactly
// (lo << 16, hi & 0xffff0000) -> 10 ops instead of 13 (2 masks + vmaxu2 + 3-op fold2 + shl).
// Bit-identical to fold2(vmaxu2(absmax2x8,absmax2x8)) << 16 for non-NaN inputs: both yield the
// exact fp32 value of the largest-magnitude bf16 with a + sign (fabs on +-0 gives +0, same bits).
__device__ __forceinline__ float item_bm(const uint4& a, const uint4& b) {
const uint32_t m = bmx_xa(bmx_xa(bmx_xa(a.x, a.y), bmx_xa(a.z, a.w)),
bmx_xa(bmx_xa(b.x, b.y), bmx_xa(b.z, b.w)));
return fmaxf(fabsf(__uint_as_float(m << 16)), fabsf(__uint_as_float(m & 0xffff0000u)));
}
// ALL-PACKED item block max (M >= 1024 paths: IPT 7 register quant, hybrid quant, persistent
// quant pass 2): the 7-op max.xorsign.abs.bf16x2 tree, then ONE more packed max against the
// half-swapped word (prmt) instead of the two fp32 widens + fp32 FMNMX: both lanes then hold the
// largest magnitude (sign garbage), and masking with 0x7fff0000 yields exactly the fp32 bits of
// +max|x| (bf16 hi lane = top half of an fp32). Same value as item_bm for non-NaN inputs
// (+0 for all-zero items) -> bit-identical; no fp32-pipe op in the block max.
__device__ __forceinline__ float item_bm_p(const uint4& a, const uint4& b) {
const uint32_t m = bmx_xa(bmx_xa(bmx_xa(a.x, a.y), bmx_xa(a.z, a.w)),
bmx_xa(bmx_xa(b.x, b.y), bmx_xa(b.z, b.w)));
return __uint_as_float(bmx_xa(m, __byte_perm(m, 0, 0x1032)) & 0x7fff0000u);
}
// Packed amax accumulation over RAW words (sign garbage, magnitude exact): m = running packed
// max.xorsign.abs accumulator (init 0); amax_fin() masks the signs once and folds the two lanes.
// Bit-identical to the former mask + __vmaxu2 accumulation + fold2 << 16 for non-NaN inputs.
__device__ __forceinline__ uint32_t acc_item(uint32_t m, const uint4& a, const uint4& b) {
return bmx_xa(m, bmx_xa(bmx_xa(bmx_xa(a.x, a.y), bmx_xa(a.z, a.w)),
bmx_xa(bmx_xa(b.x, b.y), bmx_xa(b.z, b.w))));
}
__device__ __forceinline__ uint32_t acc_u4(uint32_t m, const uint4& a) {
return bmx_xa(m, bmx_xa(bmx_xa(a.x, a.y), bmx_xa(a.z, a.w)));
}
__device__ __forceinline__ uint32_t amax_fin(uint32_t m) { return fold2(m & 0x7fff7fffu) << 16; }