diff --git a/src/split/CMakeLists.txt b/src/split/CMakeLists.txt index ca8a216501..62f89ffc3f 100644 --- a/src/split/CMakeLists.txt +++ b/src/split/CMakeLists.txt @@ -150,6 +150,15 @@ if(STRATA_BUILD_TESTS) target_compile_options(split_moe_tile_test PRIVATE $<$:--use_fast_math --expt-relaxed-constexpr -Wno-deprecated-gpu-targets>) set_target_properties(split_moe_tile_test PROPERTIES CUDA_ARCHITECTURES "${STRATA_SPLIT_ARCH}-real" CUDA_STANDARD 17 CXX_STANDARD 17) target_link_libraries(split_moe_tile_test PRIVATE Threads::Threads) + # FNX_PFX_GDN_TC's tensor-core chunk scan against the sub-chunk kernels it replaces, one card, random inputs (not a ctest: needs a GPU) + if(NOT _fnx_hip) + add_executable(split_gdn_tc_test ${_sp}/tools/gdn_tc_test.cu) + target_include_directories(split_gdn_tc_test PRIVATE ${_sp}/src ${_sp}/tools ${STRATA_GGML_DIR}/ggml/src/ggml-cuda ${STRATA_GGML_DIR}/ggml/src + ${STRATA_GGML_DIR}/ggml/include) + target_compile_definitions(split_gdn_tc_test PRIVATE FNX_NCARD=${_n0} FNX_ARCH=${STRATA_SPLIT_ARCH} FNX_27B=0) + target_compile_options(split_gdn_tc_test PRIVATE $<$:--use_fast_math --expt-relaxed-constexpr -Wno-deprecated-gpu-targets>) + set_target_properties(split_gdn_tc_test PROPERTIES CUDA_ARCHITECTURES "${STRATA_SPLIT_ARCH}-real" CUDA_STANDARD 17 CXX_STANDARD 17) + endif() # fnx_run: sFNX's test driver (teacher-forced logits to an .lgr file, prompt/decode checks), the same engine objects with its own main set(_sp_run_src ${_sp_engine}) list(REMOVE_ITEM _sp_run_src ${_sp}/tools/sfnx.cpp) diff --git a/src/split/src/gdn_tc_prompt.cuh b/src/split/src/gdn_tc_prompt.cuh new file mode 100644 index 0000000000..da0882265a --- /dev/null +++ b/src/split/src/gdn_tc_prompt.cuh @@ -0,0 +1,761 @@ +// src/split/src/gdn_tc_prompt.cuh - Strata's tensor-core chunk scan for the delta rule (src/prefill/gdn_tc.cuh) in the split's prompt GDN +// (FNX_PFX_GDN_TC=1, sm_80+ CUDA only; the HIP build and every card the scan does not fit keep k_gdn_ch_prep / k_gdn_ch_rec). +// +// Included by kernels.cu inside the anonymous namespace, after gdn_prompt.cuh (it uses HS, GCH and k_gdn_pf_norm_own from there). +// The algebra, the f16 hi / lo split products, the scaling by powers of two and the register-resident state are Strata's, unchanged; +// what changes is the geometry: the card's slice has nv local value heads (vmap: local key head | first-of-its-key-head << 8), the +// state is [local value head][key row][value column] (the split's S), the conv output xc has the row stride (2 nk + nv) HS, and +// the gate and beta come from ab (the alpha / beta logits) as k_gdn_ch_prep makes them. The scan runs NTL column tiles a head so +// that a card with 24 heads fills its SMs. Tolerances: the harness of Strata holds this scan within 1e-4 of the fp32 chunk kernel. +#pragma once +// compiled in the part that holds gdn_prompt() only (kernels.cu is built in nine parts) +#if FNX_KPART == 4 && !FNX_HIP && FNX_ARCH >= 80 +#define FNX_GDN_TC_ON 1 +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 +#define STRATA_GDN_TC_SM80 1 +#define STRATA_GDN_CP_ASYNC 1 +#else +#define STRATA_GDN_TC_SM80 0 // device code for older cards: the wrappers trap (the scan never launches there) +#define STRATA_GDN_CP_ASYNC 0 +#endif + +constexpr int GTS = HS; // head size +constexpr int GTP = GCH + 1; // padded T / P rows (the Gram arrays) +constexpr int GTC_GSB = 2048; // tokens a super-block: the prep's scratch is GTC_GSB / GCH chunks +static_assert(GCH == 32, "gdn_tc_prompt.cuh: a lane per token of the chunk"); + +__device__ __forceinline__ void gdn_cp4(float* smem, const float* gmem) { +#if STRATA_GDN_CP_ASYNC + asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem)); +#else + *smem = *gmem; +#endif +} +__device__ __forceinline__ void gdn_cp16(float* smem, const float* gmem) { +#if STRATA_GDN_CP_ASYNC + asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem)); +#else + *reinterpret_cast(smem) = *reinterpret_cast(gmem); +#endif +} +__device__ __forceinline__ void gdn_cp_commit() { +#if STRATA_GDN_CP_ASYNC + asm volatile("cp.async.commit_group;\n" ::); +#endif +} +__device__ __forceinline__ void gdn_cp_wait_all() { +#if STRATA_GDN_CP_ASYNC + asm volatile("cp.async.wait_all;\n" ::); +#endif +} + +constexpr int GTC_KP = GTS + 8; // f16 k / q rows: a 272-B stride puts the 8 rows of a ldmatrix 8x8 on 8 distinct 16-B lanes +constexpr int GTC_VP = GTS + 4; // f32 v rows: lane (gid, tig) reads word 264 tig + gid, 32 distinct banks +constexpr int GTC_PP = GCH + 8; // f16 T / P rows: an 80-B stride, 8 rows on distinct 16-B lanes +constexpr int GTC_CW = GTS / 16; // consumer warps a block: 16 value columns each +// dynamic shared memory a block, two buffers each: k / q hi / lo, v, (z), T hi / lo, P hi / lo, the token scalars +// (beta, exp(gamma), exp(gL - gamma), gamma) as float4, (the norm's o^2 partials), T's scale 2^-et: 124,944 B +// without the fused norm, 160,784 with it (the 166,912 opt-in of GA100) +template +constexpr size_t kTcScanSmem = 2 * (4 * GCH * GTC_KP * 2 + GCH * GTC_VP * 4 + (NORM ? GCH * GTC_VP * 4 : 0) + + 4 * GCH * GTC_PP * 2 + GCH * 16 + (NORM ? GCH * GTC_CW * 4 : 0)) + 16; +static_assert(kTcScanSmem == 124944 && kTcScanSmem == 160784, "gdn_tc.cuh: the shared-memory plan"); +// SPLIT (the 99-KB cards: sm_86 / sm_89 / sm_120): only k / q hi / lo and the token scalars stay double-buffered; v, T and P +// (one buffer) are staged for the next chunk after this chunk's last read of them, so that load overlaps the state update: +// 97,808 B against the 101,376 B opt-in of those cards (the full plan needs 124,944) +constexpr size_t kTcScanSmemSplit = 2 * (4 * GCH * GTC_KP * 2 + GCH * 16) + GCH * GTC_VP * 4 + 4 * GCH * GTC_PP * 2 + 16; +static_assert(kTcScanSmemSplit == 97808, "gdn_tc.cuh: the split shared-memory plan"); +// + the fused output norm's partial sums of squares [GTC_CW warps][GCH tokens] (SPLIT only): 98,832 B +constexpr size_t kTcScanSmemSplitNorm = kTcScanSmemSplit + GTC_CW * GCH * 4; +static_assert(kTcScanSmemSplitNorm == 98832, "gdn_tc.cuh: the split + norm shared-memory plan"); +// the prep's scratch for a super-block (gdn_tc_scratch, one a device, 60.3 MB): the T images x 2^et as +// [chunk][vh][2: hi, lo][GCH][GCH] f16 and their scales 2^-et as [chunk][vh], the token scalars as float4 +// [chunk][vh][GCH], the k and q images x 2^8 as [chunk][qh][4: k hi, k lo, q hi, q lo][GCH][GTS] and the P images x 2^8 +// as [chunk][vh][2: hi, lo][GCH][GCH] - every row a multiple of 16 B, so the scan stages all of it by cp.async +constexpr int GTC_NB = GTC_GSB / GCH; +// the prep's scratch for a super-block, one a device (allocated on first use for the card's heads and kept): the T images x 2^et as +// [chunk][vh][2: hi, lo][GCH][GCH] f16 and their scales 2^-et as [chunk][vh], the token scalars as float4 [chunk][vh][GCH], the k and q +// images x 2^8 as [chunk][key head][4: k hi, k lo, q hi, q lo][GCH][GTS] and the P images x 2^8 as [chunk][vh][2: hi, lo][GCH][GCH] +struct GtcScratch { + uint16_t* ti = nullptr; + float* te = nullptr; + float4* sc = nullptr; + uint16_t* kq = nullptr; + uint16_t* pi = nullptr; +}; +inline size_t gtc_scratch_bytes(int nk, int nv) { + return (size_t) GTC_NB * nv * 2 * GCH * GCH * 2 + (size_t) GTC_NB * nv * 4 + (size_t) GTC_NB * nv * GCH * 16 + + (size_t) GTC_NB * nk * 4 * GCH * GTS * 2 + (size_t) GTC_NB * nv * 2 * GCH * GCH * 2; +} +// nullptr members when the card had no room +inline GtcScratch gtc_scratch(int nk, int nv) { + static unsigned char* bufs[16] = {}; + static size_t sizes[16] = {}; + GtcScratch r; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 16) { cudaGetLastError(); return r; } + const size_t need = gtc_scratch_bytes(nk, nv); + if (bufs[dev] != nullptr && sizes[dev] < need) { cudaFree(bufs[dev]); bufs[dev] = nullptr; } + if (bufs[dev] == nullptr) { + if (cudaMalloc((void**) &bufs[dev], need) != cudaSuccess) { cudaGetLastError(); bufs[dev] = nullptr; return r; } + sizes[dev] = need; + } + unsigned char* p = bufs[dev]; + const size_t tiB = (size_t) GTC_NB * nv * 2 * GCH * GCH * 2, teB = (size_t) GTC_NB * nv * 4, scB = (size_t) GTC_NB * nv * GCH * 16, + kqB = (size_t) GTC_NB * nk * 4 * GCH * GTS * 2; + r.ti = reinterpret_cast(p); + r.te = reinterpret_cast(p + tiB); + r.sc = reinterpret_cast(p + tiB + teB); + r.kq = reinterpret_cast(p + tiB + teB + scB); + r.pi = reinterpret_cast(p + tiB + teB + scB + kqB); + return r; +} + +// the warp's largest of non-negative floats: their bits order as unsigned integers, so one redux.sync (sm_80). Under +// the full mask: __activemask() does not reconverge the warp (CUDA guide), and the first call of the scan follows a +// lane-divergent branch (the L2 prefetch of tokens past the end, in the chunk two before the end whenever +// 0 < T - f_t0 < 32), so with it the lanes could reduce under a partial mask and disagree on es. The harness build +// happened to close that branch (BSYNC) before the REDUX.MAX; the engine's build is a separate compile that nothing +// checks. The kernel has no early return, so the full mask costs no reconvergence code. +__device__ __forceinline__ float gtc_warp_max(float v) { +#if STRATA_GDN_TC_SM80 + return __uint_as_float(__reduce_max_sync(0xffffffffu, __float_as_uint(v))); +#else +#pragma unroll + for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o)); + return v; +#endif +} +__device__ __forceinline__ float gtc_pow2(int e) { return __int_as_float((e + 127) << 23); } // 2^e, |e| < 127 +// the power of two that puts m = max |x| >= 0 in [2^14, 2^15): f16 hi never overflows (65504) and the low part of +// every entry within 2^-17 of the max stays normal; clamped so that the compensating powers stay far from f32's range +__device__ __forceinline__ int gtc_scale_exp(float m) { + if (m == 0.0f) return 0; + const int e = 14 - ((__float_as_int(m) >> 23) - 127); + return e < -40 ? -40 : (e > 40 ? 40 : e); +} + +// ---- the tensor-core wrappers (PTX ISA "Matrix Fragments": lane = 4 gid + tig) +// m16n8k16 f16: A a0 = (row gid, cols 2tig, 2tig+1) a1 = (gid+8, ..) a2 = (gid, 2tig+8..) a3 = (gid+8, 2tig+8..); +// B b0 = (k 2tig, 2tig+1; n gid) b1 = (k 2tig+8..; n gid); C/D c0 = (gid, 2tig) c1 = (gid, 2tig+1) +// c2 = (gid+8, 2tig) c3 = (gid+8, 2tig+1) - so two adjacent C tiles ARE the next product's A fragment +// ldmatrix m8n8.x4.b16: lanes 8m..8m+7 give the row addresses of matrix m; a lane gets (row gid, cols 2tig, 2tig+1) +// of each matrix (the lower column in the low half), or with .trans (rows 2tig, 2tig+1; col gid) +__device__ __forceinline__ void gtc_ldsm_x4(uint32_t (&r)[4], const void* smem) { +#if STRATA_GDN_TC_SM80 + asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) + : "r"((unsigned) __cvta_generic_to_shared(smem))); +#else + r[0] = r[1] = r[2] = r[3] = 0u; (void) smem; __trap(); +#endif +} +__device__ __forceinline__ void gtc_ldsm_x4_trans(uint32_t (&r)[4], const void* smem) { +#if STRATA_GDN_TC_SM80 + asm volatile("ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0,%1,%2,%3}, [%4];" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) + : "r"((unsigned) __cvta_generic_to_shared(smem))); +#else + r[0] = r[1] = r[2] = r[3] = 0u; (void) smem; __trap(); +#endif +} +__device__ __forceinline__ void gtc_mma_f16(float (&c)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) { +#if STRATA_GDN_TC_SM80 + asm("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};" + : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) + : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1)); +#else + (void) c; (void) a; (void) b0; (void) b1; __trap(); +#endif +} +// the three passes of a split product, small terms first (as qsa_select.cu): lo.hi, hi.lo, hi.hi +__device__ __forceinline__ void gtc_mma3_f16(float (&c)[4], const uint32_t (&ah)[4], const uint32_t (&al)[4], uint32_t bh0, + uint32_t bh1, uint32_t bl0, uint32_t bl1) { + gtc_mma_f16(c, al, bh0, bh1); + gtc_mma_f16(c, ah, bl0, bl1); + gtc_mma_f16(c, ah, bh0, bh1); +} +// NP (experiment, STRATA_GDN_TC split kernels only): 3 = every product on the three passes above (the default); 2 = only the products +// that reach the OUTPUT alone (q.GTS and D.P) on one pass, the state's products (k.GTS, Y.T, the update) on three; 1 = every product on one pass +// (hi.hi, plain f16 operands as the gfx11 WMMA path). A single-pass product does not read its B operand's lo image. +template +__device__ __forceinline__ void gtc_mmaN(float (&c)[4], const uint32_t (&ah)[4], const uint32_t (&al)[4], uint32_t bh0, + uint32_t bh1, uint32_t bl0, uint32_t bl1) { + if constexpr (NP == 3) { + gtc_mma_f16(c, al, bh0, bh1); + gtc_mma_f16(c, ah, bl0, bl1); + } else if constexpr (NP == 2) { + gtc_mma_f16(c, al, bh0, bh1); + } + gtc_mma_f16(c, ah, bh0, bh1); +} +// x0, x1 -> packed f16 hi (x0 in the low half) and lo = f16(x - hi): x - hi is exact in f32 (hi carries x's exponent) +__device__ __forceinline__ void gtc_split_f16x2(float x0, float x1, uint32_t& hi, uint32_t& lo) { + union { __half2 h; uint32_t u; } cv; + cv.h = __floats2half2_rn(x0, x1); + hi = cv.u; + const float2 r = __half22float2(cv.h); + cv.h = __floats2half2_rn(x0 - r.x, x1 - r.y); + lo = cv.u; +} +// four consecutive elements of an f16 hi / lo row from a float4 x scale (an 8-byte store each) +__device__ __forceinline__ void gtc_split_store4(uint16_t* hi, uint16_t* lo, float4 v, float scale) { + uint32_t h0, l0, h1, l1; + gtc_split_f16x2(v.x * scale, v.y * scale, h0, l0); + gtc_split_f16x2(v.z * scale, v.w * scale, h1, l1); + *reinterpret_cast(hi) = make_uint2(h0, h1); + *reinterpret_cast(lo) = make_uint2(l0, l1); +} +// a float4 from shared memory the compiler does not keep: the per-token scalars are read in three phases of a chunk, +// a component each, and kept across them they cost 24 registers a thread +__device__ __forceinline__ float4 gtc_lds128(const float4* p) { + float4 v; +#if STRATA_GDN_TC_SM80 + asm volatile("ld.shared.v4.f32 {%0,%1,%2,%3}, [%4];" + : "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w) + : "r"((unsigned) __cvta_generic_to_shared(p))); +#else + v = *p; +#endif + return v; +} +// ---- the products of a chunk, a warp each (the self-test of gdn_rec_parity --selftest-frag runs them one by one) +// X^T = GTS^T K^T and QS^T = GTS^T Q^T: A = the state fragments x sA (= 2^es) split in f16 hi / lo just in time per k16-step +// (tiles 2kk and 2kk + 1 of GTS^T are that step's A fragment), B = the f16 hi / lo images of k and q ([GCH][GTC_KP] in +// shared memory, rows = tokens) by ldmatrix: matrices (n-tile 2hf + (lane >> 4), k-half (lane >> 3) & 1), a lane's +// row is token 8 n-tile + (lane & 7). The accumulators come out as 2^(8 + es) times the products. 2 x 96 mma. +template +__device__ __forceinline__ void gtc_prod_state(const float (&s)[16][4], float sA, const uint16_t* kh, const uint16_t* kl, + const uint16_t* qh, const uint16_t* ql, float (&xt)[4][4], float (&qs)[4][4]) { + const int lane = threadIdx.x & 31; + const int off = (8 * (lane >> 4) + (lane & 7)) * GTC_KP + 8 * ((lane >> 3) & 1); +#pragma unroll + for (int kk = 0; kk < GTS / 16; ++kk) { + uint32_t ah[4], al[4]; + gtc_split_f16x2(s[2 * kk][0] * sA, s[2 * kk][1] * sA, ah[0], al[0]); + gtc_split_f16x2(s[2 * kk][2] * sA, s[2 * kk][3] * sA, ah[1], al[1]); + gtc_split_f16x2(s[2 * kk + 1][0] * sA, s[2 * kk + 1][1] * sA, ah[2], al[2]); + gtc_split_f16x2(s[2 * kk + 1][2] * sA, s[2 * kk + 1][3] * sA, ah[3], al[3]); +#pragma unroll + for (int hf = 0; hf < 2; ++hf) { + const int o = off + 16 * hf * GTC_KP + 16 * kk; + uint32_t bh[4], bl[4] = {0u, 0u, 0u, 0u}; + gtc_ldsm_x4(bh, kh + o); + if constexpr (NPK == 3) gtc_ldsm_x4(bl, kl + o); + gtc_mmaN(xt[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]); + gtc_mmaN(xt[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]); + gtc_ldsm_x4(bh, qh + o); + if constexpr (NPQ == 3) gtc_ldsm_x4(bl, ql + o); + gtc_mmaN(qs[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]); + gtc_mmaN(qs[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]); + } + } +} +// o^T += (sD D^T) (2^8 P^T) on f16x3: A = the D^T tiles x sD (= 2^ed) split per k16-step, B = the f16 hi / lo images +// of P x 2^8 ([GCH][GTC_PP], rows = tokens t) by ldmatrix as in gtc_prod_state. SKIP leaves out the tiles above P's +// diagonal: tokens t < 16 (n-tiles 0, 1) see no i >= 16 (k-step 1). 18 (SKIP) or 24 mma. D^T += (sY Y^T) (2^et T^T) +// is the same product on the T images (T is zero above its diagonal too), the accumulator x 2^(ey + et). +template +__device__ __forceinline__ void gtc_prod_dt(const float (&dt)[4][4], float sD, const uint16_t* ph, const uint16_t* pl, + float (&ot)[4][4]) { + const int lane = threadIdx.x & 31; + const int off = (8 * (lane >> 4) + (lane & 7)) * GTC_PP + 8 * ((lane >> 3) & 1); +#pragma unroll + for (int ks = 0; ks < GCH / 16; ++ks) { + uint32_t ah[4], al[4]; + gtc_split_f16x2(dt[2 * ks][0] * sD, dt[2 * ks][1] * sD, ah[0], al[0]); + gtc_split_f16x2(dt[2 * ks][2] * sD, dt[2 * ks][3] * sD, ah[1], al[1]); + gtc_split_f16x2(dt[2 * ks + 1][0] * sD, dt[2 * ks + 1][1] * sD, ah[2], al[2]); + gtc_split_f16x2(dt[2 * ks + 1][2] * sD, dt[2 * ks + 1][3] * sD, ah[3], al[3]); +#pragma unroll + for (int hf = 0; hf < 2; ++hf) { + if (SKIP && ks == 1 && hf == 0) continue; + const int o = off + 16 * hf * GTC_PP + 16 * ks; + uint32_t bh[4], bl[4] = {0u, 0u, 0u, 0u}; + gtc_ldsm_x4(bh, ph + o); + if constexpr (NP == 3) gtc_ldsm_x4(bl, pl + o); + gtc_mmaN(ot[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]); + gtc_mmaN(ot[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]); + } + } +} +// GTS^T += Dd^T (2^8 K) on f16x3: A = the (already scaled) Dd^T tiles split per k16-step, B = the same k images read the +// other way by ldmatrix.trans: matrices (n-tile 2hf + (lane >> 4), k-half (lane >> 3) & 1), a lane's row is token +// 16 ks + 8 k-half + (lane & 7), its 16-B piece state rows 8 n-tile.. 96 mma. +template +__device__ __forceinline__ void gtc_update_state(float (&s)[16][4], const float (&dd)[4][4], const uint16_t* kh, + const uint16_t* kl) { + const int lane = threadIdx.x & 31; + const int off = (8 * ((lane >> 3) & 1) + (lane & 7)) * GTC_KP + 8 * (lane >> 4); +#pragma unroll + for (int ks = 0; ks < GCH / 16; ++ks) { + uint32_t ah[4], al[4]; + gtc_split_f16x2(dd[2 * ks][0], dd[2 * ks][1], ah[0], al[0]); + gtc_split_f16x2(dd[2 * ks][2], dd[2 * ks][3], ah[1], al[1]); + gtc_split_f16x2(dd[2 * ks + 1][0], dd[2 * ks + 1][1], ah[2], al[2]); + gtc_split_f16x2(dd[2 * ks + 1][2], dd[2 * ks + 1][3], ah[3], al[3]); +#pragma unroll + for (int hf = 0; hf < GTS / 16; ++hf) { + const int o = off + 16 * ks * GTC_KP + 16 * hf; + uint32_t bh[4], bl[4] = {0u, 0u, 0u, 0u}; + gtc_ldsm_x4_trans(bh, kh + o); + if constexpr (NP == 3) gtc_ldsm_x4_trans(bl, kl + o); + gtc_mmaN(s[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]); + gtc_mmaN(s[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]); + } + } +} + +// ---- the prep: gdn_chunk_prep_kernel (kernels.cu) for the tensor-core scan, a block per (chunk, key head): the same +// A, solve, T and P, but the Gram products k_t.k_i and q_t.k_i on the tensor cores (f16x3 from the k and q hi / lo +// images x 2^8, which the block builds first in shared memory straight from the float4 registers the rows arrive in, +// rows past the chunk's end zero: 48 mma a warp against ~1,150 LDS a thread for the FFMA form, which was LDS-bound at +// 233 us a 2048-token super-block), and it writes what the scan stages by cp.async with no conversion of its own: the +// same k / q images, P as f16 hi / lo images x 2^8 (the split the scan did, element by element) and the token scalars +// (beta, exp(gamma), exp(gL - gamma), gamma) as a float4 a token, T as f16 hi / lo images x 2^et, et from the warp's +// largest |T| (2^-et beside them in te). The Gram entries are within 3 x 2^-22 of exact (the scan's bound), so T and +// P differ from gdn_chunk_prep_kernel's by that. +constexpr size_t kTcPrepSmem = (size_t) 4 * GCH * GTC_KP * 2 + 2 * GCH * GTP * 4; // the images, then k_t.k_i and q_t.k_i +static_assert(1 * GCH * GTP * 4 <= 4 * GCH * GTC_KP * 2, "gdn_tc_prep_kernel: A fits where the images were"); +// A block per (chunk, LOCAL value head): the split's card holds nv value heads, vmap[lv] = local key head | first-of-its-key-head << 8. The Gram of +// the key head is done by each of its value heads' blocks (Strata's block did it once for its VPK heads); the k / q images in the scratch are written by +// the first one. The gate and beta come from ab (nv alpha then nv beta logits a row) as k_gdn_ch_prep makes them. +__global__ void __launch_bounds__(256) gdn_tc_prep_kernel(const float* __restrict__ h, const float* __restrict__ ab, + const float* __restrict__ dtb, const float* __restrict__ ssm_a, + const int* __restrict__ vmap, uint16_t* __restrict__ ti, + float* __restrict__ te, float4* __restrict__ sc, + uint16_t* __restrict__ kq, uint16_t* __restrict__ pi, int nk, int nv, int chs, + int64_t t0, int64_t T) { + extern __shared__ __align__(16) float gsm[]; + uint16_t* im = reinterpret_cast(gsm); // [4][GCH][GTC_KP] k hi, k lo, q hi, q lo (x 2^8) + float* skk = gsm + 4 * GCH * GTC_KP / 2; // [GCH][GTP] k_t.k_i + float* sqk = skk + GCH * GTP; // [GCH][GTP] q_t.k_i + float* sa = gsm; // [1][GCH][GTP] A, then T below the diagonal (over the + // images: read by then) + const int lv = blockIdx.y, ch = blockIdx.x, tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const int vmv = vmap[lv], qh = vmv & 255; // qh: the local key head + const bool first = (vmv >> 8) != 0; + const int64_t tb = t0 + (int64_t) ch * GCH; + const int n = (int) min((int64_t) GCH, T - tb); + // after the Gram: warps j and VPK + j take value head j (lane i: token i), the first A, the solve and T, the + // second P and the token scalars; their beta and gate (past the end: gate 0, beta 0, no effect on GTS) are loaded + // now so that they are in by then + const int vh = lv, i = lane; + const bool pv = warp < 2 && i < n; + float b = 0.0f, gam = 0.0f; + if (pv) { + const float* abt = ab + (tb + i) * 2 * (int64_t) nv; + const float x = abt[vh] + dtb[vh]; + gam = (x > 20.0f ? x : log1pf(__expf(x))) * ssm_a[vh]; + b = 1.0f / (1.0f + __expf(-abt[nv + vh])); + } + { // k and q as float4, every load issued before the first store; the images to shared and to global + constexpr int NP = GCH * GTS / 4 / 256; // float4 a thread, each of k and q + float4 kv[NP], qv[NP]; +#pragma unroll + for (int m = 0; m < NP; ++m) { + const int p = tid + 256 * m, t = p / (GTS / 4), r = (p % (GTS / 4)) * 4; + kv[m] = t < n ? *reinterpret_cast(h + (tb + t) * chs + nk * GTS + qh * GTS + r) : make_float4(0.f, 0.f, 0.f, 0.f); + qv[m] = t < n ? *reinterpret_cast(h + (tb + t) * chs + qh * GTS + r) : make_float4(0.f, 0.f, 0.f, 0.f); + } + uint16_t* img = kq + ((size_t) ch * nk + qh) * 4 * GCH * GTS; +#pragma unroll + for (int m = 0; m < NP; ++m) { + const int p = tid + 256 * m, t = p / (GTS / 4), r = (p % (GTS / 4)) * 4; + const int o = t * GTC_KP + r; + gtc_split_store4(im + o, im + GCH * GTC_KP + o, kv[m], 256.0f); + gtc_split_store4(im + 2 * GCH * GTC_KP + o, im + 3 * GCH * GTC_KP + o, qv[m], 256.0f); + if (first) { + gtc_split_store4(img + t * GTS + r, img + GCH * GTS + t * GTS + r, kv[m], 256.0f); + gtc_split_store4(img + 2 * GCH * GTS + t * GTS + r, img + 3 * GCH * GTS + t * GTS + r, qv[m], 256.0f); + } + } + } + __syncthreads(); + { // the Gram products: warp w takes product w >> 2 (k_t.k_i, q_t.k_i), rows 16 ((w >> 1) & 1).. (the A + // tile, by ldmatrix as a row-major [t][r] 16 x 16), columns 16 (w & 1).. (two n-tiles: B = k^T, stored + // [n][k] = the k rows, by ldmatrix as the scan's gtc_prod_state); the accumulators come out x 2^16 + const int pr = warp >> 2, mt = (warp >> 1) & 1, np = warp & 1; + const uint16_t* ah_ = im + 2 * pr * GCH * GTC_KP + (16 * mt + (lane & 7) + 8 * ((lane >> 3) & 1)) * GTC_KP + 8 * (lane >> 4); + const uint16_t* bh_ = im + (16 * np + 8 * (lane >> 4) + (lane & 7)) * GTC_KP + 8 * ((lane >> 3) & 1); + float c[2][4] = {}; +#pragma unroll + for (int kk = 0; kk < GTS / 16; ++kk) { + uint32_t ah[4], al[4], bh[4], bl[4]; + gtc_ldsm_x4(ah, ah_ + 16 * kk); + gtc_ldsm_x4(al, ah_ + GCH * GTC_KP + 16 * kk); + gtc_ldsm_x4(bh, bh_ + 16 * kk); + gtc_ldsm_x4(bl, bh_ + GCH * GTC_KP + 16 * kk); + gtc_mma3_f16(c[0], ah, al, bh[0], bh[1], bl[0], bl[1]); + gtc_mma3_f16(c[1], ah, al, bh[2], bh[3], bl[2], bl[3]); + } + float* g = pr ? sqk : skk; + const int gid = lane >> 2, tig = lane & 3; +#pragma unroll + for (int j = 0; j < 2; ++j) +#pragma unroll + for (int q = 0; q < 4; ++q) { + const int t = 16 * mt + gid + 8 * (q >> 1), i = 16 * np + 8 * j + 2 * tig + (q & 1); + g[t * GTP + i] = i <= t ? c[j][q] * gtc_pow2(-16) : 0.0f; + } + } + __syncthreads(); + if (warp >= 2) return; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const float u = __shfl_up_sync(0xffffffffu, gam, o); + if (lane >= o) gam += u; + } + if (warp >= 1) { // P = exp(gamma_t - gamma_i) q_t.k_i (i <= t) x 2^8 as f16 hi / lo; the scalars + uint16_t* Ph = pi + ((int64_t) ch * nv + vh) * 2 * GCH * GCH; + uint16_t* Pl = Ph + GCH * GCH; +#pragma unroll + for (int t = 0; t < GCH; ++t) { + const float gt = __shfl_sync(0xffffffffu, gam, t); + const float p = (i <= t ? expf(gt - gam) * sqk[t * GTP + i] : 0.0f) * 256.0f; + const __half hi = __float2half_rn(p); + Ph[t * GCH + i] = __half_as_ushort(hi); + Pl[t * GCH + i] = __half_as_ushort(__float2half_rn(p - __half2float(hi))); + } + const float gL = __shfl_sync(0xffffffffu, gam, GCH - 1); + sc[((int64_t) ch * nv + vh) * GCH + i] = make_float4(b, expf(gam), expf(gL - gam), gam); + return; + } + float* a = sa; +#pragma unroll + for (int t = 0; t < GCH; ++t) { + const float gt = __shfl_sync(0xffffffffu, gam, t), bt = __shfl_sync(0xffffffffu, b, t); + a[t * GTP + i] = i < t ? bt * expf(gt - gam) * skk[t * GTP + i] : (i == t ? 1.0f : 0.0f); + } + __syncwarp(); + // T = (I + A)^-1 by forward substitution, row by row: T[t][i] = -sum_{k < t} A[t][k] T[k][i] over the finished + // rows (diagonal 1, zeros above it: the terms k < i add an exact 0, so the same bits as summing from k = i). + // Lane i keeps its column T[.][i] in registers, so a row needs only A's row t (a broadcast load a term) and A + // is never written: no store and no __syncwarp a row + float tv[GCH]; + tv[0] = i == 0 ? 1.0f : 0.0f; +#pragma unroll + for (int t = 1; t < GCH; ++t) { + float v = 0.0f; +#pragma unroll + for (int k = 0; k < t; ++k) v = fmaf(-a[t * GTP + k], tv[k], v); + tv[t] = i < t ? v : (i == t ? 1.0f : 0.0f); + } + // T's images x 2^et (its largest entry in [2^14, 2^15), as the scan scales its own operands) + float mt4[4] = {}; +#pragma unroll + for (int t = 0; t < GCH; ++t) mt4[t & 3] = fmaxf(mt4[t & 3], fabsf(tv[t])); + const int et = gtc_scale_exp(gtc_warp_max(fmaxf(fmaxf(mt4[0], mt4[1]), fmaxf(mt4[2], mt4[3])))); + const float sT = gtc_pow2(et); + uint16_t* Th = ti + ((int64_t) ch * nv + vh) * 2 * GCH * GCH; + uint16_t* Tl = Th + GCH * GCH; +#pragma unroll + for (int t = 0; t < GCH; ++t) { + const float x = tv[t] * sT; + const __half hi = __float2half_rn(x); + Th[t * GCH + i] = __half_as_ushort(hi); + Tl[t * GCH + i] = __half_as_ushort(__float2half_rn(x - __half2float(hi))); + } + if (i == 0) te[(int64_t) ch * nv + vh] = gtc_pow2(-et); +} + +// ---- the scan: a block per value head (48 blocks, one wave on 48 of the CMP 170HX's 70 SMs), 8 consumer warps of 16 +// value columns each walking every chunk of the super-block with their state slice in registers (written back at the +// end as gdn_chunk_scan_kernel does), the prep's scratch from gdn_tc_prep_kernel. Everything a chunk needs arrives by +// cp.async, issued for the next chunk right after the one __syncthreads a chunk (which publishes the buffer just +// landed and ends every read of the other one): the k / q and P f16 images, T and the token scalars as the prep +// wrote them, v from h (its rows past the chunk's end zero-filled). The 256 threads do no conversion of their own. +// Earlier forms, measured on this card: the scan splitting k / q itself after the state update (0.282 us a token; +// ~300 split instructions a warp a chunk and the staging exposed at the chunk's end); two stager warps with named +// barriers (6 % slower: registers are allocated per SM sub-partition, 16K each, and a block of more than 8 warps puts +// 3 on a sub-partition, which caps the kernel at 168 registers a thread; the consumers need about 200 and spilled. +// 8 warps, 2 a sub-partition, may have 255). +// NORM (step 5: the output norm fused, the FP16 output written here) is not implemented yet; oc_out takes the FP32 +// output as gdn_chunk_scan_kernel writes it. +template +__global__ void __launch_bounds__(GTC_CW * 32, 1) +gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const uint16_t* __restrict__ tig_, + const float* __restrict__ teg, const float4* __restrict__ scg, const uint16_t* __restrict__ kqg, + const uint16_t* __restrict__ pig, float* __restrict__ oc_out, int64_t t0, int nch, int64_t T, + const int* __restrict__ vmap, int nk, int nv, int chs, + const float* __restrict__ zg = nullptr, const float* __restrict__ gamma = nullptr, float eps = 0.0f, + uint16_t* __restrict__ y16 = nullptr, int64_t ld16 = 0) { + // NORM (SPLIT only): the output norm of gdn_out_norm_kernel fused: the scan writes the FP16 y16 = o rsqrt(mean(o^2) + eps) gamma + // sigmoid(z) itself (the sums of squares across the block's 8 warps through shared memory), and not the FP32 o: one pass less + // over the 24 KB-a-token output. Another summation order than the kernel's 4 partials (not bitwise). + static_assert(!NORM || SPLIT, "gdn_tc_scan_kernel: the fused output norm is implemented for the split plan"); + // NTL value tiles a head (a launch of HV x NTL blocks of GTC_CW / NTL warps): block (vh, tile) owns the state columns + // [tile GTS / NTL, (tile + 1) GTS / NTL), so a card with more than 48 SMs keeps more of them busy. The k / q / T / P images are staged + // by every tile of the head; v only for its columns. The fused output norm needs the whole head in one block: NORM => NTL == 1. + static_assert(!NORM || NTL == 1, "gdn_tc_scan_kernel: the fused output norm needs a whole head in a block"); + static_assert(GTC_CW % NTL == 0, "gdn_tc_scan_kernel: tiles of whole warps"); + constexpr int NT = (GTC_CW / NTL) * 32; + extern __shared__ __align__(16) unsigned char gtc_sm[]; + uint16_t* kh = reinterpret_cast(gtc_sm); // [2][GCH][GTC_KP] f16 of k x 2^8 (hi) + uint16_t* kl = kh + 2 * GCH * GTC_KP; // [2][GCH][GTC_KP] what hi left out (lo) + uint16_t* qh = kl + 2 * GCH * GTC_KP; // q likewise + uint16_t* ql = qh + 2 * GCH * GTC_KP; + constexpr int NV = SPLIT ? 1 : 2; // buffers of v, T and P + float* sv = reinterpret_cast(ql + 2 * GCH * GTC_KP); // [NV][GCH][GTC_VP] v + uint16_t* th = reinterpret_cast(sv + NV * GCH * GTC_VP); // [NV][GCH][GTC_PP] T x 2^et hi / lo + uint16_t* tl = th + NV * GCH * GTC_PP; + uint16_t* ph = tl + NV * GCH * GTC_PP; // [NV][GCH][GTC_PP] P x 2^8 hi / lo + uint16_t* pl = ph + NV * GCH * GTC_PP; + float4* sc = reinterpret_cast(pl + NV * GCH * GTC_PP); // [2][GCH] (beta, exp(gamma), exp(gL - gamma), gamma) + float* ste = reinterpret_cast(sc + 2 * GCH); // [2] 2^-et + float* rss = ste + 2; // NORM: [GTC_CW][GCH] partial sums of squares + const int vh = blockIdx.x / NTL, qhd = vmap[vh] & 255, cb = (blockIdx.x % NTL) * (GTS / NTL); // the tile's first column + const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, gid = lane >> 2, tig = lane & 3; + const size_t rs = (size_t) nv * GTS; // the output's (and z's) row stride; the state is [local value head][key row][value column] + // chunk ch into buffer b, this thread's 16-B pieces (one cp.async group): the four k / q images (4 x GCH rows of + // 16 pieces: 8 a thread), v (4 a thread), the two T images (1), the two P images (1), the scalars (warp 0, 1), + // T's scale (thread 0, 4 B) + // parts: bit 0 = the k / q images, the scalars and T's scale (buffer b); bit 1 = v, T and P (buffer bv: b, or 0 in SPLIT) + auto stage = [&](int ch, int b, int parts) { + const int64_t c_t0 = t0 + (int64_t) ch * GCH; + const int n = (int) min((int64_t) GCH, T - c_t0); + const int bv = SPLIT ? 0 : b; + if (parts & 1) { + const uint16_t* img = kqg + ((size_t) ch * nk + qhd) * 4 * GCH * GTS; +#pragma unroll + for (int m = 0; m < 4 * GCH * GTS / 8 / NT; ++m) { + const int pc = tid + NT * m, im = pc / (GCH * GTS / 8), t = (pc % (GCH * GTS / 8)) / (GTS / 8), r = (pc % (GTS / 8)) * 8; + uint16_t* dst = (im == 0 ? kh : im == 1 ? kl : im == 2 ? qh : ql) + (b * GCH + t) * GTC_KP + r; + gdn_cp16(reinterpret_cast(dst), reinterpret_cast(img + (im * GCH + t) * GTS + r)); + } + if (tid < GCH) gdn_cp16(reinterpret_cast(sc + b * GCH + tid), reinterpret_cast(scg + ((int64_t) ch * nv + vh) * GCH + tid)); + if (tid == 0) gdn_cp4(ste + b, teg + (int64_t) ch * nv + vh); + } + if (parts & 2) { +#pragma unroll + for (int m = 0; m < GCH * (GTS / NTL) / 4 / NT; ++m) { + const int p = tid + NT * m, t = p / (GTS / NTL / 4), r = (p % (GTS / NTL / 4)) * 4; + float* dst = sv + (bv * GCH + t) * GTC_VP + r; + if (t < n) gdn_cp16(dst, h + (c_t0 + t) * chs + 2 * nk * GTS + vh * GTS + cb + r); + else *reinterpret_cast(dst) = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + } +#pragma unroll + for (int m = 0; m < 2 * GCH * GCH / 8 / NT; ++m) { + const int pc = tid + NT * m, im = pc / (GCH * GCH / 8), t = (pc % (GCH * GCH / 8)) / (GCH / 8), i = (pc % (GCH / 8)) * 8; + const int64_t src = ((((int64_t) ch * nv + vh) * 2 + im) * GCH + t) * GCH + i; + const int dst = (bv * GCH + t) * GTC_PP + i; + gdn_cp16(reinterpret_cast((im ? tl : th) + dst), reinterpret_cast(tig_ + src)); + gdn_cp16(reinterpret_cast((im ? pl : ph) + dst), reinterpret_cast(pig + src)); + } + } + gdn_cp_commit(); + }; + const int c0 = 16 * warp; // the warp's value columns c0 + gid and c0 + gid + 8 of the tile (v in shared memory) + const int ca = cb + c0; // the same in the head (state, output) + // the state slice as GTS^T fragments: tile j = rows 8j..8j+7; s[j][0] = GTS[8j + 2tig][c0 + gid], [1] the row after, + // [2] column + 8, [3] both (64 scalar loads a lane, 32-B runs, once a launch) + float s[16][4]; +#pragma unroll + for (int j = 0; j < 16; ++j) { + const float* p = state + (size_t) vh * GTS * GTS + (size_t) (8 * j + 2 * tig) * GTS + ca + gid; + s[j][0] = p[0]; s[j][1] = p[GTS]; s[j][2] = p[8]; s[j][3] = p[GTS + 8]; + } + stage(0, 0, 3); + const float out_scale = rsqrtf((float) GTS); + for (int ch = 0; ch < nch; ++ch) { + const int b = ch & 1; + const int64_t c_t0 = t0 + (int64_t) ch * GCH; + const int n = (int) min((int64_t) GCH, T - c_t0); + gdn_cp_wait_all(); // this thread's pieces of chunk ch + __syncthreads(); // every thread's: chunk ch's buffer complete; every read of the other one done + if (ch + 1 < nch) stage(ch + 1, b ^ 1, SPLIT ? 1 : 3); + const uint16_t* bkh = kh + b * GCH * GTC_KP; + const uint16_t* bkl = kl + b * GCH * GTC_KP; + const uint16_t* bqh = qh + b * GCH * GTC_KP; + const uint16_t* bql = ql + b * GCH * GTC_KP; + const int bv = SPLIT ? 0 : b; + const uint16_t* bth = th + bv * GCH * GTC_PP; + const uint16_t* btl = tl + bv * GCH * GTC_PP; + const uint16_t* bph = ph + bv * GCH * GTC_PP; + const uint16_t* bpl = pl + bv * GCH * GTC_PP; + const float* bsv = sv + bv * GCH * GTC_VP; + const float4* bsc = sc + b * GCH; + // (a) X^T = S0^T K^T and QS^T = S0^T Q^T, the state x 2^es (its largest entry in [2^14, 2^15)). The lane's + // maximum over eight chains (nvcc keeps the order written: one chain was 64 dependent FMNMX before the first mma) + float m8[8] = {}; +#pragma unroll + for (int j = 0; j < 16; ++j) +#pragma unroll + for (int q = 0; q < 4; ++q) m8[(2 * j + (q >> 1)) & 7] = fmaxf(m8[(2 * j + (q >> 1)) & 7], fabsf(s[j][q])); + const float m = fmaxf(fmaxf(fmaxf(m8[0], m8[1]), fmaxf(m8[2], m8[3])), fmaxf(fmaxf(m8[4], m8[5]), fmaxf(m8[6], m8[7]))); + const int es = gtc_scale_exp(gtc_warp_max(m)); + float xt[4][4] = {}, qs[4][4] = {}; + gtc_prod_state<(NP == 1 ? 1 : 3), (NP == 3 ? 3 : 1)>(s, gtc_pow2(es), bkh, bkl, bqh, bql, xt, qs); + // (b) Y^T = beta_i (V^T - e'_i X^T), e'_i = exp(gamma_i) 2^-(8 + es): lane (gid, tig) holds tokens + // 8nt + 2tig and + 1, columns c0 + gid and + 8 + const float eS = gtc_pow2(-(8 + es)); + float yt[4][4]; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + const float4 s0 = gtc_lds128(bsc + 8 * nt + 2 * tig), s1 = gtc_lds128(bsc + 8 * nt + 2 * tig + 1); + const float* v = bsv + (8 * nt + 2 * tig) * GTC_VP + c0 + gid; + const float e0 = s0.y * eS, e1 = s1.y * eS; + yt[nt][0] = s0.x * fmaf(-e0, xt[nt][0], v[0]); + yt[nt][1] = s1.x * fmaf(-e1, xt[nt][1], v[GTC_VP]); + yt[nt][2] = s0.x * fmaf(-e0, xt[nt][2], v[8]); + yt[nt][3] = s1.x * fmaf(-e1, xt[nt][3], v[GTC_VP + 8]); + } + // (c) D^T = Y^T T^T on f16x3: Y^T x 2^ey (its largest entry in [2^14, 2^15)), T's images x 2^et from the prep; + // the accumulator comes out x 2^(ey + et) (T above its diagonal skipped) + float my4[4] = {}; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) +#pragma unroll + for (int q = 0; q < 4; ++q) my4[q] = fmaxf(my4[q], fabsf(yt[nt][q])); + const int ey = gtc_scale_exp(gtc_warp_max(fmaxf(fmaxf(my4[0], my4[1]), fmaxf(my4[2], my4[3])))); + float dt[4][4] = {}; + gtc_prod_dt(yt, gtc_pow2(ey), bth, btl, dt); + const float sYT = gtc_pow2(-ey) * ste[b]; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) +#pragma unroll + for (int q = 0; q < 4; ++q) dt[nt][q] *= sYT; + // (d) o^T = e_t QS^T + D^T P^T: the accumulator starts as 2^(ed + 8) e_t QS^T (QS^T came out x 2^(8 + es)), + // D^T goes in x 2^ed, P x 2^8; the output is the accumulator x 2^-(ed + 8), then rsqrt(GTS) as gdn_chunk_scan_kernel + float md4[4] = {}; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) +#pragma unroll + for (int q = 0; q < 4; ++q) md4[q] = fmaxf(md4[q], fabsf(dt[nt][q])); + const int ed = gtc_scale_exp(gtc_warp_max(fmaxf(fmaxf(md4[0], md4[1]), fmaxf(md4[2], md4[3])))); + const float sD = gtc_pow2(ed), sO = gtc_pow2(ed + 8), sOi = gtc_pow2(-(ed + 8)), eO = gtc_pow2(ed - es); + float ot[4][4]; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + const float e0 = gtc_lds128(bsc + 8 * nt + 2 * tig).y * eO, e1 = gtc_lds128(bsc + 8 * nt + 2 * tig + 1).y * eO; + ot[nt][0] = qs[nt][0] * e0; ot[nt][1] = qs[nt][1] * e1; ot[nt][2] = qs[nt][2] * e0; ot[nt][3] = qs[nt][3] * e1; + } + gtc_prod_dt(dt, sD, bph, bpl, ot); + float zr[4][4] = {}, gm2[2] = {}; + if constexpr (NORM) { + // the z values and gamma of this lane's elements are loaded now, so that their latency is spent in the barrier below +#pragma unroll + for (int nt = 0; nt < 4; ++nt) +#pragma unroll + for (int q = 0; q < 4; ++q) { + const int t = 8 * nt + 2 * tig + (q & 1); + if (t < n) zr[nt][q] = zg[(c_t0 + t) * rs + (size_t) vh * GTS + c0 + gid + 8 * (q >> 1)]; + } + gm2[0] = gamma[c0 + gid]; gm2[1] = gamma[c0 + gid + 8]; + // this lane's two columns of each of its 8 tokens -> partial sums over the warp's 16 columns (the 8 gid lanes), 8 warps in rss +#pragma unroll + for (int nt = 0; nt < 4; ++nt) +#pragma unroll + for (int q = 0; q < 4; ++q) ot[nt][q] = (ot[nt][q] * sOi) * out_scale; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) +#pragma unroll + for (int e = 0; e < 2; ++e) { + float ps = ot[nt][e] * ot[nt][e] + ot[nt][e + 2] * ot[nt][e + 2]; + ps += __shfl_xor_sync(0xffffffffu, ps, 4); + ps += __shfl_xor_sync(0xffffffffu, ps, 8); + ps += __shfl_xor_sync(0xffffffffu, ps, 16); + if (gid == 0) rss[warp * GCH + 8 * nt + 2 * tig + e] = ps; + } + } else { +#pragma unroll + for (int nt = 0; nt < 4; ++nt) +#pragma unroll + for (int q = 0; q < 4; ++q) { + const int t = 8 * nt + 2 * tig + (q & 1); + if (t < n) oc_out[(c_t0 + t) * rs + (size_t) vh * GTS + ca + gid + 8 * (q >> 1)] = (ot[nt][q] * sOi) * out_scale; + } + } + if (SPLIT) { // v, T and P of this chunk are dead: every warp is past (d); the next chunk's land during (e) + __syncthreads(); + if (ch + 1 < nch) stage(ch + 1, 0, 2); + } + if constexpr (NORM) { +#pragma unroll + for (int nt = 0; nt < 4; ++nt) +#pragma unroll + for (int e = 0; e < 2; ++e) { + const int t = 8 * nt + 2 * tig + e; + if (t >= n) continue; + float ss = 0.0f; +#pragma unroll + for (int w = 0; w < GTC_CW; ++w) ss += rss[w * GCH + t]; + const float rn = rsqrtf(ss / (float) GTS + eps); +#pragma unroll + for (int hc = 0; hc < 2; ++hc) { + const int col = c0 + gid + 8 * hc; + const float zz = zr[nt][e + 2 * hc]; + const float v = ot[nt][e + 2 * hc] * rn * gm2[hc] * (1.0f / (1.0f + __expf(-zz))); + y16[(c_t0 + t) * ld16 + (size_t) vh * GTS + col] = __half_as_ushort(__float2half_rn(v)); + } + } + } + // (e) GTS^T = eL S0^T + Dd^T K, Dd^T = f_i D^T: the accumulator x (eL 2^(ed + 8)) before (one rounding, as the + // s *= gL of gdn_chunk_scan_kernel), Dd^T in x 2^ed, K x 2^8, the accumulator x 2^-(ed + 8) after + const float sPre = gtc_lds128(bsc + GCH - 1).y * sO; // exp(gL) +#pragma unroll + for (int j = 0; j < 16; ++j) +#pragma unroll + for (int q = 0; q < 4; ++q) s[j][q] *= sPre; + float dd[4][4]; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + const float f0 = gtc_lds128(bsc + 8 * nt + 2 * tig).z * sD, f1 = gtc_lds128(bsc + 8 * nt + 2 * tig + 1).z * sD; + dd[nt][0] = dt[nt][0] * f0; dd[nt][1] = dt[nt][1] * f1; dd[nt][2] = dt[nt][2] * f0; dd[nt][3] = dt[nt][3] * f1; + } + gtc_update_state<(NP == 1 ? 1 : 3)>(s, dd, bkh, bkl); +#pragma unroll + for (int j = 0; j < 16; ++j) +#pragma unroll + for (int q = 0; q < 4; ++q) s[j][q] *= sOi; + } +#pragma unroll + for (int j = 0; j < 16; ++j) { + float* p = state + (size_t) vh * GTS * GTS + (size_t) (8 * j + 2 * tig) * GTS + ca + gid; + p[0] = s[j][0]; p[GTS] = s[j][1]; p[8] = s[j][2]; p[GTS + 8] = s[j][3]; + } +} + + +// ---- the launcher: false when the scan cannot run here (the caller then takes k_gdn_ch_prep / k_gdn_ch_rec). xc: the conv output rows +// (q | k | v, row stride (2 nk + nv) HS), ab / dt / a: the gate inputs as for k_gdn_ch_prep, S: [nv][HS][HS], y32: [C][nv HS]. +template +inline void gtc_set_smem() { + cudaFuncSetAttribute(gdn_tc_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplit); +} +inline bool gdn_tc_run(const float* xc, const float* ab, const float* dt, const float* a, float* S, float* y32, int nk, int nv, + const int* vmap, int C, cudaStream_t s) { + int dev = 0, major = 0, sms = 0, smem = 0; + if (cudaGetDevice(&dev) != cudaSuccess || cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess || + cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev) != cudaSuccess || + cudaDeviceGetAttribute(&smem, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev) != cudaSuccess) { + cudaGetLastError(); + return false; + } + if (major < 8 || (size_t) smem < kTcScanSmemSplit || nv <= 0 || nk <= 0) return false; + const GtcScratch sc = gtc_scratch(nk, nv); + if (sc.ti == nullptr) return false; + // column tiles a head: the most of 1, 2, 4, 8 that keep nv x tiles blocks within one wave of the card's SMs + int ntl = 1; + while (ntl < 8 && nv * ntl * 2 <= sms) ntl *= 2; + static bool attrs[16] = {}; + if (dev >= 0 && dev < 16 && !attrs[dev]) { + gtc_set_smem<1>(); gtc_set_smem<2>(); gtc_set_smem<4>(); gtc_set_smem<8>(); + cudaFuncSetAttribute(gdn_tc_prep_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcPrepSmem); + attrs[dev] = true; + } + const int chs = (2 * nk + nv) * HS; + for (int t0 = 0; t0 < C; t0 += GTC_GSB) { + const int nch = (std::min(GTC_GSB, C - t0) + GCH - 1) / GCH; + gdn_tc_prep_kernel<<>>(xc, ab, dt, a, vmap, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, nk, nv, + chs, t0, C); +#define GTC_SCAN(NTLV) gdn_tc_scan_kernel<<>>(S, xc, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y32, t0, nch, C, vmap, nk, nv, chs) + if (ntl == 8) GTC_SCAN(8); + else if (ntl == 4) GTC_SCAN(4); + else if (ntl == 2) GTC_SCAN(2); + else GTC_SCAN(1); +#undef GTC_SCAN + } + return cudaGetLastError() == cudaSuccess; +} +#endif // FNX_KPART == 4 && !FNX_HIP && FNX_ARCH >= 80 diff --git a/src/split/src/kernels.cu b/src/split/src/kernels.cu index 115f3b2ba6..18ccfc5524 100644 --- a/src/split/src/kernels.cu +++ b/src/split/src/kernels.cu @@ -472,6 +472,7 @@ __global__ void k_gdn_out_norm(const float* o, const float* z, const float* w, f #include "gdn_core.cuh" #include "gdn_prompt.cuh" +#include "gdn_tc_prompt.cuh" // ---------------------------------------------------------------- attention // per (t, head): RMS norm with the weight, then NEOX rotary on dims [0, NROT): pairs (i, i + NROT/2) @@ -1995,13 +1996,22 @@ void gdn_core_segs(const float* qkvz, const float* ab, const float* convw, const ck_launch("gdn_core_segs"); } -void gdn_prompt(const float* qkvz, const float* ab, float* hist, const float* convw, const float* dt, const float* a, const float* nw, - float* S, const int* ctl, int ng, int nk, int nv, const int* vmap, int C, float eps, float* xc, float* sq, float* y32, - float* chw, void* st) { +static void gdn_prompt_impl(const float* qkvz, const float* ab, float* hist, const float* convw, const float* dt, const float* a, const float* nw, + float* S, const int* ctl, int ng, int nk, int nv, const int* vmap, int C, float eps, float* xc, float* sq, float* y32, + float* chw, void* st) { cudaStream_t s = (cudaStream_t) st; const int ch = (2 * nk + nv) * HS; k_gdn_pf_conv<<>>(qkvz, hist, convw, ctl, xc, nk, nv); k_gdn_pf_hist<<<(ch + 255) / 256, 256, 0, s>>>(qkvz, hist, ctl, ng, C, nk, nv); +#if FNX_GDN_TC_ON + // FNX_PFX_GDN_TC=1: Strata's tensor-core chunk scan (gdn_tc_prompt.cuh); false -> this card cannot run it, the sub-chunk kernels below do + static const bool gdn_tc = fnx::env_int("FNX_PFX_GDN_TC", 0) != 0; + if (gdn_tc && gdn_tc_run(xc, ab, dt, a, S, y32, nk, nv, vmap, C, s)) { + k_gdn_pf_norm_own<<>>(qkvz, nw, y32, nk, nv, eps); + ck_launch("gdn_prompt"); + return; + } +#endif static const bool chunked = [] { const char* e = std::getenv("FNX_PF_GDN_CHUNK"); if (e && std::strcmp(e, "0") && std::strcmp(e, "1")) throw std::runtime_error(std::string("FNX_PF_GDN_CHUNK: 0 or 1, not '") + e + "'"); @@ -2055,6 +2065,43 @@ void gdn_prompt(const float* qkvz, const float* ab, float* hist, const float* co } ck_launch("gdn_prompt"); } +// FNX_GDN_TIME=1 (measuring): CUDA events around every prompt GDN call of a card (conv, history, scan, norm), their GPU time summed per +// card and printed to stderr each time 36 x 32768 rows (a 32K prompt through the 36 recurrent layers) have gone through it (the events are read a call late, nothing waits on the GPU) +void gdn_prompt(const float* qkvz, const float* ab, float* hist, const float* convw, const float* dt, const float* a, const float* nw, + float* S, const int* ctl, int ng, int nk, int nv, const int* vmap, int C, float eps, float* xc, float* sq, float* y32, + float* chw, void* st) { + static const bool timed = fnx::env_int("FNX_GDN_TIME", 0) != 0; + if (!timed) { + gdn_prompt_impl(qkvz, ab, hist, convw, dt, a, nw, S, ctl, ng, nk, nv, vmap, C, eps, xc, sq, y32, chw, st); + return; + } + struct Rec { cudaEvent_t e0, e1; int rows; }; + struct Dev { std::vector pend; double ms = 0; long rows = 0, calls = 0, since = 0; }; + static thread_local Dev devs[16]; + int dev = 0; + cudaGetDevice(&dev); + Dev& d = devs[dev & 15]; + cudaStream_t s = (cudaStream_t) st; + Rec r{nullptr, nullptr, C}; + cudaEventCreate(&r.e0), cudaEventCreate(&r.e1); + cudaEventRecord(r.e0, s); + gdn_prompt_impl(qkvz, ab, hist, convw, dt, a, nw, S, ctl, ng, nk, nv, vmap, C, eps, xc, sq, y32, chw, st); + cudaEventRecord(r.e1, s); + d.pend.push_back(r); + while (!d.pend.empty() && cudaEventQuery(d.pend.front().e1) == cudaSuccess) { + Rec q = d.pend.front(); + d.pend.erase(d.pend.begin()); + float ms = 0; + cudaEventElapsedTime(&ms, q.e0, q.e1); + d.ms += ms, d.rows += q.rows, d.since += q.rows, ++d.calls; + cudaEventDestroy(q.e0), cudaEventDestroy(q.e1); + if (d.since >= 36L * 32768) { + std::fprintf(stderr, "gdn time: card %d: %.1f ms GPU over %ld calls, %ld rows (%.4f ms a row)\n", dev, d.ms, d.calls, d.rows, d.ms / (double) d.rows); + d.ms = 0, d.rows = d.calls = d.since = 0; + } + } +} + size_t gdn_prompt_work_floats(int C, int nv) { return (size_t) ((C + GCH - 1) / GCH) * nv * GCH_PREP_FLOATS; } } // namespace fnx #endif diff --git a/src/split/tools/gdn_tc_test.cu b/src/split/tools/gdn_tc_test.cu new file mode 100644 index 0000000000..27968a0d40 --- /dev/null +++ b/src/split/tools/gdn_tc_test.cu @@ -0,0 +1,122 @@ +// FNX_PFX_GDN_TC=1 against the kernels it replaces, on one card (not a ctest: needs a GPU, no model). +// bin/split_gdn_tc_test [nk nv [C ...]] default nk 8, nv 24 (one card of two), C = 33 1000 2048 8192 32768 +// The prompt GDN's recurrence for one card's slice, random inputs of the model's shapes (q, k unit rows, gates from ab / dt_bias / A as +// k_gdn_ch_prep makes them): the existing sub-chunk path (k_gdn_ch_prep + k_gdn_ch_rec, fp32 on the CUDA cores) and Strata's tensor-core scan +// (gdn_tc_run, f16 hi / lo split products) from the same state, compared on the outputs and the end state, and timed (the two launches each). +// Compiles kernels.cu's part 4 as one translation unit with its own main, so the kernels in the anonymous namespace are reachable. +#define FNX_KPART 4 +#include "../src/kernels.cu" + +#include +#include + +namespace fnx { std::vector& q8_twins() { static std::vector v; return v; } } // part 0 has it; nothing here registers a twin + +namespace { +using namespace fnx; + +struct Rng { + std::mt19937_64 g{12345}; + float uni() { return (float) std::uniform_real_distribution(0.0, 1.0)(g); } + float nrm() { return (float) std::normal_distribution(0.0, 1.0)(g); } +}; + +#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { std::fprintf(stderr, "%s:%d %s: %s\n", __FILE__, __LINE__, #x, cudaGetErrorString(e_)); std::exit(2); } } while (0) + +double rel_diff(const std::vector& r, const std::vector& x, double& maxval) { + double md = 0, mv = 0; + for (size_t i = 0; i < r.size(); ++i) { + md = std::max(md, (double) std::fabs(r[i] - x[i])); + mv = std::max(mv, (double) std::fabs(r[i])); + } + maxval = mv; + return md / std::max(mv, 1e-30); +} +} // namespace + +int main(int argc, char** argv) { + int nk = 8, nv = 24; + std::vector cases = {33, 1000, 2048, 8192, 32768}; + if (argc >= 3) { nk = std::atoi(argv[1]); nv = std::atoi(argv[2]); } + if (argc > 3) { cases.clear(); for (int i = 3; i < argc; ++i) cases.push_back(std::atoi(argv[i])); } + const int vpk = nv / nk; + const int ch = (2 * nk + nv) * HS; + int dev = 0; + CK(cudaGetDevice(&dev)); + cudaDeviceProp pr{}; + CK(cudaGetDeviceProperties(&pr, dev)); + std::printf("card %s (sm_%d%d, %d SMs), a slice of %d key heads and %d value heads\n", pr.name, pr.major, pr.minor, pr.multiProcessorCount, nk, nv); + CK(cudaFuncSetAttribute(k_gdn_ch_rec, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) GCH_REC_SMEM)); + cudaStream_t s; + CK(cudaStreamCreate(&s)); + std::vector vmap(nv); + for (int lv = 0; lv < nv; ++lv) vmap[lv] = (lv / vpk) | (lv % vpk == 0 ? 1 << 8 : 0); + int* d_vmap; + CK(cudaMalloc(&d_vmap, nv * 4)); + CK(cudaMemcpy(d_vmap, vmap.data(), nv * 4, cudaMemcpyHostToDevice)); + int fails = 0; + for (int variant = 0; variant < 2; ++variant) { // 0: random state, 1: zero state (a fresh prompt) + for (int C : cases) { + Rng rng; + std::vector xc((size_t) C * ch), ab((size_t) C * 2 * nv), dt(nv), a(nv), S0((size_t) nv * HS * HS); + for (int t = 0; t < C; ++t) { + float* row = xc.data() + (size_t) t * ch; + for (int h = 0; h < 2 * nk; ++h) { // q, k: unit rows per head + double ss = 0; + for (int i = 0; i < HS; ++i) { row[h * HS + i] = rng.nrm(); ss += (double) row[h * HS + i] * row[h * HS + i]; } + const float inv = (float) (1.0 / std::sqrt(ss + 1e-6)); + for (int i = 0; i < HS; ++i) row[h * HS + i] *= inv; + } + for (int i = 0; i < nv * HS; ++i) row[2 * nk * HS + i] = 0.5f * rng.nrm(); + for (int i = 0; i < 2 * nv; ++i) ab[(size_t) t * 2 * nv + i] = rng.nrm(); + } + for (int i = 0; i < nv; ++i) { dt[i] = 0.5f * rng.nrm(); a[i] = -std::exp(-3.5f + 5.5f * rng.uni()); } + for (auto& x : S0) x = variant ? 0.0f : 0.05f * rng.nrm(); + float *d_xc, *d_ab, *d_dt, *d_a, *d_S, *d_y0, *d_y1, *d_chw, *d_S0; + const size_t ny = (size_t) C * nv * HS, ns = (size_t) nv * HS * HS; + const size_t chw_n = (size_t) ((C + GCH - 1) / GCH) * nv * GCH_PREP_FLOATS; + CK(cudaMalloc(&d_xc, xc.size() * 4)); CK(cudaMalloc(&d_ab, ab.size() * 4)); CK(cudaMalloc(&d_dt, nv * 4)); CK(cudaMalloc(&d_a, nv * 4)); + CK(cudaMalloc(&d_S, ns * 4)); CK(cudaMalloc(&d_S0, ns * 4)); CK(cudaMalloc(&d_y0, ny * 4)); CK(cudaMalloc(&d_y1, ny * 4)); CK(cudaMalloc(&d_chw, chw_n * 4)); + CK(cudaMemcpy(d_xc, xc.data(), xc.size() * 4, cudaMemcpyHostToDevice)); CK(cudaMemcpy(d_ab, ab.data(), ab.size() * 4, cudaMemcpyHostToDevice)); + CK(cudaMemcpy(d_dt, dt.data(), nv * 4, cudaMemcpyHostToDevice)); CK(cudaMemcpy(d_a, a.data(), nv * 4, cudaMemcpyHostToDevice)); + CK(cudaMemcpy(d_S0, S0.data(), ns * 4, cudaMemcpyHostToDevice)); + auto run_old = [&] { + k_gdn_ch_prep<<>>(d_xc, d_ab, d_dt, d_a, d_vmap, nk, nv, C, d_chw); + k_gdn_ch_rec<<>>(d_xc, d_chw, d_S, d_y0, nk, nv, d_vmap, C); + }; + auto run_new = [&]() -> bool { return gdn_tc_run(d_xc, d_ab, d_dt, d_a, d_S, d_y1, nk, nv, d_vmap, C, s); }; + CK(cudaMemcpy(d_S, d_S0, ns * 4, cudaMemcpyDeviceToDevice)); + run_old(); + CK(cudaStreamSynchronize(s)); + std::vector y0(ny), s_old(ns), y1(ny), s_new(ns); + CK(cudaMemcpy(y0.data(), d_y0, ny * 4, cudaMemcpyDeviceToHost)); CK(cudaMemcpy(s_old.data(), d_S, ns * 4, cudaMemcpyDeviceToHost)); + CK(cudaMemcpy(d_S, d_S0, ns * 4, cudaMemcpyDeviceToDevice)); + CK(cudaMemset(d_y1, 0, ny * 4)); + if (!run_new()) { std::printf("C %6d: gdn_tc_run declined (no scratch or too small a card)\n", C); ++fails; continue; } + CK(cudaStreamSynchronize(s)); + CK(cudaGetLastError()); + CK(cudaMemcpy(y1.data(), d_y1, ny * 4, cudaMemcpyDeviceToHost)); CK(cudaMemcpy(s_new.data(), d_S, ns * 4, cudaMemcpyDeviceToHost)); + double my, ms_; + const double dy = rel_diff(y0, y1, my), ds = rel_diff(s_old, s_new, ms_); + // timing: the two launches each, back to back, 5 runs after the checked one (the state is overwritten each run: the cost does not depend on it) + cudaEvent_t e0, e1; + CK(cudaEventCreate(&e0)); CK(cudaEventCreate(&e1)); + float t_old = 0, t_new = 0; + const int reps = C >= 8192 ? 3 : 10; + CK(cudaEventRecord(e0, s)); + for (int r = 0; r < reps; ++r) run_old(); + CK(cudaEventRecord(e1, s)); CK(cudaEventSynchronize(e1)); CK(cudaEventElapsedTime(&t_old, e0, e1)); + CK(cudaEventRecord(e0, s)); + for (int r = 0; r < reps; ++r) run_new(); + CK(cudaEventRecord(e1, s)); CK(cudaEventSynchronize(e1)); CK(cudaEventElapsedTime(&t_new, e0, e1)); + const bool ok = dy < 2e-3 && ds < 2e-3 && std::isfinite(dy) && std::isfinite(ds); + fails += !ok; + std::printf("%s C %6d: y diff %.2e (max |y| %.3g), end state diff %.2e (max |S| %.3g) | old %.3f ms, tensor-core %.3f ms (%.2fx) %s\n", + variant ? "zero state " : "random state", C, dy, my, ds, ms_, t_old / reps, t_new / reps, t_old / std::max(t_new, 1e-9f), ok ? "ok" : "FAIL"); + cudaEventDestroy(e0); cudaEventDestroy(e1); + cudaFree(d_xc); cudaFree(d_ab); cudaFree(d_dt); cudaFree(d_a); cudaFree(d_S); cudaFree(d_S0); cudaFree(d_y0); cudaFree(d_y1); cudaFree(d_chw); + } + } + std::printf("%d failures\n", fails); + return fails ? 1 : 0; +}