From d8c94b45c873c32d78892a7a8c361567bba5f798 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 02:11:45 +0100 Subject: [PATCH 01/11] [Engine] CUDA prompt path: opt-in FP16 cache of dequantized dense weights (STRATA_PF_W16_CACHE_MIB) --- include/strata/prefill/gemm.hpp | 8 ++++++++ src/prefill/gemm.cu | 31 +++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/include/strata/prefill/gemm.hpp b/include/strata/prefill/gemm.hpp index 80f625ee..cf43f79d 100644 --- a/include/strata/prefill/gemm.hpp +++ b/include/strata/prefill/gemm.hpp @@ -9,6 +9,7 @@ #include #include #include +#include namespace strata::prefill { @@ -92,6 +93,13 @@ private: void* side_ready_[2] = {}; void* side_free_[2] = {}; int side_cur_ = 0; + // STRATA_PF_W16_CACHE_MIB=N (CUDA, opt-in): native() keeps the FP16 dequantization of up to N MiB of weights, so a + // repeat product skips the dequant kernel; the FP16 values and the product are the uncached form's, bit for bit. + // A weight is keyed by its device pointer and shape (the engine's dense weights never move). + struct W16Entry { const void* p; int type; int64_t n, k; uint16_t* d; }; + std::vector w16_; + int64_t w16_budget_ = -1; // bytes; -1: env not read yet, 0: off + int64_t w16_used_ = 0; void* hipblaslt_state_ = nullptr; void* rocblas_state_ = nullptr; // HIP: the rocBLAS solution table of f16_inplace (STRATA_ROCBLAS_TUNING) bool f16_io_ = false; diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu index 6d7816c9..6ee6b0c3 100644 --- a/src/prefill/gemm.cu +++ b/src/prefill/gemm.cu @@ -637,6 +637,7 @@ bool gemm_dequant_side() { } Gemm::~Gemm() { + for (W16Entry& e : w16_) if (e.d) (void) cudaFree(e.d); for (void* e : side_ready_) if (e) (void) cudaEventDestroy((cudaEvent_t) e); for (void* e : side_free_) @@ -1391,6 +1392,36 @@ void Gemm::native(const uint16_t* X, int ggml_type, const void* W_blocks, float* } #if defined(STRATA_PREFILL_MMQ) && defined(__HIPCC__) if (beta == 0.0f && (ldx == 0 || ldx == K) && native_mmq(X, ggml_type, W_blocks, Y, T, N, K, ldy)) return; +#endif +#ifndef STRATA_USE_HIP + // STRATA_PF_W16_CACHE_MIB=N: the FP16 weight kept on the device after its first dequant (same values, same product) + if (w16_budget_ < 0) { + const char* v = std::getenv("STRATA_PF_W16_CACHE_MIB"); + w16_budget_ = v ? (int64_t) std::atoll(v) * (1ll << 20) : 0; + } + if (w16_budget_ > 0 && !side_scratch_) { + const int64_t bytes = N * K * 2; + uint16_t* cw = nullptr; + for (const W16Entry& e : w16_) + if (e.p == W_blocks && e.type == ggml_type && e.n == N && e.k == K) { cw = e.d; break; } + if (cw == nullptr && w16_used_ + bytes <= w16_budget_) { + size_t fb = 0, tb = 0; + if (cudaMemGetInfo(&fb, &tb) == cudaSuccess && fb > (size_t) bytes + (2ull << 30) && + cudaMalloc((void**) &cw, (size_t) bytes) == cudaSuccess) { + strata::kernels::dequant_f16(ggml_type, W_blocks, 0, N, K, cw, stream_); + w16_.push_back({W_blocks, ggml_type, N, K, cw}); + w16_used_ += bytes; + } else { + (void) cudaGetLastError(); + cw = nullptr; + w16_budget_ = w16_used_ > 0 ? w16_used_ : 0; // out of room: stop trying + } + } + if (cw != nullptr) { + f16(X, cw, Y, T, N, K, ldy, beta); + return; + } + } #endif if (N * K > scratch_elems_) { // Too large for the scratch at once: in row slices. From 2072510a479662a615336178bb430c6a67ef6009 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 03:10:51 +0100 Subject: [PATCH 02/11] [Engine] --batch on one GPU: opt-in concurrent prompt read beside the decoding slots (STRATA_BATCH_CONCURRENT_READ) --- src/program/generate.cpp | 66 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 956d2c56..6102542c 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -15070,6 +15070,70 @@ int main(int argc, char** argv) { } return run_ok; }; + // STRATA_BATCH_CONCURRENT_READ=1 (opt-in, one GPU, --batch with --no-prefill-borrow): the prompt is read on a + // thread of its own while this thread keeps the slots' batch windows going, so the decoding slots do not + // stop for an admission. The prompt writes the main session, the windows the slots' sessions; the prompt + // borrows no cache slots (--no-prefill-borrow), so the windows' experts stay where they are. The same + // bytes are computed as in the serial form (a window's rows do not depend on what else is on the GPU). + static const bool conc1 = [] { + const char* v = std::getenv("STRATA_BATCH_CONCURRENT_READ"); + return v != nullptr && std::atoi(v) != 0; + }(); + auto run_conc = [&](int64_t q, int64_t r) -> bool { + if (!conc1 || piped || !stages.empty() || o.batch <= 0 || !o.no_prefill_borrow || !batch_on() || + !req_imgs.empty() || kvg.on) + return run(q, r); + std::atomic done{false}; + bool read_ok = false; + in_prompt_read = true; + std::thread reader([&] { + try { // (an exception leaving a std::thread ends the process: a failed read instead) + read_ok = run(q, r); + } catch (const std::exception& x) { + read_ok = false; + e = std::string("the prompt read failed: ") + x.what(); + } catch (...) { + read_ok = false; + e = "the prompt read failed"; + } + done.store(true, std::memory_order_release); + { std::lock_guard lk(in_mu); } + in_cv.notify_all(); + }); + bool step_ok = true; + int64_t windows0 = bt_windows; + const auto tc = Clock::now(); + while (!done.load(std::memory_order_acquire)) { + if (step_ok && batch_on()) { + step_ok = batch_step(); + } else { + std::unique_lock lk(in_mu); + in_cv.wait_for(lk, std::chrono::milliseconds(2), + [&] { return done.load(std::memory_order_acquire); }); + } + std::lock_guard lk(in_mu); // a BSTOP that came meanwhile ends its slot at its next window + for (auto it = in_lines.begin(); it != in_lines.end();) { + if (it->rfind("BSTOP ", 0) == 0) { + const int b = std::atoi(it->c_str() + 6); + if (b >= 0 && b < (int) bs.size()) bs[(size_t) b].stop = true; + it = in_lines.erase(it); + } else { + ++it; + } + } + } + reader.join(); + in_prompt_read = false; + std::fprintf(stderr, "strata batch: read %lld tokens on a thread of its own in %.0f ms; the slots ran %lld windows meanwhile\n", + (long long) (r - q), std::chrono::duration(Clock::now() - tc).count(), + (long long) (bt_windows - windows0)); + if (!step_ok) { + batch_fatal = true; + e = "a batch window failed"; + return false; + } + return read_ok; + }; // (a layer split reads its stages as a pipeline over one run's chunks: beside slots a chunk at a time, with // none decoding in pieces of STRATA_BATCH_YIELD_CHUNKS chunks (default 8; 0 = one run) so a BYIELD is taken) static const int64_t yield_chunks = [] { @@ -15450,7 +15514,7 @@ int main(int argc, char** argv) { for (int64_t q = a0; q < b0;) { const int64_t r = std::min(b0, q + piece); const auto tq = Clock::now(); - if (!run(q, r)) return false; + if (!run_conc(q, r)) return false; const double piece_ms = std::chrono::duration(Clock::now() - tq).count(); if (pr_on && r < b0) pr_prev_piece_ms = piece_ms; const int64_t piece_tokens = r - q; From 21f950b4b477a0006ddbae71faa6073a8e4000a9 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 03:56:23 +0100 Subject: [PATCH 03/11] [Engine] CUDA hyper-connection read (v3): exact 5..8-token down kernels with two rows per warp (same dots, same bits; decode c=8 +5%) --- src/kernels/cuda/fused_gr.cu | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index 24b00143..d35a15c8 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -709,10 +709,10 @@ __global__ void __launch_bounds__(Q32_THREADS) gr_up_q32_kernel(GrMulti m) { constexpr int PR = LR + HC; // partial rows per (token, stream): 320 down + 4 inject constexpr int TQ3 = N / 8 / 32; // uint4 weight chunks per lane in one stream's slice (10) -template +template __global__ void __launch_bounds__(THREADS) gr_down_v3_kernel(GrMulti m, float* __restrict__ part, float* __restrict__ ssg) { extern __shared__ __align__(16) float xs[]; // [T][N / S] - constexpr int R2 = 1; // down rows per warp + constexpr int R2 = R2V; // down rows per warp (R2V > 1: fewer blocks, each stages its stream slice once for R2V x the rows; the same dots) __shared__ float red[WARPS][MAX_T]; const int t = threadIdx.x, lane = t & 31, warp = t >> 5; const int T = EXACT_T ? MAX_T : m.T; @@ -1331,6 +1331,12 @@ int down_tg(int ct) { return per_dev[dev] == 2 && (ct == 4 || ct == 6) ? 2 : 0; #endif } +// STRATA_GR_R2 (v3 read, 5..8-token launches; default 2): 0 = the generic kernels as before, 1 / 2 / 4 = the exact-T kernels with that many down +// rows per warp (the same dots in the same order, so the same bits; fewer blocks stage the same activations less often) +static int gr_r2() { + static const int v = [] { const char* e = std::getenv("STRATA_GR_R2"); return e != nullptr ? std::atoi(e) : 2; }(); + return v == 1 || v == 2 || v == 4 ? v : 0; +} void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long long* stamp_buf, int stamp_i0) { const int n_tok = m.T; const bool q8w = m.a[0].s_down != nullptr; // STRATA_HC_REQ8: w_down / w_up hold int8 codes @@ -2385,6 +2391,17 @@ static bool fused_gr_read_multi_slice(const FusedGrArgs* a, int n_tok, float* xn cudaFuncSetAttribute(gr_down_v3_kernel<1, kFusedGrMaxT, false>, cudaFuncAttributeMaxDynamicSharedMemorySize, need1) == cudaSuccess && cudaFuncSetAttribute(gr_down_v3_kernel<1, 6, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, need6) == cudaSuccess && cudaFuncSetAttribute(gr_down_v3_kernel<1, 5, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, need5) == cudaSuccess) { + if (kFusedGrMaxT >= 8) { // the exact 7- and 8-token instantiations (STRATA_GR_R2: rows per warp 1 / 2 / 4) + const int need7 = (int) (7 * N * sizeof(float)), need8 = (int) (8 * N * sizeof(float)); + cudaFuncSetAttribute(gr_down_v3_kernel<1, 5, true, 2>, cudaFuncAttributeMaxDynamicSharedMemorySize, need5); + cudaFuncSetAttribute(gr_down_v3_kernel<1, 6, true, 2>, cudaFuncAttributeMaxDynamicSharedMemorySize, need6); + cudaFuncSetAttribute(gr_down_v3_kernel<1, 7, true, 1>, cudaFuncAttributeMaxDynamicSharedMemorySize, need7); + cudaFuncSetAttribute(gr_down_v3_kernel<1, 7, true, 2>, cudaFuncAttributeMaxDynamicSharedMemorySize, need7); + cudaFuncSetAttribute(gr_down_v3_kernel<1, 7, true, 4>, cudaFuncAttributeMaxDynamicSharedMemorySize, need7); + cudaFuncSetAttribute(gr_down_v3_kernel<1, 8, true, 1>, cudaFuncAttributeMaxDynamicSharedMemorySize, need8); + cudaFuncSetAttribute(gr_down_v3_kernel<1, 8, true, 2>, cudaFuncAttributeMaxDynamicSharedMemorySize, need8); + cudaFuncSetAttribute(gr_down_v3_kernel<1, 8, true, 4>, cudaFuncAttributeMaxDynamicSharedMemorySize, need8); + } cudaFuncSetAttribute(gr_down_v3_kernel<1, 1, true>, cudaFuncAttributePreferredSharedMemoryCarveout, 100); cudaFuncSetAttribute(gr_down_v3_kernel<1, 2, true>, cudaFuncAttributePreferredSharedMemoryCarveout, 100); cudaFuncSetAttribute(gr_down_v3_kernel<1, 3, true>, cudaFuncAttributePreferredSharedMemoryCarveout, 100); @@ -2414,8 +2431,16 @@ static bool fused_gr_read_multi_slice(const FusedGrArgs* a, int n_tok, float* xn else if (n_tok == 2) gr_down_v3_kernel<1, 2, true><<>>(m, part, ssg); else if (n_tok == 3) gr_down_v3_kernel<1, 3, true><<>>(m, part, ssg); else if (n_tok == 4) gr_down_v3_kernel<1, 4, true><<>>(m, part, ssg); + else if (n_tok == 5 && gr_r2() == 2) gr_down_v3_kernel<1, 5, true, 2><<>>(m, part, ssg); else if (n_tok == 5) gr_down_v3_kernel<1, 5, true><<>>(m, part, ssg); + else if (n_tok == 6 && gr_r2() == 2) gr_down_v3_kernel<1, 6, true, 2><<>>(m, part, ssg); else if (n_tok == 6) gr_down_v3_kernel<1, 6, true><<>>(m, part, ssg); + else if (n_tok == 7 && kFusedGrMaxT >= 7 && gr_r2() == 2) gr_down_v3_kernel<1, 7, true, 2><<>>(m, part, ssg); + else if (n_tok == 7 && kFusedGrMaxT >= 7 && gr_r2() == 4) gr_down_v3_kernel<1, 7, true, 4><<>>(m, part, ssg); + else if (n_tok == 7 && kFusedGrMaxT >= 7 && gr_r2() == 1) gr_down_v3_kernel<1, 7, true, 1><<>>(m, part, ssg); + else if (n_tok == 8 && kFusedGrMaxT >= 8 && gr_r2() == 2) gr_down_v3_kernel<1, 8, true, 2><<>>(m, part, ssg); + else if (n_tok == 8 && kFusedGrMaxT >= 8 && gr_r2() == 4) gr_down_v3_kernel<1, 8, true, 4><<>>(m, part, ssg); + else if (n_tok == 8 && kFusedGrMaxT >= 8 && gr_r2() == 1) gr_down_v3_kernel<1, 8, true, 1><<>>(m, part, ssg); else gr_down_v3_kernel<1, kFusedGrMaxT, false><<>>(m, part, ssg); if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, stream); if (split == 2) gr_up_v3_kernel<2><<>>(m, part, ssg); @@ -2425,6 +2450,8 @@ static bool fused_gr_read_multi_slice(const FusedGrArgs* a, int n_tok, float* xn else if (n_tok == 4) gr_up_v3_kernel<1, 4, true><<>>(m, part, ssg); else if (n_tok == 5) gr_up_v3_kernel<1, 5, true><<>>(m, part, ssg); else if (n_tok == 6) gr_up_v3_kernel<1, 6, true><<>>(m, part, ssg); + else if (n_tok == 7 && kFusedGrMaxT >= 7 && gr_r2() > 0) gr_up_v3_kernel<1, 7, true><<>>(m, part, ssg); + else if (n_tok == 8 && kFusedGrMaxT >= 8 && gr_r2() > 0) gr_up_v3_kernel<1, 8, true><<>>(m, part, ssg); else gr_up_v3_kernel<1, kFusedGrMaxT, false><<>>(m, part, ssg); const cudaError_t e3 = cudaGetLastError(); if (e3 != cudaSuccess) { From 05cd12e7a27b97b37429f6b0d3dcf8b24ed53b6b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 04:19:00 +0100 Subject: [PATCH 04/11] [Engine] batch window: STRATA_BATCH_GDN_GROUPS now also works with STRATA_BATCH_SELF_COMMIT (the grouped GDN launch keeps its one-row groups itself) --- src/core/verify.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 69f9cf33..50d50883 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -1626,10 +1626,11 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { gg.state[gg.n] = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats; gg.first[gg.n] = first; gg.ntok[gg.n] = t - first; + gg.keep[gg.n] = keep_rows ? one_ : nullptr; // STRATA_BATCH_SELF_COMMIT: the window keeps its one-row groups itself ++gg.n; } strata::kernels::gdn_step_norm_groups(gg, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, - y_, (int) HK, (int) HV, false, cs); + y_, (int) HK, (int) HV, keep_rows, cs); } else if (batch_rec_) { // each slot's recurrence over its own proposed-token group for (int t = tb; t < te;) { From 42aee7a349c071d71f5384acdf9c4cd73c46d03e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 04:47:30 +0100 Subject: [PATCH 05/11] [Engine] CUDA hyper-connection read (v3), 8-token launches: the eight warp sums in one transposed butterfly (same additions, same bits; decode c=8 +2%) --- src/kernels/cuda/fused_gr.cu | 40 ++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index d35a15c8..5636a301 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -50,6 +50,28 @@ __device__ __forceinline__ float warp_sum(float v) { for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); return v; } +// warp_sum of 8 independent values at once, token t's total ending in every lane whose bits 4..2 spell t ((lane >> 2) & 7). The same +// additions as warp_sum(a[t]) in the same order (offset 16, 8, 4, 2, 1; a + b = b + a, so a lane adding its partner's value to its own gets the +// bits the plain butterfly gets): each level only exchanges the half of the values the partner keeps, 4 + 2 + 1 + 1 + 1 shuffles instead of 40. +__device__ __forceinline__ float warp_sum8(const float (&a)[8], int lane) { + const bool h4 = (lane & 16) != 0, h3 = (lane & 8) != 0, h2 = (lane & 4) != 0; + float b[4], c[2]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float send = h4 ? a[j] : a[j + 4], keep = h4 ? a[j + 4] : a[j]; + b[j] = keep + __shfl_xor_sync(0xffffffffu, send, 16); + } +#pragma unroll + for (int j = 0; j < 2; ++j) { + const float send = h3 ? b[j] : b[j + 2], keep = h3 ? b[j + 2] : b[j]; + c[j] = keep + __shfl_xor_sync(0xffffffffu, send, 8); + } + const float send = h2 ? c[0] : c[1], keep = h2 ? c[1] : c[0]; + float d = keep + __shfl_xor_sync(0xffffffffu, send, 4); + d += __shfl_xor_sync(0xffffffffu, d, 2); + d += __shfl_xor_sync(0xffffffffu, d, 1); + return d; +} __device__ __forceinline__ float sigmoidf_(float x) { return 1.0f / (1.0f + __expf(-x)); } // 8 bf16 packed in a uint4, unpacked to two float4 once when reused across tokens. @@ -778,12 +800,18 @@ __global__ void __launch_bounds__(THREADS) gr_down_v3_kernel(GrMulti m, float* _ if (EXACT_T || k < T) acc[k] += dot8u_ptr(wvq, xs + (size_t) k * SL + j * 8); } const int prow = inject_block ? LR + warp : row0 + r; + if constexpr (EXACT_T && MAX_T == 8) { // warp_sum8: token k's total sits in lanes 4k..4k+3 + const float d8 = warp_sum8(acc, lane); + const int k = (lane >> 2) & 7; + if ((lane & 3) == 0) part[(((size_t) k * HC + c) * S + h) * PR + prow] = d8; + } else { #pragma unroll for (int k = 0; k < MAX_T; ++k) { if (!EXACT_T && k >= T) break; const float v = warp_sum(acc[k]); if (lane == 0) part[(((size_t) k * HC + c) * S + h) * PR + prow] = v; } + } } } @@ -852,6 +880,17 @@ __global__ void __launch_bounds__(THREADS) gr_up_v3_kernel(GrMulti m, const floa if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; } } float mine = 0.0f; + if constexpr (EXACT_T && MAX_T == 8) { // the 8 tokens' warp sums together (warp_sum8): the same bits + float accs[8]; +#pragma unroll + for (int k = 0; k < 8; ++k) { + float acc = dot8u_ptr(wa, lo[k] + lane * 8); + if (lane < LR / 8 - 32) acc += dot8u_ptr(wb, lo[k] + (32 + lane) * 8); + accs[k] = acc; + } + const float d8 = warp_sum8(accs, lane); + mine = __shfl_sync(0xffffffffu, d8, (lane & 7) << 2); + } else { #pragma unroll for (int k = 0; k < MAX_T; ++k) { if (!EXACT_T && k >= T) break; @@ -860,6 +899,7 @@ __global__ void __launch_bounds__(THREADS) gr_up_v3_kernel(GrMulti m, const floa acc = warp_sum(acc); if (lane == k) mine = acc; } + } if (lane < T) { if (apply) { rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv); From 1f05fdc283e6d6f5420d4def35094debb9ea7aa8 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 04:52:35 +0100 Subject: [PATCH 06/11] [Engine] CUDA hyper-connection read (v3): the transposed warp sums also for 5..7-token launches --- src/kernels/cuda/fused_gr.cu | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index 5636a301..9e504694 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -800,10 +800,13 @@ __global__ void __launch_bounds__(THREADS) gr_down_v3_kernel(GrMulti m, float* _ if (EXACT_T || k < T) acc[k] += dot8u_ptr(wvq, xs + (size_t) k * SL + j * 8); } const int prow = inject_block ? LR + warp : row0 + r; - if constexpr (EXACT_T && MAX_T == 8) { // warp_sum8: token k's total sits in lanes 4k..4k+3 - const float d8 = warp_sum8(acc, lane); + if constexpr (EXACT_T && MAX_T >= 5 && MAX_T <= 8) { // warp_sum8: token k's total sits in lanes 4k..4k+3 + float accs[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; +#pragma unroll + for (int k = 0; k < MAX_T; ++k) accs[k] = acc[k]; + const float d8 = warp_sum8(accs, lane); const int k = (lane >> 2) & 7; - if ((lane & 3) == 0) part[(((size_t) k * HC + c) * S + h) * PR + prow] = d8; + if ((lane & 3) == 0 && k < MAX_T) part[(((size_t) k * HC + c) * S + h) * PR + prow] = d8; } else { #pragma unroll for (int k = 0; k < MAX_T; ++k) { @@ -880,10 +883,10 @@ __global__ void __launch_bounds__(THREADS) gr_up_v3_kernel(GrMulti m, const floa if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; } } float mine = 0.0f; - if constexpr (EXACT_T && MAX_T == 8) { // the 8 tokens' warp sums together (warp_sum8): the same bits - float accs[8]; + if constexpr (EXACT_T && MAX_T >= 5 && MAX_T <= 8) { // the tokens' warp sums together (warp_sum8, missing tokens 0): the same bits + float accs[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; #pragma unroll - for (int k = 0; k < 8; ++k) { + for (int k = 0; k < MAX_T; ++k) { float acc = dot8u_ptr(wa, lo[k] + lane * 8); if (lane < LR / 8 - 32) acc += dot8u_ptr(wb, lo[k] + (32 + lane) * 8); accs[k] = acc; From dc149ef0031ac41cca183a2f1c18f71c6b980d37 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 01:12:19 +0100 Subject: [PATCH 07/11] GDN: production-linked parity/bench harness, dispatch probe, FP64 fixtures, contract doc; opt-in STRATA_GDN_TC on 99-KB cards (split v/T/P buffering) --- CMakeLists.txt | 14 + docs/GDN_CONTRACT.md | 88 +++++ include/strata/prefill/gdn_probe.hpp | 56 ++++ src/prefill/gdn_harness.cu | 470 +++++++++++++++++++++++++++ src/prefill/gdn_tc.cuh | 75 +++-- src/prefill/kernels.cu | 129 +++++++- tests/gdn/gdn_fixture.hpp | 245 ++++++++++++++ 7 files changed, 1030 insertions(+), 47 deletions(-) create mode 100644 docs/GDN_CONTRACT.md create mode 100644 include/strata/prefill/gdn_probe.hpp create mode 100644 src/prefill/gdn_harness.cu create mode 100644 tests/gdn/gdn_fixture.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index ee7e9f1b..54de4c88 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1278,6 +1278,20 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) # "not on this card" for the tc variant add_test(NAME gdn_rec_parity_selftest_frag COMMAND gdn_rec_parity --selftest-frag) set_tests_properties(gdn_rec_parity_selftest_frag PROPERTIES SKIP_RETURN_CODE 77) + # the production-linked GDN parity / benchmark harness (no kernel copies: it calls gdn_gates, gdn_conv and + # gdn_recurrence of strata_prefill through the GdnProbe of include/strata/prefill/gdn_probe.hpp, against an FP64 + # oracle from tests/gdn/gdn_fixture.hpp). Usage: docs/GDN_CONTRACT.md. The smoke test is small and CPU-cheap. + execute_process(COMMAND git -C ${CMAKE_CURRENT_SOURCE_DIR} rev-parse --short=9 HEAD OUTPUT_VARIABLE _gdn_sha + OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) + if(NOT _gdn_sha) + set(_gdn_sha unknown) + endif() + add_executable(gdn_harness src/prefill/gdn_harness.cu) + target_include_directories(gdn_harness PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/tests/gdn) + target_compile_definitions(gdn_harness PRIVATE GDN_HARNESS_SHA="${_gdn_sha}") + target_link_libraries(gdn_harness PRIVATE strata_prefill) + add_test(NAME gdn_harness_smoke COMMAND gdn_harness --T 400 --chunk 160 --cuts 37 --paths auto,keyhead,pipe --ref-heads 0,17) + set_tests_properties(gdn_harness_smoke PROPERTIES TIMEOUT 300) # the prompt path's BF16 products against cuBLAS's own BF16 GEMM, within fp32 rounding (sm_7x runs them on the # FP16 tensor cores; GPU, synthetic, no model; --bench adds timings) add_executable(gemm_bf16_parity src/prefill/gemm_bf16_parity.cu) diff --git a/docs/GDN_CONTRACT.md b/docs/GDN_CONTRACT.md new file mode 100644 index 00000000..3e1ea2b0 --- /dev/null +++ b/docs/GDN_CONTRACT.md @@ -0,0 +1,88 @@ +# GDN prompt-path contract (Flash-Next, CUDA reference) + +Audited on main `870aedd9e` (v0.2.8), `src/prefill/kernels.cu` and `src/prefill/prefill.cpp`. Everything below is read from +that source; the harness (`gdn_harness`, `tests/gdn/gdn_fixture.hpp`) checks it against an FP64 oracle that starts from the +raw inputs, so a wrong reading shows up as a failed parity case. + +## Shapes + +`S = 128` (head size), `HK = 16` key heads, `HV = 48` value heads (3 per key head, `VPK = 3`), `C = 2*HK*S + HV*S = 10240` +channels per token. Value head `vh` uses key head `qh = vh % HK` (NOT `vh / 3`; FLA groups the other way, an adapter is needed +for any comparison with FLA). One layer's prompt call has `T` tokens (the engine's prefill chunk, not the whole prompt); the +state and the convolution history carry from call to call. + +## One layer, in the order the engine runs it (`prefill.cpp`, `pt.mark` stages) + +| Stage (STRATA_PREFILL_TIMING name) | Work | In the harness | +|---|---|---| +| `gdn` (kPfGdn) | attn_qkv, attn_gate (z), ssm_alpha, ssm_beta projections (quantized GEMMs) | no (not a GDN kernel) | +| `gdn conv+gates` (kPfGdnConv) | `gdn_gates`, `gdn_conv` | yes, timed separately | +| `gdn recurrence` (kPfGdnRec) | `gdn_recurrence`: scan + output norm | yes | +| `gdn out proj` (kPfGdnOut) | ssm_out projection from `y16` (quantized GEMM) | no | + +Note the stage names: the profile line `gdn` is the INPUT projections, `gdn out proj` is the output projection. The task's +"GDN stage = kPfGdn + Conv + Rec + Out" therefore contains two dense GEMM stages the recurrence work cannot speed up. + +## Tensors (all FP32 unless noted, row-major, `t` = token in the call) + +| Tensor | Layout | Meaning | +|---|---|---| +| `qkv` | `[T][C]` | projection output, channels `q (HK*S) | k (HK*S) | v (HV*S)` | +| `ab` | `[T][2*HV]` | alpha at `[t][h]`, beta input at `[t][HV+h]` | +| `dt`, `ssm_a` | `[HV]` | per-head bias and (negative) decay base | +| `conv_w` | `[C][4]` | depthwise causal 4-tap filter, tap 3 is the current token | +| `history` | `[C][3]` | the three previous raw `qkv` inputs of every channel (a state object of its own) | +| `state` | `[S][HV][S]` (row i, head, column) | recurrent state, in place; `history` follows it in the engine's layer state | +| `gate`, `beta` | `[T][HV]` | outputs of `gdn_gates` | +| `h` | `[T][C]` | outputs of `gdn_conv` (SiLU, then q and k L2-normalized per head) | +| `z` | `[T][HV*S]` | output gate input | +| `y` | `[T][HV*S]` FP32 | scratch the recurrence writes the raw output to | +| `y16` | FP16, row stride `ld16` | normalized output the out projection reads | + +`ld16 = HV*S = 6144`, or `6144 + 64` when STRATA_PF_PAD is on and `T >= max(pf_switch_min_t, 64)`. A kernel must write exactly +the 6144 columns and leave the pad columns untouched (the harness fills them with a sentinel and fails if they change). + +## Math (per value head, `g_t = exp(gate_t)`) + +- `gate_t = softplus(alpha_t + dt) * ssm_a` (softplus is the identity above 20); `beta_t = sigmoid(beta_input_t)` +- `h_c(t) = silu(sum_k w[c][k] * x_c(t-3+k))` with `x_c(t<0)` from `history`; q and k heads are then scaled by `1/sqrt(sum^2 + 1e-6)` +- `kv = S^T k`, `delta = (v - g*kv) * beta`, `S <- g*S + k delta^T`, `o = S^T q / sqrt(128)` (uses the UPDATED state) +- `y16 = fp16( o * rsqrt(mean(o^2) + 1e-6) * gamma[col] * sigmoid(z) )` +- after the call: `history <- last three raw inputs` (older history where `T < 3`) + +## State mutation rules + +- A call with `T <= 0` does nothing. +- The call advances `state` and `history` in place. A path that cannot run must decline BEFORE touching the state (the helper + returns an error and "nothing was launched"); once a kernel has started, there is no replay. A forced path that is not + eligible launches nothing and reports kGdnNone with the reason (`gdn_probe.hpp`); the harness never times it. +- Calls are sequential per layer state. The chunked path's scratch is one static buffer per device (single prompt stream per + device); concurrent prompt streams on one device are not supported by it. + +## Dispatch on CUDA (production, no probe) + +1. `STRATA_GDN_TC=1` and `T >= 128`: `gdn_rec_tc` (tensor-core scan; sm_80+, >= 48 SMs, ~122 KB smem per block). Not mentioned in the + 2026-10-26 research pack: it landed with PR #3779. FP16 operands, FP32 accumulation: mixed-precision tier. +2. `STRATA_GDN_CHUNKED=1` (`=2` skips the SM-count test) and `T >= 128`: `gdn_rec_chunked` (FP32, C = 32, scan grid `HK x S/16 = 128` + blocks of 384 threads, 93.7 KB smem; sm_80+). +3. else `gdn_rec_kh_kernel` when `gdn_keyhead_ok()` (sm_80+, all 64 blocks resident), otherwise `gdn_rec_cols_pipe_kernel` + (`STRATA_GDN_PIPELINE=0`: `gdn_rec_cols_kernel`). +4. `gdn_out_norm_kernel` after any of them (it is the part that writes `y16`). +`STRATA_GDN_REC_WARP` and `STRATA_GDN_CHUNK` exist only in `STRATA_EXPERIMENTAL_SM60` builds and act only on a cc 7.0 device at run +time (`gdn_chunk_available()`): they do nothing on sm_60, sm_86 or sm_120. + +## Numerical tiers (gdn-research 06) + +1. exact: output and state bitwise equal to the incumbent (`kh` and `pipe` are the same bits by construction). +2. reordered FP32 (chunked): same recurrence, other summation order. Verdict in the harness: FP64-oracle error not above + `max(floor, 3 x the incumbent's own error)` with floors 2e-3 (normalized max of the FP16 output) and 1e-4 (state); finite; the + conv history exact. +3. mixed precision (tc): same checks, plus the stress fixtures (`--stress`). +The harness prints `normalized_max = max|d| / max|ref|` and relative L2 against the oracle and against the incumbent over ALL +heads, tokens and state elements. + +## Test hook + +`include/strata/prefill/gdn_probe.hpp`: a thread-local `GdnProbe` installed by a test selects/forces a path, a smaller chunked scratch +segment (`gsb`), or the SM-count bypass, and reads back `selected`, `wanted` and the fallback `reason`. With no probe installed the +dispatch is unchanged. The engine never installs one. diff --git a/include/strata/prefill/gdn_probe.hpp b/include/strata/prefill/gdn_probe.hpp new file mode 100644 index 00000000..905bdf54 --- /dev/null +++ b/include/strata/prefill/gdn_probe.hpp @@ -0,0 +1,56 @@ +// include/strata/prefill/gdn_probe.hpp - the GDN recurrence dispatch, made observable and forceable by tests. +// +// strata::prefill::gdn_recurrence picks its kernel from environment switches that are read once per process. A +// test or benchmark that links the real strata_prefill library installs a GdnProbe on its thread to +// * read back which path ran for the last call (`selected`) and why a path that was asked for did not run +// (`reason`), instead of guessing from timings, and +// * force one path for the call (`force`): a forced path that is not eligible launches NOTHING and reports +// kGdnNone plus the reason, so a harness can never time a silent fallback as if it were the candidate. +// Without a probe (the engine) the dispatch is byte-for-byte what it was: one thread-local pointer read. +// Header only; CUDA builds fill the probe (src/prefill/kernels.cu), other backends may adopt the same struct. +#pragma once + +namespace strata::prefill { + +enum GdnPath : int { + kGdnNone = -1, // out: nothing was launched + kGdnAuto = 0, // in: the production choice (the environment switches decide) + kGdnKeyHead = 1, // gdn_rec_kh_kernel: the three value heads of a key head in one thread (sm_80+, 64 blocks resident) + kGdnPipe = 2, // gdn_rec_cols_pipe_kernel: the software-pipelined column kernel + kGdnCols = 3, // gdn_rec_cols_kernel (STRATA_GDN_PIPELINE=0) + kGdnChunked = 4, // STRATA_GDN_CHUNKED: FP32 chunked prep + scan (CUDA, C = 32) + kGdnTc = 5, // STRATA_GDN_TC=1: chunked, scan on the tensor cores (CUDA sm_80+, 125 KB of shared memory a block) + kGdnTcSplit = 6, // the same scan with v / T / P single-buffered: 98 KB, fits the 99-KB cards (sm_86, sm_89, sm_120) + kGdnPathCount = 7 +}; + +struct GdnProbe { + // in + int force = kGdnAuto; // kGdnAuto: dispatch as production does; otherwise only this path may run + bool any_sms = false; // chunked: skip the 128-SM test, as STRATA_GDN_CHUNKED=2 does + int gsb = 0; // chunked: tokens per scratch super-block (a multiple of 32, at most 2048; 0 = 2048) + // out (set by every gdn_recurrence call made on the thread that installed the probe) + int selected = kGdnNone; // the path that launched + int wanted = kGdnAuto; // the path that was asked for: `force`, or the first the environment enabled + const char* reason = ""; // when selected != wanted: why the wanted path did not run + long calls = 0; +}; + +inline thread_local GdnProbe* g_gdn_probe = nullptr; +inline void gdn_probe_install(GdnProbe* p) { g_gdn_probe = p; } +inline GdnProbe* gdn_probe_get() { return g_gdn_probe; } + +inline const char* gdn_path_name(int p) { + switch (p) { + case kGdnKeyHead: return "keyhead"; + case kGdnPipe: return "pipe"; + case kGdnCols: return "cols"; + case kGdnChunked: return "chunked"; + case kGdnTc: return "tc"; + case kGdnTcSplit: return "tcs"; + case kGdnAuto: return "auto"; + default: return "none"; + } +} + +} // namespace strata::prefill diff --git a/src/prefill/gdn_harness.cu b/src/prefill/gdn_harness.cu new file mode 100644 index 00000000..2c6bc671 --- /dev/null +++ b/src/prefill/gdn_harness.cu @@ -0,0 +1,470 @@ +// src/prefill/gdn_harness.cu - production-linked parity and benchmark harness for the prompt GDN path (CUDA). +// +// Links the real strata_prefill library and calls the real gdn_gates / gdn_conv / gdn_recurrence: there is not one +// copy of a kernel in this file. Which recurrence runs is chosen through the GdnProbe (gdn_probe.hpp): a path can be +// forced, the path that actually ran and the reason a wanted path did not run are read back after every call, and a +// forced path that is not eligible launches nothing and is reported INELIGIBLE (it is never timed as a fallback). +// Fixtures and the FP64 oracle are tests/gdn/gdn_fixture.hpp (shared with the other backends' harnesses). +// Usage and output format: Desktop\30thOctober\results\gdn\HARNESS.md and docs/GDN_CONTRACT.md. +#include "gdn_fixture.hpp" +#include "strata/prefill/gdn_probe.hpp" +#include "strata/prefill/kernels.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef GDN_HARNESS_SHA +#define GDN_HARNESS_SHA "unknown" +#endif + +using namespace gdnfx; +namespace sp = strata::prefill; + +namespace { + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(2); + } +} +template T* dalloc(size_t n) { + T* p = nullptr; + ck(cudaMalloc(&p, n * sizeof(T)), "cudaMalloc"); + return p; +} +template T* dupload(const std::vector& v) { + T* p = dalloc(v.size()); + ck(cudaMemcpy(p, v.data(), v.size() * sizeof(T), cudaMemcpyHostToDevice), "upload"); + return p; +} + +struct Args { + int64_t T = 4096; + std::vector Ts; // --T a,b,c : several lengths (one case each) + int64_t chunk = 2048; // tokens per engine call + std::vector cuts; // explicit first call sizes (unaligned splits), then `chunk` + std::vector paths; // default: auto + every forced path + int incumbent = sp::kGdnKeyHead; // the path others are compared with (falls to pipe where ineligible) + bool parity = true, bench = false, ref = true; + std::vector ref_heads = {0, 17, 34, 5, 22, 47}; + int reps = 7, warmup = 2; + bool any_sms = false; + int gsb = 0; + bool fallback_incumbent = false; // a forced path takes the incumbent for calls it cannot run (mirrors production) + int64_t ld16 = 0; + FixtureSpec fx; + std::string json; + std::string label; + bool stress = false; // run the stress fixtures (parity only) +}; + +std::vector parse_list(const char* s) { + std::vector v; + for (const char* p = s; *p;) { + char* e = nullptr; + long long x = std::strtoll(p, &e, 10); + if (e == p) break; + if (*e == 'k' || *e == 'K') { x *= 1024; ++e; } + v.push_back(x); + p = *e == ',' ? e + 1 : e; + } + return v; +} +int path_from_name(const std::string& n) { + for (int p = 0; p < sp::kGdnPathCount; ++p) + if (n == sp::gdn_path_name(p)) return p; + return -2; +} + +struct Dev { // device-resident fixture + int64_t T = 0; + float *qkv = nullptr, *ab = nullptr, *dt = nullptr, *ssm_a = nullptr, *conv_w = nullptr, *z = nullptr, *gamma = nullptr; + float* state0 = nullptr; // [S*HV*S state | C*3 history] + float *gate = nullptr, *beta = nullptr, *h = nullptr, *y = nullptr, *state = nullptr; + uint16_t* y16 = nullptr; + int64_t ld16 = 0, chunk_max = 0; + char* flush = nullptr; + size_t flush_bytes = 256u << 20; +}; +constexpr size_t kStateFloats = (size_t) S * HV * S; + +Dev upload(const Fixture& f, int64_t chunk_max, int64_t ld16) { + Dev d; + d.T = f.T; + d.chunk_max = chunk_max; + d.ld16 = ld16 > 0 ? ld16 : (int64_t) HV * S; + d.qkv = dupload(f.qkv); + d.ab = dupload(f.ab); + d.dt = dupload(f.dt); + d.ssm_a = dupload(f.ssm_a); + d.conv_w = dupload(f.conv_w); + d.z = dupload(f.z); + d.gamma = dupload(f.gamma); + std::vector st(kStateFloats + (size_t) C * 3); + std::memcpy(st.data(), f.state0.data(), kStateFloats * 4); + std::memcpy(st.data() + kStateFloats, f.hist.data(), (size_t) C * 3 * 4); + d.state0 = dupload(st); + d.state = dalloc(st.size()); + d.gate = dalloc((size_t) chunk_max * HV); + d.beta = dalloc((size_t) chunk_max * HV); + d.h = dalloc((size_t) chunk_max * C); + d.y = dalloc((size_t) chunk_max * HV * S); + d.y16 = dalloc((size_t) f.T * d.ld16 + 64); + ck(cudaMemset(d.y16, 0xAB, ((size_t) f.T * d.ld16 + 64) * 2), "memset y16 sentinel"); + d.flush = dalloc(d.flush_bytes); + return d; +} +void release(Dev& d) { + for (void* p : {(void*) d.qkv, (void*) d.ab, (void*) d.dt, (void*) d.ssm_a, (void*) d.conv_w, (void*) d.z, (void*) d.gamma, + (void*) d.state0, (void*) d.state, (void*) d.gate, (void*) d.beta, (void*) d.h, (void*) d.y, + (void*) d.y16, (void*) d.flush}) + cudaFree(p); + d = Dev(); +} + +std::vector plan_calls(int64_t T, const Args& a) { + std::vector v; + int64_t left = T; + for (int64_t c : a.cuts) { + if (left <= 0) break; + v.push_back(std::min(c, left)); + left -= v.back(); + } + while (left > 0) { v.push_back(std::min(a.chunk, left)); left -= v.back(); } + return v; +} + +struct RunOut { + int path = 0; + bool eligible = true; + std::string reason; + std::set logged; // distinct "wanted->selected [reason]" over the calls + int fallback_calls = 0; + double ms_gates = 0, ms_conv = 0, ms_rec = 0; + std::vector y16; // dense [T][HV*S] + std::vector state; +}; + +// Runs the layer pipeline for every call of the plan. timed: events around each stage. +RunOut run_path(Dev& d, const Args& a, const std::vector& calls, int path, bool timed, bool download) { + RunOut r; + r.path = path; + ck(cudaMemcpy(d.state, d.state0, (kStateFloats + (size_t) C * 3) * 4, cudaMemcpyDeviceToDevice), "reset state"); + float* conv_hist = d.state + kStateFloats; + sp::GdnProbe probe; + probe.any_sms = a.any_sms; + probe.gsb = a.gsb; + sp::gdn_probe_install(&probe); + std::vector ev; + if (timed) { + ev.resize(calls.size() * 4); + for (auto& e : ev) ck(cudaEventCreate(&e), "event"); + } + int64_t t0 = 0; + size_t ci = 0; + for (int64_t T : calls) { + if (timed) ck(cudaEventRecord(ev[ci * 4]), "ev"); + sp::gdn_gates(d.ab + t0 * 2 * HV, d.dt, d.ssm_a, d.gate, d.beta, T, nullptr); + if (timed) ck(cudaEventRecord(ev[ci * 4 + 1]), "ev"); + sp::gdn_conv(conv_hist, d.qkv + t0 * C, d.conv_w, d.h, T, EPS, nullptr); + if (timed) ck(cudaEventRecord(ev[ci * 4 + 2]), "ev"); + probe.force = path; + sp::gdn_recurrence(d.state, d.h, d.gate, d.beta, d.z + t0 * HV * S, d.gamma, EPS, d.y, d.y16 + t0 * d.ld16, T, nullptr, d.ld16); + if (probe.selected == sp::kGdnNone && a.fallback_incumbent && path != a.incumbent) { + probe.force = a.incumbent; + sp::gdn_recurrence(d.state, d.h, d.gate, d.beta, d.z + t0 * HV * S, d.gamma, EPS, d.y, d.y16 + t0 * d.ld16, T, nullptr, d.ld16); + if (probe.selected == sp::kGdnNone) probe.force = sp::kGdnPipe, sp::gdn_recurrence(d.state, d.h, d.gate, d.beta, d.z + t0 * HV * S, d.gamma, EPS, d.y, d.y16 + t0 * d.ld16, T, nullptr, d.ld16); + ++r.fallback_calls; + } + if (timed) ck(cudaEventRecord(ev[ci * 4 + 3]), "ev"); + if (probe.selected == sp::kGdnNone) { + r.eligible = false; + r.reason = std::string("call of ") + std::to_string((long long) T) + " tokens: " + probe.reason; + break; + } + char b[200]; + std::snprintf(b, sizeof b, "%s->%s%s%s", sp::gdn_path_name(probe.wanted), sp::gdn_path_name(probe.selected), + probe.reason[0] ? " [" : "", probe.reason[0] ? probe.reason : ""); + std::string s = b; + if (probe.reason[0]) s += "]"; + r.logged.insert(s); + t0 += T; + ++ci; + } + ck(cudaDeviceSynchronize(), "run_path sync"); + sp::gdn_probe_install(nullptr); + if (timed && r.eligible) + for (size_t i = 0; i < ci; ++i) { + float x = 0; + cudaEventElapsedTime(&x, ev[i * 4], ev[i * 4 + 1]); r.ms_gates += x; + cudaEventElapsedTime(&x, ev[i * 4 + 1], ev[i * 4 + 2]); r.ms_conv += x; + cudaEventElapsedTime(&x, ev[i * 4 + 2], ev[i * 4 + 3]); r.ms_rec += x; + } + for (auto e : ev) cudaEventDestroy(e); + if (download && r.eligible) { + r.y16.resize((size_t) d.T * HV * S); + if (d.ld16 == (int64_t) HV * S) { + ck(cudaMemcpy(r.y16.data(), d.y16, r.y16.size() * 2, cudaMemcpyDeviceToHost), "y16 down"); + } else { + ck(cudaMemcpy2D(r.y16.data(), (size_t) HV * S * 2, d.y16, (size_t) d.ld16 * 2, (size_t) HV * S * 2, d.T, cudaMemcpyDeviceToHost), "y16 down 2d"); + // padding columns of a padded stride must be untouched (sentinel 0xABAB) + std::vector pad((size_t) d.T * d.ld16); + ck(cudaMemcpy(pad.data(), d.y16, pad.size() * 2, cudaMemcpyDeviceToHost), "pad down"); + for (int64_t t = 0; t < d.T; ++t) + for (int64_t c = HV * S; c < d.ld16; ++c) + if (pad[(size_t) t * d.ld16 + c] != 0xABAB) { r.eligible = false; r.reason = "PADDING OVERWRITTEN (stride contract broken)"; return r; } + } + r.state.resize(kStateFloats + (size_t) C * 3); + ck(cudaMemcpy(r.state.data(), d.state, r.state.size() * 4, cudaMemcpyDeviceToHost), "state down"); + } + return r; +} + +double median(std::vector v) { + std::sort(v.begin(), v.end()); + return v.empty() ? 0 : v[v.size() / 2]; +} + +struct Cmp { double y_nmax = 0, y_rl2 = 0, s_nmax = 0, s_rl2 = 0; long nonfinite = 0; }; + +Cmp vs_ref(const RunOut& r, const RefResult& ref, int64_t T) { + Cmp c; + ErrStat ey, es; + for (size_t n = 0; n < ref.heads.size(); ++n) { + const int vh = ref.heads[n]; + for (int64_t t = 0; t < T; ++t) + for (int col = 0; col < S; ++col) + ey.add(half_to_float(r.y16[(size_t) t * HV * S + (size_t) vh * S + col]), ref.y[n][(size_t) t * S + col]); + for (int i = 0; i < S; ++i) + for (int col = 0; col < S; ++col) es.add(r.state[((size_t) i * HV + vh) * S + col], ref.state[n][(size_t) i * S + col]); + } + c.y_nmax = ey.normalized_max(); c.y_rl2 = ey.rel_l2(); c.s_nmax = es.normalized_max(); c.s_rl2 = es.rel_l2(); + c.nonfinite = ey.nonfinite + es.nonfinite; + return c; +} +// candidate against the incumbent over every head, token and state element (not a subset) +Cmp vs_incumbent(const RunOut& r, const RunOut& inc, int64_t T) { + Cmp c; + ErrStat ey, es; + for (size_t i = 0; i < r.y16.size(); ++i) ey.add(half_to_float(r.y16[i]), half_to_float(inc.y16[i])); + for (size_t i = 0; i < kStateFloats; ++i) es.add(r.state[i], inc.state[i]); + c.y_nmax = ey.normalized_max(); c.y_rl2 = ey.rel_l2(); c.s_nmax = es.normalized_max(); c.s_rl2 = es.rel_l2(); + c.nonfinite = ey.nonfinite + es.nonfinite; + (void) T; + return c; +} + +std::string join(const std::set& s) { + std::string o; + for (auto& x : s) { if (!o.empty()) o += "; "; o += x; } + return o; +} + +void json_line(const Args& a, const char* kind, const char* fixture, int64_t T, const RunOut& r, const Cmp* ref, const Cmp* inc, + bool exact, double ms_med, double ms_min, const char* verdict, const cudaDeviceProp& pr) { + if (a.json.empty()) return; + FILE* f = std::fopen(a.json.c_str(), "a"); + if (!f) return; + std::fprintf(f, "{\"kind\":\"%s\",\"label\":\"%s\",\"device\":\"%s\",\"sms\":%d,\"cc\":\"%d.%d\",\"sha\":\"%s\",\"fixture\":\"%s\"," + "\"T\":%lld,\"chunk\":%lld,\"path\":\"%s\",\"eligible\":%s,\"reason\":\"%s\",\"log\":\"%s\",\"fallback_calls\":%d," + "\"ms_gates\":%.4f,\"ms_conv\":%.4f,\"ms_rec\":%.4f,\"ms_total_med\":%.4f,\"ms_total_min\":%.4f,\"exact_vs_incumbent\":%s,\"verdict\":\"%s\"", + kind, a.label.c_str(), pr.name, pr.multiProcessorCount, pr.major, pr.minor, GDN_HARNESS_SHA, fixture, (long long) T, + (long long) a.chunk, sp::gdn_path_name(r.path), r.eligible ? "true" : "false", r.reason.c_str(), join(r.logged).c_str(), + r.fallback_calls, r.ms_gates, r.ms_conv, r.ms_rec, ms_med, ms_min, exact ? "true" : "false", verdict); + if (ref) std::fprintf(f, ",\"ref_y_nmax\":%.3e,\"ref_y_rl2\":%.3e,\"ref_s_nmax\":%.3e,\"ref_s_rl2\":%.3e,\"nonfinite\":%ld", ref->y_nmax, ref->y_rl2, ref->s_nmax, ref->s_rl2, ref->nonfinite); + if (inc) std::fprintf(f, ",\"inc_y_nmax\":%.3e,\"inc_y_rl2\":%.3e,\"inc_s_nmax\":%.3e,\"inc_s_rl2\":%.3e", inc->y_nmax, inc->y_rl2, inc->s_nmax, inc->s_rl2); + std::fprintf(f, "}\n"); + std::fclose(f); +} + +// One case: a fixture of T tokens, every wanted path. Returns the number of failed verdicts. +int run_case(const Args& a, const FixtureSpec& spec, const char* fname, const cudaDeviceProp& pr) { + const int64_t T = spec.T; + const std::vector calls = plan_calls(T, a); + int64_t cmax = 0; + for (auto c : calls) cmax = std::max(cmax, c); + Fixture f = make_fixture(spec); + Dev d = upload(f, cmax, a.ld16); + std::printf("\n=== case %s T=%lld calls=%zu (first %lld, max %lld) ld16=%lld device %s (%d SMs, cc %d.%d)\n", fname, (long long) T, + calls.size(), (long long) calls[0], (long long) cmax, (long long) d.ld16, pr.name, pr.multiProcessorCount, pr.major, pr.minor); + RefResult ref; + if (a.parity && a.ref) { + auto t0 = std::chrono::steady_clock::now(); + ref = ref_run(f, a.ref_heads); + std::printf("FP64 oracle for %zu value heads: %.1f s\n", a.ref_heads.size(), + std::chrono::duration(std::chrono::steady_clock::now() - t0).count()); + } + // the incumbent first (it may itself be ineligible: then pipe, which always runs) + std::vector order = a.paths; + RunOut inc = run_path(d, a, calls, a.incumbent, false, true); + int inc_path = a.incumbent; + if (!inc.eligible) { + std::printf("incumbent %s INELIGIBLE (%s): using pipe\n", sp::gdn_path_name(a.incumbent), inc.reason.c_str()); + inc = run_path(d, a, calls, sp::kGdnPipe, false, true); + inc_path = sp::kGdnPipe; + } + std::map runs; + for (int p : order) { + RunOut r = (p == inc_path) ? inc : run_path(d, a, calls, p, false, true); + runs[p] = std::move(r); + } + int fails = 0; + std::map> total_ms; + std::map timed_last; + if (a.bench) { + for (int w = 0; w < a.warmup + a.reps; ++w) + for (int p : order) { + if (!runs[p].eligible) continue; + ck(cudaMemset(d.flush, w & 255, d.flush_bytes), "flush"); + RunOut t = run_path(d, a, calls, p, true, false); + if (w >= a.warmup) { + total_ms[p].push_back(t.ms_gates + t.ms_conv + t.ms_rec); + timed_last[p].ms_gates += t.ms_gates / a.reps; + timed_last[p].ms_conv += t.ms_conv / a.reps; + timed_last[p].ms_rec += t.ms_rec / a.reps; + } + } + } + std::printf("%-8s %-6s %-9s %9s %9s %9s %9s %-34s %s\n", "path", "elig", "bitwise", "ref_y", "ref_state", "inc_y", "inc_state", "ms gates/conv/rec (mean)", "ran"); + for (int p : order) { + RunOut& r = runs[p]; + const char* name = sp::gdn_path_name(p); + if (!r.eligible) { + std::printf("%-8s %-6s %s\n", name, "NO", r.reason.c_str()); + json_line(a, "case", fname, T, r, nullptr, nullptr, false, 0, 0, "INELIGIBLE", pr); + continue; + } + Cmp cr{}, ci{}; + const bool have_ref = a.parity && a.ref; + if (have_ref) cr = vs_ref(r, ref, T); + ci = vs_incumbent(r, inc, T); + const bool exact = r.y16 == inc.y16 && std::memcmp(r.state.data(), inc.state.data(), (kStateFloats + C * 3) * 4) == 0; + // conv history after the last call is a copy of inputs: it must match the oracle's exactly + bool hist_ok = true; + if (have_ref) hist_ok = std::memcmp(r.state.data() + kStateFloats, ref.hist.data(), (size_t) C * 3 * 4) == 0; + // verdict: finite, history exact, and not worse than max(floor, 3 x the incumbent's own error vs the oracle) + const char* verdict = "PASS"; + if (have_ref) { + const Cmp ir = vs_ref(inc, ref, T); + const double ys = std::max(2e-3, 3 * ir.y_nmax), ss = std::max(1e-4, 3 * ir.s_nmax); + if (cr.nonfinite || !hist_ok) verdict = "FAIL-nonfinite-or-history"; + else if (cr.y_nmax > ys) verdict = "FAIL-output-vs-oracle"; + else if (cr.s_nmax > ss) verdict = "FAIL-state-vs-oracle"; + else if (exact) verdict = "PASS-bitwise"; + } else if (exact) verdict = "PASS-bitwise"; + else verdict = "NO-ORACLE"; + if (!std::strncmp(verdict, "FAIL", 4)) ++fails; + double med = 0, mn = 0; + if (a.bench && !total_ms[p].empty()) { + med = median(total_ms[p]); + mn = *std::min_element(total_ms[p].begin(), total_ms[p].end()); + r.ms_gates = timed_last[p].ms_gates; r.ms_conv = timed_last[p].ms_conv; r.ms_rec = timed_last[p].ms_rec; + } + char tb[120] = ""; + if (a.bench) std::snprintf(tb, sizeof tb, "%.3f/%.3f/%.3f (tot med %.3f min %.3f)", r.ms_gates, r.ms_conv, r.ms_rec, med, mn); + std::printf("%-8s %-6s %-9s %9.2e %9.2e %9.2e %9.2e %-34s %s %s\n", name, "yes", exact ? "identical" : "differs", cr.y_nmax, cr.s_nmax, + ci.y_nmax, ci.s_nmax, tb, join(r.logged).c_str(), verdict); + if (r.fallback_calls) std::printf(" (%d call(s) ran on the incumbent: the forced path could not take them)\n", r.fallback_calls); + json_line(a, "case", fname, T, r, have_ref ? &cr : nullptr, &ci, exact, med, mn, verdict, pr); + } + release(d); + return fails; +} + +} // namespace + +int main(int argc, char** argv) { + Args a; + bool paths_given = false; + for (int i = 1; i < argc; ++i) { + std::string k = argv[i]; + auto val = [&]() -> const char* { if (i + 1 >= argc) { std::fprintf(stderr, "%s needs a value\n", k.c_str()); std::exit(2); } return argv[++i]; }; + if (k == "--T") { a.Ts = parse_list(val()); } + else if (k == "--chunk") a.chunk = parse_list(val())[0]; + else if (k == "--cuts") a.cuts = parse_list(val()); + else if (k == "--paths") { + paths_given = true; + std::string s = val(); + for (size_t p = 0; p <= s.size();) { + size_t e = s.find(',', p); + if (e == std::string::npos) e = s.size(); + const int id = path_from_name(s.substr(p, e - p)); + if (id < 0) { std::fprintf(stderr, "unknown path %s (auto,keyhead,pipe,cols,chunked,tc,tcs)\n", s.substr(p, e - p).c_str()); return 2; } + a.paths.push_back(id); + p = e + 1; + } + } + else if (k == "--incumbent") a.incumbent = path_from_name(val()); + else if (k == "--parity") a.parity = true; + else if (k == "--no-parity") a.parity = false; + else if (k == "--bench") a.bench = true; + else if (k == "--no-ref") a.ref = false; + else if (k == "--ref-heads") { a.ref_heads.clear(); for (auto x : parse_list(val())) a.ref_heads.push_back((int) x); } + else if (k == "--reps") a.reps = std::atoi(val()); + else if (k == "--warmup") a.warmup = std::atoi(val()); + else if (k == "--any-sms") a.any_sms = true; + else if (k == "--gsb") a.gsb = std::atoi(val()); + else if (k == "--fallback-incumbent") a.fallback_incumbent = true; + else if (k == "--ld16") a.ld16 = parse_list(val())[0]; + else if (k == "--state") a.fx.state = argv[++i]; + else if (k == "--v-scale") a.fx.v_scale = (float) std::atof(val()); + else if (k == "--gate-scale") a.fx.gate_scale = (float) std::atof(val()); + else if (k == "--coherent-keys") a.fx.coherent_keys = true; + else if (k == "--alt-beta") a.fx.alt_beta = true; + else if (k == "--tiny-k") a.fx.tiny_k = true; + else if (k == "--stress") a.stress = true; + else if (k == "--seed") a.fx.seed = (uint64_t) std::atoll(val()); + else if (k == "--json") a.json = val(); + else if (k == "--label") a.label = val(); + else { + std::fprintf(stderr, "unknown option %s (see Desktop\\30thOctober\\results\\gdn\\HARNESS.md)\n", k.c_str()); + return 2; + } + } + if (a.Ts.empty()) a.Ts = {a.T}; + if (!paths_given) a.paths = {sp::kGdnAuto, sp::kGdnKeyHead, sp::kGdnPipe, sp::kGdnChunked, sp::kGdnTc, sp::kGdnTcSplit}; + if (a.incumbent < 0) { std::fprintf(stderr, "bad --incumbent\n"); return 2; } + int dev = 0; + ck(cudaGetDevice(&dev), "device"); + cudaDeviceProp pr{}; + ck(cudaGetDeviceProperties(&pr, dev), "props"); + int drv = 0, rt = 0; + cudaDriverGetVersion(&drv); + cudaRuntimeGetVersion(&rt); + std::printf("gdn_harness sha=%s device=%s sms=%d cc=%d.%d driver=%d runtime=%d smem_optin=%zu\n", GDN_HARNESS_SHA, pr.name, + pr.multiProcessorCount, pr.major, pr.minor, drv, rt, (size_t) pr.sharedMemPerBlockOptin); + for (const char* e : {"STRATA_GDN_CHUNKED", "STRATA_GDN_TC", "STRATA_GDN_KEYHEAD", "STRATA_GDN_PIPELINE", "STRATA_GDN_REC_WARP", + "STRATA_GDN_CONVL2", "STRATA_GDN_CONV_SERIAL", "STRATA_GDN_REC_HEADS", "STRATA_PF_PAD"}) + if (const char* v = std::getenv(e)) std::printf("env %s=%s\n", e, v); + int fails = 0; + for (int64_t T : a.Ts) { + FixtureSpec s = a.fx; + s.T = T; + fails += run_case(a, s, "default", pr); + if (a.stress) { + struct { const char* n; const char* st; float v, g; bool coh, alt, tiny; } cases[] = { + {"state-zero", "zero", 1, 1, false, false, false}, {"state-big", "big", 1, 1, false, false, false}, + {"state-small", "small", 1, 1, false, false, false}, {"v-x50", "random", 50, 1, false, false, false}, + {"slow-gates", "random", 1, 0.005f, false, false, false}, {"fast-gates", "random", 1, 3, false, false, false}, + {"coherent-keys", "random", 1, 1, true, false, false}, {"beta-endpoints", "random", 1, 1, false, true, false}, + {"tiny-keys", "random", 1, 1, false, false, true}}; + for (auto& c : cases) { + FixtureSpec t = a.fx; + t.T = T; t.state = c.st; t.v_scale = c.v; t.gate_scale = c.g; t.coherent_keys = c.coh; t.alt_beta = c.alt; t.tiny_k = c.tiny; + fails += run_case(a, t, c.n, pr); + } + } + } + std::printf("\n%s: %d failed verdict(s)\n", fails ? "FAIL" : "OK", fails); + return fails ? 1 : 0; +} diff --git a/src/prefill/gdn_tc.cuh b/src/prefill/gdn_tc.cuh index 6d09ea83..54fb7ecf 100644 --- a/src/prefill/gdn_tc.cuh +++ b/src/prefill/gdn_tc.cuh @@ -46,6 +46,11 @@ 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 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][S] and the P images x 2^8 @@ -414,7 +419,7 @@ __global__ void __launch_bounds__(256) gdn_tc_prep_kernel(const float* __restric // 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 +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, @@ -426,12 +431,13 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const 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; - float* sv = reinterpret_cast(ql + 2 * GCH * GTC_KP); // [2][GCH][GTC_VP] v - uint16_t* th = reinterpret_cast(sv + 2 * GCH * GTC_VP); // [2][GCH][GTC_PP] T x 2^et hi / lo - uint16_t* tl = th + 2 * GCH * GTC_PP; - uint16_t* ph = tl + 2 * GCH * GTC_PP; // [2][GCH][GTC_PP] P x 2^8 hi / lo - uint16_t* pl = ph + 2 * GCH * GTC_PP; - float4* sc = reinterpret_cast(pl + 2 * GCH * GTC_PP); // [2][GCH] (beta, exp(gamma), exp(gL - gamma), gamma) + 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 const int vh = blockIdx.x, qhd = vh % HK; const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, gid = lane >> 2, tig = lane & 3; @@ -439,32 +445,36 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const // 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) - auto stage = [&](int ch, int 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 uint16_t* img = kqg + ((size_t) ch * HK + qhd) * 4 * GCH * S; + const int bv = SPLIT ? 0 : b; + if (parts & 1) { + const uint16_t* img = kqg + ((size_t) ch * HK + qhd) * 4 * GCH * S; #pragma unroll - for (int m = 0; m < 4 * GCH * S / 8 / NT; ++m) { - const int im = m >> 1, t = ((m & 1) * NT + tid) / (S / 8), r = (tid % (S / 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) * S + r)); + for (int m = 0; m < 4 * GCH * S / 8 / NT; ++m) { + const int im = m >> 1, t = ((m & 1) * NT + tid) / (S / 8), r = (tid % (S / 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) * S + r)); + } + if (tid < GCH) gdn_cp16(reinterpret_cast(sc + b * GCH + tid), reinterpret_cast(scg + ((int64_t) ch * HV + vh) * GCH + tid)); + if (tid == 0) gdn_cp4(ste + b, teg + (int64_t) ch * HV + vh); } + if (parts & 2) { #pragma unroll - for (int m = 0; m < GCH * S / 4 / NT; ++m) { - const int p = tid + NT * m, t = p / (S / 4), r = (p % (S / 4)) * 4; - float* dst = sv + (b * GCH + t) * GTC_VP + r; - if (t < n) gdn_cp16(dst, h + (c_t0 + t) * C + 2 * HK * S + vh * S + r); - else *reinterpret_cast(dst) = make_float4(0.0f, 0.0f, 0.0f, 0.0f); - } - { + for (int m = 0; m < GCH * S / 4 / NT; ++m) { + const int p = tid + NT * m, t = p / (S / 4), r = (p % (S / 4)) * 4; + float* dst = sv + (bv * GCH + t) * GTC_VP + r; + if (t < n) gdn_cp16(dst, h + (c_t0 + t) * C + 2 * HK * S + vh * S + r); + else *reinterpret_cast(dst) = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + } const int im = tid / (GCH * GCH / 8), t = (tid % (GCH * GCH / 8)) / (GCH / 8), i = (tid % (GCH / 8)) * 8; const int64_t src = ((((int64_t) ch * HV + vh) * 2 + im) * GCH + t) * GCH + i; - const int dst = (b * GCH + t) * GTC_PP + 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)); } - if (tid < GCH) gdn_cp16(reinterpret_cast(sc + b * GCH + tid), reinterpret_cast(scg + ((int64_t) ch * HV + vh) * GCH + tid)); - if (tid == 0) gdn_cp4(ste + b, teg + (int64_t) ch * HV + vh); gdn_cp_commit(); }; const int c0 = 16 * warp; // the warp's value columns c0 + gid and c0 + gid + 8 @@ -476,7 +486,7 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const const float* p = state + (size_t) (8 * j + 2 * tig) * rs + (size_t) vh * S + c0 + gid; s[j][0] = p[0]; s[j][1] = p[rs]; s[j][2] = p[8]; s[j][3] = p[rs + 8]; } - stage(0, 0); + stage(0, 0, 3); const float out_scale = rsqrtf((float) S); for (int ch = 0; ch < nch; ++ch) { const int b = ch & 1; @@ -484,16 +494,17 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const 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); + 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 uint16_t* bth = th + b * GCH * GTC_PP; - const uint16_t* btl = tl + b * GCH * GTC_PP; - const uint16_t* bph = ph + b * GCH * GTC_PP; - const uint16_t* bpl = pl + b * GCH * GTC_PP; - const float* bsv = sv + b * GCH * GTC_VP; + 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) @@ -558,6 +569,10 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const const int t = 8 * nt + 2 * tig + (q & 1); if (t < n) oc_out[(c_t0 + t) * rs + (size_t) vh * S + c0 + 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); + } // (e) S^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) diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 365d5a90..66e2f82c 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -1,6 +1,7 @@ // src/prefill/kernels.cu - see include/strata/prefill/kernels.hpp. #include "strata/prefill/kernels.hpp" #include "strata/prefill/gdn_chunk.hpp" +#include "strata/prefill/gdn_probe.hpp" #include "strata/kernels/mrope.hpp" #include "strata/kernels/gfx_arch.hpp" #include "strata/kernels/router_top10.hpp" @@ -1191,13 +1192,19 @@ cudaError_t gdn_rec_chunked(float* state, const float* h, const float* gate, con // STRATA_GDN_CHUNKED=2 skips the SM-count test (measurement on a card under 128 SMs: the scan then runs in // several waves and is expected to be slower than the default kernel; the architecture and shared-memory // tests stay) - static const bool any_sms = [] { const char* v = std::getenv("STRATA_GDN_CHUNKED"); return v != nullptr && std::atoi(v) >= 2; }(); + static const bool any_sms_env = [] { const char* v = std::getenv("STRATA_GDN_CHUNKED"); return v != nullptr && std::atoi(v) >= 2; }(); + const GdnProbe* pr = gdn_probe_get(); // tests only: the same as =2, per call + const bool any_sms = any_sms_env || (pr != nullptr && pr->any_sms); if (strata::cc_major_of(major) < 8 || (!any_sms && sms < HK * (S / GDV)) || (size_t) strata::smem_optin_of(smem) < kChunkScanSmem) return cudaErrorNotSupported; } float* scratch = gdn_chunk_scratch(); if (scratch == nullptr) return cudaErrorMemoryAllocation; - const int nb = (int) ((std::min(GSB, T) + GCH - 1) / GCH); + // the scratch segment: a test may ask for a smaller one than GSB (a multiple of GCH); production always GSB + int64_t gsb = GSB; + if (const GdnProbe* pr = gdn_probe_get()) + if (pr->gsb >= GCH && pr->gsb < GSB) gsb = (pr->gsb / GCH) * GCH; + const int nb = (int) ((std::min(gsb, T) + GCH - 1) / GCH); const size_t tsz = (size_t) nb * HV * GCH * GCH; float *tm = scratch, *pm = tm + tsz, *gm = pm + tsz; { // once a device @@ -1210,8 +1217,8 @@ cudaError_t gdn_rec_chunked(float* state, const float* h, const float* gate, con attrs[dev] = true; } } - for (int64_t t0 = 0; t0 < T; t0 += GSB) { - const int nch = (int) ((std::min(GSB, T - t0) + GCH - 1) / GCH); + for (int64_t t0 = 0; t0 < T; t0 += gsb) { + const int nch = (int) ((std::min(gsb, T - t0) + GCH - 1) / GCH); gdn_chunk_prep_kernel<<>>(h, gate, beta, tm, pm, gm, t0, T); gdn_chunk_scan_kernel<<>>(state, h, beta, tm, pm, gm, y, t0, nch, T); } @@ -1221,7 +1228,7 @@ cudaError_t gdn_rec_chunked(float* state, const float* h, const float* gate, con // that also writes its f16 images (gdn_tc_prep_kernel, scratch gdn_tc_scratch), 48 blocks of 256 threads in one wave. An error return means nothing was launched: the card is below // sm_80, has fewer than 48 SMs, or less than 122 KB of shared memory a block. cudaError_t gdn_rec_tc(float* state, const float* h, const float* gate, const float* beta, float* y, int64_t T, - cudaStream_t s) { + cudaStream_t s, bool split = false) { if (T <= 0) return cudaSuccess; { int dev = 0, major = 0, sms = 0, smem = 0; @@ -1232,27 +1239,57 @@ cudaError_t gdn_rec_tc(float* state, const float* h, const float* gate, const fl cudaGetLastError(); return cudaErrorNotSupported; } - if (strata::cc_major_of(major) < 8 || sms < HV || (size_t) strata::smem_optin_of(smem) < kTcScanSmem) + if (strata::cc_major_of(major) < 8 || sms < HV || + (size_t) strata::smem_optin_of(smem) < (split ? kTcScanSmemSplit : kTcScanSmem)) return cudaErrorNotSupported; } const GtcScratch sc = gdn_tc_scratch(); if (sc.ti == nullptr) return cudaErrorMemoryAllocation; { // once a device - static bool attrs[64] = {}; + static bool attrs[2][64] = {}; int dev = 0; cudaGetDevice(&dev); - if (dev >= 0 && dev < 64 && !attrs[dev]) { - cudaFuncSetAttribute(gdn_tc_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmem); - attrs[dev] = true; + if (dev >= 0 && dev < 64 && !attrs[split][dev]) { + if (split) cudaFuncSetAttribute(gdn_tc_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplit); + else cudaFuncSetAttribute(gdn_tc_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmem); + attrs[split][dev] = true; } } for (int64_t t0 = 0; t0 < T; t0 += GSB) { const int nch = (int) ((std::min(GSB, T - t0) + GCH - 1) / GCH); gdn_tc_prep_kernel<<>>(h, gate, beta, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, t0, T); - gdn_tc_scan_kernel<<, s>>>(state, h, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y, t0, nch, T); + if (split) + gdn_tc_scan_kernel<<>>(state, h, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y, t0, nch, T); + else + gdn_tc_scan_kernel<<, s>>>(state, h, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y, t0, nch, T); } return cudaSuccess; } +// Why gdn_rec_chunked (tc false) or gdn_rec_tc (tc true) launched nothing, in words: the same tests asked again. Only +// the gdn_probe.hpp `reason` uses it (a test says what it timed); the dispatch itself never calls it. +const char* gdn_chunk_why(bool tc, cudaError_t e, bool any_sms, bool split = false) { + static thread_local char buf[200]; + if (e == cudaErrorMemoryAllocation) return "scratch allocation failed"; + 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 "device attributes unavailable"; + } + const int cc = strata::cc_major_of(major); + const size_t need = tc ? (split ? kTcScanSmemSplit : (size_t) kTcScanSmem) : kChunkScanSmem; + const int sm_need = tc ? HV : HK * (S / GDV); + if (cc < 8) std::snprintf(buf, sizeof buf, "compute capability %d < 8 (cp.async)", cc); + else if (!tc && !any_sms && sms < sm_need) + std::snprintf(buf, sizeof buf, "%d SMs < %d: the scan would run in several waves (STRATA_GDN_CHUNKED=2 bypasses)", sms, sm_need); + else if (tc && sms < sm_need) std::snprintf(buf, sizeof buf, "%d SMs < %d (one block per value head)", sms, sm_need); + else if ((size_t) strata::smem_optin_of(smem) < need) + std::snprintf(buf, sizeof buf, "shared memory per block %d B < %zu B needed", strata::smem_optin_of(smem), need); + else std::snprintf(buf, sizeof buf, "not supported (%s)", cudaGetErrorString(e)); + return buf; +} #endif #if defined(__HIPCC__) // the Aurora (gfx11) recurrence kernels: AMD builds only // Aurora (S23): the recurrence with the column-split grid of gdn_rec_cols_pipe_kernel (four 32-column blocks per value @@ -2777,16 +2814,74 @@ static void gdn_recurrence_impl(int variant, float* state, const float* h, const // chunks of kGdnTcMin+ tokens: within 1e-4 of the kernels below (gdn_rec_parity), 3.75x gdn_rec_kh_kernel on a // CMP 170HX; a shorter chunk, a card it does not fit or a failed scratch allocation takes the kernels below static const bool tc = [] { const char* v = std::getenv("STRATA_GDN_TC"); return v != nullptr && std::atoi(v) != 0; }(); - if (tc && T >= kGdnTcMin && gdn_rec_tc(state, h, gate, beta, y, T, (cudaStream_t) stream) == cudaSuccess) { - } else if (chunked && T >= kGdnChunkedMin && gdn_rec_chunked(state, h, gate, beta, y, T, (cudaStream_t) stream) == cudaSuccess) { - } else if (pipe && gdn_keyhead_ok()) // the value heads of a key head in one thread (same bits) - gdn_rec_kh_kernel<<>>(state, h, gate, beta, y, T); - else -#endif + // A test's probe (gdn_probe.hpp) reads back the path that ran and may force one; without a probe this is the + // dispatch it was. A forced path that cannot run launches nothing (selected = none, reason says why). + GdnProbe* pr = gdn_probe_get(); + const int force = pr ? pr->force : (int) kGdnAuto; + int sel = kGdnNone, wanted = force; + const char* why = ""; + const cudaStream_t cs = (cudaStream_t) stream; + if (force != kGdnAuto) { + if (force == kGdnTc || force == kGdnTcSplit) { + const bool sp = force == kGdnTcSplit; + cudaError_t e = T >= kGdnTcMin ? gdn_rec_tc(state, h, gate, beta, y, T, cs, sp) : cudaErrorInvalidValue; + if (e == cudaSuccess) sel = force; + else why = T < kGdnTcMin ? "T below the tc minimum (128)" : gdn_chunk_why(true, e, false, sp); + } else if (force == kGdnChunked) { + cudaError_t e = T >= kGdnChunkedMin ? gdn_rec_chunked(state, h, gate, beta, y, T, cs) : cudaErrorInvalidValue; + if (e == cudaSuccess) sel = kGdnChunked; + else why = T < kGdnChunkedMin ? "T below the chunked minimum (128)" : gdn_chunk_why(false, e, pr->any_sms); + } else if (force == kGdnKeyHead) { + if (gdn_keyhead_ok()) { + gdn_rec_kh_kernel<<>>(state, h, gate, beta, y, T); + sel = kGdnKeyHead; + } else why = "keyhead kernel not eligible here (needs sm_80+ with all 64 blocks resident, or STRATA_GDN_KEYHEAD=0 is set)"; + } else if (force == kGdnPipe) { + gdn_rec_cols_pipe_kernel<<>>(state, h, gate, beta, y, T); + sel = kGdnPipe; + } else if (force == kGdnCols) { + gdn_rec_cols_kernel<<>>(state, h, gate, beta, y, T); + sel = kGdnCols; + } else why = "unknown path"; + } else { + if (tc && T >= kGdnTcMin) { + wanted = kGdnTc; + cudaError_t e = gdn_rec_tc(state, h, gate, beta, y, T, cs); + if (e == cudaSuccess) sel = kGdnTc; + else { // the 99-KB cards (sm_86 / 89 / 120): the single-buffered v / T / P plan + if (pr) why = gdn_chunk_why(true, e, false); + e = gdn_rec_tc(state, h, gate, beta, y, T, cs, true); + if (e == cudaSuccess) { sel = kGdnTcSplit; why = ""; } + } + } + if (sel == kGdnNone && chunked && T >= kGdnChunkedMin) { + if (wanted == kGdnAuto) wanted = kGdnChunked; + const cudaError_t e = gdn_rec_chunked(state, h, gate, beta, y, T, cs); + if (e == cudaSuccess) sel = kGdnChunked; + else if (pr && wanted == kGdnChunked) why = gdn_chunk_why(false, e, false); + } + if (sel == kGdnNone) { + if (pipe && gdn_keyhead_ok()) { // the value heads of a key head in one thread (same bits) + gdn_rec_kh_kernel<<>>(state, h, gate, beta, y, T); + sel = kGdnKeyHead; + } else if (pipe) { // the software-pipelined loads (same bits) + gdn_rec_cols_pipe_kernel<<>>(state, h, gate, beta, y, T); + sel = kGdnPipe; + } else { + gdn_rec_cols_kernel<<>>(state, h, gate, beta, y, T); + sel = kGdnCols; + } + if (wanted == kGdnAuto) wanted = sel; + } + } + if (pr) { pr->selected = sel; pr->wanted = wanted == kGdnAuto ? sel : wanted; pr->reason = why; ++pr->calls; } + if (sel == kGdnNone) { check("gdn_recurrence (forced path not eligible: nothing launched)"); return; } +#else if (pipe) // the software-pipelined loads (same bits) gdn_rec_cols_pipe_kernel<<>>(state, h, gate, beta, y, T); else gdn_rec_cols_kernel<<>>(state, h, gate, beta, y, T); +#endif if (with_out) gdn_out_norm_kernel<<>>(z, gamma, eps, y, y16, ld16); } diff --git a/tests/gdn/gdn_fixture.hpp b/tests/gdn/gdn_fixture.hpp new file mode 100644 index 00000000..1d5f0805 --- /dev/null +++ b/tests/gdn/gdn_fixture.hpp @@ -0,0 +1,245 @@ +// tests/gdn/gdn_fixture.hpp - backend-independent fixtures and an FP64 oracle for the Flash-Next GDN prompt path. +// +// Plain C++17, no GPU headers: the CUDA harness (src/prefill/gdn_harness.cu) uses it today; the HIP and Metal/SYCL +// harnesses are meant to include the same file, so every backend is judged against the same inputs and the same +// reference. Contract: docs/GDN_CONTRACT.md (shapes, layouts, what a candidate may change). +// +// Fixture raw inputs of one layer for T tokens: qkv [T][C], ab [T][2 HV], dt, ssm_a, conv_w [C][4], conv +// history [C][3], the recurrent state [S][HV][S] (row, head, column), z [T][HV][S], gamma [S] +// RefResult FP64 oracle for some value heads over the whole sequence: normalised output (what the out +// projection reads, before the FP16 rounding), the final state of those heads, the conv history +// ErrStat max_abs, normalized_max (max_abs / max|ref|), relative_L2 (gdn-research 06) +// The oracle starts from the RAW inputs (conv, SiLU, L2 norm, gates, recurrence, output norm), so a bug shared by a +// kernel and a test copy of it cannot hide. +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace gdnfx { + +constexpr int S = 128, HK = 16, HV = 48, VPK = HV / HK, C = 2 * HK * S + HV * S; // C = 10240 +constexpr float EPS = 1e-6f; // the engine's L2 / RMS epsilon + +struct Rng { // splitmix64: identical on every platform and compiler + uint64_t s; + explicit Rng(uint64_t seed) : s(seed * 0x9E3779B97F4A7C15ULL + 0x1234567ULL) {} + uint64_t next() { + uint64_t z = (s += 0x9E3779B97F4A7C15ULL); + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL; + return z ^ (z >> 31); + } + double uni() { return (double) (next() >> 11) * (1.0 / 9007199254740992.0); } // [0, 1) + double gauss() { + double u1 = uni(), u2 = uni(); + if (u1 < 1e-300) u1 = 1e-300; + return std::sqrt(-2.0 * std::log(u1)) * std::cos(6.283185307179586 * u2); + } +}; + +struct FixtureSpec { + int64_t T = 0; + uint64_t seed = 1; + // state0: "random" (as after an earlier prompt chunk), "zero" (a fresh conversation), "big", "small" + const char* state = "random"; + float v_scale = 1.0f; // values x this (50: range stress) + float gate_scale = 1.0f; // ssm_a x this (0.005: near-zero decay, 3: strong decay) + bool coherent_keys = false; // every token's k is a head constant plus a small variation (T = (I+A)^-1 large) + bool alt_beta = false; // beta alternates 0.02 / 0.98 per token (endpoint regime) + bool tiny_k = false; // every 7th token's k/q channels are ~1e-4 before the L2 norm (eps matters) +}; + +struct Fixture { + FixtureSpec spec; + int64_t T = 0; + std::vector qkv, ab, dt, ssm_a, conv_w, hist, state0, z, gamma; +}; + +inline Fixture make_fixture(const FixtureSpec& sp) { + Fixture f; + f.spec = sp; + f.T = sp.T; + const int64_t T = sp.T; + Rng r(sp.seed); + f.qkv.resize((size_t) T * C); + f.ab.resize((size_t) T * 2 * HV); + f.dt.resize(HV); + f.ssm_a.resize(HV); + f.conv_w.resize((size_t) C * 4); + f.hist.resize((size_t) C * 3); + f.state0.resize((size_t) S * HV * S); + f.z.resize((size_t) T * HV * S); + f.gamma.resize(S); + for (auto& x : f.qkv) x = (float) r.gauss(); + if (sp.coherent_keys) { + std::vector base((size_t) HK * S); + for (auto& x : base) x = (float) r.gauss(); + for (int64_t t = 0; t < T; ++t) + for (int i = 0; i < HK * S; ++i) { + float& x = f.qkv[(size_t) t * C + HK * S + i]; // k channels + x = base[i] + 0.05f * x; + } + } + if (sp.tiny_k) + for (int64_t t = 0; t < T; t += 7) + for (int i = 0; i < 2 * HK * S; ++i) f.qkv[(size_t) t * C + i] *= 1e-4f; + if (sp.v_scale != 1.0f) + for (int64_t t = 0; t < T; ++t) + for (int i = 0; i < HV * S; ++i) f.qkv[(size_t) t * C + 2 * HK * S + i] *= sp.v_scale; + for (auto& x : f.ab) x = (float) r.gauss(); + if (sp.alt_beta) + for (int64_t t = 0; t < T; ++t) + for (int h = 0; h < HV; ++h) f.ab[(size_t) t * 2 * HV + HV + h] = (t & 1) ? 3.9f : -3.9f; + for (int h = 0; h < HV; ++h) { + f.dt[h] = (float) (0.5 * r.gauss() - 0.5); + const double u = r.uni(); + f.ssm_a[h] = (float) (-(0.05 + 1.5 * u * u) * sp.gate_scale); + } + for (auto& x : f.conv_w) x = (float) (0.35 * r.gauss()); + for (auto& x : f.hist) x = (float) r.gauss(); + for (auto& x : f.z) x = (float) r.gauss(); + for (auto& x : f.gamma) x = (float) (1.0 + 0.1 * r.gauss()); + float ss = 0.05f; + if (!std::strcmp(sp.state, "zero")) ss = 0.0f; + else if (!std::strcmp(sp.state, "big")) ss = 2.5f; + else if (!std::strcmp(sp.state, "small")) ss = 5e-4f; + for (auto& x : f.state0) x = ss == 0.0f ? 0.0f : (float) (ss * r.gauss()); + return f; +} + +// ------------------------------------------------------------------------------------------------ FP64 oracle +inline double sigm(double x) { return 1.0 / (1.0 + std::exp(-x)); } + +struct RefResult { + std::vector heads; // value heads computed + std::vector> y; // per head: [T][S] normalised output (before FP16) + std::vector> state; // per head: final [S][S] (row, column) + std::vector hist; // conv history after the whole sequence (exact: copies of inputs) +}; + +// One value head over tokens [0, T). state_io: that head's [S][S] (row, column), updated in place. +inline void ref_head(const Fixture& f, int vh, std::vector& st, std::vector& y) { + const int64_t T = f.T; + const int qh = vh % HK; + y.assign((size_t) T * S, 0.0); + std::vector q(S), k(S), v(S), kv(S), delta(S), o(S); + auto in = [&](int64_t t, int c) -> double { + return t >= 0 ? (double) f.qkv[(size_t) t * C + c] : (double) f.hist[(size_t) c * 3 + (int) (t + 3)]; + }; + auto conv = [&](int64_t t, int c) -> double { + const double s = (double) f.conv_w[(size_t) c * 4] * in(t - 3, c) + (double) f.conv_w[(size_t) c * 4 + 1] * in(t - 2, c) + + (double) f.conv_w[(size_t) c * 4 + 2] * in(t - 1, c) + (double) f.conv_w[(size_t) c * 4 + 3] * in(t, c); + return s / (1.0 + std::exp(-s)); + }; + for (int64_t t = 0; t < T; ++t) { + double qq = 0, kk = 0; + for (int i = 0; i < S; ++i) { + q[i] = conv(t, qh * S + i); + k[i] = conv(t, HK * S + qh * S + i); + v[i] = conv(t, 2 * HK * S + vh * S + i); + qq += q[i] * q[i]; + kk += k[i] * k[i]; + } + const double qs = 1.0 / std::sqrt(qq + (double) EPS), ks = 1.0 / std::sqrt(kk + (double) EPS); + for (int i = 0; i < S; ++i) { q[i] *= qs; k[i] *= ks; } + const double a = (double) f.ab[(size_t) t * 2 * HV + vh] + (double) f.dt[vh]; + const double sp = a > 20.0 ? a : std::log1p(std::exp(a)); + const double g = std::exp(sp * (double) f.ssm_a[vh]); + const double beta = sigm((double) f.ab[(size_t) t * 2 * HV + HV + vh]); + for (int c = 0; c < S; ++c) kv[c] = 0; + for (int i = 0; i < S; ++i) { + const double* row = &st[(size_t) i * S]; + for (int c = 0; c < S; ++c) kv[c] += row[c] * k[i]; + } + for (int c = 0; c < S; ++c) delta[c] = (v[c] - g * kv[c]) * beta; + for (int c = 0; c < S; ++c) o[c] = 0; + for (int i = 0; i < S; ++i) { + double* row = &st[(size_t) i * S]; + for (int c = 0; c < S; ++c) { + row[c] = g * row[c] + k[i] * delta[c]; + o[c] += row[c] * q[i]; + } + } + double ss = 0; + for (int c = 0; c < S; ++c) { o[c] /= std::sqrt((double) S); ss += o[c] * o[c]; } + const double rn = 1.0 / std::sqrt(ss / S + (double) EPS); + for (int c = 0; c < S; ++c) + y[(size_t) t * S + c] = o[c] * rn * (double) f.gamma[c] * sigm((double) f.z[((size_t) t * HV + vh) * S + c]); + } +} + +// The oracle for `heads`, one thread each (state taken from the fixture's state0, layout [row][head][col]). +inline RefResult ref_run(const Fixture& f, const std::vector& heads) { + RefResult r; + r.heads = heads; + r.y.resize(heads.size()); + r.state.resize(heads.size()); + std::vector th; + for (size_t n = 0; n < heads.size(); ++n) + th.emplace_back([&, n] { + const int vh = heads[n]; + std::vector st((size_t) S * S); + for (int i = 0; i < S; ++i) + for (int c = 0; c < S; ++c) st[(size_t) i * S + c] = (double) f.state0[((size_t) i * HV + vh) * S + c]; + ref_head(f, vh, st, r.y[n]); + r.state[n] = std::move(st); + }); + for (auto& t : th) t.join(); + r.hist.resize((size_t) C * 3); + for (int c = 0; c < C; ++c) + for (int k = 0; k < 3; ++k) { + const int64_t t = f.T - 3 + k; + r.hist[(size_t) c * 3 + k] = t >= 0 ? f.qkv[(size_t) t * C + c] : f.hist[(size_t) c * 3 + (int) (t + 3)]; + } + return r; +} + +// ------------------------------------------------------------------------------------------------ metrics +struct ErrStat { + double max_abs = 0, ref_max = 0, sq_diff = 0, sq_ref = 0; + long nonfinite = 0, n = 0; + void add(double got, double ref) { + ++n; + if (!std::isfinite(got)) { ++nonfinite; return; } + const double d = std::fabs(got - ref); + if (d > max_abs) max_abs = d; + const double a = std::fabs(ref); + if (a > ref_max) ref_max = a; + sq_diff += d * d; + sq_ref += ref * ref; + } + double normalized_max() const { return max_abs / std::max(ref_max, 1e-30); } + double rel_l2() const { return std::sqrt(sq_diff) / std::max(std::sqrt(sq_ref), 1e-30); } +}; + +inline uint64_t fnv1a(const void* p, size_t bytes) { + const unsigned char* b = (const unsigned char*) p; + uint64_t h = 1469598103934665603ULL; + for (size_t i = 0; i < bytes; ++i) { h ^= b[i]; h *= 1099511628211ULL; } + return h; +} + +inline float half_to_float(uint16_t h) { // IEEE binary16 -> float, host side + const uint32_t sign = (uint32_t) (h >> 15) << 31; + uint32_t e = (h >> 10) & 0x1f, m = h & 0x3ff, out; + if (e == 0) { + if (m == 0) out = sign; + else { + e = 127 - 15 + 1; + while (!(m & 0x400)) { m <<= 1; --e; } + out = sign | (e << 23) | ((m & 0x3ff) << 13); + } + } else if (e == 31) out = sign | 0x7f800000u | (m << 13); + else out = sign | ((e + 112) << 23) | (m << 13); + float f; + std::memcpy(&f, &out, 4); + return f; +} + +} // namespace gdnfx From a0e7f5160d0a826b048f4a3a29002f1e08011f1f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 01:47:46 +0100 Subject: [PATCH 08/11] GDN harness: tc any_sms bypass for multi-wave tests, output hash --- src/prefill/gdn_harness.cu | 5 +++-- src/prefill/kernels.cu | 6 ++++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/prefill/gdn_harness.cu b/src/prefill/gdn_harness.cu index 2c6bc671..c5f87a69 100644 --- a/src/prefill/gdn_harness.cu +++ b/src/prefill/gdn_harness.cu @@ -372,8 +372,9 @@ int run_case(const Args& a, const FixtureSpec& spec, const char* fname, const cu } char tb[120] = ""; if (a.bench) std::snprintf(tb, sizeof tb, "%.3f/%.3f/%.3f (tot med %.3f min %.3f)", r.ms_gates, r.ms_conv, r.ms_rec, med, mn); - std::printf("%-8s %-6s %-9s %9.2e %9.2e %9.2e %9.2e %-34s %s %s\n", name, "yes", exact ? "identical" : "differs", cr.y_nmax, cr.s_nmax, - ci.y_nmax, ci.s_nmax, tb, join(r.logged).c_str(), verdict); + std::printf("%-8s %-6s %-9s %9.2e %9.2e %9.2e %9.2e %-34s %s %s h=%08llx\n", name, "yes", exact ? "identical" : "differs", cr.y_nmax, cr.s_nmax, + ci.y_nmax, ci.s_nmax, tb, join(r.logged).c_str(), verdict, + (unsigned long long) (fnv1a(r.y16.data(), r.y16.size() * 2) & 0xffffffffULL)); if (r.fallback_calls) std::printf(" (%d call(s) ran on the incumbent: the forced path could not take them)\n", r.fallback_calls); json_line(a, "case", fname, T, r, have_ref ? &cr : nullptr, &ci, exact, med, mn, verdict, pr); } diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 66e2f82c..7c10bdbf 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -1239,7 +1239,9 @@ cudaError_t gdn_rec_tc(float* state, const float* h, const float* gate, const fl cudaGetLastError(); return cudaErrorNotSupported; } - if (strata::cc_major_of(major) < 8 || sms < HV || + const GdnProbe* pr = gdn_probe_get(); // tests only: fewer SMs than value heads run the 48 blocks in several waves + const bool any_sms = pr != nullptr && pr->any_sms; + if (strata::cc_major_of(major) < 8 || (!any_sms && sms < HV) || (size_t) strata::smem_optin_of(smem) < (split ? kTcScanSmemSplit : kTcScanSmem)) return cudaErrorNotSupported; } @@ -1284,7 +1286,7 @@ const char* gdn_chunk_why(bool tc, cudaError_t e, bool any_sms, bool split = fal if (cc < 8) std::snprintf(buf, sizeof buf, "compute capability %d < 8 (cp.async)", cc); else if (!tc && !any_sms && sms < sm_need) std::snprintf(buf, sizeof buf, "%d SMs < %d: the scan would run in several waves (STRATA_GDN_CHUNKED=2 bypasses)", sms, sm_need); - else if (tc && sms < sm_need) std::snprintf(buf, sizeof buf, "%d SMs < %d (one block per value head)", sms, sm_need); + else if (tc && !any_sms && sms < sm_need) std::snprintf(buf, sizeof buf, "%d SMs < %d (one block per value head)", sms, sm_need); else if ((size_t) strata::smem_optin_of(smem) < need) std::snprintf(buf, sizeof buf, "shared memory per block %d B < %zu B needed", strata::smem_optin_of(smem), need); else std::snprintf(buf, sizeof buf, "not supported (%s)", cudaGetErrorString(e)); From 1a865fb3dbf22e22a7f62ca9d892e75e7ba20883 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 02:12:18 +0100 Subject: [PATCH 09/11] GDN TC: fused output norm for the split scan, NP experiment variants (STRATA_GDN_TC_NP), STRATA_GDN_TC_FUSE --- include/strata/prefill/gdn_probe.hpp | 6 +- src/prefill/gdn_tc.cuh | 128 +++++++++++++++++++++------ src/prefill/kernels.cu | 65 +++++++++++--- 3 files changed, 156 insertions(+), 43 deletions(-) diff --git a/include/strata/prefill/gdn_probe.hpp b/include/strata/prefill/gdn_probe.hpp index 905bdf54..2c58143a 100644 --- a/include/strata/prefill/gdn_probe.hpp +++ b/include/strata/prefill/gdn_probe.hpp @@ -21,7 +21,9 @@ enum GdnPath : int { kGdnChunked = 4, // STRATA_GDN_CHUNKED: FP32 chunked prep + scan (CUDA, C = 32) kGdnTc = 5, // STRATA_GDN_TC=1: chunked, scan on the tensor cores (CUDA sm_80+, 125 KB of shared memory a block) kGdnTcSplit = 6, // the same scan with v / T / P single-buffered: 98 KB, fits the 99-KB cards (sm_86, sm_89, sm_120) - kGdnPathCount = 7 + kGdnTcS2 = 7, // experiment: the split scan with 2 passes a product (lo.hi + hi.hi), not for production + kGdnTcS1 = 8, // experiment: the split scan with plain f16 operands (1 pass), not for production + kGdnPathCount = 9 }; struct GdnProbe { @@ -48,6 +50,8 @@ inline const char* gdn_path_name(int p) { case kGdnChunked: return "chunked"; case kGdnTc: return "tc"; case kGdnTcSplit: return "tcs"; + case kGdnTcS2: return "tcs2"; + case kGdnTcS1: return "tcs1"; case kGdnAuto: return "auto"; default: return "none"; } diff --git a/src/prefill/gdn_tc.cuh b/src/prefill/gdn_tc.cuh index 54fb7ecf..eda8c354 100644 --- a/src/prefill/gdn_tc.cuh +++ b/src/prefill/gdn_tc.cuh @@ -51,6 +51,9 @@ static_assert(kTcScanSmem == 124944 && kTcScanSmem == 160784, "gdn_ // 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][S] and the P images x 2^8 @@ -151,6 +154,19 @@ __device__ __forceinline__ void gtc_mma3_f16(float (&c)[4], const uint32_t (&ah) gtc_mma_f16(c, ah, bl0, bl1); gtc_mma_f16(c, ah, bh0, bh1); } +// NP passes of a split product (experiment, STRATA_GDN_TC split kernels only): 3 = the three above (the default); 2 = lo.hi and +// hi.hi (the A operand split, B in f16 only); 1 = hi.hi (plain f16 operands, as the gfx11 WMMA path). B's lo image is not read for NP < 3. +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; @@ -186,6 +202,7 @@ __device__ __forceinline__ float4 gtc_lds128(const float4* p) { // (tiles 2kk and 2kk + 1 of S^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; @@ -200,15 +217,15 @@ __device__ __forceinline__ void gtc_prod_state(const float (&s)[16][4], float sA #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]; + uint32_t bh[4], bl[4] = {0u, 0u, 0u, 0u}; gtc_ldsm_x4(bh, kh + o); - gtc_ldsm_x4(bl, kl + o); - gtc_mma3_f16(xt[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]); - gtc_mma3_f16(xt[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]); + if constexpr (NP == 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); - gtc_ldsm_x4(bl, ql + o); - gtc_mma3_f16(qs[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]); - gtc_mma3_f16(qs[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]); + if constexpr (NP == 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]); } } } @@ -216,7 +233,7 @@ __device__ __forceinline__ void gtc_prod_state(const float (&s)[16][4], float sA // 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 +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; @@ -232,17 +249,18 @@ __device__ __forceinline__ void gtc_prod_dt(const float (&dt)[4][4], float sD, c 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]; + uint32_t bh[4], bl[4] = {0u, 0u, 0u, 0u}; gtc_ldsm_x4(bh, ph + o); - gtc_ldsm_x4(bl, pl + o); - gtc_mma3_f16(ot[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]); - gtc_mma3_f16(ot[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]); + 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]); } } } // S^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; @@ -257,11 +275,11 @@ __device__ __forceinline__ void gtc_update_state(float (&s)[16][4], const float #pragma unroll for (int hf = 0; hf < S / 16; ++hf) { const int o = off + 16 * ks * GTC_KP + 16 * hf; - uint32_t bh[4], bl[4]; + uint32_t bh[4], bl[4] = {0u, 0u, 0u, 0u}; gtc_ldsm_x4_trans(bh, kh + o); - gtc_ldsm_x4_trans(bl, kl + o); - gtc_mma3_f16(s[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]); - gtc_mma3_f16(s[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]); + 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]); } } } @@ -419,12 +437,17 @@ __global__ void __launch_bounds__(256) gdn_tc_prep_kernel(const float* __restric // 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 +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) { - static_assert(!NORM, "gdn_tc_scan_kernel: the fused output norm is not implemented yet"); + const uint16_t* __restrict__ pig, float* __restrict__ oc_out, int64_t t0, int nch, int64_t T, + 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"); constexpr int NT = GTC_CW * 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) @@ -439,6 +462,7 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const 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, qhd = vh % HK; const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, gid = lane >> 2, tig = lane & 3; const size_t rs = (size_t) HV * S; @@ -516,7 +540,7 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const 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(s, gtc_pow2(es), bkh, bkl, bqh, bql, xt, qs); + gtc_prod_state(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)); @@ -540,7 +564,7 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const 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); + 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) @@ -561,18 +585,66 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const 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); + 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) + 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 * S + c0 + gid + 8 * (q >> 1)] = (ot[nt][q] * sOi) * out_scale; - } + 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 * S + 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 * S + c0 + 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) S + 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 * S + col] = __half_as_ushort(__float2half_rn(v)); + } + } + } // (e) S^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) @@ -586,7 +658,7 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const 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(s, dd, bkh, bkl); + gtc_update_state(s, dd, bkh, bkl); #pragma unroll for (int j = 0; j < 16; ++j) #pragma unroll diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 7c10bdbf..5eb8d6a1 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -1227,8 +1227,16 @@ cudaError_t gdn_rec_chunked(float* state, const float* h, const float* gate, con // STRATA_GDN_TC=1: gdn_rec_chunked with the scan on the tensor cores (gdn_tc_scan_kernel, gdn_tc.cuh) and the prep // that also writes its f16 images (gdn_tc_prep_kernel, scratch gdn_tc_scratch), 48 blocks of 256 threads in one wave. An error return means nothing was launched: the card is below // sm_80, has fewer than 48 SMs, or less than 122 KB of shared memory a block. +// the output norm's operands, when the split scan fuses it (see gdn_tc_scan_kernel NORM) +struct GdnTcNorm { + const float* z; + const float* gamma; + float eps; + uint16_t* y16; + int64_t ld16; +}; cudaError_t gdn_rec_tc(float* state, const float* h, const float* gate, const float* beta, float* y, int64_t T, - cudaStream_t s, bool split = false) { + cudaStream_t s, bool split = false, int np = 3, const GdnTcNorm* nm = nullptr) { if (T <= 0) return cudaSuccess; { int dev = 0, major = 0, sms = 0, smem = 0; @@ -1242,25 +1250,44 @@ cudaError_t gdn_rec_tc(float* state, const float* h, const float* gate, const fl const GdnProbe* pr = gdn_probe_get(); // tests only: fewer SMs than value heads run the 48 blocks in several waves const bool any_sms = pr != nullptr && pr->any_sms; if (strata::cc_major_of(major) < 8 || (!any_sms && sms < HV) || - (size_t) strata::smem_optin_of(smem) < (split ? kTcScanSmemSplit : kTcScanSmem)) + (size_t) strata::smem_optin_of(smem) < (split ? (nm ? kTcScanSmemSplitNorm : kTcScanSmemSplit) : kTcScanSmem)) return cudaErrorNotSupported; } const GtcScratch sc = gdn_tc_scratch(); if (sc.ti == nullptr) return cudaErrorMemoryAllocation; { // once a device - static bool attrs[2][64] = {}; + static bool attrs[3][64] = {}; + const int ai = nm && split ? 2 : (split ? 1 : 0); int dev = 0; cudaGetDevice(&dev); - if (dev >= 0 && dev < 64 && !attrs[split][dev]) { - if (split) cudaFuncSetAttribute(gdn_tc_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplit); + if (dev >= 0 && dev < 64 && !attrs[ai][dev]) { + if (ai == 2) { + cudaFuncSetAttribute(gdn_tc_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplitNorm); + cudaFuncSetAttribute(gdn_tc_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplitNorm); + cudaFuncSetAttribute(gdn_tc_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplitNorm); + } else if (split) { + cudaFuncSetAttribute(gdn_tc_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplit); + cudaFuncSetAttribute(gdn_tc_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplit); + cudaFuncSetAttribute(gdn_tc_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplit); + } else cudaFuncSetAttribute(gdn_tc_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmem); - attrs[split][dev] = true; + attrs[ai][dev] = true; } } for (int64_t t0 = 0; t0 < T; t0 += GSB) { const int nch = (int) ((std::min(GSB, T - t0) + GCH - 1) / GCH); gdn_tc_prep_kernel<<>>(h, gate, beta, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, t0, T); - if (split) + if (nm && split) { +#define STRATA_TCN(NPV) gdn_tc_scan_kernel<<>>(state, h, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y, t0, nch, T, nm->z, nm->gamma, nm->eps, nm->y16, nm->ld16) + if (np == 2) STRATA_TCN(2); + else if (np == 1) STRATA_TCN(1); + else STRATA_TCN(3); +#undef STRATA_TCN + } else if (split && np == 2) + gdn_tc_scan_kernel<<>>(state, h, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y, t0, nch, T); + else if (split && np == 1) + gdn_tc_scan_kernel<<>>(state, h, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y, t0, nch, T); + else if (split) gdn_tc_scan_kernel<<>>(state, h, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y, t0, nch, T); else gdn_tc_scan_kernel<<, s>>>(state, h, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y, t0, nch, T); @@ -2808,6 +2835,7 @@ static void gdn_recurrence_impl(int variant, float* state, const float* h, const gdn_rec_kernel<<>>(state, h, gate, beta, z, gamma, eps, y, y16, T, ld16); } else { static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }(); + bool normed_any = false; // the tensor-core scan wrote y16 (the norm kernel below is skipped) #if !defined(__HIPCC__) // STRATA_GDN_CHUNKED=1 (opt-in): the recurrence in chunks for prompt chunks of kGdnChunkedMin+ tokens (other // bits; a shorter chunk, a card it does not fit or a failed scratch allocation takes the kernels below) @@ -2821,13 +2849,19 @@ static void gdn_recurrence_impl(int variant, float* state, const float* h, const GdnProbe* pr = gdn_probe_get(); const int force = pr ? pr->force : (int) kGdnAuto; int sel = kGdnNone, wanted = force; + bool normed = false; // the scan wrote y16 itself const char* why = ""; const cudaStream_t cs = (cudaStream_t) stream; + // the split tensor-core scan can write y16 itself (STRATA_GDN_TC_FUSE=0 off): then the norm kernel below is skipped + static const bool tc_fuse = [] { const char* v = std::getenv("STRATA_GDN_TC_FUSE"); return v == nullptr || std::atoi(v) != 0; }(); + const GdnTcNorm tcn = {z, gamma, eps, y16, ld16}; + const GdnTcNorm* tcnp = with_out && tc_fuse ? &tcn : nullptr; if (force != kGdnAuto) { - if (force == kGdnTc || force == kGdnTcSplit) { - const bool sp = force == kGdnTcSplit; - cudaError_t e = T >= kGdnTcMin ? gdn_rec_tc(state, h, gate, beta, y, T, cs, sp) : cudaErrorInvalidValue; - if (e == cudaSuccess) sel = force; + if (force == kGdnTc || force == kGdnTcSplit || force == kGdnTcS2 || force == kGdnTcS1) { + const bool sp = force != kGdnTc; + const int np = force == kGdnTcS2 ? 2 : force == kGdnTcS1 ? 1 : 3; + cudaError_t e = T >= kGdnTcMin ? gdn_rec_tc(state, h, gate, beta, y, T, cs, sp, np, sp ? tcnp : nullptr) : cudaErrorInvalidValue; + if (e == cudaSuccess) { sel = force; normed = sp && tcnp != nullptr; } else why = T < kGdnTcMin ? "T below the tc minimum (128)" : gdn_chunk_why(true, e, false, sp); } else if (force == kGdnChunked) { cudaError_t e = T >= kGdnChunkedMin ? gdn_rec_chunked(state, h, gate, beta, y, T, cs) : cudaErrorInvalidValue; @@ -2852,8 +2886,10 @@ static void gdn_recurrence_impl(int variant, float* state, const float* h, const if (e == cudaSuccess) sel = kGdnTc; else { // the 99-KB cards (sm_86 / 89 / 120): the single-buffered v / T / P plan if (pr) why = gdn_chunk_why(true, e, false); - e = gdn_rec_tc(state, h, gate, beta, y, T, cs, true); - if (e == cudaSuccess) { sel = kGdnTcSplit; why = ""; } + // STRATA_GDN_TC_NP=1|2 (experiment, not a default): fewer split passes a product on this plan, other bits + static const int tc_np = [] { const char* v = std::getenv("STRATA_GDN_TC_NP"); const int x = v ? std::atoi(v) : 3; return x == 1 || x == 2 ? x : 3; }(); + e = gdn_rec_tc(state, h, gate, beta, y, T, cs, true, tc_np, tcnp); + if (e == cudaSuccess) { sel = kGdnTcSplit; why = ""; normed = tcnp != nullptr; } } } if (sel == kGdnNone && chunked && T >= kGdnChunkedMin) { @@ -2877,6 +2913,7 @@ static void gdn_recurrence_impl(int variant, float* state, const float* h, const } } if (pr) { pr->selected = sel; pr->wanted = wanted == kGdnAuto ? sel : wanted; pr->reason = why; ++pr->calls; } + normed_any = normed; if (sel == kGdnNone) { check("gdn_recurrence (forced path not eligible: nothing launched)"); return; } #else if (pipe) // the software-pipelined loads (same bits) @@ -2884,7 +2921,7 @@ static void gdn_recurrence_impl(int variant, float* state, const float* h, const else gdn_rec_cols_kernel<<>>(state, h, gate, beta, y, T); #endif - if (with_out) + if (with_out && !normed_any) gdn_out_norm_kernel<<>>(z, gamma, eps, y, y16, ld16); } check("gdn_recurrence"); From d3af2d42ad55baee27073c2fa4e8af97bafe862c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 03:05:51 +0100 Subject: [PATCH 10/11] GDN: single-pass conv+SiLU+L2 (STRATA_GDN_CONVL2=2), output-only reduced-precision experiment mode (STRATA_GDN_TC_NP=2) --- src/prefill/gdn_tc.cuh | 27 +++++++++--------- src/prefill/kernels.cu | 62 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 75 insertions(+), 14 deletions(-) diff --git a/src/prefill/gdn_tc.cuh b/src/prefill/gdn_tc.cuh index eda8c354..145be94a 100644 --- a/src/prefill/gdn_tc.cuh +++ b/src/prefill/gdn_tc.cuh @@ -154,8 +154,9 @@ __device__ __forceinline__ void gtc_mma3_f16(float (&c)[4], const uint32_t (&ah) gtc_mma_f16(c, ah, bl0, bl1); gtc_mma_f16(c, ah, bh0, bh1); } -// NP passes of a split product (experiment, STRATA_GDN_TC split kernels only): 3 = the three above (the default); 2 = lo.hi and -// hi.hi (the A operand split, B in f16 only); 1 = hi.hi (plain f16 operands, as the gfx11 WMMA path). B's lo image is not read for NP < 3. +// 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.S and D.P) on one pass, the state's products (k.S, 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) { @@ -202,7 +203,7 @@ __device__ __forceinline__ float4 gtc_lds128(const float4* p) { // (tiles 2kk and 2kk + 1 of S^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 +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; @@ -219,13 +220,13 @@ __device__ __forceinline__ void gtc_prod_state(const float (&s)[16][4], float sA 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 (NP == 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]); + 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 (NP == 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]); + 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]); } } } @@ -540,7 +541,7 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const 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(s, gtc_pow2(es), bkh, bkl, bqh, bql, xt, qs); + 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)); @@ -564,7 +565,7 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const 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); + 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) @@ -585,7 +586,7 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const 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); + 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 @@ -658,7 +659,7 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const 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(s, dd, bkh, bkl); + gtc_update_state<(NP == 1 ? 1 : 3)>(s, dd, bkh, bkl); #pragma unroll for (int j = 0; j < 16; ++j) #pragma unroll diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 5eb8d6a1..5ecf1d85 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -398,6 +398,58 @@ __global__ void gdn_conv_l2_kernel(const float* __restrict__ hist, const float* __syncthreads(); } } +// STRATA_GDN_CONVL2=2: the conv, SiLU and q / k L2 norm in ONE pass, a warp per (head, run of CONVW_TOK tokens): a lane owns +// four consecutive channels of the head's 128 (a float4 each way), walks the tokens keeping the three previous inputs in +// registers, and the head's sum of squares is one 5-step warp reduction a token - no shared memory, no barrier, h written +// once, normalised. The conv + SiLU value is the expression of gdn_conv_tiled_kernel (same bits); the sum of squares is +// added in another order than gdn_l2_kernel's (FP32-level difference). The first three inputs of a run are re-read from +// qkv (L2 hits; 3 / CONVW_TOK extra reads). Bytes a token: 41 KB read, 41 KB written, against 114 KB for conv + l2. +constexpr int CONVW_TOK = 32; +__global__ void __launch_bounds__(128) gdn_conv_w_kernel(const float* __restrict__ hist, const float* __restrict__ qkv, + const float* __restrict__ w, float* __restrict__ h, int64_t T, + float eps) { + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int64_t tb = ((int64_t) blockIdx.y * 4 + warp) * CONVW_TOK; + if (tb >= T) return; + const int64_t te = tb + CONVW_TOK < T ? tb + CONVW_TOK : T; + const int c0 = blockIdx.x * 128 + lane * 4; + const bool norm = blockIdx.x < 2 * HK; // q / k heads + float wr[4][4]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int k = 0; k < 4; ++k) wr[i][k] = w[(c0 + i) * 4 + k]; + float4 p0, p1, p2; // inputs t - 3, t - 2, t - 1 + auto input = [&](int64_t t) -> float4 { + if (t >= 0) return *reinterpret_cast(qkv + t * C + c0); + return make_float4(hist[(c0 + 0) * 3 + (int) (t + 3)], hist[(c0 + 1) * 3 + (int) (t + 3)], + hist[(c0 + 2) * 3 + (int) (t + 3)], hist[(c0 + 3) * 3 + (int) (t + 3)]); + }; + p0 = input(tb - 3); p1 = input(tb - 2); p2 = input(tb - 1); +#pragma unroll 4 + for (int64_t t = tb; t < te; ++t) { + const float4 x = *reinterpret_cast(qkv + t * C + c0); + const float xv[4] = {x.x, x.y, x.z, x.w}, a0[4] = {p0.x, p0.y, p0.z, p0.w}, a1[4] = {p1.x, p1.y, p1.z, p1.w}, + a2[4] = {p2.x, p2.y, p2.z, p2.w}; + float o[4]; + float sq = 0.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const float s = a0[i] * wr[i][0] + a1[i] * wr[i][1] + a2[i] * wr[i][2] + xv[i] * wr[i][3]; + o[i] = s / (1.0f + __expf(-s)); + sq = fmaf(o[i], o[i], sq); + } + if (norm) { +#pragma unroll + for (int m = 16; m > 0; m >>= 1) sq += __shfl_xor_sync(0xffffffffu, sq, m); + const float rn = rsqrtf(sq + eps); +#pragma unroll + for (int i = 0; i < 4; ++i) o[i] *= rn; + } + *reinterpret_cast(h + t * C + c0) = make_float4(o[0], o[1], o[2], o[3]); + p0 = p1; p1 = p2; p2 = x; + } +} // the history after the chunk: its last three inputs (the older history where the chunk is shorter than 3) __global__ void gdn_conv_hist_kernel(float* __restrict__ hist, const float* __restrict__ qkv, int64_t T) { const int c = blockIdx.x * blockDim.x + threadIdx.x; @@ -2715,7 +2767,15 @@ void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, i if (serial || T <= CONV_TILE) { gdn_conv_kernel<<>>(history, qkv, conv_w, h, T); } else { - static const bool fused = [] { const char* v = std::getenv("STRATA_GDN_CONVL2"); return v && std::atoi(v) != 0; }(); + static const int fused_mode = [] { const char* v = std::getenv("STRATA_GDN_CONVL2"); return v ? std::atoi(v) : 0; }(); + const bool fused = fused_mode != 0; + if (fused_mode >= 2) { + gdn_conv_w_kernel<<>>(history, qkv, conv_w, h, T, eps); + gdn_conv_hist_kernel<<>>(history, qkv, T); + check("gdn_conv"); + return; + } if (fused) { gdn_conv_l2_kernel<<>>(history, qkv, conv_w, h, T, eps); From 714438ec19f688d4d35c4cb98d2bd9c8f16f0200 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 03:46:18 +0100 Subject: [PATCH 11/11] GDN TC: two value tiles per head on cards with >= 96 SMs (STRATA_GDN_TC_TILES), harness --tiles --- include/strata/prefill/gdn_probe.hpp | 1 + src/prefill/gdn_harness.cu | 3 ++ src/prefill/gdn_tc.cuh | 41 +++++++++++++++++----------- src/prefill/kernels.cu | 32 ++++++++++++++++++---- 4 files changed, 56 insertions(+), 21 deletions(-) diff --git a/include/strata/prefill/gdn_probe.hpp b/include/strata/prefill/gdn_probe.hpp index 2c58143a..ffc0288d 100644 --- a/include/strata/prefill/gdn_probe.hpp +++ b/include/strata/prefill/gdn_probe.hpp @@ -30,6 +30,7 @@ struct GdnProbe { // in int force = kGdnAuto; // kGdnAuto: dispatch as production does; otherwise only this path may run bool any_sms = false; // chunked: skip the 128-SM test, as STRATA_GDN_CHUNKED=2 does + int tc_tiles = 0; // tcs: value tiles a head (1, 2; 0 = STRATA_GDN_TC_TILES, else automatic: 2 on cards with >= 96 SMs) int gsb = 0; // chunked: tokens per scratch super-block (a multiple of 32, at most 2048; 0 = 2048) // out (set by every gdn_recurrence call made on the thread that installed the probe) int selected = kGdnNone; // the path that launched diff --git a/src/prefill/gdn_harness.cu b/src/prefill/gdn_harness.cu index c5f87a69..8bcbec3a 100644 --- a/src/prefill/gdn_harness.cu +++ b/src/prefill/gdn_harness.cu @@ -60,6 +60,7 @@ struct Args { int reps = 7, warmup = 2; bool any_sms = false; int gsb = 0; + int tiles = 0; bool fallback_incumbent = false; // a forced path takes the incumbent for calls it cannot run (mirrors production) int64_t ld16 = 0; FixtureSpec fx; @@ -164,6 +165,7 @@ RunOut run_path(Dev& d, const Args& a, const std::vector& calls, int pa sp::GdnProbe probe; probe.any_sms = a.any_sms; probe.gsb = a.gsb; + probe.tc_tiles = a.tiles; sp::gdn_probe_install(&probe); std::vector ev; if (timed) { @@ -415,6 +417,7 @@ int main(int argc, char** argv) { else if (k == "--warmup") a.warmup = std::atoi(val()); else if (k == "--any-sms") a.any_sms = true; else if (k == "--gsb") a.gsb = std::atoi(val()); + else if (k == "--tiles") a.tiles = std::atoi(val()); else if (k == "--fallback-incumbent") a.fallback_incumbent = true; else if (k == "--ld16") a.ld16 = parse_list(val())[0]; else if (k == "--state") a.fx.state = argv[++i]; diff --git a/src/prefill/gdn_tc.cuh b/src/prefill/gdn_tc.cuh index 145be94a..3f322e35 100644 --- a/src/prefill/gdn_tc.cuh +++ b/src/prefill/gdn_tc.cuh @@ -438,7 +438,7 @@ __global__ void __launch_bounds__(256) gdn_tc_prep_kernel(const float* __restric // 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 +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, @@ -449,7 +449,12 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const // 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"); - constexpr int NT = GTC_CW * 32; + // 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 S / NTL, (tile + 1) S / 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) @@ -464,7 +469,7 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const 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, qhd = vh % HK; + const int vh = blockIdx.x / NTL, qhd = vh % HK, cb = (blockIdx.x % NTL) * (S / 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) HV * S; // 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 @@ -479,7 +484,7 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const const uint16_t* img = kqg + ((size_t) ch * HK + qhd) * 4 * GCH * S; #pragma unroll for (int m = 0; m < 4 * GCH * S / 8 / NT; ++m) { - const int im = m >> 1, t = ((m & 1) * NT + tid) / (S / 8), r = (tid % (S / 8)) * 8; + const int pc = tid + NT * m, im = pc / (GCH * S / 8), t = (pc % (GCH * S / 8)) / (S / 8), r = (pc % (S / 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) * S + r)); } @@ -488,27 +493,31 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const } if (parts & 2) { #pragma unroll - for (int m = 0; m < GCH * S / 4 / NT; ++m) { - const int p = tid + NT * m, t = p / (S / 4), r = (p % (S / 4)) * 4; + for (int m = 0; m < GCH * (S / NTL) / 4 / NT; ++m) { + const int p = tid + NT * m, t = p / (S / NTL / 4), r = (p % (S / NTL / 4)) * 4; float* dst = sv + (bv * GCH + t) * GTC_VP + r; - if (t < n) gdn_cp16(dst, h + (c_t0 + t) * C + 2 * HK * S + vh * S + r); + if (t < n) gdn_cp16(dst, h + (c_t0 + t) * C + 2 * HK * S + vh * S + cb + r); else *reinterpret_cast(dst) = make_float4(0.0f, 0.0f, 0.0f, 0.0f); } - const int im = tid / (GCH * GCH / 8), t = (tid % (GCH * GCH / 8)) / (GCH / 8), i = (tid % (GCH / 8)) * 8; - const int64_t src = ((((int64_t) ch * HV + 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)); +#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 * HV + 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 + 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 S^T fragments: tile j = rows 8j..8j+7; s[j][0] = S[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) (8 * j + 2 * tig) * rs + (size_t) vh * S + c0 + gid; + const float* p = state + (size_t) (8 * j + 2 * tig) * rs + (size_t) vh * S + ca + gid; s[j][0] = p[0]; s[j][1] = p[rs]; s[j][2] = p[8]; s[j][3] = p[rs + 8]; } stage(0, 0, 3); @@ -619,7 +628,7 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const #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 * S + c0 + gid + 8 * (q >> 1)] = (ot[nt][q] * sOi) * out_scale; + if (t < n) oc_out[(c_t0 + t) * rs + (size_t) vh * S + 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) @@ -667,7 +676,7 @@ gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const } #pragma unroll for (int j = 0; j < 16; ++j) { - float* p = state + (size_t) (8 * j + 2 * tig) * rs + (size_t) vh * S + c0 + gid; + float* p = state + (size_t) (8 * j + 2 * tig) * rs + (size_t) vh * S + ca + gid; p[0] = s[j][0]; p[rs] = s[j][1]; p[8] = s[j][2]; p[rs + 8] = s[j][3]; } } diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 5ecf1d85..98903e26 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -1279,6 +1279,24 @@ cudaError_t gdn_rec_chunked(float* state, const float* h, const float* gate, con // STRATA_GDN_TC=1: gdn_rec_chunked with the scan on the tensor cores (gdn_tc_scan_kernel, gdn_tc.cuh) and the prep // that also writes its f16 images (gdn_tc_prep_kernel, scratch gdn_tc_scratch), 48 blocks of 256 threads in one wave. An error return means nothing was launched: the card is below // sm_80, has fewer than 48 SMs, or less than 122 KB of shared memory a block. +// value tiles a head for the split tensor-core scan: STRATA_GDN_TC_TILES=1|2 (or the probe's tc_tiles) asks; 1 otherwise +int gdn_tc_tiles() { + const GdnProbe* pr = gdn_probe_get(); + if (pr != nullptr && pr->tc_tiles > 0) return pr->tc_tiles >= 2 ? 2 : 1; + static const int e = [] { const char* v = std::getenv("STRATA_GDN_TC_TILES"); return v ? std::atoi(v) : 0; }(); + if (e > 0) return e >= 2 ? 2 : 1; + // automatic: two tiles when all 2 x 48 blocks fit the card in one wave (measured: PRO 5000 / 110 SMs rec 1.47x; A6000 / 84 SMs + // is 1.25x SLOWER with two tiles, its 96 blocks need a second wave) + static int sms_of[64] = {}; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return 1; } + if (sms_of[dev] == 0) { + int n = 0; + if (cudaDeviceGetAttribute(&n, cudaDevAttrMultiProcessorCount, dev) != cudaSuccess) { cudaGetLastError(); n = 1; } + sms_of[dev] = n; + } + return sms_of[dev] >= 2 * HV ? 2 : 1; +} // the output norm's operands, when the split scan fuses it (see gdn_tc_scan_kernel NORM) struct GdnTcNorm { const float* z; @@ -1288,7 +1306,7 @@ struct GdnTcNorm { int64_t ld16; }; cudaError_t gdn_rec_tc(float* state, const float* h, const float* gate, const float* beta, float* y, int64_t T, - cudaStream_t s, bool split = false, int np = 3, const GdnTcNorm* nm = nullptr) { + cudaStream_t s, bool split = false, int np = 3, const GdnTcNorm* nm = nullptr, int tiles = 1) { if (T <= 0) return cudaSuccess; { int dev = 0, major = 0, sms = 0, smem = 0; @@ -1313,6 +1331,7 @@ cudaError_t gdn_rec_tc(float* state, const float* h, const float* gate, const fl int dev = 0; cudaGetDevice(&dev); if (dev >= 0 && dev < 64 && !attrs[ai][dev]) { + if (split) cudaFuncSetAttribute(gdn_tc_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplit); if (ai == 2) { cudaFuncSetAttribute(gdn_tc_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplitNorm); cudaFuncSetAttribute(gdn_tc_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplitNorm); @@ -1329,7 +1348,9 @@ cudaError_t gdn_rec_tc(float* state, const float* h, const float* gate, const fl for (int64_t t0 = 0; t0 < T; t0 += GSB) { const int nch = (int) ((std::min(GSB, T - t0) + GCH - 1) / GCH); gdn_tc_prep_kernel<<>>(h, gate, beta, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, t0, T); - if (nm && split) { + if (tiles == 2 && split && !nm && np == 3) { + gdn_tc_scan_kernel<<>>(state, h, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y, t0, nch, T); + } else if (nm && split) { #define STRATA_TCN(NPV) gdn_tc_scan_kernel<<>>(state, h, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y, t0, nch, T, nm->z, nm->gamma, nm->eps, nm->y16, nm->ld16) if (np == 2) STRATA_TCN(2); else if (np == 1) STRATA_TCN(1); @@ -2915,12 +2936,13 @@ static void gdn_recurrence_impl(int variant, float* state, const float* h, const // the split tensor-core scan can write y16 itself (STRATA_GDN_TC_FUSE=0 off): then the norm kernel below is skipped static const bool tc_fuse = [] { const char* v = std::getenv("STRATA_GDN_TC_FUSE"); return v == nullptr || std::atoi(v) != 0; }(); const GdnTcNorm tcn = {z, gamma, eps, y16, ld16}; - const GdnTcNorm* tcnp = with_out && tc_fuse ? &tcn : nullptr; + const int tcl = gdn_tc_tiles(); + const GdnTcNorm* tcnp = with_out && tc_fuse && tcl == 1 ? &tcn : nullptr; // 2 tiles a head: the norm kernel (a head's norm spans both) if (force != kGdnAuto) { if (force == kGdnTc || force == kGdnTcSplit || force == kGdnTcS2 || force == kGdnTcS1) { const bool sp = force != kGdnTc; const int np = force == kGdnTcS2 ? 2 : force == kGdnTcS1 ? 1 : 3; - cudaError_t e = T >= kGdnTcMin ? gdn_rec_tc(state, h, gate, beta, y, T, cs, sp, np, sp ? tcnp : nullptr) : cudaErrorInvalidValue; + cudaError_t e = T >= kGdnTcMin ? gdn_rec_tc(state, h, gate, beta, y, T, cs, sp, np, sp ? tcnp : nullptr, sp ? tcl : 1) : cudaErrorInvalidValue; if (e == cudaSuccess) { sel = force; normed = sp && tcnp != nullptr; } else why = T < kGdnTcMin ? "T below the tc minimum (128)" : gdn_chunk_why(true, e, false, sp); } else if (force == kGdnChunked) { @@ -2948,7 +2970,7 @@ static void gdn_recurrence_impl(int variant, float* state, const float* h, const if (pr) why = gdn_chunk_why(true, e, false); // STRATA_GDN_TC_NP=1|2 (experiment, not a default): fewer split passes a product on this plan, other bits static const int tc_np = [] { const char* v = std::getenv("STRATA_GDN_TC_NP"); const int x = v ? std::atoi(v) : 3; return x == 1 || x == 2 ? x : 3; }(); - e = gdn_rec_tc(state, h, gate, beta, y, T, cs, true, tc_np, tcnp); + e = gdn_rec_tc(state, h, gate, beta, y, T, cs, true, tc_np, tcnp, tcl); if (e == cudaSuccess) { sel = kGdnTcSplit; why = ""; normed = tcnp != nullptr; } } }