From d4f15adf873b5a1901f2e5c55a2fe2c3400aa2fa Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 00:39:06 +0100 Subject: [PATCH 1/9] tests/hip: gdn_stage_bench, the GDN prompt stage (gates, conv, recurrence) per piece with output and state hashes --- CMakeLists.txt | 4 + tests/hip/gdn_stage_bench.cpp | 135 ++++++++++++++++++++++++++++++++++ 2 files changed, 139 insertions(+) create mode 100644 tests/hip/gdn_stage_bench.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index ee7e9f1b..fc5bb544 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1076,6 +1076,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_test(NAME hip_gdn_chunked_off COMMAND hip_gdn_chunked --off) add_test(NAME hip_gdn_chunked_default COMMAND hip_gdn_chunked --default) list(APPEND _strata_hip_tests hip_gdn_chunked hip_gdn_chunked_off hip_gdn_chunked_default) + # GDN prompt stage bench (gates + conv + recurrence, per-piece times and output/state hashes at 4K/16K/32K); a measurement + # tool, run by hand with the STRATA_GDN_* knobs under test - no add_test + add_executable(hip_gdn_stage_bench tests/hip/gdn_stage_bench.cpp) + target_link_libraries(hip_gdn_stage_bench PRIVATE strata_prefill strata_hip_runtime) # #313: the RDNA3 / RDNA3.5 WMMA dense GEMMs (opt-in STRATA_WMMA_GEMM=1) against a reference add_executable(hip_prefill_wmma_gemm_parity tests/hip/prefill_wmma_gemm_parity.cpp) target_include_directories(hip_prefill_wmma_gemm_parity PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src/prefill") diff --git a/tests/hip/gdn_stage_bench.cpp b/tests/hip/gdn_stage_bench.cpp new file mode 100644 index 00000000..8b9edf80 --- /dev/null +++ b/tests/hip/gdn_stage_bench.cpp @@ -0,0 +1,135 @@ +// GDN prompt stage bench (production-linked): one layer's gates + conv + recurrence/out through the public entry points, +// timed per piece, at the prompt lengths of the 4K / 16K / 32K tables. Unlike gdn_chunked --bench it sets NO environment: +// the STRATA_GDN_* knobs (and the arch defaults a real run would apply, passed by the caller) are read as they are, so one +// process measures one knob set. It prints a hash of the output rows and the final state, so an "exact" knob can be +// checked bit for bit against the default run, and a split-call hash (the prompt cut at an unaligned token, state carried) +// for the continuation gate. +// +// gdn_stage_bench [T ...] default T = 4096 16384 32768 +// env GDN_BENCH_REPS=N timed repeats (median), default 7 +// env GDN_BENCH_SPLIT=0 skip the split-call hash +#include "strata/prefill/kernels.hpp" +#include "strata/kernels/gfx_arch.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +constexpr int S = 128, HK = 16, HV = 48, C = 10240, ROW = HV * S; +void ck(cudaError_t e, const char* where) { + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", where, cudaGetErrorString(e)); std::exit(2); } +} +template X* up(const std::vector& v) { + X* p = nullptr; + ck(cudaMalloc(&p, v.size() * sizeof(X)), "malloc"); + ck(cudaMemcpy(p, v.data(), v.size() * sizeof(X), cudaMemcpyHostToDevice), "upload"); + return p; +} +template std::vector down(const X* p, size_t n) { + std::vector v(n); + ck(cudaMemcpy(v.data(), p, n * sizeof(X), cudaMemcpyDeviceToHost), "download"); + return v; +} +uint64_t fnv(const void* p, size_t n, uint64_t h = 1469598103934665603ull) { + const unsigned char* b = static_cast(p); + for (size_t i = 0; i < n; ++i) { h ^= b[i]; h *= 1099511628211ull; } + return h; +} +struct Rng { + std::mt19937 g{7}; + std::normal_distribution n{0, 1}; + std::uniform_real_distribution u{0, 1}; +}; +} + +int main(int argc, char** argv) { + std::vector lens; + for (int i = 1; i < argc; ++i) lens.push_back(std::atoll(argv[i])); + if (lens.empty()) lens = {4096, 16384, 32768}; + const char* rp = std::getenv("GDN_BENCH_REPS"); + const int reps = rp ? std::max(1, std::atoi(rp)) : 7; + const bool do_split = !(std::getenv("GDN_BENCH_SPLIT") && std::atoi(std::getenv("GDN_BENCH_SPLIT")) == 0); + int dev = 0; + cudaDeviceProp props{}; + ck(cudaGetDevice(&dev), "device"); ck(cudaGetDeviceProperties(&props, dev), "props"); + std::printf("device=%s CUs=%d\n", props.gcnArchName, props.multiProcessorCount); + for (const char* k : {"STRATA_GDN_CHUNKED", "STRATA_GDN_HEAD", "STRATA_GDN_PP", "STRATA_GDN_CONVL2", "STRATA_GDN_NOY", + "STRATA_GDN_CONV_SERIAL", "STRATA_GDN_REC_HEADS"}) + std::printf("env %s=%s\n", k, std::getenv(k) ? std::getenv(k) : "(unset)"); + const int64_t Tmax = *std::max_element(lens.begin(), lens.end()); + Rng r; + std::vector qkv(Tmax * C), ab(Tmax * 2 * HV), dt(HV), ssm_a(HV), cw(C * 4), hist0(C * 3), z(Tmax * ROW), gamma(S), + state0(S * ROW); + for (auto& x : qkv) x = r.n(r.g); + for (int64_t t = 0; t < Tmax; ++t) + for (int j = 0; j < HV; ++j) { ab[t * 2 * HV + j] = r.n(r.g) - 1; ab[t * 2 * HV + HV + j] = r.n(r.g); } + for (auto& x : dt) x = r.n(r.g); + for (auto& x : ssm_a) x = -(0.5f + r.u(r.g)); + for (auto& x : cw) x = 0.4f * r.n(r.g); + for (auto& x : hist0) x = r.n(r.g); + for (auto& x : z) x = r.n(r.g); + for (auto& x : gamma) x = 0.5f + r.u(r.g); + for (auto& x : state0) x = 0.05f * r.n(r.g); + auto dqkv = up(qkv), dab = up(ab), ddt = up(dt), dssm = up(ssm_a), dcw = up(cw), dz = up(z), dgamma = up(gamma); + std::vector().swap(qkv); std::vector().swap(z); + float *dgate = nullptr, *dbeta = nullptr, *dh = nullptr, *dhist = nullptr, *dstate = nullptr, *dy = nullptr; + uint16_t* dy16 = nullptr; + const int64_t ld = ROW + 8; + ck(cudaMalloc(&dgate, Tmax * HV * 4), "m"); ck(cudaMalloc(&dbeta, Tmax * HV * 4), "m"); + ck(cudaMalloc(&dh, Tmax * C * 4), "m"); ck(cudaMalloc(&dhist, C * 3 * 4), "m"); + ck(cudaMalloc(&dstate, S * ROW * 4), "m"); ck(cudaMalloc(&dy, Tmax * ROW * 4), "m"); + ck(cudaMalloc(&dy16, (Tmax * ld + 8) * 2), "m"); + cudaEvent_t e0, e1, e2; + ck(cudaEventCreate(&e0), "ev"); ck(cudaEventCreate(&e1), "ev"); ck(cudaEventCreate(&e2), "ev"); + auto reset = [&] { + ck(cudaMemcpy(dhist, hist0.data(), hist0.size() * 4, cudaMemcpyHostToDevice), "reset"); + ck(cudaMemcpy(dstate, state0.data(), state0.size() * 4, cudaMemcpyHostToDevice), "reset"); + }; + auto layer = [&](int64_t t0, int64_t n) { // the prompt-path order: gates, conv, recurrence (+ norm) + strata::prefill::gdn_gates(dab + t0 * 2 * HV, ddt, dssm, dgate + t0 * HV, dbeta + t0 * HV, n, nullptr); + strata::prefill::gdn_conv(dhist, dqkv + t0 * C, dcw, dh + t0 * C, n, 1e-6f, nullptr); + strata::prefill::gdn_recurrence(dstate, dh + t0 * C, dgate + t0 * HV, dbeta + t0 * HV, dz + t0 * ROW, dgamma, 1e-6f, + dy, dy16 + t0 * ld, n, nullptr, ld); + }; + for (int64_t T : lens) { + std::vector conv_ms, rec_ms; + for (int round = -2; round < reps; ++round) { + reset(); + ck(cudaEventRecord(e0), "ev"); + strata::prefill::gdn_gates(dab, ddt, dssm, dgate, dbeta, T, nullptr); + strata::prefill::gdn_conv(dhist, dqkv, dcw, dh, T, 1e-6f, nullptr); + ck(cudaEventRecord(e1), "ev"); + strata::prefill::gdn_recurrence(dstate, dh, dgate, dbeta, dz, dgamma, 1e-6f, dy, dy16, T, nullptr, ld); + ck(cudaEventRecord(e2), "ev"); + ck(cudaEventSynchronize(e2), "sync"); + float a = 0, b = 0; + ck(cudaEventElapsedTime(&a, e0, e1), "t"); ck(cudaEventElapsedTime(&b, e1, e2), "t"); + if (round >= 0) { conv_ms.push_back(a); rec_ms.push_back(b); } + } + std::sort(conv_ms.begin(), conv_ms.end()); std::sort(rec_ms.begin(), rec_ms.end()); + const double cm = conv_ms[conv_ms.size() / 2], rm = rec_ms[rec_ms.size() / 2]; + // hashes of one clean whole-prompt run (the state is the one-call result) + reset(); layer(0, T); ck(cudaDeviceSynchronize(), "sync"); + const auto y16 = down(dy16, T * ld), st = down(dstate, S * ROW); + uint64_t hy = 1469598103934665603ull; + for (int64_t t = 0; t < T; ++t) hy = fnv(y16.data() + t * ld, ROW * 2, hy); // padding columns excluded + const uint64_t hs = fnv(st.data(), st.size() * 4); + bool same = true; + if (do_split) { + const int64_t cut = (T / 2) | 1; // unaligned (odd) split point + reset(); layer(0, cut); layer(cut, T - cut); ck(cudaDeviceSynchronize(), "sync"); + const auto y2 = down(dy16, T * ld), s2 = down(dstate, S * ROW); + uint64_t hy2 = 1469598103934665603ull; + for (int64_t t = 0; t < T; ++t) hy2 = fnv(y2.data() + t * ld, ROW * 2, hy2); + same = hy == hy2 && hs == fnv(s2.data(), s2.size() * 4); + } + std::printf("STAGE T=%lld gates_conv_ms=%.4f rec_out_ms=%.4f sum_ms=%.4f y_hash=%016llx state_hash=%016llx split_same=%d\n", + (long long) T, cm, rm, cm + rm, (unsigned long long) hy, (unsigned long long) hs, same); + } + return 0; +} From ae2657a19d947c5ab0a213be61cbf34d7707f6e3 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 00:42:26 +0100 Subject: [PATCH 2/9] gdn_stage_bench: fix auto deduction --- tests/hip/gdn_stage_bench.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/hip/gdn_stage_bench.cpp b/tests/hip/gdn_stage_bench.cpp index 8b9edf80..00896c1f 100644 --- a/tests/hip/gdn_stage_bench.cpp +++ b/tests/hip/gdn_stage_bench.cpp @@ -115,7 +115,7 @@ int main(int argc, char** argv) { const double cm = conv_ms[conv_ms.size() / 2], rm = rec_ms[rec_ms.size() / 2]; // hashes of one clean whole-prompt run (the state is the one-call result) reset(); layer(0, T); ck(cudaDeviceSynchronize(), "sync"); - const auto y16 = down(dy16, T * ld), st = down(dstate, S * ROW); + const auto y16 = down(dy16, T * ld); const auto st = down(dstate, S * ROW); uint64_t hy = 1469598103934665603ull; for (int64_t t = 0; t < T; ++t) hy = fnv(y16.data() + t * ld, ROW * 2, hy); // padding columns excluded const uint64_t hs = fnv(st.data(), st.size() * 4); @@ -123,7 +123,7 @@ int main(int argc, char** argv) { if (do_split) { const int64_t cut = (T / 2) | 1; // unaligned (odd) split point reset(); layer(0, cut); layer(cut, T - cut); ck(cudaDeviceSynchronize(), "sync"); - const auto y2 = down(dy16, T * ld), s2 = down(dstate, S * ROW); + const auto y2 = down(dy16, T * ld); const auto s2 = down(dstate, S * ROW); uint64_t hy2 = 1469598103934665603ull; for (int64_t t = 0; t < T; ++t) hy2 = fnv(y2.data() + t * ld, ROW * 2, hy2); same = hy == hy2 && hs == fnv(s2.data(), s2.size() * 4); From f34ab1c8f51f2562069bafbee79181f5499064c0 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 00:55:55 +0100 Subject: [PATCH 3/9] GDN gfx11 WMMA: compile the device pass for gfx1103 too (the runtime gate lists it; the pass trapped there) --- src/prefill/kernels.cu | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 365d5a90..157f915d 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -1672,7 +1672,7 @@ __global__ void __launch_bounds__(S) gdn_out_norm_loop_kernel(const float* __res // (FP32), each product a 16 x 16 x 16 WMMA: k, q, T, P, D and the state as an operand are rounded to FP16 (relative // 2^-11), so the output differs from the FP32 kernels by more than their rounding (tests/hip/gdn_chunked.cpp holds it // to the bounds of its Error::ok). The norm and the z gate run in the scan. -#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || defined(__gfx1150__) || defined(__gfx1151__) #define STRATA_GDN_WMMA 1 // device pass with the gfx11 WMMA intrinsic (the list of gfx_arch_is_gfx11_wmma) #endif constexpr int GW_CK = 16; // tokens per chunk (a WMMA tile) From 4d9d9cefd303ea7113eec5ef29a978f12706ab5e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 00:59:13 +0100 Subject: [PATCH 4/9] GDN: the chunked WMMA recurrence on gfx12 (opt-in STRATA_GDN_CHUNKED=1), gfx12 fragment layout --- src/prefill/gdn_wmma12.inc | 212 +++++++++++++++++++++++++++++++++++++ src/prefill/kernels.cu | 14 ++- tests/hip/gdn_chunked.cpp | 2 +- 3 files changed, 224 insertions(+), 4 deletions(-) create mode 100644 src/prefill/gdn_wmma12.inc diff --git a/src/prefill/gdn_wmma12.inc b/src/prefill/gdn_wmma12.inc new file mode 100644 index 00000000..864c14f4 --- /dev/null +++ b/src/prefill/gdn_wmma12.inc @@ -0,0 +1,212 @@ +// Included by kernels.cu right after the gfx11 chunked-GDN kernels (it uses their constants, types and helpers). +// +// STRATA_GDN_CHUNKED=1 on gfx12 (RDNA4: R9700 / 9070 / 9060): the same chunked algorithm as the gfx11 kernels above, on +// the gfx12 matrix cores. The fragment layout differs from gfx11 (wave32, v_wmma_f32_16x16x16_f16; checked on an R9700 by +// results/gdn/GDN-A/micro/wmma12.cpp): A and B take 8 halves a lane, lane l holding row (A) or column (B) l & 15 and +// k = 8 * (l >> 4) + 0..7; the accumulator lane l holds column l & 15 and rows 8 * (l >> 4) + 0..7. So an accumulator IS the +// next product's B operand (an FP16 conversion only: no permlane / byte permute as on gfx11), and the row of accumulator +// element v is 8 * hi + v (gfx11: 2 * v + hi). Everything else (chunk of 16, FP16 operands, FP32 accumulate and state, the +// norm fused, T and P from a prep kernel) is the gfx11 design, so the numerics are the same class (FP16 operands). +#if defined(__gfx1200__) || defined(__gfx1201__) +#define STRATA_GDN_WMMA12 1 +#endif +__device__ __forceinline__ gw_f8 gw_mma12(gw_h8 a, gw_h8 b, gw_f8 c) { +#if defined(STRATA_GDN_WMMA12) + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); +#else + (void) a; (void) b; (void) c; + __builtin_trap(); // not a gfx12 device pass: the runtime gate never launches it +#endif +} +__device__ __forceinline__ gw_h8 gw_acc_to_b12(gw_f8 x) { + gw_h8 r; +#pragma unroll + for (int i = 0; i < 8; ++i) r[i] = (_Float16) x[i]; + return r; +} +__device__ __forceinline__ gw_h8 gw_ld8(const _Float16* p) { return *reinterpret_cast(p); } // 16 bytes of LDS + +__global__ void __launch_bounds__(32 * GW_VPK) gdn_w12_prep_kernel(const float* __restrict__ h, const float* __restrict__ gate, + const float* __restrict__ beta, _Float16* __restrict__ tp, + int64_t T) { + __shared__ float sa[GW_VPK][GW_CK * GW_CK], sg[GW_VPK][GW_CK], sb[GW_VPK][GW_CK]; + const int qh = blockIdx.x, ch = blockIdx.y, w = threadIdx.x >> 5, l = threadIdx.x & 31, c = l & 15, hi = l >> 4; + const int vh = qh + w * HK; + const int64_t t0 = (int64_t) ch * GW_CK; + gw_f8 kk = {}, qk = {}; // k_t.k_i and q_t.k_i (lane: column i = c, rows t = 8 * hi + v) + { + const bool ok = t0 + c < T; // past the end: zero rows + const float* ht = h + (ok ? t0 + c : 0) * C; +#pragma unroll + for (int j = 0; j < S / 16; ++j) { + gw_h8 ka, qa; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const gw_f4 k4 = *reinterpret_cast(ht + HK * S + qh * S + 16 * j + 8 * hi + 4 * i); + const gw_f4 q4 = *reinterpret_cast(ht + qh * S + 16 * j + 8 * hi + 4 * i); +#pragma unroll + for (int e = 0; e < 4; ++e) { + ka[4 * i + e] = (_Float16) (ok ? k4[e] : 0.0f); + qa[4 * i + e] = (_Float16) (ok ? q4[e] : 0.0f); + } + } + kk = gw_mma12(ka, ka, kk); // B = K^T: lane i holds column i of K^T = row i of K, the A operand itself + qk = gw_mma12(qa, ka, qk); + } + } + if (l < GW_CK) { // past the end: gate 0, beta 0 + const bool ok = t0 + l < T; + float g = ok ? gate[(t0 + l) * HV + vh] : 0.0f; +#pragma unroll + for (int o = 1; o < GW_CK; o <<= 1) { + const float u = __shfl_up(g, o, GW_CK); + if (l >= o) g += u; + } + sg[w][l] = g; + sb[w][l] = ok ? beta[(t0 + l) * HV + vh] : 0.0f; + } + __syncthreads(); + _Float16* out = tp + ((int64_t) ch * HV + vh) * (2 * GW_CK * GW_CK); +#pragma unroll + for (int v = 0; v < 8; ++v) { + const int t = 8 * hi + v; + sa[w][t * GW_CK + c] = c < t ? sb[w][t] * __expf(sg[w][t] - sg[w][c]) * kk[v] : 0.0f; + out[GW_CK * GW_CK + t * GW_CK + c] = (_Float16) (c <= t ? __expf(sg[w][t] - sg[w][c]) * qk[v] : 0.0f); + } + __syncthreads(); + if (l < GW_CK) { // lane c: column c of T = (I + A)^-1 by forward substitution + float tc[GW_CK]; +#pragma unroll + for (int t = 0; t < GW_CK; ++t) { + float v = t == c ? 1.0f : 0.0f; +#pragma unroll + for (int k = 0; k < t; ++k) v = fmaf(-sa[w][t * GW_CK + k], tc[k], v); + tc[t] = v; + out[t * GW_CK + c] = (_Float16) v; + } + } +} + +__global__ void __launch_bounds__(GW_NW * 32) gdn_w12_scan_kernel(float* __restrict__ state, const float* __restrict__ h, + const float* __restrict__ gate, const float* __restrict__ beta, + const float* __restrict__ z, const float* __restrict__ gamma, + const unsigned* __restrict__ tp, float eps, + uint16_t* __restrict__ y16, int64_t T, int64_t ld16) { + __shared__ __attribute__((aligned(16))) _Float16 sk[GW_CK * GW_KP], sq[GW_CK * GW_KP], skt[S * GW_CK], + stp[2 * GW_CK * GW_CK]; + __shared__ __attribute__((aligned(16))) float sv[GW_CK * S], so[GW_CK * S], sn[GW_CK * GW_NW]; + __shared__ float sg[GW_CK], sb[GW_CK], sgam[S]; + const _Float16 *st_ = stp, *sp_ = stp + GW_CK * GW_CK; // T, P + const int vh = blockIdx.x, qh = vh % HK, w = threadIdx.x >> 5, l = threadIdx.x & 31, c = l & 15, hi = l >> 4; + const int col = 16 * w + c; + const int st = threadIdx.x >> 4, sr = (threadIdx.x & 15) * 8; + const size_t rs = (size_t) HV * S; + gw_f8 s[S / 16]; // the state: rows 16j + 8 * hi + v, column col +#pragma unroll + for (int j = 0; j < S / 16; ++j) +#pragma unroll + for (int v = 0; v < 8; ++v) s[j][v] = state[(size_t) (16 * j + 8 * hi + v) * rs + (size_t) vh * S + col]; + if (threadIdx.x < S) sgam[threadIdx.x] = gamma[threadIdx.x]; + const float out_scale = rsqrtf((float) S); + GwChunk cur; + gw_load(cur, h, gate, beta, tp, 0, T, vh, qh); + unsigned touched = 0; + gw_f4 z0 = {}, z1 = {}; + auto store_rows = [&](int64_t c0) { + if (c0 + st >= T) return; + const float* o = &so[st * S + sr]; + gw_h8 r; +#pragma unroll + for (int i = 0; i < 8; ++i) r[i] = (_Float16) (o[i] * sigm(i < 4 ? z0[i] : z1[i - 4])); + *reinterpret_cast(y16 + (c0 + st) * ld16 + vh * S + sr) = __builtin_bit_cast(uint4, r); + }; + for (int64_t t0 = 0; t0 < T; t0 += GW_CK) { + { // stage this chunk + gw_h8 kh, qq; +#pragma unroll + for (int i = 0; i < 8; ++i) { + kh[i] = (_Float16) (i < 4 ? cur.k0[i] : cur.k1[i - 4]); + qq[i] = (_Float16) (i < 4 ? cur.q0[i] : cur.q1[i - 4]); + skt[(sr + i) * GW_CK + st] = kh[i]; + } + *reinterpret_cast(&sk[st * GW_KP + sr]) = __builtin_bit_cast(uint4, kh); + *reinterpret_cast(&sq[st * GW_KP + sr]) = __builtin_bit_cast(uint4, qq); + *reinterpret_cast(&sv[st * S + sr]) = cur.v0; + *reinterpret_cast(&sv[st * S + sr + 4]) = cur.v1; + reinterpret_cast(stp)[threadIdx.x] = cur.tp; + if (threadIdx.x < GW_CK) { // past the end: gate 0, beta 0 + const bool ok = t0 + l < T; + float g = ok ? cur.g : 0.0f; +#pragma unroll + for (int o = 1; o < GW_CK; o <<= 1) { + const float u = __shfl_up(g, o, GW_CK); + if (l >= o) g += u; + } + sg[l] = g; + sb[l] = ok ? cur.b : 0.0f; + } + } + if (t0 + GW_CK < T) gw_load(cur, h, gate, beta, tp, t0 + GW_CK, T, vh, qh); + const unsigned touch_now = gw_touch(h, z, t0 + GW_AHEAD * GW_CK, T, vh, qh); + __syncthreads(); // (1) this chunk staged; the previous chunk's norm in so + if (t0 > 0) store_rows(t0 - GW_CK); + __asm__ volatile("" ::"v"(touched)); + touched = touch_now; + { + const int64_t tz = std::min(t0 + st, T - 1); + z0 = *reinterpret_cast(z + tz * HV * S + vh * S + sr); + z1 = *reinterpret_cast(z + tz * HV * S + vh * S + sr + 4); + } + gw_f8 x = {}, qs = {}; // K S0 and Q S0, this wave's columns +#pragma unroll + for (int j = 0; j < S / 16; ++j) { + const gw_h8 b = gw_acc_to_b12(s[j]); + x = gw_mma12(gw_ld8(sk + c * GW_KP + 16 * j + 8 * hi), b, x); + qs = gw_mma12(gw_ld8(sq + c * GW_KP + 16 * j + 8 * hi), b, qs); + } + gw_f8 y; +#pragma unroll + for (int v = 0; v < 8; ++v) { + const int t = 8 * hi + v; + y[v] = sb[t] * (sv[t * S + col] - __expf(sg[t]) * x[v]); + } + const gw_f8 d = gw_mma12(gw_ld8(st_ + c * GW_CK + 8 * hi), gw_acc_to_b12(y), gw_f8{}); + gw_f8 o; +#pragma unroll + for (int v = 0; v < 8; ++v) o[v] = __expf(sg[8 * hi + v]) * qs[v]; + o = gw_mma12(gw_ld8(sp_ + c * GW_CK + 8 * hi), gw_acc_to_b12(d), o); +#pragma unroll + for (int v = 0; v < 8; ++v) { + o[v] *= out_scale; + float p = o[v] * o[v]; +#pragma unroll + for (int m = 1; m < 16; m <<= 1) p += __shfl_xor(p, m); + if (c == 0) sn[(8 * hi + v) * GW_NW + w] = p; + } + const float gl = sg[GW_CK - 1]; + gw_f8 dd; +#pragma unroll + for (int v = 0; v < 8; ++v) dd[v] = __expf(gl - sg[8 * hi + v]) * d[v]; + const gw_h8 db = gw_acc_to_b12(dd); + const float eg = __expf(gl); +#pragma unroll + for (int j = 0; j < S / 16; ++j) s[j] = gw_mma12(gw_ld8(skt + (16 * j + c) * GW_CK + 8 * hi), db, s[j] * eg); + __syncthreads(); // (2) the sums of o^2 + const float g_col = sgam[col]; +#pragma unroll + for (int v = 0; v < 8; ++v) { + const int t = 8 * hi + v; + const gw_f4 n0 = *reinterpret_cast(&sn[t * GW_NW]), n1 = *reinterpret_cast(&sn[t * GW_NW + 4]); + const float ss = n0[0] + n0[1] + n0[2] + n0[3] + n1[0] + n1[1] + n1[2] + n1[3]; + so[t * S + col] = o[v] * rsqrtf(ss * (1.0f / S) + eps) * g_col; + } + } + __asm__ volatile("" ::"v"(touched)); + __syncthreads(); + store_rows((T - 1) / GW_CK * GW_CK); + __asm__ volatile("" : "+s"(state)); +#pragma unroll + for (int j = 0; j < S / 16; ++j) +#pragma unroll + for (int v = 0; v < 8; ++v) state[(size_t) (16 * j + 8 * hi + v) * rs + (size_t) vh * S + col] = s[j][v]; +} diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 157f915d..9e8987ca 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -1970,7 +1970,8 @@ __global__ void __launch_bounds__(GW_NW * 32) gdn_wmma_scan_kernel(float* __rest #pragma unroll for (int v = 0; v < 8; ++v) state[(size_t) (16 * j + 2 * v + hi) * rs + (size_t) vh * S + col] = s[j][v]; } -// The opt-in chunked recurrence on gfx11 (STRATA_GDN_CHUNKED=1): false (nothing launched) on another part. y, the +#include "gdn_wmma12.inc" +// The opt-in chunked recurrence on gfx11 and gfx12 (STRATA_GDN_CHUNKED=1): false (nothing launched) on another part. y, the // FP32 scratch of the other kernels (T x 6144 floats), holds T and P (1 KB per chunk and value head: T x 3 KB). bool gdn_rec_wmma(float* state, const float* h, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, cudaStream_t s, int64_t ld16) { @@ -1978,18 +1979,25 @@ bool gdn_rec_wmma(float* state, const float* h, const float* gate, const float* // A layer-split worker can change devices: a process-wide answer for the first card can launch a trapping // gfx11 kernel on a later gfx12 card. Cache only the current thread's last device, as properties are not cheap. static thread_local int last_device = -1; - static thread_local bool gfx11 = false; + static thread_local bool gfx11 = false, gfx12 = false; int dev = 0; if (cudaGetDevice(&dev) != cudaSuccess) return false; if (dev != last_device) { cudaDeviceProp p{}; if (cudaGetDeviceProperties(&p, dev) != cudaSuccess) return false; gfx11 = strata::kernels::gfx_arch_is_gfx11_wmma(p.gcnArchName); + gfx12 = strata::kernels::gfx_arch_is_gfx12_wmma(p.gcnArchName); last_device = dev; } - if (!gfx11) return false; + if (!gfx11 && !gfx12) return false; const int64_t nch = (T + GW_CK - 1) / GW_CK; _Float16* tp = reinterpret_cast<_Float16*>(y); + if (gfx12) { + gdn_w12_prep_kernel<<>>(h, gate, beta, tp, T); + gdn_w12_scan_kernel<<>>(state, h, gate, beta, z, gamma, reinterpret_cast(tp), eps, + y16, T, ld16); + return true; + } gdn_wmma_prep_kernel<<>>(h, gate, beta, tp, T); gdn_wmma_scan_kernel<<>>(state, h, gate, beta, z, gamma, reinterpret_cast(tp), eps, y16, T, ld16); diff --git a/tests/hip/gdn_chunked.cpp b/tests/hip/gdn_chunked.cpp index a0f29cf2..4a5fe5dd 100644 --- a/tests/hip/gdn_chunked.cpp +++ b/tests/hip/gdn_chunked.cpp @@ -202,7 +202,7 @@ int main(int argc, char** argv) { int device = 0; cudaDeviceProp props{}; ck(cudaGetDevice(&device), "device"); ck(cudaGetDeviceProperties(&props, device), "properties"); - const bool wmma = strata::kernels::gfx_arch_is_gfx11_wmma(props.gcnArchName); + const bool wmma = strata::kernels::gfx_arch_is_gfx11_wmma(props.gcnArchName) || strata::kernels::gfx_arch_is_gfx12_wmma(props.gcnArchName); std::printf("device=%s chunked=%d wmma=%d\n", props.gcnArchName, !off, wmma); if (argc > 1 && std::strcmp(argv[1], "--bench") == 0) { bench("chunked"); return 0; } if (bench_default) { bench("default"); return 0; } From 5e9995d296070c3d86462069be5bd8119c97e10e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 01:33:37 +0100 Subject: [PATCH 5/9] GDN gfx12: LDS-only barrier in the chunked scan; conv + SiLU + q/k norm folded into the chunked kernels (opt-in STRATA_GDN_CHUNKED=1, STRATA_GDN_FUSE=0 off), bench check mode --- include/strata/prefill/kernels.hpp | 5 + src/prefill/gdn_wmma12.inc | 23 ++- src/prefill/gdn_wmma12f.inc | 306 +++++++++++++++++++++++++++++ src/prefill/kernels.cu | 61 +++++- src/prefill/prefill.cpp | 24 ++- tests/hip/gdn_stage_bench.cpp | 64 +++++- 6 files changed, 470 insertions(+), 13 deletions(-) create mode 100644 src/prefill/gdn_wmma12f.inc diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp index 9be33b71..0244c8dc 100644 --- a/include/strata/prefill/kernels.hpp +++ b/include/strata/prefill/kernels.hpp @@ -75,6 +75,11 @@ void gdn_recurrence(float* state, const float* h, const float* gate, const float void gdn_recurrence_variant(int variant, float* state, const float* h, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream, int64_t ld16 = 0); +/// HIP gfx12 only, STRATA_GDN_CHUNKED=1 (STRATA_GDN_FUSE=0 off): gdn_conv + gdn_recurrence in one go, the conv read inside the +/// chunked kernels (no h buffer). Returns false, having launched nothing, when it does not apply: the caller then calls the two. +bool gdn_conv_recurrence_fused(float* history, const float* qkv, const float* conv_w, float* state, const float* gate, + const float* beta, const float* z, const float* gamma, float eps, float l2eps, float* y, + uint16_t* y16, int64_t T, void* stream, int64_t ld16 = 0); /// KVA (CUDA/HIP only): the same recurrence kernels as gdn_recurrence, bit for bit, without the output /// normalization: state, h, gate, beta and the scratch `y` only. The output projection and the gated residual /// write have no consumer when only the state advances, and their input (z, the gate projection) is not needed diff --git a/src/prefill/gdn_wmma12.inc b/src/prefill/gdn_wmma12.inc index 864c14f4..264e21eb 100644 --- a/src/prefill/gdn_wmma12.inc +++ b/src/prefill/gdn_wmma12.inc @@ -24,6 +24,22 @@ __device__ __forceinline__ gw_h8 gw_acc_to_b12(gw_f8 x) { for (int i = 0; i < 8; ++i) r[i] = (_Float16) x[i]; return r; } +// A barrier over LDS only (LB): __syncthreads() is a workgroup fence over all memory, which also waits for the global loads of the +// next chunk that the scan keeps in flight (the same reason gfx11 has gw_lds_barrier). gfx12: wait for this wave's LDS accesses +// (DScnt), then the barrier; the compiler still waits for each load before its first use. +template __device__ __forceinline__ void gw12_barrier() { +#if defined(STRATA_GDN_WMMA12) + if (LB) { + __asm__ volatile("s_wait_dscnt 0x0" ::: "memory"); + __builtin_amdgcn_s_barrier(); + __asm__ volatile("" ::: "memory"); + } else { + __syncthreads(); + } +#else + __syncthreads(); +#endif +} __device__ __forceinline__ gw_h8 gw_ld8(const _Float16* p) { return *reinterpret_cast(p); } // 16 bytes of LDS __global__ void __launch_bounds__(32 * GW_VPK) gdn_w12_prep_kernel(const float* __restrict__ h, const float* __restrict__ gate, @@ -87,6 +103,7 @@ __global__ void __launch_bounds__(32 * GW_VPK) gdn_w12_prep_kernel(const float* } } +template __global__ void __launch_bounds__(GW_NW * 32) gdn_w12_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const float* __restrict__ gate, const float* __restrict__ beta, const float* __restrict__ z, const float* __restrict__ gamma, @@ -148,7 +165,7 @@ __global__ void __launch_bounds__(GW_NW * 32) gdn_w12_scan_kernel(float* __restr } if (t0 + GW_CK < T) gw_load(cur, h, gate, beta, tp, t0 + GW_CK, T, vh, qh); const unsigned touch_now = gw_touch(h, z, t0 + GW_AHEAD * GW_CK, T, vh, qh); - __syncthreads(); // (1) this chunk staged; the previous chunk's norm in so + gw12_barrier(); // (1) this chunk staged; the previous chunk's norm in so if (t0 > 0) store_rows(t0 - GW_CK); __asm__ volatile("" ::"v"(touched)); touched = touch_now; @@ -191,7 +208,7 @@ __global__ void __launch_bounds__(GW_NW * 32) gdn_w12_scan_kernel(float* __restr const float eg = __expf(gl); #pragma unroll for (int j = 0; j < S / 16; ++j) s[j] = gw_mma12(gw_ld8(skt + (16 * j + c) * GW_CK + 8 * hi), db, s[j] * eg); - __syncthreads(); // (2) the sums of o^2 + gw12_barrier(); // (2) the sums of o^2 const float g_col = sgam[col]; #pragma unroll for (int v = 0; v < 8; ++v) { @@ -202,7 +219,7 @@ __global__ void __launch_bounds__(GW_NW * 32) gdn_w12_scan_kernel(float* __restr } } __asm__ volatile("" ::"v"(touched)); - __syncthreads(); + gw12_barrier(); store_rows((T - 1) / GW_CK * GW_CK); __asm__ volatile("" : "+s"(state)); #pragma unroll diff --git a/src/prefill/gdn_wmma12f.inc b/src/prefill/gdn_wmma12f.inc new file mode 100644 index 00000000..c51691fb --- /dev/null +++ b/src/prefill/gdn_wmma12f.inc @@ -0,0 +1,306 @@ +// Included by kernels.cu after gdn_wmma12.inc. The gfx12 chunked GDN with the causal conv + SiLU + q/k L2 norm folded in: +// the two kernels read the conv's RAW input (the qkv projection, plus the 3-token history in front of the first token) and +// no h buffer is written or read back (41 KB a token in each direction at 10240 FP32 channels). The arithmetic is the +// unfused path's: the conv in FP32 (four taps, SiLU), the q/k heads normalised with rsqrtf(sum + eps) before their FP16 +// rounding for the matrix cores, v kept FP32. The history is rewritten afterwards by gdn_conv_hist_kernel. +// prep: block (key head, chunk): the 16 tokens' q and k conv'd into LDS (cooperatively, once for the three value heads), +// normalised, then the gdn_w12_prep_kernel body reading its A / B operands from LDS. +// scan: block per value head; per chunk the 19 raw rows (3 history + 16) of its q, k and v channels are staged in LDS +// (a chunk ahead in registers), k / q conv'd and normalised into the FP16 operands, v conv'd where it is used. +#if defined(__HIPCC__) +constexpr int GF_ROWS = GW_CK + 3; // raw rows of a chunk: 3 history + 16 +constexpr int GF_RS = 3 * S + 4; // the scan's raw row stride (q | k | v), floats +constexpr int GF_RAWV = (GF_ROWS * 3 * S / 4 + 255) / 256; // f4 slots a thread keeps for the next chunk: 8 +__device__ __forceinline__ float gf_silu(float s) { return s / (1.0f + __expf(-s)); } + +__global__ void __launch_bounds__(128) gdn_w12f_prep_kernel(const float* __restrict__ hist, const float* __restrict__ qkv, + const float* __restrict__ cw, const float* __restrict__ gate, + const float* __restrict__ beta, _Float16* __restrict__ tp, int64_t T, + float eps) { + constexpr int RS = 2 * S + 1; // padded LDS row (q 0..127, k 128..255) + __shared__ float sc[GW_CK * RS]; + __shared__ float sinv[GW_CK][2]; + __shared__ float sa[GW_VPK][GW_CK * GW_CK], sg[GW_VPK][GW_CK], sb[GW_VPK][GW_CK]; + const int qh = blockIdx.x, ch = blockIdx.y, tid = threadIdx.x, w = tid >> 5, l = tid & 31, c = l & 15, hi = l >> 4; + const int64_t t0 = (int64_t) ch * GW_CK; + for (int idx = tid; idx < GW_CK * 2 * S; idx += 128) { // conv + SiLU of the 16 tokens x 256 channels (coalesced) + const int tt = idx >> 8, cc = idx & 255; + const int chn = cc < S ? qh * S + cc : HK * S + qh * S + (cc - S); + const int64_t t = t0 + tt; + float v = 0.0f; + if (t < T) { + const float4 wv = *reinterpret_cast(cw + (size_t) chn * 4); + auto in = [&](int64_t u) -> float { return u >= 0 ? qkv[u * C + chn] : hist[chn * 3 + (int) (u + 3)]; }; + const float s = in(t - 3) * wv.x + in(t - 2) * wv.y + in(t - 1) * wv.z + in(t) * wv.w; + v = gf_silu(s); + } + sc[tt * RS + cc] = v; + } + __syncthreads(); + if (tid < 2 * GW_CK) { // token tid >> 1, part tid & 1 (0 = q, 1 = k): the head's sum of squares + const float* r = sc + (tid >> 1) * RS + (tid & 1) * S; + float ss = 0.0f; + for (int i = 0; i < S; ++i) ss = fmaf(r[i], r[i], ss); + sinv[tid >> 1][tid & 1] = rsqrtf(ss + eps); + } + __syncthreads(); + const bool act = w < GW_VPK; // the fourth wave only helped with the conv; it still takes every barrier + const int vh = qh + w * HK; + gw_f8 kk = {}, qk = {}; + if (act) { + const float ik = sinv[c][1], iq = sinv[c][0]; +#pragma unroll + for (int j = 0; j < S / 16; ++j) { + gw_h8 ka, qa; +#pragma unroll + for (int e = 0; e < 8; ++e) { + ka[e] = (_Float16) (sc[c * RS + S + 16 * j + 8 * hi + e] * ik); + qa[e] = (_Float16) (sc[c * RS + 16 * j + 8 * hi + e] * iq); + } + kk = gw_mma12(ka, ka, kk); + qk = gw_mma12(qa, ka, qk); + } + } + if (act && l < GW_CK) { + const bool ok = t0 + l < T; + float g = ok ? gate[(t0 + l) * HV + vh] : 0.0f; +#pragma unroll + for (int o = 1; o < GW_CK; o <<= 1) { + const float u = __shfl_up(g, o, GW_CK); + if (l >= o) g += u; + } + sg[w][l] = g; + sb[w][l] = ok ? beta[(t0 + l) * HV + vh] : 0.0f; + } + __syncthreads(); + _Float16* out = tp + ((int64_t) ch * HV + vh) * (2 * GW_CK * GW_CK); + if (act) { +#pragma unroll + for (int v = 0; v < 8; ++v) { + const int t = 8 * hi + v; + sa[w][t * GW_CK + c] = c < t ? sb[w][t] * __expf(sg[w][t] - sg[w][c]) * kk[v] : 0.0f; + out[GW_CK * GW_CK + t * GW_CK + c] = (_Float16) (c <= t ? __expf(sg[w][t] - sg[w][c]) * qk[v] : 0.0f); + } + } + __syncthreads(); + if (act && l < GW_CK) { + float tc[GW_CK]; +#pragma unroll + for (int t = 0; t < GW_CK; ++t) { + float v = t == c ? 1.0f : 0.0f; +#pragma unroll + for (int k = 0; k < t; ++k) v = fmaf(-sa[w][t * GW_CK + k], tc[k], v); + tc[t] = v; + out[t * GW_CK + c] = (_Float16) v; + } + } +} + +// The raw rows of the chunk at t0 (rows t0 - 3 .. t0 + 15 of the qkv projection; rows before the prompt come from the +// history; rows past the end repeat the last row: finite, their gate and beta are 0), 8 f4 a thread, and its gate / beta. +struct GfChunk { + gw_f4 raw[GF_RAWV]; + float g, b; + unsigned tp; +}; +__device__ __forceinline__ void gf_load(GfChunk& in, const float* __restrict__ hist, const float* __restrict__ qkv, + const float* __restrict__ gate, const float* __restrict__ beta, + const unsigned* __restrict__ tp, int64_t t0, int64_t T, int vh, int qh) { + in.tp = tp[((t0 / GW_CK) * HV + vh) * (GW_CK * GW_CK) + threadIdx.x]; +#pragma unroll + for (int m = 0; m < GF_RAWV; ++m) { + const int idx = threadIdx.x + 256 * m; + gw_f4 r = {}; + if (idx < GF_ROWS * 96) { + const int row = idx / 96, f = idx % 96, seg = f >> 5, within = (f & 31) * 4; + const int chn = (seg == 0 ? qh * S : seg == 1 ? HK * S + qh * S : 2 * HK * S + vh * S) + within; + const int64_t t = t0 - 3 + row; + if (t >= 0) { + r = *reinterpret_cast(qkv + std::min(t, T - 1) * C + chn); + } else { +#pragma unroll + for (int e = 0; e < 4; ++e) r[e] = hist[(chn + e) * 3 + (int) (t + 3)]; + } + } + in.raw[m] = r; + } + if (threadIdx.x < GW_CK) { + const int64_t tl = std::min(t0 + threadIdx.x, T - 1); + in.g = gate[tl * HV + vh]; + in.b = beta[tl * HV + vh]; + } +} +// the cache warm-up of a later chunk: this block's q, k, v rows (96 f4 lines of 128 bytes each... one line a thread) and z +__device__ __forceinline__ unsigned gf_touch(const float* __restrict__ qkv, const float* __restrict__ z, int64_t t0, int64_t T, + int vh, int qh) { + const int t = threadIdx.x >> 4, part = threadIdx.x & 15, kind = part >> 2; + if (t0 + t >= T) return 0u; + const float* p = kind == 0 ? qkv + (t0 + t) * C + HK * S + qh * S + : kind == 1 ? qkv + (t0 + t) * C + qh * S + : kind == 2 ? qkv + (t0 + t) * C + 2 * HK * S + vh * S + : z + (t0 + t) * HV * S + vh * S; + return __float_as_uint(p[32 * (part & 3)]); +} + +template +__global__ void __launch_bounds__(GW_NW * 32) gdn_w12f_scan_kernel(float* __restrict__ state, const float* __restrict__ hist, + const float* __restrict__ qkv, const float* __restrict__ cw, + const float* __restrict__ gate, const float* __restrict__ beta, + const float* __restrict__ z, const float* __restrict__ gamma, + const unsigned* __restrict__ tp, float eps, float l2eps, + uint16_t* __restrict__ y16, int64_t T, int64_t ld16) { + __shared__ __attribute__((aligned(16))) _Float16 sk[GW_CK * GW_KP], sq[GW_CK * GW_KP], skt[S * GW_CK], stp[2 * GW_CK * GW_CK]; + __shared__ __attribute__((aligned(16))) float sraw[GF_ROWS * GF_RS], so[GW_CK * S], sn[GW_CK * GW_NW], swq[2 * S * 4]; + __shared__ float sg[GW_CK], sb[GW_CK], sgam[S]; + const _Float16 *st_ = stp, *sp_ = stp + GW_CK * GW_CK; + const int vh = blockIdx.x, qh = vh % HK, w = threadIdx.x >> 5, l = threadIdx.x & 31, c = l & 15, hi = l >> 4; + const int col = 16 * w + c; + const int st = threadIdx.x >> 4, sr = (threadIdx.x & 15) * 8; + const size_t rs = (size_t) HV * S; + gw_f8 s[S / 16]; +#pragma unroll + for (int j = 0; j < S / 16; ++j) +#pragma unroll + for (int v = 0; v < 8; ++v) s[j][v] = state[(size_t) (16 * j + 8 * hi + v) * rs + (size_t) vh * S + col]; + if (threadIdx.x < S) sgam[threadIdx.x] = gamma[threadIdx.x]; + { // the q and k conv weights of this head's channels (q 0..127, k 128..255), and this lane's v column + for (int i = threadIdx.x; i < 2 * S; i += 256) + *reinterpret_cast(&swq[i * 4]) = + *reinterpret_cast(cw + (size_t) (i < S ? qh * S + i : HK * S + qh * S + (i - S)) * 4); + } + const float4 wvv = *reinterpret_cast(cw + (size_t) (2 * HK * S + vh * S + col) * 4); + const float out_scale = rsqrtf((float) S); + GfChunk cur; + gf_load(cur, hist, qkv, gate, beta, tp, 0, T, vh, qh); + unsigned touched = 0; + gw_f4 z0 = {}, z1 = {}; + auto store_rows = [&](int64_t c0) { + if (c0 + st >= T) return; + const float* o = &so[st * S + sr]; + gw_h8 r; +#pragma unroll + for (int i = 0; i < 8; ++i) r[i] = (_Float16) (o[i] * sigm(i < 4 ? z0[i] : z1[i - 4])); + *reinterpret_cast(y16 + (c0 + st) * ld16 + vh * S + sr) = __builtin_bit_cast(uint4, r); + }; + for (int64_t t0 = 0; t0 < T; t0 += GW_CK) { + { // this chunk's raw rows to LDS (the previous chunk's reads of them ended before its barrier (2)), T / P, gates +#pragma unroll + for (int m = 0; m < GF_RAWV; ++m) { + const int idx = threadIdx.x + 256 * m; + if (idx < GF_ROWS * 96) { + const int row = idx / 96, f = idx % 96; + *reinterpret_cast(&sraw[row * GF_RS + f * 4]) = cur.raw[m]; + } + } + reinterpret_cast(stp)[threadIdx.x] = cur.tp; + if (threadIdx.x < GW_CK) { + const bool ok = t0 + l < T; + float g = ok ? cur.g : 0.0f; +#pragma unroll + for (int o = 1; o < GW_CK; o <<= 1) { + const float u = __shfl_up(g, o, GW_CK); + if (l >= o) g += u; + } + sg[l] = g; + sb[l] = ok ? cur.b : 0.0f; + } + } + if (t0 + GW_CK < T) gf_load(cur, hist, qkv, gate, beta, tp, t0 + GW_CK, T, vh, qh); + const unsigned touch_now = gf_touch(qkv, z, t0 + GW_AHEAD * GW_CK, T, vh, qh); + gw12_barrier(); // (A) raw rows staged + { // k and q of token st: conv + SiLU on the thread's 8 channels, the head's sum of squares over the 16 lanes + gw_h8 kh, qq; + float ssk = 0.0f, ssq = 0.0f, kv[8], qv[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const float4 wq = *reinterpret_cast(&swq[(sr + e) * 4]); + const float4 wk = *reinterpret_cast(&swq[(S + sr + e) * 4]); + const float* rq = &sraw[st * GF_RS + sr + e]; + const float* rk = rq + S; + const float sq_ = rq[0] * wq.x + rq[GF_RS] * wq.y + rq[2 * GF_RS] * wq.z + rq[3 * GF_RS] * wq.w; + const float sk_ = rk[0] * wk.x + rk[GF_RS] * wk.y + rk[2 * GF_RS] * wk.z + rk[3 * GF_RS] * wk.w; + qv[e] = gf_silu(sq_); + kv[e] = gf_silu(sk_); + ssq = fmaf(qv[e], qv[e], ssq); + ssk = fmaf(kv[e], kv[e], ssk); + } +#pragma unroll + for (int m = 1; m < 16; m <<= 1) { + ssq += __shfl_xor(ssq, m); + ssk += __shfl_xor(ssk, m); + } + const float iq = rsqrtf(ssq + l2eps), ik = rsqrtf(ssk + l2eps); +#pragma unroll + for (int e = 0; e < 8; ++e) { + kh[e] = (_Float16) (kv[e] * ik); + qq[e] = (_Float16) (qv[e] * iq); + skt[(sr + e) * GW_CK + st] = kh[e]; + } + *reinterpret_cast(&sk[st * GW_KP + sr]) = __builtin_bit_cast(uint4, kh); + *reinterpret_cast(&sq[st * GW_KP + sr]) = __builtin_bit_cast(uint4, qq); + } + gw12_barrier(); // (B) k / q / T / P / gates staged; the previous chunk's norm in so + if (t0 > 0) store_rows(t0 - GW_CK); + __asm__ volatile("" ::"v"(touched)); + touched = touch_now; + { + const int64_t tz = std::min(t0 + st, T - 1); + z0 = *reinterpret_cast(z + tz * HV * S + vh * S + sr); + z1 = *reinterpret_cast(z + tz * HV * S + vh * S + sr + 4); + } + gw_f8 x = {}, qs = {}; +#pragma unroll + for (int j = 0; j < S / 16; ++j) { + const gw_h8 b = gw_acc_to_b12(s[j]); + x = gw_mma12(gw_ld8(sk + c * GW_KP + 16 * j + 8 * hi), b, x); + qs = gw_mma12(gw_ld8(sq + c * GW_KP + 16 * j + 8 * hi), b, qs); + } + gw_f8 y; +#pragma unroll + for (int v = 0; v < 8; ++v) { + const int t = 8 * hi + v; + const float* rv = &sraw[t * GF_RS + 2 * S + col]; // raw v rows t .. t + 3 (token t - 3 .. t of the conv) + const float sv_ = rv[0] * wvv.x + rv[GF_RS] * wvv.y + rv[2 * GF_RS] * wvv.z + rv[3 * GF_RS] * wvv.w; + y[v] = sb[t] * (gf_silu(sv_) - __expf(sg[t]) * x[v]); + } + const gw_f8 d = gw_mma12(gw_ld8(st_ + c * GW_CK + 8 * hi), gw_acc_to_b12(y), gw_f8{}); + gw_f8 o; +#pragma unroll + for (int v = 0; v < 8; ++v) o[v] = __expf(sg[8 * hi + v]) * qs[v]; + o = gw_mma12(gw_ld8(sp_ + c * GW_CK + 8 * hi), gw_acc_to_b12(d), o); +#pragma unroll + for (int v = 0; v < 8; ++v) { + o[v] *= out_scale; + float p = o[v] * o[v]; +#pragma unroll + for (int m = 1; m < 16; m <<= 1) p += __shfl_xor(p, m); + if (c == 0) sn[(8 * hi + v) * GW_NW + w] = p; + } + const float gl = sg[GW_CK - 1]; + gw_f8 dd; +#pragma unroll + for (int v = 0; v < 8; ++v) dd[v] = __expf(gl - sg[8 * hi + v]) * d[v]; + const gw_h8 db = gw_acc_to_b12(dd); + const float eg = __expf(gl); +#pragma unroll + for (int j = 0; j < S / 16; ++j) s[j] = gw_mma12(gw_ld8(skt + (16 * j + c) * GW_CK + 8 * hi), db, s[j] * eg); + gw12_barrier(); // (2) the sums of o^2; every read of this chunk's raw rows is done + const float g_col = sgam[col]; +#pragma unroll + for (int v = 0; v < 8; ++v) { + const int t = 8 * hi + v; + const gw_f4 n0 = *reinterpret_cast(&sn[t * GW_NW]), n1 = *reinterpret_cast(&sn[t * GW_NW + 4]); + const float ss = n0[0] + n0[1] + n0[2] + n0[3] + n1[0] + n1[1] + n1[2] + n1[3]; + so[t * S + col] = o[v] * rsqrtf(ss * (1.0f / S) + eps) * g_col; + } + } + __asm__ volatile("" ::"v"(touched)); + gw12_barrier(); + store_rows((T - 1) / GW_CK * GW_CK); + __asm__ volatile("" : "+s"(state)); +#pragma unroll + for (int j = 0; j < S / 16; ++j) +#pragma unroll + for (int v = 0; v < 8; ++v) state[(size_t) (16 * j + 8 * hi + v) * rs + (size_t) vh * S + col] = s[j][v]; +} +#endif // __HIPCC__ diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 9e8987ca..6ae6cff1 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -1971,6 +1971,7 @@ __global__ void __launch_bounds__(GW_NW * 32) gdn_wmma_scan_kernel(float* __rest for (int v = 0; v < 8; ++v) state[(size_t) (16 * j + 2 * v + hi) * rs + (size_t) vh * S + col] = s[j][v]; } #include "gdn_wmma12.inc" +#include "gdn_wmma12f.inc" // The opt-in chunked recurrence on gfx11 and gfx12 (STRATA_GDN_CHUNKED=1): false (nothing launched) on another part. y, the // FP32 scratch of the other kernels (T x 6144 floats), holds T and P (1 KB per chunk and value head: T x 3 KB). bool gdn_rec_wmma(float* state, const float* h, const float* gate, const float* beta, const float* z, const float* gamma, @@ -1994,8 +1995,13 @@ bool gdn_rec_wmma(float* state, const float* h, const float* gate, const float* _Float16* tp = reinterpret_cast<_Float16*>(y); if (gfx12) { gdn_w12_prep_kernel<<>>(h, gate, beta, tp, T); - gdn_w12_scan_kernel<<>>(state, h, gate, beta, z, gamma, reinterpret_cast(tp), eps, - y16, T, ld16); + static const bool lb = [] { const char* v = std::getenv("STRATA_GDN_W12_LB"); return v == nullptr || std::atoi(v) != 0; }(); + if (lb) + gdn_w12_scan_kernel<<>>(state, h, gate, beta, z, gamma, reinterpret_cast(tp), + eps, y16, T, ld16); + else + gdn_w12_scan_kernel<<>>(state, h, gate, beta, z, gamma, reinterpret_cast(tp), + eps, y16, T, ld16); return true; } gdn_wmma_prep_kernel<<>>(h, gate, beta, tp, T); @@ -2003,6 +2009,46 @@ bool gdn_rec_wmma(float* state, const float* h, const float* gate, const float* eps, y16, T, ld16); return true; } +// STRATA_GDN_CHUNKED=1 on gfx12 with the conv folded in (gdn_wmma12f.inc; STRATA_GDN_FUSE=0 keeps conv and recurrence apart): +// the work of gdn_conv + gdn_recurrence in three launches, no h buffer. False (nothing launched) when the chunked path or +// the fusion is off, the device is not gfx12, or the call is short / unaligned: the caller then runs the two entry points. +bool gdn_fused_impl(float* history, const float* qkv, const float* conv_w, float* state, const float* gate, + const float* beta, const float* z, const float* gamma, float eps, float l2eps, float* y, + uint16_t* y16, int64_t T, void* stream, int64_t ld16) { + static const bool on = [] { + const char* c = std::getenv("STRATA_GDN_CHUNKED"); + const char* f = std::getenv("STRATA_GDN_FUSE"); + return c != nullptr && std::atoi(c) != 0 && (f == nullptr || std::atoi(f) != 0); + }(); + if (!on || T < kGdnWmmaMin) return false; + if (ld16 <= 0) ld16 = (int64_t) HV * S; + if (ld16 % 8 != 0) return false; + static thread_local int last_device = -1; + static thread_local bool gfx12 = false; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess) return false; + if (dev != last_device) { + cudaDeviceProp p{}; + if (cudaGetDeviceProperties(&p, dev) != cudaSuccess) return false; + gfx12 = strata::kernels::gfx_arch_is_gfx12_wmma(p.gcnArchName); + last_device = dev; + } + if (!gfx12) return false; + cudaStream_t s = (cudaStream_t) stream; + const int64_t nch = (T + GW_CK - 1) / GW_CK; + _Float16* tp = reinterpret_cast<_Float16*>(y); + gdn_w12f_prep_kernel<<>>(history, qkv, conv_w, gate, beta, tp, T, l2eps); + static const bool lb = [] { const char* v = std::getenv("STRATA_GDN_W12_LB"); return v == nullptr || std::atoi(v) != 0; }(); + if (lb) + gdn_w12f_scan_kernel<<>>(state, history, qkv, conv_w, gate, beta, z, gamma, + reinterpret_cast(tp), eps, l2eps, y16, T, ld16); + else + gdn_w12f_scan_kernel<<>>(state, history, qkv, conv_w, gate, beta, z, gamma, + reinterpret_cast(tp), eps, l2eps, y16, T, ld16); + gdn_conv_hist_kernel<<>>(history, qkv, T); // after the scan: it reads the old history + check("gdn_conv_recurrence_fused"); + return true; +} #endif // __HIPCC__ __global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma, float eps, float* __restrict__ y, uint16_t* __restrict__ y16, @@ -2817,6 +2863,17 @@ void gdn_recurrence(float* state, const float* h, const float* gate, const float /// KVA: the same recurrence, bit for bit, without the output normalisation (its readers - the output projection /// and the gated residual write - have no consumer when only the state advances). `y` is still the scratch the /// recurrence kernels write; `z`/`gamma` are not read. +bool gdn_conv_recurrence_fused(float* history, const float* qkv, const float* conv_w, float* state, const float* gate, + const float* beta, const float* z, const float* gamma, float eps, float l2eps, float* y, + uint16_t* y16, int64_t T, void* stream, int64_t ld16) { +#if defined(__HIPCC__) + return gdn_fused_impl(history, qkv, conv_w, state, gate, beta, z, gamma, eps, l2eps, y, y16, T, stream, ld16); +#else + (void) history; (void) qkv; (void) conv_w; (void) state; (void) gate; (void) beta; (void) z; (void) gamma; (void) eps; + (void) l2eps; (void) y; (void) y16; (void) T; (void) stream; (void) ld16; + return false; +#endif +} void gdn_recurrence_state_only(float* state, const float* h, const float* gate, const float* beta, float* y, int64_t T, void* stream) { static const bool head = [] { const char* v = std::getenv("STRATA_GDN_HEAD"); return v != nullptr && std::atoi(v) != 0; }(); diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 16a609a5..b2790c85 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -3808,10 +3808,18 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri if (!bf16_proj(m.gemm, wb, m.mixed_bf, m.ab + HV, T, v.name("ssm_beta.weight"), err, 2 * HV, m.mixed_bf_lo)) return false; pt.mark(kPfGdnConv, cs); // "gdn" is the projections in; the rest on their own lines gdn_gates(m.ab, (const float*) wdt->data, (const float*) wsa->data, m.gate, m.beta, T, m.cs); - gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, m.cs); - pt.mark(kPfGdnRec, cs); const int64_t ld_y = pf_pad() && T >= std::max(pf_switch_min_t(), 64) ? ZV + ZV_PAD : 0; - if (kva_state_only && !kva_gdn_norm) // KVA: the recurrence without the output normalization + bool fused_gdn = false; +#if defined(STRATA_USE_HIP) + // gfx12, STRATA_GDN_CHUNKED=1: the conv is read inside the chunked recurrence (this stage's time then moves into "gdn conv+gates") + if (!kva_state_only) + fused_gdn = gdn_conv_recurrence_fused(conv, m.qkv, (const float*) wc->data, state, m.gate, m.beta, m.z, + (const float*) wnm->data, EPS, EPS, m.y, m.y_h, T, m.cs, ld_y); +#endif + if (!fused_gdn) gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, m.cs); + pt.mark(kPfGdnRec, cs); + if (fused_gdn) { + } else if (kva_state_only && !kva_gdn_norm) // KVA: the recurrence without the output normalization gdn_recurrence_state_only(state, m.hbuf, m.gate, m.beta, m.y, T, m.cs); else gdn_recurrence(state, m.hbuf, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, m.y, m.y_h, T, m.cs, @@ -6806,9 +6814,15 @@ bool Prefill::run_layer_major(const int64_t* tokens, int64_t n, int64_t pos0, st if (!bf16_proj(m.gemm, wb, m.mixed_bf, m.ab + HV, T, v.name("ssm_beta.weight"), err, 2 * HV, m.mixed_bf_lo)) return false; pt.mark(kPfGdnConv, cs); gdn_gates(m.ab, (const float*) wdt->data, (const float*) wsa->data, m.gate, m.beta, T, cs); - gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, cs); + bool fused_gdn = false; +#if defined(STRATA_USE_HIP) + fused_gdn = gdn_conv_recurrence_fused(conv, m.qkv, (const float*) wc->data, state, m.gate, m.beta, m.z, + (const float*) wnm->data, EPS, EPS, m.y, m.y_h, T, cs, 0); +#endif + if (!fused_gdn) gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, cs); pt.mark(kPfGdnRec, cs); - gdn_recurrence(state, m.hbuf, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, m.y, m.y_h, T, cs); + if (!fused_gdn) + gdn_recurrence(state, m.hbuf, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, m.y, m.y_h, T, cs); pt.mark(kPfGdnOut, cs); if (!native_proj(m.gemm, wo, m.y_h, m.bo, T, v.name("ssm_out.weight"), err)) return false; ++gdn_index; diff --git a/tests/hip/gdn_stage_bench.cpp b/tests/hip/gdn_stage_bench.cpp index 00896c1f..a803c42e 100644 --- a/tests/hip/gdn_stage_bench.cpp +++ b/tests/hip/gdn_stage_bench.cpp @@ -11,6 +11,7 @@ #include "strata/prefill/kernels.hpp" #include "strata/kernels/gfx_arch.hpp" #include +#include #include #include #include @@ -92,19 +93,76 @@ int main(int argc, char** argv) { }; auto layer = [&](int64_t t0, int64_t n) { // the prompt-path order: gates, conv, recurrence (+ norm) strata::prefill::gdn_gates(dab + t0 * 2 * HV, ddt, dssm, dgate + t0 * HV, dbeta + t0 * HV, n, nullptr); + if (strata::prefill::gdn_conv_recurrence_fused(dhist, dqkv + t0 * C, dcw, dstate, dgate + t0 * HV, dbeta + t0 * HV, + dz + t0 * ROW, dgamma, 1e-6f, 1e-6f, dy, dy16 + t0 * ld, n, nullptr, ld)) + return; strata::prefill::gdn_conv(dhist, dqkv + t0 * C, dcw, dh + t0 * C, n, 1e-6f, nullptr); strata::prefill::gdn_recurrence(dstate, dh + t0 * C, dgate + t0 * HV, dbeta + t0 * HV, dz + t0 * ROW, dgamma, 1e-6f, dy, dy16 + t0 * ld, n, nullptr, ld); }; + if (std::getenv("GDN_BENCH_CHECK")) { // fused / unfused chunked path against the FP32 sequential kernels, and a split-call check + for (int64_t T : lens) { + auto half = [](uint16_t b) { __half_raw x; x.x = b; return __half2float(__half(x)); }; + struct R { std::vector y; std::vector st, hist; }; + auto grab = [&] { return R{down(dy16, T * ld), down(dstate, S * ROW), down(dhist, C * 3)}; }; + auto prep = [&] { reset(); strata::prefill::gdn_gates(dab, ddt, dssm, dgate, dbeta, T, nullptr); }; + prep(); + strata::prefill::gdn_conv(dhist, dqkv, dcw, dh, T, 1e-6f, nullptr); + strata::prefill::gdn_recurrence_variant(5, dstate, dh, dgate, dbeta, dz, dgamma, 1e-6f, dy, dy16, T, nullptr, ld); + ck(cudaDeviceSynchronize(), "sync"); + const R ref = grab(); + prep(); + strata::prefill::gdn_conv(dhist, dqkv, dcw, dh, T, 1e-6f, nullptr); + strata::prefill::gdn_recurrence(dstate, dh, dgate, dbeta, dz, dgamma, 1e-6f, dy, dy16, T, nullptr, ld); + ck(cudaDeviceSynchronize(), "sync"); + const R unf = grab(); + prep(); + const bool f = strata::prefill::gdn_conv_recurrence_fused(dhist, dqkv, dcw, dstate, dgate, dbeta, dz, dgamma, 1e-6f, + 1e-6f, dy, dy16, T, nullptr, ld); + ck(cudaDeviceSynchronize(), "sync"); + const R fus = grab(); + auto err = [&](const R& a, const R& b, const char* what) { + double sq = 0, rf = 0, mx = 0, mr = 0, ssq = 0, srf = 0; + for (int64_t t = 0; t < T; ++t) + for (int d = 0; d < ROW; ++d) { + const double x = half(a.y[t * ld + d]), y = half(b.y[t * ld + d]); + sq += (x - y) * (x - y); rf += x * x; mx = std::max(mx, std::fabs(x - y)); mr = std::max(mr, std::fabs(x)); + } + for (size_t i = 0; i < a.st.size(); ++i) { const double x = a.st[i], y = b.st[i]; ssq += (x - y) * (x - y); srf += x * x; } + double hm = 0; + for (size_t i = 0; i < a.hist.size(); ++i) hm = std::max(hm, (double) std::fabs(a.hist[i] - b.hist[i])); + std::printf("CHECK T=%lld %s: y_rms=%.3e y_max=%.3e (ref max %.3e) state_rms=%.3e hist_maxdiff=%.1e\n", (long long) T, what, + std::sqrt(sq / std::max(rf, 1e-30)), mx, mr, std::sqrt(ssq / std::max(srf, 1e-30)), hm); + }; + err(ref, unf, "unfused-vs-fp32"); + if (f) err(ref, fus, "fused-vs-fp32"); else std::printf("CHECK T=%lld fused path not taken\n", (long long) T); + if (f) err(unf, fus, "fused-vs-unfused"); + if (f) { // continuation: the fused path in two calls (odd cut) against one call + reset(); + const int64_t cut = (T / 2) | 1; + auto call = [&](int64_t t0, int64_t n) { + strata::prefill::gdn_gates(dab + t0 * 2 * HV, ddt, dssm, dgate + t0 * HV, dbeta + t0 * HV, n, nullptr); + strata::prefill::gdn_conv_recurrence_fused(dhist, dqkv + t0 * C, dcw, dstate, dgate + t0 * HV, dbeta + t0 * HV, + dz + t0 * ROW, dgamma, 1e-6f, 1e-6f, dy, dy16 + t0 * ld, n, nullptr, ld); + }; + call(0, cut); call(cut, T - cut); + ck(cudaDeviceSynchronize(), "sync"); + err(fus, grab(), "fused split-vs-whole"); + } + } + return 0; + } for (int64_t T : lens) { std::vector conv_ms, rec_ms; for (int round = -2; round < reps; ++round) { reset(); ck(cudaEventRecord(e0), "ev"); strata::prefill::gdn_gates(dab, ddt, dssm, dgate, dbeta, T, nullptr); - strata::prefill::gdn_conv(dhist, dqkv, dcw, dh, T, 1e-6f, nullptr); - ck(cudaEventRecord(e1), "ev"); - strata::prefill::gdn_recurrence(dstate, dh, dgate, dbeta, dz, dgamma, 1e-6f, dy, dy16, T, nullptr, ld); + const bool fused = strata::prefill::gdn_conv_recurrence_fused(dhist, dqkv, dcw, dstate, dgate, dbeta, dz, dgamma, + 1e-6f, 1e-6f, dy, dy16, T, nullptr, ld); + if (!fused) strata::prefill::gdn_conv(dhist, dqkv, dcw, dh, T, 1e-6f, nullptr); + ck(cudaEventRecord(e1), "ev"); // fused: conv and recurrence are both inside the FIRST piece + if (!fused) strata::prefill::gdn_recurrence(dstate, dh, dgate, dbeta, dz, dgamma, 1e-6f, dy, dy16, T, nullptr, ld); ck(cudaEventRecord(e2), "ev"); ck(cudaEventSynchronize(e2), "sync"); float a = 0, b = 0; From 236adb39877157b061fe61a2365f77cf86302a34 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 01:51:05 +0100 Subject: [PATCH 6/9] GDN gfx12: conv + SiLU + q/k norm written as FP16 and read by the chunked kernels (one entry, STRATA_GDN_FUSE=0 off); ablation hooks removed --- include/strata/prefill/kernels.hpp | 7 +- src/prefill/gdn_wmma12.inc | 121 ++++++++++-- src/prefill/gdn_wmma12f.inc | 306 ----------------------------- src/prefill/kernels.cu | 37 ++-- src/prefill/prefill.cpp | 6 +- tests/hip/gdn_stage_bench.cpp | 8 +- 6 files changed, 138 insertions(+), 347 deletions(-) delete mode 100644 src/prefill/gdn_wmma12f.inc diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp index 0244c8dc..6b93c94e 100644 --- a/include/strata/prefill/kernels.hpp +++ b/include/strata/prefill/kernels.hpp @@ -75,9 +75,10 @@ void gdn_recurrence(float* state, const float* h, const float* gate, const float void gdn_recurrence_variant(int variant, float* state, const float* h, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream, int64_t ld16 = 0); -/// HIP gfx12 only, STRATA_GDN_CHUNKED=1 (STRATA_GDN_FUSE=0 off): gdn_conv + gdn_recurrence in one go, the conv read inside the -/// chunked kernels (no h buffer). Returns false, having launched nothing, when it does not apply: the caller then calls the two. -bool gdn_conv_recurrence_fused(float* history, const float* qkv, const float* conv_w, float* state, const float* gate, +/// HIP gfx12 only, STRATA_GDN_CHUNKED=1 (STRATA_GDN_FUSE=0 off): gdn_conv + gdn_recurrence on the chunked matrix-core path with +/// the conv output kept as FP16 in `hbuf` (the FP32 h buffer of gdn_conv, reused). Returns false, having launched nothing, when +/// it does not apply (not gfx12, short prompt, unaligned stride, off): the caller then calls the two. +bool gdn_conv_recurrence_fused(float* history, const float* qkv, const float* conv_w, float* hbuf, float* state, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float l2eps, float* y, uint16_t* y16, int64_t T, void* stream, int64_t ld16 = 0); /// KVA (CUDA/HIP only): the same recurrence kernels as gdn_recurrence, bit for bit, without the output diff --git a/src/prefill/gdn_wmma12.inc b/src/prefill/gdn_wmma12.inc index 264e21eb..7c15728b 100644 --- a/src/prefill/gdn_wmma12.inc +++ b/src/prefill/gdn_wmma12.inc @@ -42,7 +42,57 @@ template __device__ __forceinline__ void gw12_barrier() { } __device__ __forceinline__ gw_h8 gw_ld8(const _Float16* p) { return *reinterpret_cast(p); } // 16 bytes of LDS -__global__ void __launch_bounds__(32 * GW_VPK) gdn_w12_prep_kernel(const float* __restrict__ h, const float* __restrict__ gate, +// The causal conv + SiLU + q/k L2 norm (gdn_conv_l2_kernel's arithmetic) with the result written as FP16: half the traffic of +// the FP32 h in the conv and in both chunked kernels. One block per (head of 128 channels, tile of 64 tokens). +__global__ void __launch_bounds__(128) gdn_conv_l2_h16_kernel(const float* __restrict__ hist, const float* __restrict__ qkv, + const float* __restrict__ w, _Float16* __restrict__ h, int64_t T, + float eps) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + const int64_t t0 = (int64_t) blockIdx.y * CONV_TILE; + if (t0 >= T) return; + const int64_t t1 = t0 + CONV_TILE < T ? t0 + CONV_TILE : T; + auto input = [&](int64_t t) -> float { return t >= 0 ? qkv[t * C + c] : hist[c * 3 + (int) (t + 3)]; }; + float v0 = input(t0 - 3), v1 = input(t0 - 2), v2 = input(t0 - 1); + const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3]; + const bool norm = blockIdx.x < 2 * HK; // q and k heads; v channels are not normalised + __shared__ float part[16][4]; + for (int64_t tb = t0; tb < t1; tb += 16) { + const int n = (int) (t1 - tb < 16 ? t1 - tb : 16); + float val[16]; +#pragma unroll + for (int j = 0; j < 16; ++j) { + val[j] = 0.0f; + if (j < n) { + const float x = qkv[(tb + j) * C + c]; + const float s = v0 * w0 + v1 * w1 + v2 * w2 + x * w3; + val[j] = s / (1.0f + __expf(-s)); + v0 = v1; v1 = v2; v2 = x; + } + } + if (norm) { +#pragma unroll + for (int j = 0; j < 16; ++j) { + float sq = val[j] * val[j]; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) sq += __shfl_xor(sq, o); + if ((threadIdx.x & 31) == 0) part[j][threadIdx.x >> 5] = sq; + } + __syncthreads(); +#pragma unroll + for (int j = 0; j < 16; ++j) val[j] *= rsqrtf(part[j][0] + part[j][1] + part[j][2] + part[j][3] + eps); + __syncthreads(); + } +#pragma unroll + for (int j = 0; j < 16; ++j) + if (j < n) h[(tb + j) * C + c] = (_Float16) val[j]; + } +} + +// H16: h is the FP16 conv output of gdn_conv_l2_h16_kernel (the matrix-core operands are FP16 anyway; v keeps 11 bits, the +// same rounding the y operand takes a step later), else the FP32 h of gdn_conv. +template +__global__ void __launch_bounds__(32 * GW_VPK) gdn_w12_prep_kernel(const float* __restrict__ hf, const _Float16* __restrict__ hh, + const float* __restrict__ gate, const float* __restrict__ beta, _Float16* __restrict__ tp, int64_t T) { __shared__ float sa[GW_VPK][GW_CK * GW_CK], sg[GW_VPK][GW_CK], sb[GW_VPK][GW_CK]; @@ -52,18 +102,25 @@ __global__ void __launch_bounds__(32 * GW_VPK) gdn_w12_prep_kernel(const float* gw_f8 kk = {}, qk = {}; // k_t.k_i and q_t.k_i (lane: column i = c, rows t = 8 * hi + v) { const bool ok = t0 + c < T; // past the end: zero rows - const float* ht = h + (ok ? t0 + c : 0) * C; + const float* ht = hf + (ok ? t0 + c : 0) * C; + const _Float16* hth = hh + (ok ? t0 + c : 0) * C; #pragma unroll for (int j = 0; j < S / 16; ++j) { gw_h8 ka, qa; + if (H16) { + ka = *reinterpret_cast(hth + HK * S + qh * S + 16 * j + 8 * hi); + qa = *reinterpret_cast(hth + qh * S + 16 * j + 8 * hi); + if (!ok) { ka = gw_h8{}; qa = gw_h8{}; } + } else { #pragma unroll - for (int i = 0; i < 2; ++i) { - const gw_f4 k4 = *reinterpret_cast(ht + HK * S + qh * S + 16 * j + 8 * hi + 4 * i); - const gw_f4 q4 = *reinterpret_cast(ht + qh * S + 16 * j + 8 * hi + 4 * i); + for (int i = 0; i < 2; ++i) { + const gw_f4 k4 = *reinterpret_cast(ht + HK * S + qh * S + 16 * j + 8 * hi + 4 * i); + const gw_f4 q4 = *reinterpret_cast(ht + qh * S + 16 * j + 8 * hi + 4 * i); #pragma unroll - for (int e = 0; e < 4; ++e) { - ka[4 * i + e] = (_Float16) (ok ? k4[e] : 0.0f); - qa[4 * i + e] = (_Float16) (ok ? q4[e] : 0.0f); + for (int e = 0; e < 4; ++e) { + ka[4 * i + e] = (_Float16) (ok ? k4[e] : 0.0f); + qa[4 * i + e] = (_Float16) (ok ? q4[e] : 0.0f); + } } } kk = gw_mma12(ka, ka, kk); // B = K^T: lane i holds column i of K^T = row i of K, the A operand itself @@ -103,8 +160,42 @@ __global__ void __launch_bounds__(32 * GW_VPK) gdn_w12_prep_kernel(const float* } } -template -__global__ void __launch_bounds__(GW_NW * 32) gdn_w12_scan_kernel(float* __restrict__ state, const float* __restrict__ h, +// gw_load / gw_touch for the FP16 h (a thread's 8 channels of k, q, v are one 16-byte load each) +__device__ __forceinline__ void gw12_load16(GwChunk& in, const _Float16* __restrict__ hh, const float* __restrict__ gate, + const float* __restrict__ beta, const unsigned* __restrict__ tp, int64_t t0, int64_t T, + int vh, int qh) { + const int t = threadIdx.x >> 4, r = (threadIdx.x & 15) * 8; + const _Float16* ht = hh + std::min(t0 + t, T - 1) * C; + in.tp = tp[((t0 / GW_CK) * HV + vh) * (GW_CK * GW_CK) + threadIdx.x]; + const gw_h8 k = *reinterpret_cast(ht + HK * S + qh * S + r); + const gw_h8 q = *reinterpret_cast(ht + qh * S + r); + const gw_h8 v = *reinterpret_cast(ht + 2 * HK * S + vh * S + r); + in.k0 = gw_f4{(float) k[0], (float) k[1], (float) k[2], (float) k[3]}; + in.k1 = gw_f4{(float) k[4], (float) k[5], (float) k[6], (float) k[7]}; + in.q0 = gw_f4{(float) q[0], (float) q[1], (float) q[2], (float) q[3]}; + in.q1 = gw_f4{(float) q[4], (float) q[5], (float) q[6], (float) q[7]}; + in.v0 = gw_f4{(float) v[0], (float) v[1], (float) v[2], (float) v[3]}; + in.v1 = gw_f4{(float) v[4], (float) v[5], (float) v[6], (float) v[7]}; + if (threadIdx.x < GW_CK) { + const int64_t tl = std::min(t0 + threadIdx.x, T - 1); + in.g = gate[tl * HV + vh]; + in.b = beta[tl * HV + vh]; + } +} +__device__ __forceinline__ unsigned gw12_touch16(const _Float16* __restrict__ hh, const float* __restrict__ z, int64_t t0, int64_t T, + int vh, int qh) { + const int t = threadIdx.x >> 4, part = threadIdx.x & 15, kind = part >> 2; + if (t0 + t >= T) return 0u; + if (kind == 3) return __float_as_uint((z + (t0 + t) * HV * S + vh * S)[32 * (part & 3)]); + const _Float16* p = kind == 0 ? hh + (t0 + t) * C + HK * S + qh * S + : kind == 1 ? hh + (t0 + t) * C + qh * S + : hh + (t0 + t) * C + 2 * HK * S + vh * S; + return *reinterpret_cast(p + 64 * (part & 1)); // 256 bytes of FP16: two lines +} + +template +__global__ void __launch_bounds__(GW_NW * 32) gdn_w12_scan_kernel(float* __restrict__ state, const float* __restrict__ hf, + const _Float16* __restrict__ hh, const float* __restrict__ gate, const float* __restrict__ beta, const float* __restrict__ z, const float* __restrict__ gamma, const unsigned* __restrict__ tp, float eps, @@ -126,7 +217,7 @@ __global__ void __launch_bounds__(GW_NW * 32) gdn_w12_scan_kernel(float* __restr if (threadIdx.x < S) sgam[threadIdx.x] = gamma[threadIdx.x]; const float out_scale = rsqrtf((float) S); GwChunk cur; - gw_load(cur, h, gate, beta, tp, 0, T, vh, qh); + if (H16) gw12_load16(cur, hh, gate, beta, tp, 0, T, vh, qh); else gw_load(cur, hf, gate, beta, tp, 0, T, vh, qh); unsigned touched = 0; gw_f4 z0 = {}, z1 = {}; auto store_rows = [&](int64_t c0) { @@ -163,8 +254,12 @@ __global__ void __launch_bounds__(GW_NW * 32) gdn_w12_scan_kernel(float* __restr sb[l] = ok ? cur.b : 0.0f; } } - if (t0 + GW_CK < T) gw_load(cur, h, gate, beta, tp, t0 + GW_CK, T, vh, qh); - const unsigned touch_now = gw_touch(h, z, t0 + GW_AHEAD * GW_CK, T, vh, qh); + if (t0 + GW_CK < T) { + if (H16) gw12_load16(cur, hh, gate, beta, tp, t0 + GW_CK, T, vh, qh); + else gw_load(cur, hf, gate, beta, tp, t0 + GW_CK, T, vh, qh); + } + const unsigned touch_now = H16 ? gw12_touch16(hh, z, t0 + GW_AHEAD * GW_CK, T, vh, qh) + : gw_touch(hf, z, t0 + GW_AHEAD * GW_CK, T, vh, qh); gw12_barrier(); // (1) this chunk staged; the previous chunk's norm in so if (t0 > 0) store_rows(t0 - GW_CK); __asm__ volatile("" ::"v"(touched)); diff --git a/src/prefill/gdn_wmma12f.inc b/src/prefill/gdn_wmma12f.inc deleted file mode 100644 index c51691fb..00000000 --- a/src/prefill/gdn_wmma12f.inc +++ /dev/null @@ -1,306 +0,0 @@ -// Included by kernels.cu after gdn_wmma12.inc. The gfx12 chunked GDN with the causal conv + SiLU + q/k L2 norm folded in: -// the two kernels read the conv's RAW input (the qkv projection, plus the 3-token history in front of the first token) and -// no h buffer is written or read back (41 KB a token in each direction at 10240 FP32 channels). The arithmetic is the -// unfused path's: the conv in FP32 (four taps, SiLU), the q/k heads normalised with rsqrtf(sum + eps) before their FP16 -// rounding for the matrix cores, v kept FP32. The history is rewritten afterwards by gdn_conv_hist_kernel. -// prep: block (key head, chunk): the 16 tokens' q and k conv'd into LDS (cooperatively, once for the three value heads), -// normalised, then the gdn_w12_prep_kernel body reading its A / B operands from LDS. -// scan: block per value head; per chunk the 19 raw rows (3 history + 16) of its q, k and v channels are staged in LDS -// (a chunk ahead in registers), k / q conv'd and normalised into the FP16 operands, v conv'd where it is used. -#if defined(__HIPCC__) -constexpr int GF_ROWS = GW_CK + 3; // raw rows of a chunk: 3 history + 16 -constexpr int GF_RS = 3 * S + 4; // the scan's raw row stride (q | k | v), floats -constexpr int GF_RAWV = (GF_ROWS * 3 * S / 4 + 255) / 256; // f4 slots a thread keeps for the next chunk: 8 -__device__ __forceinline__ float gf_silu(float s) { return s / (1.0f + __expf(-s)); } - -__global__ void __launch_bounds__(128) gdn_w12f_prep_kernel(const float* __restrict__ hist, const float* __restrict__ qkv, - const float* __restrict__ cw, const float* __restrict__ gate, - const float* __restrict__ beta, _Float16* __restrict__ tp, int64_t T, - float eps) { - constexpr int RS = 2 * S + 1; // padded LDS row (q 0..127, k 128..255) - __shared__ float sc[GW_CK * RS]; - __shared__ float sinv[GW_CK][2]; - __shared__ float sa[GW_VPK][GW_CK * GW_CK], sg[GW_VPK][GW_CK], sb[GW_VPK][GW_CK]; - const int qh = blockIdx.x, ch = blockIdx.y, tid = threadIdx.x, w = tid >> 5, l = tid & 31, c = l & 15, hi = l >> 4; - const int64_t t0 = (int64_t) ch * GW_CK; - for (int idx = tid; idx < GW_CK * 2 * S; idx += 128) { // conv + SiLU of the 16 tokens x 256 channels (coalesced) - const int tt = idx >> 8, cc = idx & 255; - const int chn = cc < S ? qh * S + cc : HK * S + qh * S + (cc - S); - const int64_t t = t0 + tt; - float v = 0.0f; - if (t < T) { - const float4 wv = *reinterpret_cast(cw + (size_t) chn * 4); - auto in = [&](int64_t u) -> float { return u >= 0 ? qkv[u * C + chn] : hist[chn * 3 + (int) (u + 3)]; }; - const float s = in(t - 3) * wv.x + in(t - 2) * wv.y + in(t - 1) * wv.z + in(t) * wv.w; - v = gf_silu(s); - } - sc[tt * RS + cc] = v; - } - __syncthreads(); - if (tid < 2 * GW_CK) { // token tid >> 1, part tid & 1 (0 = q, 1 = k): the head's sum of squares - const float* r = sc + (tid >> 1) * RS + (tid & 1) * S; - float ss = 0.0f; - for (int i = 0; i < S; ++i) ss = fmaf(r[i], r[i], ss); - sinv[tid >> 1][tid & 1] = rsqrtf(ss + eps); - } - __syncthreads(); - const bool act = w < GW_VPK; // the fourth wave only helped with the conv; it still takes every barrier - const int vh = qh + w * HK; - gw_f8 kk = {}, qk = {}; - if (act) { - const float ik = sinv[c][1], iq = sinv[c][0]; -#pragma unroll - for (int j = 0; j < S / 16; ++j) { - gw_h8 ka, qa; -#pragma unroll - for (int e = 0; e < 8; ++e) { - ka[e] = (_Float16) (sc[c * RS + S + 16 * j + 8 * hi + e] * ik); - qa[e] = (_Float16) (sc[c * RS + 16 * j + 8 * hi + e] * iq); - } - kk = gw_mma12(ka, ka, kk); - qk = gw_mma12(qa, ka, qk); - } - } - if (act && l < GW_CK) { - const bool ok = t0 + l < T; - float g = ok ? gate[(t0 + l) * HV + vh] : 0.0f; -#pragma unroll - for (int o = 1; o < GW_CK; o <<= 1) { - const float u = __shfl_up(g, o, GW_CK); - if (l >= o) g += u; - } - sg[w][l] = g; - sb[w][l] = ok ? beta[(t0 + l) * HV + vh] : 0.0f; - } - __syncthreads(); - _Float16* out = tp + ((int64_t) ch * HV + vh) * (2 * GW_CK * GW_CK); - if (act) { -#pragma unroll - for (int v = 0; v < 8; ++v) { - const int t = 8 * hi + v; - sa[w][t * GW_CK + c] = c < t ? sb[w][t] * __expf(sg[w][t] - sg[w][c]) * kk[v] : 0.0f; - out[GW_CK * GW_CK + t * GW_CK + c] = (_Float16) (c <= t ? __expf(sg[w][t] - sg[w][c]) * qk[v] : 0.0f); - } - } - __syncthreads(); - if (act && l < GW_CK) { - float tc[GW_CK]; -#pragma unroll - for (int t = 0; t < GW_CK; ++t) { - float v = t == c ? 1.0f : 0.0f; -#pragma unroll - for (int k = 0; k < t; ++k) v = fmaf(-sa[w][t * GW_CK + k], tc[k], v); - tc[t] = v; - out[t * GW_CK + c] = (_Float16) v; - } - } -} - -// The raw rows of the chunk at t0 (rows t0 - 3 .. t0 + 15 of the qkv projection; rows before the prompt come from the -// history; rows past the end repeat the last row: finite, their gate and beta are 0), 8 f4 a thread, and its gate / beta. -struct GfChunk { - gw_f4 raw[GF_RAWV]; - float g, b; - unsigned tp; -}; -__device__ __forceinline__ void gf_load(GfChunk& in, const float* __restrict__ hist, const float* __restrict__ qkv, - const float* __restrict__ gate, const float* __restrict__ beta, - const unsigned* __restrict__ tp, int64_t t0, int64_t T, int vh, int qh) { - in.tp = tp[((t0 / GW_CK) * HV + vh) * (GW_CK * GW_CK) + threadIdx.x]; -#pragma unroll - for (int m = 0; m < GF_RAWV; ++m) { - const int idx = threadIdx.x + 256 * m; - gw_f4 r = {}; - if (idx < GF_ROWS * 96) { - const int row = idx / 96, f = idx % 96, seg = f >> 5, within = (f & 31) * 4; - const int chn = (seg == 0 ? qh * S : seg == 1 ? HK * S + qh * S : 2 * HK * S + vh * S) + within; - const int64_t t = t0 - 3 + row; - if (t >= 0) { - r = *reinterpret_cast(qkv + std::min(t, T - 1) * C + chn); - } else { -#pragma unroll - for (int e = 0; e < 4; ++e) r[e] = hist[(chn + e) * 3 + (int) (t + 3)]; - } - } - in.raw[m] = r; - } - if (threadIdx.x < GW_CK) { - const int64_t tl = std::min(t0 + threadIdx.x, T - 1); - in.g = gate[tl * HV + vh]; - in.b = beta[tl * HV + vh]; - } -} -// the cache warm-up of a later chunk: this block's q, k, v rows (96 f4 lines of 128 bytes each... one line a thread) and z -__device__ __forceinline__ unsigned gf_touch(const float* __restrict__ qkv, const float* __restrict__ z, int64_t t0, int64_t T, - int vh, int qh) { - const int t = threadIdx.x >> 4, part = threadIdx.x & 15, kind = part >> 2; - if (t0 + t >= T) return 0u; - const float* p = kind == 0 ? qkv + (t0 + t) * C + HK * S + qh * S - : kind == 1 ? qkv + (t0 + t) * C + qh * S - : kind == 2 ? qkv + (t0 + t) * C + 2 * HK * S + vh * S - : z + (t0 + t) * HV * S + vh * S; - return __float_as_uint(p[32 * (part & 3)]); -} - -template -__global__ void __launch_bounds__(GW_NW * 32) gdn_w12f_scan_kernel(float* __restrict__ state, const float* __restrict__ hist, - const float* __restrict__ qkv, const float* __restrict__ cw, - const float* __restrict__ gate, const float* __restrict__ beta, - const float* __restrict__ z, const float* __restrict__ gamma, - const unsigned* __restrict__ tp, float eps, float l2eps, - uint16_t* __restrict__ y16, int64_t T, int64_t ld16) { - __shared__ __attribute__((aligned(16))) _Float16 sk[GW_CK * GW_KP], sq[GW_CK * GW_KP], skt[S * GW_CK], stp[2 * GW_CK * GW_CK]; - __shared__ __attribute__((aligned(16))) float sraw[GF_ROWS * GF_RS], so[GW_CK * S], sn[GW_CK * GW_NW], swq[2 * S * 4]; - __shared__ float sg[GW_CK], sb[GW_CK], sgam[S]; - const _Float16 *st_ = stp, *sp_ = stp + GW_CK * GW_CK; - const int vh = blockIdx.x, qh = vh % HK, w = threadIdx.x >> 5, l = threadIdx.x & 31, c = l & 15, hi = l >> 4; - const int col = 16 * w + c; - const int st = threadIdx.x >> 4, sr = (threadIdx.x & 15) * 8; - const size_t rs = (size_t) HV * S; - gw_f8 s[S / 16]; -#pragma unroll - for (int j = 0; j < S / 16; ++j) -#pragma unroll - for (int v = 0; v < 8; ++v) s[j][v] = state[(size_t) (16 * j + 8 * hi + v) * rs + (size_t) vh * S + col]; - if (threadIdx.x < S) sgam[threadIdx.x] = gamma[threadIdx.x]; - { // the q and k conv weights of this head's channels (q 0..127, k 128..255), and this lane's v column - for (int i = threadIdx.x; i < 2 * S; i += 256) - *reinterpret_cast(&swq[i * 4]) = - *reinterpret_cast(cw + (size_t) (i < S ? qh * S + i : HK * S + qh * S + (i - S)) * 4); - } - const float4 wvv = *reinterpret_cast(cw + (size_t) (2 * HK * S + vh * S + col) * 4); - const float out_scale = rsqrtf((float) S); - GfChunk cur; - gf_load(cur, hist, qkv, gate, beta, tp, 0, T, vh, qh); - unsigned touched = 0; - gw_f4 z0 = {}, z1 = {}; - auto store_rows = [&](int64_t c0) { - if (c0 + st >= T) return; - const float* o = &so[st * S + sr]; - gw_h8 r; -#pragma unroll - for (int i = 0; i < 8; ++i) r[i] = (_Float16) (o[i] * sigm(i < 4 ? z0[i] : z1[i - 4])); - *reinterpret_cast(y16 + (c0 + st) * ld16 + vh * S + sr) = __builtin_bit_cast(uint4, r); - }; - for (int64_t t0 = 0; t0 < T; t0 += GW_CK) { - { // this chunk's raw rows to LDS (the previous chunk's reads of them ended before its barrier (2)), T / P, gates -#pragma unroll - for (int m = 0; m < GF_RAWV; ++m) { - const int idx = threadIdx.x + 256 * m; - if (idx < GF_ROWS * 96) { - const int row = idx / 96, f = idx % 96; - *reinterpret_cast(&sraw[row * GF_RS + f * 4]) = cur.raw[m]; - } - } - reinterpret_cast(stp)[threadIdx.x] = cur.tp; - if (threadIdx.x < GW_CK) { - const bool ok = t0 + l < T; - float g = ok ? cur.g : 0.0f; -#pragma unroll - for (int o = 1; o < GW_CK; o <<= 1) { - const float u = __shfl_up(g, o, GW_CK); - if (l >= o) g += u; - } - sg[l] = g; - sb[l] = ok ? cur.b : 0.0f; - } - } - if (t0 + GW_CK < T) gf_load(cur, hist, qkv, gate, beta, tp, t0 + GW_CK, T, vh, qh); - const unsigned touch_now = gf_touch(qkv, z, t0 + GW_AHEAD * GW_CK, T, vh, qh); - gw12_barrier(); // (A) raw rows staged - { // k and q of token st: conv + SiLU on the thread's 8 channels, the head's sum of squares over the 16 lanes - gw_h8 kh, qq; - float ssk = 0.0f, ssq = 0.0f, kv[8], qv[8]; -#pragma unroll - for (int e = 0; e < 8; ++e) { - const float4 wq = *reinterpret_cast(&swq[(sr + e) * 4]); - const float4 wk = *reinterpret_cast(&swq[(S + sr + e) * 4]); - const float* rq = &sraw[st * GF_RS + sr + e]; - const float* rk = rq + S; - const float sq_ = rq[0] * wq.x + rq[GF_RS] * wq.y + rq[2 * GF_RS] * wq.z + rq[3 * GF_RS] * wq.w; - const float sk_ = rk[0] * wk.x + rk[GF_RS] * wk.y + rk[2 * GF_RS] * wk.z + rk[3 * GF_RS] * wk.w; - qv[e] = gf_silu(sq_); - kv[e] = gf_silu(sk_); - ssq = fmaf(qv[e], qv[e], ssq); - ssk = fmaf(kv[e], kv[e], ssk); - } -#pragma unroll - for (int m = 1; m < 16; m <<= 1) { - ssq += __shfl_xor(ssq, m); - ssk += __shfl_xor(ssk, m); - } - const float iq = rsqrtf(ssq + l2eps), ik = rsqrtf(ssk + l2eps); -#pragma unroll - for (int e = 0; e < 8; ++e) { - kh[e] = (_Float16) (kv[e] * ik); - qq[e] = (_Float16) (qv[e] * iq); - skt[(sr + e) * GW_CK + st] = kh[e]; - } - *reinterpret_cast(&sk[st * GW_KP + sr]) = __builtin_bit_cast(uint4, kh); - *reinterpret_cast(&sq[st * GW_KP + sr]) = __builtin_bit_cast(uint4, qq); - } - gw12_barrier(); // (B) k / q / T / P / gates staged; the previous chunk's norm in so - if (t0 > 0) store_rows(t0 - GW_CK); - __asm__ volatile("" ::"v"(touched)); - touched = touch_now; - { - const int64_t tz = std::min(t0 + st, T - 1); - z0 = *reinterpret_cast(z + tz * HV * S + vh * S + sr); - z1 = *reinterpret_cast(z + tz * HV * S + vh * S + sr + 4); - } - gw_f8 x = {}, qs = {}; -#pragma unroll - for (int j = 0; j < S / 16; ++j) { - const gw_h8 b = gw_acc_to_b12(s[j]); - x = gw_mma12(gw_ld8(sk + c * GW_KP + 16 * j + 8 * hi), b, x); - qs = gw_mma12(gw_ld8(sq + c * GW_KP + 16 * j + 8 * hi), b, qs); - } - gw_f8 y; -#pragma unroll - for (int v = 0; v < 8; ++v) { - const int t = 8 * hi + v; - const float* rv = &sraw[t * GF_RS + 2 * S + col]; // raw v rows t .. t + 3 (token t - 3 .. t of the conv) - const float sv_ = rv[0] * wvv.x + rv[GF_RS] * wvv.y + rv[2 * GF_RS] * wvv.z + rv[3 * GF_RS] * wvv.w; - y[v] = sb[t] * (gf_silu(sv_) - __expf(sg[t]) * x[v]); - } - const gw_f8 d = gw_mma12(gw_ld8(st_ + c * GW_CK + 8 * hi), gw_acc_to_b12(y), gw_f8{}); - gw_f8 o; -#pragma unroll - for (int v = 0; v < 8; ++v) o[v] = __expf(sg[8 * hi + v]) * qs[v]; - o = gw_mma12(gw_ld8(sp_ + c * GW_CK + 8 * hi), gw_acc_to_b12(d), o); -#pragma unroll - for (int v = 0; v < 8; ++v) { - o[v] *= out_scale; - float p = o[v] * o[v]; -#pragma unroll - for (int m = 1; m < 16; m <<= 1) p += __shfl_xor(p, m); - if (c == 0) sn[(8 * hi + v) * GW_NW + w] = p; - } - const float gl = sg[GW_CK - 1]; - gw_f8 dd; -#pragma unroll - for (int v = 0; v < 8; ++v) dd[v] = __expf(gl - sg[8 * hi + v]) * d[v]; - const gw_h8 db = gw_acc_to_b12(dd); - const float eg = __expf(gl); -#pragma unroll - for (int j = 0; j < S / 16; ++j) s[j] = gw_mma12(gw_ld8(skt + (16 * j + c) * GW_CK + 8 * hi), db, s[j] * eg); - gw12_barrier(); // (2) the sums of o^2; every read of this chunk's raw rows is done - const float g_col = sgam[col]; -#pragma unroll - for (int v = 0; v < 8; ++v) { - const int t = 8 * hi + v; - const gw_f4 n0 = *reinterpret_cast(&sn[t * GW_NW]), n1 = *reinterpret_cast(&sn[t * GW_NW + 4]); - const float ss = n0[0] + n0[1] + n0[2] + n0[3] + n1[0] + n1[1] + n1[2] + n1[3]; - so[t * S + col] = o[v] * rsqrtf(ss * (1.0f / S) + eps) * g_col; - } - } - __asm__ volatile("" ::"v"(touched)); - gw12_barrier(); - store_rows((T - 1) / GW_CK * GW_CK); - __asm__ volatile("" : "+s"(state)); -#pragma unroll - for (int j = 0; j < S / 16; ++j) -#pragma unroll - for (int v = 0; v < 8; ++v) state[(size_t) (16 * j + 8 * hi + v) * rs + (size_t) vh * S + col] = s[j][v]; -} -#endif // __HIPCC__ diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 6ae6cff1..1c63206d 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -1971,7 +1971,6 @@ __global__ void __launch_bounds__(GW_NW * 32) gdn_wmma_scan_kernel(float* __rest for (int v = 0; v < 8; ++v) state[(size_t) (16 * j + 2 * v + hi) * rs + (size_t) vh * S + col] = s[j][v]; } #include "gdn_wmma12.inc" -#include "gdn_wmma12f.inc" // The opt-in chunked recurrence on gfx11 and gfx12 (STRATA_GDN_CHUNKED=1): false (nothing launched) on another part. y, the // FP32 scratch of the other kernels (T x 6144 floats), holds T and P (1 KB per chunk and value head: T x 3 KB). bool gdn_rec_wmma(float* state, const float* h, const float* gate, const float* beta, const float* z, const float* gamma, @@ -1994,14 +1993,14 @@ bool gdn_rec_wmma(float* state, const float* h, const float* gate, const float* const int64_t nch = (T + GW_CK - 1) / GW_CK; _Float16* tp = reinterpret_cast<_Float16*>(y); if (gfx12) { - gdn_w12_prep_kernel<<>>(h, gate, beta, tp, T); + gdn_w12_prep_kernel<<>>(h, nullptr, gate, beta, tp, T); static const bool lb = [] { const char* v = std::getenv("STRATA_GDN_W12_LB"); return v == nullptr || std::atoi(v) != 0; }(); if (lb) - gdn_w12_scan_kernel<<>>(state, h, gate, beta, z, gamma, reinterpret_cast(tp), - eps, y16, T, ld16); + gdn_w12_scan_kernel<<>>(state, h, nullptr, gate, beta, z, gamma, + reinterpret_cast(tp), eps, y16, T, ld16); else - gdn_w12_scan_kernel<<>>(state, h, gate, beta, z, gamma, reinterpret_cast(tp), - eps, y16, T, ld16); + gdn_w12_scan_kernel<<>>(state, h, nullptr, gate, beta, z, gamma, + reinterpret_cast(tp), eps, y16, T, ld16); return true; } gdn_wmma_prep_kernel<<>>(h, gate, beta, tp, T); @@ -2012,9 +2011,9 @@ bool gdn_rec_wmma(float* state, const float* h, const float* gate, const float* // STRATA_GDN_CHUNKED=1 on gfx12 with the conv folded in (gdn_wmma12f.inc; STRATA_GDN_FUSE=0 keeps conv and recurrence apart): // the work of gdn_conv + gdn_recurrence in three launches, no h buffer. False (nothing launched) when the chunked path or // the fusion is off, the device is not gfx12, or the call is short / unaligned: the caller then runs the two entry points. -bool gdn_fused_impl(float* history, const float* qkv, const float* conv_w, float* state, const float* gate, - const float* beta, const float* z, const float* gamma, float eps, float l2eps, float* y, - uint16_t* y16, int64_t T, void* stream, int64_t ld16) { +bool gdn_fused_impl(float* history, const float* qkv, const float* conv_w, float* hbuf, float* state, const float* gate, + const float* beta, const float* z, const float* gamma, float eps, float l2eps, float* y, uint16_t* y16, + int64_t T, void* stream, int64_t ld16) { static const bool on = [] { const char* c = std::getenv("STRATA_GDN_CHUNKED"); const char* f = std::getenv("STRATA_GDN_FUSE"); @@ -2037,15 +2036,17 @@ bool gdn_fused_impl(float* history, const float* qkv, const float* conv_w, float cudaStream_t s = (cudaStream_t) stream; const int64_t nch = (T + GW_CK - 1) / GW_CK; _Float16* tp = reinterpret_cast<_Float16*>(y); - gdn_w12f_prep_kernel<<>>(history, qkv, conv_w, gate, beta, tp, T, l2eps); + _Float16* h16 = reinterpret_cast<_Float16*>(hbuf); // the FP32 h buffer holds the FP16 one + gdn_conv_l2_h16_kernel<<>>(history, qkv, conv_w, h16, T, l2eps); + gdn_conv_hist_kernel<<>>(history, qkv, T); // the history after the chunk (the conv above read the old one) + gdn_w12_prep_kernel<<>>(nullptr, h16, gate, beta, tp, T); static const bool lb = [] { const char* v = std::getenv("STRATA_GDN_W12_LB"); return v == nullptr || std::atoi(v) != 0; }(); if (lb) - gdn_w12f_scan_kernel<<>>(state, history, qkv, conv_w, gate, beta, z, gamma, - reinterpret_cast(tp), eps, l2eps, y16, T, ld16); + gdn_w12_scan_kernel<<>>(state, nullptr, h16, gate, beta, z, gamma, + reinterpret_cast(tp), eps, y16, T, ld16); else - gdn_w12f_scan_kernel<<>>(state, history, qkv, conv_w, gate, beta, z, gamma, - reinterpret_cast(tp), eps, l2eps, y16, T, ld16); - gdn_conv_hist_kernel<<>>(history, qkv, T); // after the scan: it reads the old history + gdn_w12_scan_kernel<<>>(state, nullptr, h16, gate, beta, z, gamma, + reinterpret_cast(tp), eps, y16, T, ld16); check("gdn_conv_recurrence_fused"); return true; } @@ -2863,13 +2864,13 @@ void gdn_recurrence(float* state, const float* h, const float* gate, const float /// KVA: the same recurrence, bit for bit, without the output normalisation (its readers - the output projection /// and the gated residual write - have no consumer when only the state advances). `y` is still the scratch the /// recurrence kernels write; `z`/`gamma` are not read. -bool gdn_conv_recurrence_fused(float* history, const float* qkv, const float* conv_w, float* state, const float* gate, +bool gdn_conv_recurrence_fused(float* history, const float* qkv, const float* conv_w, float* hbuf, float* state, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float l2eps, float* y, uint16_t* y16, int64_t T, void* stream, int64_t ld16) { #if defined(__HIPCC__) - return gdn_fused_impl(history, qkv, conv_w, state, gate, beta, z, gamma, eps, l2eps, y, y16, T, stream, ld16); + return gdn_fused_impl(history, qkv, conv_w, hbuf, state, gate, beta, z, gamma, eps, l2eps, y, y16, T, stream, ld16); #else - (void) history; (void) qkv; (void) conv_w; (void) state; (void) gate; (void) beta; (void) z; (void) gamma; (void) eps; + (void) history; (void) qkv; (void) conv_w; (void) hbuf; (void) state; (void) gate; (void) beta; (void) z; (void) gamma; (void) eps; (void) l2eps; (void) y; (void) y16; (void) T; (void) stream; (void) ld16; return false; #endif diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index b2790c85..0e5776d7 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -3811,9 +3811,9 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri const int64_t ld_y = pf_pad() && T >= std::max(pf_switch_min_t(), 64) ? ZV + ZV_PAD : 0; bool fused_gdn = false; #if defined(STRATA_USE_HIP) - // gfx12, STRATA_GDN_CHUNKED=1: the conv is read inside the chunked recurrence (this stage's time then moves into "gdn conv+gates") + // gfx12, STRATA_GDN_CHUNKED=1: conv and recurrence together, the conv output as FP16 (their time then shows in "gdn conv+gates") if (!kva_state_only) - fused_gdn = gdn_conv_recurrence_fused(conv, m.qkv, (const float*) wc->data, state, m.gate, m.beta, m.z, + fused_gdn = gdn_conv_recurrence_fused(conv, m.qkv, (const float*) wc->data, m.hbuf, state, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, EPS, m.y, m.y_h, T, m.cs, ld_y); #endif if (!fused_gdn) gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, m.cs); @@ -6816,7 +6816,7 @@ bool Prefill::run_layer_major(const int64_t* tokens, int64_t n, int64_t pos0, st gdn_gates(m.ab, (const float*) wdt->data, (const float*) wsa->data, m.gate, m.beta, T, cs); bool fused_gdn = false; #if defined(STRATA_USE_HIP) - fused_gdn = gdn_conv_recurrence_fused(conv, m.qkv, (const float*) wc->data, state, m.gate, m.beta, m.z, + fused_gdn = gdn_conv_recurrence_fused(conv, m.qkv, (const float*) wc->data, m.hbuf, state, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, EPS, m.y, m.y_h, T, cs, 0); #endif if (!fused_gdn) gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, cs); diff --git a/tests/hip/gdn_stage_bench.cpp b/tests/hip/gdn_stage_bench.cpp index a803c42e..0b7a7c5b 100644 --- a/tests/hip/gdn_stage_bench.cpp +++ b/tests/hip/gdn_stage_bench.cpp @@ -93,7 +93,7 @@ int main(int argc, char** argv) { }; auto layer = [&](int64_t t0, int64_t n) { // the prompt-path order: gates, conv, recurrence (+ norm) strata::prefill::gdn_gates(dab + t0 * 2 * HV, ddt, dssm, dgate + t0 * HV, dbeta + t0 * HV, n, nullptr); - if (strata::prefill::gdn_conv_recurrence_fused(dhist, dqkv + t0 * C, dcw, dstate, dgate + t0 * HV, dbeta + t0 * HV, + if (strata::prefill::gdn_conv_recurrence_fused(dhist, dqkv + t0 * C, dcw, dh, dstate, dgate + t0 * HV, dbeta + t0 * HV, dz + t0 * ROW, dgamma, 1e-6f, 1e-6f, dy, dy16 + t0 * ld, n, nullptr, ld)) return; strata::prefill::gdn_conv(dhist, dqkv + t0 * C, dcw, dh + t0 * C, n, 1e-6f, nullptr); @@ -117,7 +117,7 @@ int main(int argc, char** argv) { ck(cudaDeviceSynchronize(), "sync"); const R unf = grab(); prep(); - const bool f = strata::prefill::gdn_conv_recurrence_fused(dhist, dqkv, dcw, dstate, dgate, dbeta, dz, dgamma, 1e-6f, + const bool f = strata::prefill::gdn_conv_recurrence_fused(dhist, dqkv, dcw, dh, dstate, dgate, dbeta, dz, dgamma, 1e-6f, 1e-6f, dy, dy16, T, nullptr, ld); ck(cudaDeviceSynchronize(), "sync"); const R fus = grab(); @@ -142,7 +142,7 @@ int main(int argc, char** argv) { const int64_t cut = (T / 2) | 1; auto call = [&](int64_t t0, int64_t n) { strata::prefill::gdn_gates(dab + t0 * 2 * HV, ddt, dssm, dgate + t0 * HV, dbeta + t0 * HV, n, nullptr); - strata::prefill::gdn_conv_recurrence_fused(dhist, dqkv + t0 * C, dcw, dstate, dgate + t0 * HV, dbeta + t0 * HV, + strata::prefill::gdn_conv_recurrence_fused(dhist, dqkv + t0 * C, dcw, dh, dstate, dgate + t0 * HV, dbeta + t0 * HV, dz + t0 * ROW, dgamma, 1e-6f, 1e-6f, dy, dy16 + t0 * ld, n, nullptr, ld); }; call(0, cut); call(cut, T - cut); @@ -158,7 +158,7 @@ int main(int argc, char** argv) { reset(); ck(cudaEventRecord(e0), "ev"); strata::prefill::gdn_gates(dab, ddt, dssm, dgate, dbeta, T, nullptr); - const bool fused = strata::prefill::gdn_conv_recurrence_fused(dhist, dqkv, dcw, dstate, dgate, dbeta, dz, dgamma, + const bool fused = strata::prefill::gdn_conv_recurrence_fused(dhist, dqkv, dcw, dh, dstate, dgate, dbeta, dz, dgamma, 1e-6f, 1e-6f, dy, dy16, T, nullptr, ld); if (!fused) strata::prefill::gdn_conv(dhist, dqkv, dcw, dh, T, 1e-6f, nullptr); ck(cudaEventRecord(e1), "ev"); // fused: conv and recurrence are both inside the FIRST piece From 84aa2d7d57d56616b989ac52a802f20bfae5158b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 03:45:42 +0100 Subject: [PATCH 7/9] GDN gfx12: chunked path only from calls of 12000 tokens (measured crossover for the +5% bar); p2006/KL scripts --- src/prefill/kernels.cu | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 1c63206d..61446aed 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -1681,6 +1681,11 @@ constexpr int GW_VPK = HV / HK; // value heads per key head: the prep's waves constexpr int GW_KP = S + 8; // the scan's padded FP16 k / q rows constexpr int GW_AHEAD = 3; // the scan warms the cache this many chunks ahead constexpr int64_t kGdnWmmaMin = 64; // STRATA_GDN_CHUNKED=1 takes prompt chunks of this many tokens and more +// gfx12: the chunked kernels are faster than the sequential ones at every call length from 64 tokens up (1.7x to 2.5x on the +// layer), but the prompt-speed gain depends on the prompt: IQ3_S on an R9700, +3.9% at 4K, +5.2% at 8K, +6.9% at 16K, +10.1% at +// 32K. The owner's bar for a non-bitwise path is +5%, so gfx12 takes the chunked path only from calls of this many tokens (a +// prompt of 12K and more; longer prompts arrive in calls of up to 16K). gfx11 keeps kGdnWmmaMin (not measured at model level). +constexpr int64_t kGdnW12MinT = 12000; typedef _Float16 gw_h16 __attribute__((ext_vector_type(16))); typedef _Float16 gw_h8 __attribute__((ext_vector_type(8))); typedef _Float16 gw_h2 __attribute__((ext_vector_type(2))); @@ -1990,6 +1995,7 @@ bool gdn_rec_wmma(float* state, const float* h, const float* gate, const float* last_device = dev; } if (!gfx11 && !gfx12) return false; + if (gfx12 && T < kGdnW12MinT) return false; const int64_t nch = (T + GW_CK - 1) / GW_CK; _Float16* tp = reinterpret_cast<_Float16*>(y); if (gfx12) { @@ -2032,7 +2038,7 @@ bool gdn_fused_impl(float* history, const float* qkv, const float* conv_w, float gfx12 = strata::kernels::gfx_arch_is_gfx12_wmma(p.gcnArchName); last_device = dev; } - if (!gfx12) return false; + if (!gfx12 || T < kGdnW12MinT) return false; cudaStream_t s = (cudaStream_t) stream; const int64_t nch = (T + GW_CK - 1) / GW_CK; _Float16* tp = reinterpret_cast<_Float16*>(y); From f0a34fa9bfa27483d6607f37ebf6b53e0bfbfa86 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 03:46:05 +0100 Subject: [PATCH 8/9] kGdnW12MinT comment: the 8K figure --- src/prefill/kernels.cu | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 61446aed..76b18be1 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -1682,7 +1682,7 @@ constexpr int GW_KP = S + 8; // the scan's padded FP16 k / q rows constexpr int GW_AHEAD = 3; // the scan warms the cache this many chunks ahead constexpr int64_t kGdnWmmaMin = 64; // STRATA_GDN_CHUNKED=1 takes prompt chunks of this many tokens and more // gfx12: the chunked kernels are faster than the sequential ones at every call length from 64 tokens up (1.7x to 2.5x on the -// layer), but the prompt-speed gain depends on the prompt: IQ3_S on an R9700, +3.9% at 4K, +5.2% at 8K, +6.9% at 16K, +10.1% at +// layer), but the prompt-speed gain depends on the prompt: IQ3_S on an R9700, +3.9% at 4K, +5.0% at 8K (median of 7 pairs: borderline), +6.9% at 16K, +10.1% at // 32K. The owner's bar for a non-bitwise path is +5%, so gfx12 takes the chunked path only from calls of this many tokens (a // prompt of 12K and more; longer prompts arrive in calls of up to 16K). gfx11 keeps kGdnWmmaMin (not measured at model level). constexpr int64_t kGdnW12MinT = 12000; From ac3e0e17b590acd945973985ad0bf9db5247c3f0 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 16:05:14 +0100 Subject: [PATCH 9/9] GDN gfx12: the chunked path from 64 tokens, as on gfx11 (owner: every gain counts; final gate at 64: +1.7% to +6.1%, KL 0.0025/0.038, 55/61 tasks, soak clean) --- src/prefill/kernels.cu | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 76b18be1..d0cf2ca5 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -1683,9 +1683,10 @@ constexpr int GW_AHEAD = 3; // the scan warms the cache this many chunks constexpr int64_t kGdnWmmaMin = 64; // STRATA_GDN_CHUNKED=1 takes prompt chunks of this many tokens and more // gfx12: the chunked kernels are faster than the sequential ones at every call length from 64 tokens up (1.7x to 2.5x on the // layer), but the prompt-speed gain depends on the prompt: IQ3_S on an R9700, +3.9% at 4K, +5.0% at 8K (median of 7 pairs: borderline), +6.9% at 16K, +10.1% at -// 32K. The owner's bar for a non-bitwise path is +5%, so gfx12 takes the chunked path only from calls of this many tokens (a -// prompt of 12K and more; longer prompts arrive in calls of up to 16K). gfx11 keeps kGdnWmmaMin (not measured at model level). -constexpr int64_t kGdnW12MinT = 12000; +// 32K. It first started at 12000 tokens for the old +5% bar; the owner then chose every gain (2026-10-30), and the final gate +// with the start at 64 measured +1.7% to +3.2% at 1-3K, +3.5% at 4K, +4.7% at 16K, +6.1% at 32K (20 pairs), KL 0.0025 mean / +// 0.0381 max, 55 of 61 tasks, a 30-minute soak clean. So gfx12 takes it from the same 64 tokens as gfx11. +constexpr int64_t kGdnW12MinT = kGdnWmmaMin; typedef _Float16 gw_h16 __attribute__((ext_vector_type(16))); typedef _Float16 gw_h8 __attribute__((ext_vector_type(8))); typedef _Float16 gw_h2 __attribute__((ext_vector_type(2)));