okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-amd-f16 8d7f997d4 into f-p4-int (the Radeon 780M on Linux reads its 16-bit prompt GEMMs FP16 in and out by default; the hyper-connection up-mix kernel has an FP16 path)27cf035e5

main
198.3 KiB3515 linesraw
1// src/prefill/kernels.cu - see include/strata/prefill/kernels.hpp.
2#include "strata/prefill/kernels.hpp"
3#include "strata/prefill/gdn_chunk.hpp"
4#include "strata/prefill/gdn_probe.hpp"
5#include "strata/kernels/mrope.hpp"
6#include "strata/kernels/gfx_arch.hpp"
7#include "strata/kernels/router_top10.hpp"
8#include "strata/core/emulate.hpp"
9
10#include <cuda_fp16.h>
11#include <cuda_runtime.h>
12#include <algorithm>
13
14#include <algorithm>
15#include <cfloat>
16#include <cmath>
17#include <cstdio>
18#include <cstdlib>
19#include <cstring>
20
21#include "strata/core/geometry.hpp"
22
23namespace strata::prefill {
24namespace {
25
26constexpr int N = strata::core::kCompiledGeometry.n_embd, HC = strata::core::kCompiledGeometry.hc, D = N * HC, LR = strata::core::kCompiledGeometry.hc_lr;
27constexpr int KU = strata::core::kCompiledGeometry.n_expert_used;   // routed experts per token (10 for Flash-Next)
28constexpr int64_t FFC = strata::core::kCompiledGeometry.n_ff;   // the routed (and shared) expert width: 640 for Flash-Next
29constexpr int S = strata::core::kCompiledGeometry.ssm_state_size, HK = strata::core::kCompiledGeometry.ssm_k_heads, HV = strata::core::kCompiledGeometry.ssm_v_heads, C = strata::core::kCompiledGeometry.ssm_conv_channels;
30
31__device__ __forceinline__ float warp_sum(float v) {
32#pragma unroll
33    for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
34    return v;
35}
36__device__ __forceinline__ float warp_max(float v) {
37#pragma unroll
38    for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o));
39    return v;
40}
41__device__ __forceinline__ uint16_t bf(float f) {
42    uint32_t u = __float_as_uint(f);
43    u += 0x7fffu + ((u >> 16) & 1u);
44    return (uint16_t) (u >> 16);
45}
46// The BF16 GEMMs' second operand (STRATA_PREFILL_BF16X2): what the BF16 image `hi` left out of f, itself in BF16.
47// W.hi + W.lo carries ~16 mantissa bits of the activation - the decode path's FP32 x to within ~1e-5.
48__device__ __forceinline__ uint16_t bf_lo(float f, uint16_t hi) { return bf(f - __uint_as_float((uint32_t) hi << 16)); }
49__device__ __forceinline__ float sigm(float x) { return 1.0f / (1.0f + __expf(-x)); }
50__device__ __forceinline__ uint16_t hf(float f) { return __half_as_ushort(__float2half_rn(f)); }
51// A SwiGLU product for an FP16 GEMM: saturated, so a token with a massive activation cannot turn into inf and then
52// NaN in the down projection (decode's q8_1 has room to ~8e6; FP16 ends at 65504).  A NaN stays NaN (fminf/fmaxf
53// would make it -65504 and hide where it came from); finite values below 65504 round exactly as before.
54// STRATA_F16_RANGE=1 (set_f16_range): what reaches FP16's range on this device - the largest |value| the activation
55// images converted (hf_sat is their one funnel) and how many were beyond 65504 or NaN; W and Y are counted in gemm.cu.
56// Off, the cost is one flag read per value.  The max is kept as float bits (positive floats order as unsigned ints),
57// and a thread takes the atomic only when it beats the value it read, so the atomics stop once the max has settled.
58#if defined(__HIPCC__)   // HIP only: the CUDA kernels stay exactly as they were (no flag read in hf_sat)
59__device__ int g_f16_range_on = 0;
60__device__ unsigned g_f16_range_max = 0;
61__device__ unsigned long long g_f16_range_over = 0;
62__device__ __forceinline__ void f16_range_note(float f) {
63    const float a = fabsf(f);
64    const unsigned bits = __float_as_uint(a);
65    if (bits > g_f16_range_max) atomicMax(&g_f16_range_max, bits);
66    if (a > 65504.0f || isnan(f)) atomicAdd(&g_f16_range_over, 1ull);
67}
68#endif
69__device__ __forceinline__ uint16_t hf_sat(float f) {
70#if defined(__HIPCC__)
71    if (g_f16_range_on) f16_range_note(f);
72#endif
73    return hf(isnan(f) ? f : fminf(fmaxf(f, -65504.0f), 65504.0f));
74}
75
76// Turing's FP16 image of the hyper-connection's xn16 (gemm.cu's bf16_to_f16_kernel applied to a BF16 value): the
77// writers store what the BF16 tensor-core path would convert, so the GEMM reads it without a conversion pass
78__device__ __forceinline__ uint16_t bf_to_hf_conv(uint16_t b) {
79    float f = __uint_as_float((uint32_t) b << 16);
80    if (f > 65504.0f && !isinf(f)) f = 65504.0f;
81    else if (f < -65504.0f && !isinf(f)) f = -65504.0f;
82    return __half_as_ushort(__float2half_rn(f));
83}
84// The prompt path's 16-bit activation image for the BF16-weight GEMMs: BF16, or FP16 where the GEMM library is fast
85// only in FP16 (prompt_f16() in gemm.cu: rocBLAS on gfx103x).  Set once per device before the first prompt.
86#if defined(__HIPCC__)   // HIP only (#835): the CUDA kernels stay exactly as they were, they never read the flag
87__device__ int g_act_f16 = 0;
88__device__ __forceinline__ uint16_t act16(float f) { return g_act_f16 ? hf_sat(f) : bf(f); }
89#else
90__device__ __forceinline__ uint16_t act16(float f) { return bf(f); }
91#endif
92// block-wide sum for blockDim.x <= 1024, result broadcast
93__device__ float block_sum(float v, float* sh) {
94    const int lane = threadIdx.x & 31, w = threadIdx.x >> 5;
95    v = warp_sum(v);
96    __syncthreads();
97    if (lane == 0) sh[w] = v;
98    __syncthreads();
99    const int nw = (blockDim.x + 31) >> 5;
100    float t = (threadIdx.x < nw) ? sh[threadIdx.x] : 0.0f;
101    if (w == 0) t = warp_sum(t);
102    if (threadIdx.x == 0) sh[0] = t;
103    __syncthreads();
104    return sh[0];
105}
106void check(const char* what) {
107    const cudaError_t e = cudaGetLastError();
108    if (e != cudaSuccess) { std::fprintf(stderr, "prefill %s: %s\n", what, cudaGetErrorString(e)); std::exit(1); }
109}
110unsigned blocks_for(int64_t n, int t = 256) { return (unsigned) ((n + t - 1) / t); }
111
112// ---------------------------------------------------------------- hyper-connection
113__global__ void gr_norm_kernel(const float* __restrict__ R, const float* __restrict__ w, float eps,
114                               float* __restrict__ xn, uint16_t* __restrict__ xn16, uint16_t* __restrict__ xn16_lo,
115                               int f16img) {
116    __shared__ float sh[32];
117    const int64_t row = blockIdx.x;                 // t * 4 + c
118    const int c = (int) (row % HC);
119    const float* r = R + row * N;
120    float ss = 0.0f;
121    for (int d = threadIdx.x; d < N; d += blockDim.x) ss += r[d] * r[d];
122    const float rs = rsqrtf(block_sum(ss, sh) / (float) N + eps);
123    for (int d = threadIdx.x; d < N; d += blockDim.x) {
124        const float v = r[d] * rs * w[c * N + d];
125        xn[row * N + d] = v;
126        const uint16_t h = act16(v);
127        xn16[row * N + d] = f16img ? bf_to_hf_conv(h) : h;
128        if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h);
129    }
130}
131// F-1: the row scale only (and the BF16 image); gr_mix_r_kernel recomputes r * rs * w itself, in the same order,
132// so the FP32 copy of the normalized rows (T x 10240 floats) is neither written nor read
133__global__ void gr_norm_rs_kernel(const float* __restrict__ R, const float* __restrict__ w, float eps,
134                                  float* __restrict__ rs_out, uint16_t* __restrict__ xn16,
135                                  uint16_t* __restrict__ xn16_lo, int64_t ldx, int f16img) {
136    __shared__ float sh[32];
137    const int64_t row = blockIdx.x;                 // t * 4 + c
138    const int c = (int) (row % HC);
139    const float* r = R + row * N;
140    const int64_t xo = (row / HC) * ldx + (int64_t) c * N;   // the BF16 image's row (token stride ldx)
141    float ss = 0.0f;
142    for (int d = threadIdx.x; d < N; d += blockDim.x) ss += r[d] * r[d];
143    const float rs = rsqrtf(block_sum(ss, sh) / (float) N + eps);
144    if (threadIdx.x == 0) rs_out[row] = rs;
145    for (int d = threadIdx.x; d < N; d += blockDim.x) {
146        const float v = r[d] * rs * w[c * N + d];
147        const uint16_t h = act16(v);
148        xn16[xo + d] = f16img ? bf_to_hf_conv(h) : h;
149        if (xn16_lo) xn16_lo[xo + d] = bf_lo(v, h);
150    }
151}
152__global__ void gr_mix_r_kernel(const float* __restrict__ R, const float* __restrict__ rs, const float* __restrict__ w,
153                                const float* __restrict__ g, float* __restrict__ mixed, uint16_t* __restrict__ mixed16,
154                                int64_t T, uint16_t* __restrict__ mixed_h, uint16_t* __restrict__ mixed16_lo) {
155    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
156    if (i >= T * N) return;
157    const int64_t t = i / N, d = i % N;
158    float s = 0.0f;
159#pragma unroll
160    for (int c = 0; c < HC; ++c) {
161        const int64_t j = t * D + c * N + d;
162        const float x = R[j] * rs[t * HC + c] * w[c * N + d];   // gr_norm_kernel's value, bit for bit
163        s = fmaf(x, sigm(g[j]), s);
164    }
165    s /= (float) HC;
166    mixed[i] = s;
167    if (mixed16) {
168        const uint16_t h = act16(s);
169        mixed16[i] = h;
170        if (mixed16_lo) mixed16_lo[i] = bf_lo(s, h);
171    }
172    if (mixed_h) mixed_h[i] = hf(s);
173}
174// F-2: gr_write_kernel for one row (t, c), then gr_norm_rs_kernel's reduction over it with the next half's norm
175// weights - the same thread-to-element mapping (256 threads, stride 256) and block_sum, so rs and the BF16 image are
176// the same bits, and R is not read back
177constexpr int GRW_PER = (N + 255) / 256;
178__global__ void __launch_bounds__(256) gr_write_norm_rs_kernel(float* __restrict__ R, const float* __restrict__ bo,
179                                                               const float* __restrict__ inj, int64_t inj_ld,
180                                                               const float* __restrict__ w, float eps,
181                                                               float* __restrict__ rs_out, uint16_t* __restrict__ xn16,
182                                                               uint16_t* __restrict__ xn16_lo, int64_t ldx, int f16img) {
183    __shared__ float sh[32];
184    const int64_t row = blockIdx.x;                 // t * 4 + c
185    const int64_t t = row / HC;
186    const int c = (int) (row % HC);
187    float* r = R + row * N;
188    const int64_t xo = t * ldx + (int64_t) c * N;
189    const float sc = 2.0f * sigm(inj[t * inj_ld + c] / (float) HC);
190    float v[GRW_PER];
191    float ss = 0.0f;
192    int k = 0;
193#pragma unroll
194    for (int d = threadIdx.x; d < N; d += 256, ++k) {
195        const float x = fmaf(bo[t * N + d], sc, r[d]);
196        r[d] = x;
197        v[k] = x;
198        ss += x * x;
199    }
200    const float rs = rsqrtf(block_sum(ss, sh) / (float) N + eps);
201    if (threadIdx.x == 0) rs_out[row] = rs;
202    k = 0;
203#pragma unroll
204    for (int d = threadIdx.x; d < N; d += 256, ++k) {
205        const float x = v[k] * rs * w[c * N + d];
206        const uint16_t h = act16(x);
207        xn16[xo + d] = f16img ? bf_to_hf_conv(h) : h;
208        if (xn16_lo) xn16_lo[xo + d] = bf_lo(x, h);
209    }
210}
211// S23 (opt-in STRATA_CVEC_FUSE=1): a steered layer's FFN write, its control vector and the next half's norm in one
212// pass over R (was gr_write + cvec_apply + gr_norm_rs: three).  The write is gr_write_kernel's, the vector
213// cvec_kernel's (the same per-thread dot order over d = tid + 256 k, the same two-level xor reduction), the norm
214// gr_norm_rs_kernel's (the same ss order and block_sum): the same bits.
215__global__ void __launch_bounds__(256) gr_write_cvec_norm_rs_kernel(
216    float* __restrict__ R, const float* __restrict__ bo, const float* __restrict__ inj, int64_t inj_ld,
217    const float* __restrict__ v_l, const float* __restrict__ s_l, const int* __restrict__ on, int mode,
218    const float* __restrict__ w, float eps, float* __restrict__ rs_out, uint16_t* __restrict__ xn16,
219    uint16_t* __restrict__ xn16_lo, int64_t ldx, int f16img) {
220    __shared__ float sh[32];
221    __shared__ float part[8];
222    const int64_t row = blockIdx.x;                 // t * 4 + c
223    const int64_t t = row / HC;
224    const int c = (int) (row % HC);
225    float* r = R + row * N;
226    const float sc = 2.0f * sigm(inj[t * inj_ld + c] / (float) HC);
227    const float s = *s_l;
228    const bool steer = *on != 0 && s != 0.0f;
229    float x[GRW_PER];
230    float dot = 0.0f;
231    int k = 0;
232#pragma unroll
233    for (int d = threadIdx.x; d < N; d += 256, ++k) {
234        const float xv = fmaf(bo[t * N + d], sc, r[d]);
235        x[k] = xv;
236        if (steer && mode == 0) dot = fmaf(xv, v_l[d], dot);
237    }
238    if (steer && mode == 0) {
239#pragma unroll
240        for (int o = 16; o > 0; o >>= 1) dot += __shfl_xor_sync(0xffffffffu, dot, o);
241        if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = dot;
242        __syncthreads();
243        if (threadIdx.x < 32) {
244            float p = threadIdx.x < 8 ? part[threadIdx.x] : 0.0f;
245#pragma unroll
246            for (int o = 16; o > 0; o >>= 1) p += __shfl_xor_sync(0xffffffffu, p, o);
247            if (threadIdx.x == 0) part[0] = p;
248        }
249        __syncthreads();
250        dot = part[0] * s;
251    }
252    float ss = 0.0f;
253    k = 0;
254#pragma unroll
255    for (int d = threadIdx.x; d < N; d += 256, ++k) {
256        float xv = x[k];
257        if (steer) xv = mode == 0 ? fmaf(-dot, v_l[d], xv) : xv + v_l[d];
258        r[d] = xv;
259        x[k] = xv;
260        ss += xv * xv;
261    }
262    const float rs = rsqrtf(block_sum(ss, sh) / (float) N + eps);
263    if (threadIdx.x == 0) rs_out[row] = rs;
264    k = 0;
265#pragma unroll
266    for (int d = threadIdx.x; d < N; d += 256, ++k) {
267        const float y = x[k] * rs * w[c * N + d];
268        const uint16_t h = act16(y);
269        xn16[t * ldx + (int64_t) c * N + d] = f16img ? bf_to_hf_conv(h) : h;
270        if (xn16_lo) xn16_lo[t * ldx + (int64_t) c * N + d] = bf_lo(y, h);
271    }
272}
273__global__ void gr_silu_kernel(const float* __restrict__ lo, uint16_t* __restrict__ lo16, uint16_t* __restrict__ lo16_lo,
274                               int64_t n) {
275    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
276    if (i >= n) return;
277    const float x = lo[i] / (float) HC;
278    const float v = x / (1.0f + __expf(-x));
279    const uint16_t h = act16(v);
280    lo16[i] = h;
281    if (lo16_lo) lo16_lo[i] = bf_lo(v, h);
282}
283__global__ void gr_mix_kernel(const float* __restrict__ xn, const float* __restrict__ g, float* __restrict__ mixed,
284                              uint16_t* __restrict__ mixed16, int64_t T, uint16_t* __restrict__ mixed_h,
285                              uint16_t* __restrict__ mixed16_lo) {
286    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
287    if (i >= T * N) return;
288    const int64_t t = i / N, d = i % N;
289    float s = 0.0f;
290#pragma unroll
291    for (int c = 0; c < HC; ++c) {
292        const int64_t j = t * D + c * N + d;
293        s = fmaf(xn[j], sigm(g[j]), s);
294    }
295    s /= (float) HC;
296    mixed[i] = s;
297    if (mixed16) {
298        const uint16_t h = act16(s);
299        mixed16[i] = h;
300        if (mixed16_lo) mixed16_lo[i] = bf_lo(s, h);
301    }
302    if (mixed_h) mixed_h[i] = hf(s);
303}
304__global__ void gr_write_kernel(float* __restrict__ R, const float* __restrict__ bo, const float* __restrict__ inj,
305                                int64_t inj_ld, int64_t T) {
306    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
307    if (i >= T * D) return;
308    const int64_t t = i / D, c = (i % D) / N, d = i % N;
309    R[i] = fmaf(bo[t * N + d], 2.0f * sigm(inj[t * inj_ld + c] / (float) HC), R[i]);
310}
311__global__ void gr_broadcast_kernel(const float* __restrict__ e, float* __restrict__ R, int64_t T) {
312    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
313    if (i >= T * D) return;
314    const int64_t t = i / D, d = i % N;
315    R[i] = e[t * N + d];
316}
317
318// ---------------------------------------------------------------- GDN
319__global__ void gdn_gates_kernel(const float* __restrict__ ab, const float* __restrict__ dt,
320                                 const float* __restrict__ ssm_a, float* __restrict__ gate, float* __restrict__ beta,
321                                 int64_t T) {
322    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
323    if (i >= T * HV) return;
324    const int64_t t = i / HV, h = i % HV;
325    const float v = ab[t * 2 * HV + h] + dt[h];
326    gate[i] = (v > 20.0f ? v : log1pf(__expf(v))) * ssm_a[h];
327    beta[i] = sigm(ab[t * 2 * HV + HV + h]);
328}
329// one thread per channel, walks the chunk; then a second kernel normalises
330__global__ void gdn_conv_kernel(float* __restrict__ hist, const float* __restrict__ qkv, const float* __restrict__ w,
331                                float* __restrict__ h, int64_t T) {
332    const int c = blockIdx.x * blockDim.x + threadIdx.x;
333    if (c >= C) return;
334    float v0 = hist[c * 3], v1 = hist[c * 3 + 1], v2 = hist[c * 3 + 2];
335    const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3];
336    for (int64_t t = 0; t < T; ++t) {
337        const float x = qkv[t * C + c];
338        const float s = v0 * w0 + v1 * w1 + v2 * w2 + x * w3;
339        h[t * C + c] = s / (1.0f + __expf(-s));
340        v0 = v1; v1 = v2; v2 = x;
341    }
342    hist[c * 3] = v0; hist[c * 3 + 1] = v1; hist[c * 3 + 2] = v2;
343}
344// C-3: the same 4-tap causal conv, tiled over tokens: thread (c, tile) reads its tile's 3 predecessors from the
345// chunk (or the history before it) instead of carrying them - the conv reads inputs, not its own outputs, so the
346// tiles are independent. The same expression per element (so the same bits); the history is written afterwards.
347constexpr int CONV_TILE = 64;
348__global__ void gdn_conv_tiled_kernel(const float* __restrict__ hist, const float* __restrict__ qkv,
349                                      const float* __restrict__ w, float* __restrict__ h, int64_t T) {
350    const int c = blockIdx.x * blockDim.x + threadIdx.x;
351    if (c >= C) return;
352    const int64_t t0 = (int64_t) blockIdx.y * CONV_TILE;
353    if (t0 >= T) return;
354    const int64_t t1 = t0 + CONV_TILE < T ? t0 + CONV_TILE : T;
355    auto input = [&](int64_t t) -> float { return t >= 0 ? qkv[t * C + c] : hist[c * 3 + (int) (t + 3)]; };
356    float v0 = input(t0 - 3), v1 = input(t0 - 2), v2 = input(t0 - 1);
357    const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3];
358    for (int64_t t = t0; t < t1; ++t) {
359        const float x = qkv[t * C + c];
360        const float s = v0 * w0 + v1 * w1 + v2 * w2 + x * w3;
361        h[t * C + c] = s / (1.0f + __expf(-s));
362        v0 = v1; v1 = v2; v2 = x;
363    }
364}
365// Aurora (S23, opt-in STRATA_GDN_CONVL2=1): gdn_conv_tiled_kernel with gdn_l2_kernel folded in.  A block's 128 threads
366// are the 128 channels of one head, so for the q / k heads (block < 2 HK) the norm's sum of squares is the block's:
367// the same warp_sum, the same four partials added in the same order, the same v * rsqrtf(ss + eps) on the same
368// stored value - the same bits, without writing h and reading it back (16 tokens per round).
369__global__ void gdn_conv_l2_kernel(const float* __restrict__ hist, const float* __restrict__ qkv,
370                                   const float* __restrict__ w, float* __restrict__ h, int64_t T, float eps) {
371    const int c = blockIdx.x * blockDim.x + threadIdx.x;
372    const int64_t t0 = (int64_t) blockIdx.y * CONV_TILE;
373    if (t0 >= T) return;
374    const int64_t t1 = t0 + CONV_TILE < T ? t0 + CONV_TILE : T;
375    auto input = [&](int64_t t) -> float { return t >= 0 ? qkv[t * C + c] : hist[c * 3 + (int) (t + 3)]; };
376    float v0 = input(t0 - 3), v1 = input(t0 - 2), v2 = input(t0 - 1);
377    const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3];
378    for (int64_t t = t0; t < t1; ++t) {   // gdn_conv_tiled_kernel's loop, verbatim
379        const float x = qkv[t * C + c];
380        const float s = v0 * w0 + v1 * w1 + v2 * w2 + x * w3;
381        h[t * C + c] = s / (1.0f + __expf(-s));
382        v0 = v1; v1 = v2; v2 = x;
383    }
384    if (blockIdx.x >= 2 * HK) return;   // v channels: no norm
385    __shared__ float part[16][4];
386    for (int64_t tb = t0; tb < t1; tb += 16) {
387        const int n = (int) (t1 - tb < 16 ? t1 - tb : 16);
388        for (int j = 0; j < n; ++j) {   // (each thread reads back its own stored value)
389            const float v = h[(tb + j) * C + c];
390            // gdn_l2_kernel as the compiler built it: the first xor step adds the partner's rounded square to an
391            // unrounded own one (an fma), the other steps are plain adds - spelled out so no contraction can differ
392            float sq = __fmaf_rn(v, v, __shfl_xor_sync(0xffffffffu, __fmul_rn(v, v), 16));
393#pragma unroll
394            for (int o = 8; o > 0; o >>= 1) sq = __fadd_rn(sq, __shfl_xor_sync(0xffffffffu, sq, o));
395            if ((threadIdx.x & 31) == 0) part[j][threadIdx.x >> 5] = sq;
396        }
397        __syncthreads();
398        for (int j = 0; j < n; ++j) {
399            const float ss = part[j][0] + part[j][1] + part[j][2] + part[j][3];
400            h[(tb + j) * C + c] = h[(tb + j) * C + c] * rsqrtf(ss + eps);
401        }
402        __syncthreads();
403    }
404}
405// STRATA_GDN_CONVL2=2: the conv, SiLU and q / k L2 norm in ONE pass, a warp per (head, run of CONVW_TOK tokens): a lane owns
406// four consecutive channels of the head's 128 (a float4 each way), walks the tokens keeping the three previous inputs in
407// registers, and the head's sum of squares is one 5-step warp reduction a token - no shared memory, no barrier, h written
408// once, normalised.  The conv + SiLU value is the expression of gdn_conv_tiled_kernel (same bits); the sum of squares is
409// added in another order than gdn_l2_kernel's (FP32-level difference).  The first three inputs of a run are re-read from
410// qkv (L2 hits; 3 / CONVW_TOK extra reads).  Bytes a token: 41 KB read, 41 KB written, against 114 KB for conv + l2.
411constexpr int CONVW_TOK = 32;
412__global__ void __launch_bounds__(128) gdn_conv_w_kernel(const float* __restrict__ hist, const float* __restrict__ qkv,
413                                                         const float* __restrict__ w, float* __restrict__ h, int64_t T,
414                                                         float eps) {
415    const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
416    const int64_t tb = ((int64_t) blockIdx.y * 4 + warp) * CONVW_TOK;
417    if (tb >= T) return;
418    const int64_t te = tb + CONVW_TOK < T ? tb + CONVW_TOK : T;
419    const int c0 = blockIdx.x * 128 + lane * 4;
420    const bool norm = blockIdx.x < 2 * HK;   // q / k heads
421    float wr[4][4];
422#pragma unroll
423    for (int i = 0; i < 4; ++i)
424#pragma unroll
425        for (int k = 0; k < 4; ++k) wr[i][k] = w[(c0 + i) * 4 + k];
426    float4 p0, p1, p2;   // inputs t - 3, t - 2, t - 1
427    auto input = [&](int64_t t) -> float4 {
428        if (t >= 0) return *reinterpret_cast<const float4*>(qkv + t * C + c0);
429        return make_float4(hist[(c0 + 0) * 3 + (int) (t + 3)], hist[(c0 + 1) * 3 + (int) (t + 3)],
430                           hist[(c0 + 2) * 3 + (int) (t + 3)], hist[(c0 + 3) * 3 + (int) (t + 3)]);
431    };
432    p0 = input(tb - 3); p1 = input(tb - 2); p2 = input(tb - 1);
433#pragma unroll 4
434    for (int64_t t = tb; t < te; ++t) {
435        const float4 x = *reinterpret_cast<const float4*>(qkv + t * C + c0);
436        const float xv[4] = {x.x, x.y, x.z, x.w}, a0[4] = {p0.x, p0.y, p0.z, p0.w}, a1[4] = {p1.x, p1.y, p1.z, p1.w},
437                    a2[4] = {p2.x, p2.y, p2.z, p2.w};
438        float o[4];
439        float sq = 0.0f;
440#pragma unroll
441        for (int i = 0; i < 4; ++i) {
442            const float s = a0[i] * wr[i][0] + a1[i] * wr[i][1] + a2[i] * wr[i][2] + xv[i] * wr[i][3];
443            o[i] = s / (1.0f + __expf(-s));
444            sq = fmaf(o[i], o[i], sq);
445        }
446        if (norm) {
447#pragma unroll
448            for (int m = 16; m > 0; m >>= 1) sq += __shfl_xor_sync(0xffffffffu, sq, m);
449            const float rn = rsqrtf(sq + eps);
450#pragma unroll
451            for (int i = 0; i < 4; ++i) o[i] *= rn;
452        }
453        *reinterpret_cast<float4*>(h + t * C + c0) = make_float4(o[0], o[1], o[2], o[3]);
454        p0 = p1; p1 = p2; p2 = x;
455    }
456}
457// the history after the chunk: its last three inputs (the older history where the chunk is shorter than 3)
458__global__ void gdn_conv_hist_kernel(float* __restrict__ hist, const float* __restrict__ qkv, int64_t T) {
459    const int c = blockIdx.x * blockDim.x + threadIdx.x;
460    if (c >= C) return;
461    float v[3];
462    for (int k = 0; k < 3; ++k) {
463        const int64_t t = T - 3 + k;
464        v[k] = t >= 0 ? qkv[t * C + c] : hist[c * 3 + (int) (t + 3)];
465    }
466    hist[c * 3] = v[0]; hist[c * 3 + 1] = v[1]; hist[c * 3 + 2] = v[2];
467}
468__global__ void gdn_l2_kernel(float* __restrict__ h, float eps) {
469    // block (t, head) over the 32 q/k heads, 128 threads
470    const int64_t t = blockIdx.y;
471    const int head = blockIdx.x;
472    float* x = h + t * C + head * S;
473    const float v = x[threadIdx.x];
474    float sq = warp_sum(v * v);
475    __shared__ float part[4];
476    if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sq;
477    __syncthreads();
478    const float ss = part[0] + part[1] + part[2] + part[3];
479    x[threadIdx.x] = v * rsqrtf(ss + eps);
480}
481constexpr int RG = 4, RPG = S / RG;
482constexpr int CB = 32, NCB = S / CB;  // value columns per block kernel / blocks per head
483// v100/gdn-chunk: Volta-only (sm_70), inside the experimental build.  Main's recurrence kernels above are
484// untouched for every other architecture; the chain-split is dispatched only when the device is cc 7.0.
485#if defined(STRATA_EXPERIMENTAL_SM60)
486// v100/gdn-chunk: the same recurrence with WARP-LOCAL reductions - no __syncthreads at all.  gdn_rec_cols_*'
487// per-token shape is two cross-warp reductions (k^T W and q^T W) behind two barriers each (six barriers per
488// token in the pipelined kernel); here a warp owns 8 columns and the 4 row-groups are lanes within the warp,
489// so the reductions are __shfl's.  The arithmetic is the same expressions in the same order - the four
490// row-group partials still sum as ((p0+p1)+p2)+p3 - so this kernel is BIT-EXACT against gdn_rec_cols_pipe
491// (the parity test asserts it).  The state has the same (S, h_v, S) layout and the same j-fastest column.
492__global__ void __launch_bounds__(S) gdn_rec_cols_warp_kernel(float* __restrict__ state, const float* __restrict__ h,
493                                                             const float* __restrict__ gate,
494                                                             const float* __restrict__ beta,
495                                                             float* __restrict__ oc_out, int64_t T) {
496    const int head = blockIdx.x / NCB, cb = blockIdx.x % NCB;
497    const int w = threadIdx.x >> 5, l = threadIdx.x & 31;   // warp w: columns w*8..w*8+7
498    const int col = cb * CB + w * 8 + (l & 7);              // lane: column within the warp's 8
499    const int rg = l >> 3;                                  // lane group: 4 row-groups of 32 rows
500    const int qh = head % HK;
501    float s[RPG];
502    float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col;
503    const size_t rs = (size_t) HV * S;
504#pragma unroll
505    for (int r = 0; r < RPG; ++r) s[r] = base[r * rs];
506    const unsigned full = 0xffffffffu;
507    for (int64_t t = 0; t < T; ++t) {
508        const float* ht = h + t * C;
509        const float* krow = ht + HK * S + qh * S + rg * RPG;
510        const float* qrow = ht + qh * S + rg * RPG;
511        float kv = 0.0f;
512#pragma unroll
513        for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], krow[r], kv);
514        // ((p0 + p1) + p2) + p3 over the row-groups, exactly as red[0]+red[1]+red[2]+red[3]
515        float p0 = __shfl_sync(full, kv, (l & 7));
516        float p1 = __shfl_sync(full, kv, (l & 7) + 8);
517        float p2 = __shfl_sync(full, kv, (l & 7) + 16);
518        float p3 = __shfl_sync(full, kv, (l & 7) + 24);
519        const float kv_col = ((p0 + p1) + p2) + p3;
520        const float g = __expf(gate[t * HV + head]);
521        const float delta = (ht[2 * HK * S + head * S + col] - g * kv_col) * beta[t * HV + head];
522        float o = 0.0f;
523#pragma unroll
524        for (int r = 0; r < RPG; ++r) {
525            s[r] = fmaf(g, s[r], krow[r] * delta);
526            o = fmaf(s[r], qrow[r], o);
527        }
528        float q0 = __shfl_sync(full, o, (l & 7));
529        float q1 = __shfl_sync(full, o, (l & 7) + 8);
530        float q2 = __shfl_sync(full, o, (l & 7) + 16);
531        float q3 = __shfl_sync(full, o, (l & 7) + 24);
532        oc_out[t * HV * S + head * S + col] = (((q0 + q1) + q2) + q3) * rsqrtf((float) S);
533    }
534#pragma unroll
535    for (int r = 0; r < RPG; ++r) base[r * rs] = s[r];
536}
537#endif
538__global__ void __launch_bounds__(S * RG) gdn_rec_kernel(float* __restrict__ state, const float* __restrict__ h,
539                                                         const float* __restrict__ gate,
540                                                         const float* __restrict__ beta, const float* __restrict__ z,
541                                                         const float* __restrict__ gamma, float eps,
542                                                         float* __restrict__ y, uint16_t* __restrict__ y16, int64_t T,
543                                                         int64_t ld16) {
544    __shared__ float sk[S], sq[S], red[RG][S], wsum[16];
545    const int head = blockIdx.x, col = threadIdx.x, rg = threadIdx.y, tid = rg * S + col;
546    const int qh = head % HK;
547    float s[RPG];
548    float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col;
549    const size_t rs = (size_t) HV * S;
550#pragma unroll
551    for (int r = 0; r < RPG; ++r) s[r] = base[r * rs];
552    const float g_col = gamma[col];
553    for (int64_t t = 0; t < T; ++t) {
554        const float* ht = h + t * C;
555        __syncthreads();
556        if (tid < S) { sq[tid] = ht[qh * S + tid]; sk[tid] = ht[HK * S + qh * S + tid]; }
557        __syncthreads();
558        const float g = __expf(gate[t * HV + head]);
559        float kv = 0.0f;
560#pragma unroll
561        for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv);
562        red[rg][col] = kv;
563        __syncthreads();
564        const float kv_col = red[0][col] + red[1][col] + red[2][col] + red[3][col];
565        const float delta = (ht[2 * HK * S + head * S + col] - g * kv_col) * beta[t * HV + head];
566        float o = 0.0f;
567#pragma unroll
568        for (int r = 0; r < RPG; ++r) {
569            s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta);
570            o = fmaf(s[r], sq[rg * RPG + r], o);
571        }
572        __syncthreads();
573        red[rg][col] = o;
574        __syncthreads();
575        float oc = 0.0f, sp = 0.0f;
576        if (rg == 0) {
577            oc = (red[0][col] + red[1][col] + red[2][col] + red[3][col]) * rsqrtf((float) S);
578            sp = oc * oc;
579        }
580        sp = warp_sum(sp);
581        if ((tid & 31) == 0) wsum[tid >> 5] = sp;
582        __syncthreads();
583        if (rg == 0) {
584            const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
585            const float v = oc * rsqrtf(ss / (float) S + eps) * g_col * sigm(z[t * HV * S + head * S + col]);
586            y[t * HV * S + head * S + col] = v;
587            y16[t * ld16 + head * S + col] = hf(v);
588        }
589    }
590#pragma unroll
591    for (int r = 0; r < RPG; ++r) base[r * rs] = s[r];
592}
593
594// D-2: the recurrence with the value columns split over 4 blocks per head (4x the blocks of the kernel above, a
595// quarter of its threads per __syncthreads), and the output norm - the only step that couples the head's columns -
596// in its own kernel. Per column the same arithmetic in the same order (the 4 row-group partial sums added as
597// red[0] + red[1] + red[2] + red[3]; the norm's warp sums over the same 32-column warps): the same bits.
598
599__global__ void __launch_bounds__(CB * RG) gdn_rec_cols_kernel(float* __restrict__ state, const float* __restrict__ h,
600                                                                const float* __restrict__ gate,
601                                                                const float* __restrict__ beta,
602                                                                float* __restrict__ oc_out, int64_t T) {
603    __shared__ float sk[S], sq[S], red[RG][CB];
604    const int head = blockIdx.x / NCB, cb = blockIdx.x % NCB;
605    const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c;
606    const int qh = head % HK;
607    float s[RPG];
608    float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col;
609    const size_t rs = (size_t) HV * S;
610#pragma unroll
611    for (int r = 0; r < RPG; ++r) s[r] = base[r * rs];
612    for (int64_t t = 0; t < T; ++t) {
613        const float* ht = h + t * C;
614        __syncthreads();
615        if (tid < S) { sq[tid] = ht[qh * S + tid]; sk[tid] = ht[HK * S + qh * S + tid]; }
616        __syncthreads();
617        const float g = __expf(gate[t * HV + head]);
618        float kv = 0.0f;
619#pragma unroll
620        for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv);
621        red[rg][c] = kv;
622        __syncthreads();
623        const float kv_col = red[0][c] + red[1][c] + red[2][c] + red[3][c];
624        const float delta = (ht[2 * HK * S + head * S + col] - g * kv_col) * beta[t * HV + head];
625        float o = 0.0f;
626#pragma unroll
627        for (int r = 0; r < RPG; ++r) {
628            s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta);
629            o = fmaf(s[r], sq[rg * RPG + r], o);
630        }
631        __syncthreads();
632        red[rg][c] = o;
633        __syncthreads();
634        if (rg == 0) oc_out[t * HV * S + head * S + col] = (red[0][c] + red[1][c] + red[2][c] + red[3][c]) * rsqrtf((float) S);
635    }
636#pragma unroll
637    for (int r = 0; r < RPG; ++r) base[r * rs] = s[r];
638}
639// gdn_rec_cols_kernel with the next token's inputs (q/k rows, v, gate, beta) loaded into registers while this token
640// computes (software pipelining).  The same arithmetic in the same order: the same bits, and the same CB-column split.
641// STRATA_GDN_PIPELINE=0: gdn_rec_cols_kernel.
642__global__ void __launch_bounds__(CB * RG) gdn_rec_cols_pipe_kernel(float* __restrict__ state, const float* __restrict__ h,
643                                                                      const float* __restrict__ gate,
644                                                                      const float* __restrict__ beta,
645                                                                      float* __restrict__ oc_out, int64_t T) {
646    constexpr int NT = CB * RG, LPT = S / NT;   // threads, q/k rows loaded per thread
647    __shared__ float sk[S], sq[S], red[RG][CB];
648    const int head = blockIdx.x / NCB, cb = blockIdx.x % NCB;
649    const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c;
650    const int qh = head % HK;
651    float s[RPG];
652    float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col;
653    const size_t rs = (size_t) HV * S;
654#pragma unroll
655    for (int r = 0; r < RPG; ++r) s[r] = base[r * rs];
656    float nq[LPT], nk[LPT], nv = 0.0f, ng = 0.0f, nb = 0.0f;
657    auto fetch = [&](int64_t t) {
658        const float* ht = h + t * C;
659#pragma unroll
660        for (int u = 0; u < LPT; ++u) { nq[u] = ht[qh * S + tid + u * NT]; nk[u] = ht[HK * S + qh * S + tid + u * NT]; }
661        nv = ht[2 * HK * S + head * S + col];
662        ng = gate[t * HV + head];
663        nb = beta[t * HV + head];
664    };
665    if (T > 0) fetch(0);
666    for (int64_t t = 0; t < T; ++t) {
667        float cq[LPT], ck[LPT];
668#pragma unroll
669        for (int u = 0; u < LPT; ++u) { cq[u] = nq[u]; ck[u] = nk[u]; }
670        const float cv = nv, cg = ng, cbt = nb;
671        __syncthreads();
672#pragma unroll
673        for (int u = 0; u < LPT; ++u) { sq[tid + u * NT] = cq[u]; sk[tid + u * NT] = ck[u]; }
674        __syncthreads();
675        if (t + 1 < T) fetch(t + 1);
676        const float g = __expf(cg);
677        float kv = 0.0f;
678#pragma unroll
679        for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv);
680        red[rg][c] = kv;
681        __syncthreads();
682        const float kv_col = red[0][c] + red[1][c] + red[2][c] + red[3][c];
683        const float delta = (cv - g * kv_col) * cbt;
684        float o = 0.0f;
685#pragma unroll
686        for (int r = 0; r < RPG; ++r) {
687            s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta);
688            o = fmaf(s[r], sq[rg * RPG + r], o);
689        }
690        __syncthreads();
691        red[rg][c] = o;
692        __syncthreads();
693        if (rg == 0) oc_out[t * HV * S + head * S + col] = (red[0][c] + red[1][c] + red[2][c] + red[3][c]) * rsqrtf((float) S);
694    }
695#pragma unroll
696    for (int r = 0; r < RPG; ++r) base[r * rs] = s[r];
697}
698// v100/gdn-chunk: gdn_rec_cols_pipe_kernel with the two 32-deep FMA chains (k^T W and q^T W) split into 4
699// accumulators each.  The chain is the recurrence's per-token floor (a 32-step dependent FFMA chain is ~128
700// cycles before the barriers); the split keeps the load pattern, the barriers and the (S, h_v, S) state
701// layout untouched.  FP32-level, NOT bit-exact - the four partial sums group the 32 products differently -
702// so it is opt-in by measured benefit (STRATA_GDN_REC_WARP=2; gdn_chunk_parity bounds the error).
703#if defined(STRATA_EXPERIMENTAL_SM60)
704__global__ void __launch_bounds__(CB * RG) gdn_rec_cols_pipe_fast_kernel(float* __restrict__ state,
705                                                                        const float* __restrict__ h,
706                                                                        const float* __restrict__ gate,
707                                                                        const float* __restrict__ beta,
708                                                                        float* __restrict__ oc_out, int64_t T) {
709    constexpr int NT = CB * RG, LPT = S / NT;
710    __shared__ float sk[S], sq[S], red[RG][CB];
711    const int head = blockIdx.x / NCB, cb = blockIdx.x % NCB;
712    const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c;
713    const int qh = head % HK;
714    float s[RPG];
715    float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col;
716    const size_t rs = (size_t) HV * S;
717#pragma unroll
718    for (int r = 0; r < RPG; ++r) s[r] = base[r * rs];
719    float nq[LPT], nk[LPT], nv = 0.0f, ng = 0.0f, nb = 0.0f;
720    auto fetch = [&](int64_t t) {
721        const float* ht = h + t * C;
722#pragma unroll
723        for (int u = 0; u < LPT; ++u) { nq[u] = ht[qh * S + tid + u * NT]; nk[u] = ht[HK * S + qh * S + tid + u * NT]; }
724        nv = ht[2 * HK * S + head * S + col];
725        ng = gate[t * HV + head];
726        nb = beta[t * HV + head];
727    };
728    if (T > 0) fetch(0);
729    for (int64_t t = 0; t < T; ++t) {
730        float cq[LPT], ck[LPT];
731#pragma unroll
732        for (int u = 0; u < LPT; ++u) { cq[u] = nq[u]; ck[u] = nk[u]; }
733        const float cv = nv, cg = ng, cbt = nb;
734        __syncthreads();
735#pragma unroll
736        for (int u = 0; u < LPT; ++u) { sq[tid + u * NT] = cq[u]; sk[tid + u * NT] = ck[u]; }
737        __syncthreads();
738        if (t + 1 < T) fetch(t + 1);
739        const float g = __expf(cg);
740        float kv[4] = {0.0f, 0.0f, 0.0f, 0.0f};
741#pragma unroll
742        for (int r = 0; r < RPG; ++r) kv[r & 3] = fmaf(s[r], sk[rg * RPG + r], kv[r & 3]);
743        red[rg][c] = (kv[0] + kv[1]) + (kv[2] + kv[3]);
744        __syncthreads();
745        const float kv_col = red[0][c] + red[1][c] + red[2][c] + red[3][c];
746        const float delta = (cv - g * kv_col) * cbt;
747        float o[4] = {0.0f, 0.0f, 0.0f, 0.0f};
748#pragma unroll
749        for (int r = 0; r < RPG; ++r) {
750            s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta);
751            o[r & 3] = fmaf(s[r], sq[rg * RPG + r], o[r & 3]);
752        }
753        __syncthreads();
754        red[rg][c] = (o[0] + o[1]) + (o[2] + o[3]);
755        __syncthreads();
756        if (rg == 0) oc_out[t * HV * S + head * S + col] = (red[0][c] + red[1][c] + red[2][c] + red[3][c]) * rsqrtf((float) S);
757    }
758#pragma unroll
759    for (int r = 0; r < RPG; ++r) base[r * rs] = s[r];
760}
761#endif
762
763#if !defined(__HIPCC__)
764// The recurrence with one thread for the three value heads that share a key head (head % HK): column c of heads
765// qh, qh + 16 and qh + 32, row group rg.  gdn_rec_cols_pipe_kernel spends its time in shared memory, not in
766// arithmetic: every thread of a warp needs the same 32 q and k values per token (the k twice), and a warp receives one
767// such broadcast value per clock however wide the load.  Here every q/k value a thread loads feeds three heads, and a
768// token's k row goes into registers once for both of its uses.  The inputs come in blocks of GDN_TB tokens, copied to
769// shared memory by cp.async while the block before computes (one token ahead is shorter than a load from L2 takes),
770// and the two cross-row-group sums have their own arrays, so a token needs 2 __syncthreads instead of 5: the second
771// one of a token orders every read of rkv before the next token's writes, the next token's first one every read of ro
772// before the writes after it.  64 blocks instead of 192.  Per value head and column the same arithmetic in the same
773// order: the same bits (src/prefill/gdn_rec_parity.cu checks them and times the variants: 1.41x on a 4080 Super).
774// sm_80+ cards that hold its 64 blocks at once (gdn_keyhead_ok); STRATA_GDN_KEYHEAD=0: gdn_rec_cols_pipe_kernel.
775#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
776#define STRATA_GDN_CP_ASYNC 0   // Turing builds: plain copies (never launched there, see gdn_keyhead_ok)
777#else
778#define STRATA_GDN_CP_ASYNC 1
779#endif
780__device__ __forceinline__ void gdn_cp4(float* smem, const float* gmem) {
781#if STRATA_GDN_CP_ASYNC
782    asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem));
783#else
784    *smem = *gmem;
785#endif
786}
787__device__ __forceinline__ void gdn_cp16(float* smem, const float* gmem) {
788#if STRATA_GDN_CP_ASYNC
789    asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem));
790#else
791    *reinterpret_cast<float4*>(smem) = *reinterpret_cast<const float4*>(gmem);
792#endif
793}
794__device__ __forceinline__ void gdn_cp_commit() {
795#if STRATA_GDN_CP_ASYNC
796    asm volatile("cp.async.commit_group;\n" ::);
797#endif
798}
799__device__ __forceinline__ void gdn_cp_wait_prev() {   // every group but the newest has landed
800#if STRATA_GDN_CP_ASYNC
801    asm volatile("cp.async.wait_group 1;\n" ::);
802#endif
803}
804constexpr int GDN_TB = 8, VPK = HV / HK;   // tokens per staged block, value heads per key head
805__global__ void __launch_bounds__(CB * RG) gdn_rec_kh_kernel(float* __restrict__ state, const float* __restrict__ h,
806                                                               const float* __restrict__ gate,
807                                                               const float* __restrict__ beta,
808                                                               float* __restrict__ oc_out, int64_t T) {
809    constexpr int TB = GDN_TB, NT = CB * RG, QKP = S / 4, VP = CB / 4;   // threads, 16-byte pieces of a q/k row, of v
810    __shared__ __align__(16) float sq[2][TB][S];
811    __shared__ __align__(16) float sk[2][TB][S];
812    __shared__ __align__(16) float sv[2][TB][VPK][CB];
813    __shared__ float sg[2][TB][VPK], sb[2][TB][VPK], rkv[VPK][RG][CB], ro[VPK][RG][CB];
814    const int qh = blockIdx.x / NCB, cb = blockIdx.x % NCB;
815    const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c;
816    float s[VPK][RPG];
817    const size_t rs = (size_t) HV * S;
818#pragma unroll
819    for (int j = 0; j < VPK; ++j) {
820        const float* base = state + ((size_t) (rg * RPG) * HV + qh + j * HK) * S + col;
821#pragma unroll
822        for (int r = 0; r < RPG; ++r) s[j][r] = base[r * rs];
823    }
824    const int64_t nblk = (T + TB - 1) / TB;
825    auto stage = [&](int64_t k) {   // tokens [k * TB, k * TB + TB) into buffer k & 1
826        const int bb = (int) (k & 1);
827        const int64_t t0 = k * TB;
828        for (int p = tid; p < TB * 2 * QKP; p += NT) {
829            const int i = p / (2 * QKP), w = p % (2 * QKP), isk = w / QKP, jj = (w % QKP) * 4;
830            if (t0 + i < T)
831                gdn_cp16(isk ? &sk[bb][i][jj] : &sq[bb][i][jj], h + (t0 + i) * C + (isk ? HK * S : 0) + qh * S + jj);
832        }
833        for (int p = tid; p < TB * VPK * VP; p += NT) {
834            const int i = p / (VPK * VP), w = p % (VPK * VP), j = w / VP, jj = (w % VP) * 4;
835            if (t0 + i < T)
836                gdn_cp16(&sv[bb][i][j][jj], h + (t0 + i) * C + 2 * HK * S + (qh + j * HK) * S + cb * CB + jj);
837        }
838        for (int p = tid; p < 2 * TB * VPK; p += NT) {
839            const int isb = p / (TB * VPK), w = p % (TB * VPK), i = w / VPK, j = w % VPK;
840            if (t0 + i < T)
841                gdn_cp4(isb ? &sb[bb][i][j] : &sg[bb][i][j], (isb ? beta : gate) + (t0 + i) * HV + qh + j * HK);
842        }
843    };
844    if (nblk > 0) stage(0);
845    gdn_cp_commit();
846    for (int64_t k = 0; k < nblk; ++k) {
847        // buffer (k + 1) & 1 was read by block k - 1, whose last token's second __syncthreads every thread has passed
848        if (k + 1 < nblk) stage(k + 1);
849        gdn_cp_commit();
850        gdn_cp_wait_prev();
851        __syncthreads();
852        const int bb = (int) (k & 1);
853        const int n = (int) ((T - k * TB) < TB ? (T - k * TB) : TB);
854        for (int i = 0; i < n; ++i) {
855            const int64_t t = k * TB + i;
856            float kc[RPG];
857#pragma unroll
858            for (int r = 0; r < RPG; ++r) kc[r] = sk[bb][i][rg * RPG + r];
859            float g[VPK], kv[VPK], delta[VPK], o[VPK];
860#pragma unroll
861            for (int j = 0; j < VPK; ++j) { g[j] = __expf(sg[bb][i][j]); kv[j] = 0.0f; o[j] = 0.0f; }
862#pragma unroll
863            for (int r = 0; r < RPG; ++r)
864#pragma unroll
865                for (int j = 0; j < VPK; ++j) kv[j] = fmaf(s[j][r], kc[r], kv[j]);
866#pragma unroll
867            for (int j = 0; j < VPK; ++j) rkv[j][rg][c] = kv[j];
868            __syncthreads();
869#pragma unroll
870            for (int j = 0; j < VPK; ++j) {
871                const float kv_col = rkv[j][0][c] + rkv[j][1][c] + rkv[j][2][c] + rkv[j][3][c];
872                delta[j] = (sv[bb][i][j][c] - g[j] * kv_col) * sb[bb][i][j];
873            }
874#pragma unroll
875            for (int r = 0; r < RPG; ++r) {
876                const float qr = sq[bb][i][rg * RPG + r];
877#pragma unroll
878                for (int j = 0; j < VPK; ++j) {
879                    s[j][r] = fmaf(g[j], s[j][r], kc[r] * delta[j]);
880                    o[j] = fmaf(s[j][r], qr, o[j]);
881                }
882            }
883#pragma unroll
884            for (int j = 0; j < VPK; ++j) ro[j][rg][c] = o[j];
885            __syncthreads();
886            if (rg < VPK)   // row group j writes head j's output
887                oc_out[t * HV * S + (qh + rg * HK) * S + col] =
888                    (ro[rg][0][c] + ro[rg][1][c] + ro[rg][2][c] + ro[rg][3][c]) * rsqrtf((float) S);
889        }
890    }
891#pragma unroll
892    for (int j = 0; j < VPK; ++j) {
893        float* base = state + ((size_t) (rg * RPG) * HV + qh + j * HK) * S + col;
894#pragma unroll
895        for (int r = 0; r < RPG; ++r) base[r * rs] = s[j][r];
896    }
897}
898// gdn_rec_kh_kernel where it pays: a CUDA card with cp.async (sm_80+) that holds all 64 of its blocks at once (each
899// walks the whole chunk, so blocks left for a second wave would double the time).  The busiest SM sets the pace: from
900// 64 SMs up this kernel has one block per SM, below that two on some SMs, while the kernel before has ceil(192 / SMs).
901// With the engine's grids on fewer SMs (gdn_rec_parity --bench), on a 4080 SUPER / a 3090: 1.40-1.42x / 1.28-1.29x at
902// 64 SMs and more, 1.02-1.04x / 1.03-1.06x at 48 to 63 (two blocks against four: a draw, slower on neither),
903// 1.28-1.31x / 1.28-1.30x at 39 to 47, 1.53-1.57x / 1.54-1.55x at 32 to 38.  Per call, from the current device (a
904// layer split can mix cards).
905bool gdn_keyhead_ok() {
906    static const bool off = [] { const char* v = std::getenv("STRATA_GDN_KEYHEAD"); return v != nullptr && std::atoi(v) == 0; }();
907    if (off) return false;
908    static int known[64] = {};   // per device: 0 not asked yet, 1 yes, 2 no
909    int dev = 0;
910    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
911    if (known[dev] == 0) {
912        int major = 0, sms = 0, per_sm = 0;
913        const bool yes = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
914                         cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev) == cudaSuccess && major >= 8 &&
915                         cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm, gdn_rec_kh_kernel, CB * RG, 0) ==
916                             cudaSuccess &&
917                         (int64_t) per_sm * sms >= (int64_t) HK * NCB;
918        if (!yes) cudaGetLastError();
919        known[dev] = yes ? 1 : 2;
920    }
921    return known[dev] == 1;
922}
923// STRATA_GDN_CHUNKED=1 (opt-in): the recurrence in chunks of GCH tokens (the WY form of the gated delta rule, as
924// flash-linear-attention computes it), all in FP32.  Per value head, with g_t = exp(gate_t), gamma_t the gate's sum
925// from the chunk's start to t (inclusive) and S0 the state before the chunk:
926//   A[t][i] = beta_t exp(gamma_t - gamma_i) k_t.k_i (i < t),   T = (I + A)^-1 (unit lower triangular),
927//   Y_t = beta_t (v_t - exp(gamma_t) S0^T k_t),   D = T Y (the delta rule's corrections, one per token),
928//   o_t = exp(gamma_t) S0^T q_t + sum_{i <= t} exp(gamma_t - gamma_i) (q_t.k_i) D_i,
929//   S = exp(gamma_last) S0 + sum_t exp(gamma_last - gamma_t) k_t D_t^T,
930// the same state and outputs as the token-by-token kernels up to FP32 rounding (another order of the sums).
931// gdn_chunk_prep_kernel builds T, P = exp(gamma_t - gamma_i) q_t.k_i (i <= t) and gamma for every chunk of a
932// super-block at once (a block per chunk and key head: its three value heads share k and q); gdn_chunk_scan_kernel then
933// walks the super-block's chunks per (value head, 16 columns): the state slice in registers, the products as small
934// register-tiled matmuls from shared memory.  Every exponent is <= 0 (gates are negative), so nothing overflows.
935// STRATA_GDN_CHUNKED=1 takes prompt chunks of this many tokens and more: on an RTX 5090 the two launches cost more
936// than they save below ~100 tokens (gdn_rec_parity --bench: 32 tokens 0.58x gdn_rec_kh_kernel, 96 1.03x, 128 1.20x,
937// 512 1.67x, 2048+ 1.81x)
938constexpr int64_t kGdnChunkedMin = 128;
939constexpr int64_t kGdnTcMin = 128;        // STRATA_GDN_TC: the two launches cost ~20 us; below this the kh kernel wins
940constexpr int GCH = 32;            // tokens per chunk (the prep's solve is a lane per token)
941constexpr int GSB = 2048;          // tokens per super-block: the prep's scratch is GSB / GCH chunks of T, P and gamma
942constexpr int GDV = 16;            // value columns per scan block
943constexpr int GKP = S + 4;         // the scan's padded q / k rows (8 rows of a warp land on 8 banks)
944constexpr int GTP = GCH + 1;       // padded T / P rows
945static_assert(GCH == 32, "gdn_chunk_prep_kernel: a lane per token of the chunk");
946constexpr size_t kChunkPrepSmem = sizeof(float) * (2 * GCH * (S + 1) + 2 * GCH * GTP);   // A over k / q
947static_assert(VPK * GCH * GTP <= 2 * GCH * (S + 1), "gdn_chunk_prep_kernel: A fits where k and q were");
948constexpr size_t kChunkScanSmem = sizeof(float) * (3 * GCH * GKP + VPK * (S * GDV + 3 * GCH * GDV));
949
950__global__ void __launch_bounds__(256) gdn_chunk_prep_kernel(const float* __restrict__ h, const float* __restrict__ gate,
951                                                             const float* __restrict__ beta, float* __restrict__ tm,
952                                                             float* __restrict__ pm, float* __restrict__ gm, int64_t t0,
953                                                             int64_t T) {
954    extern __shared__ __align__(16) float gsm[];
955    float* sk = gsm;                       // [GCH][S + 1]
956    float* sq = sk + GCH * (S + 1);        // [GCH][S + 1]
957    float* skk = sq + GCH * (S + 1);       // [GCH][GTP]  k_t.k_i
958    float* sqk = skk + GCH * GTP;          // [GCH][GTP]  q_t.k_i
959    float* sa = gsm;                       // [VPK][GCH][GTP]  A, then T below the diagonal (over k and q:
960                                           // read by then, so two blocks share an SM)
961    const int qh = blockIdx.y, ch = blockIdx.x, tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
962    const int64_t tb = t0 + (int64_t) ch * GCH;
963    const int n = (int) min((int64_t) GCH, T - tb);
964    {   // k and q as float4, every load issued before the first store
965        constexpr int NP = GCH * S / 4 / 256;   // float4 a thread, each of k and q
966        float4 kv[NP], qv[NP];
967#pragma unroll
968        for (int m = 0; m < NP; ++m) {
969            const int p = tid + 256 * m, t = p / (S / 4), r = (p % (S / 4)) * 4;
970            kv[m] = t < n ? *reinterpret_cast<const float4*>(h + (tb + t) * C + HK * S + qh * S + r) : make_float4(0.f, 0.f, 0.f, 0.f);
971            qv[m] = t < n ? *reinterpret_cast<const float4*>(h + (tb + t) * C + qh * S + r) : make_float4(0.f, 0.f, 0.f, 0.f);
972        }
973#pragma unroll
974        for (int m = 0; m < NP; ++m) {
975            const int p = tid + 256 * m, t = p / (S / 4), r = (p % (S / 4)) * 4;
976            float* dk = sk + t * (S + 1) + r;
977            float* dq = sq + t * (S + 1) + r;
978            dk[0] = kv[m].x; dk[1] = kv[m].y; dk[2] = kv[m].z; dk[3] = kv[m].w;
979            dq[0] = qv[m].x; dq[1] = qv[m].y; dq[2] = qv[m].z; dq[3] = qv[m].w;
980        }
981    }
982    __syncthreads();
983    {   // lane i, rows warp + 8m: k_t.k_i and q_t.k_i on eight independent sums (rows 129 apart: 32 banks)
984        constexpr int RW = GCH / 8;
985        float kk[RW] = {}, qk[RW] = {};
986        for (int r = 0; r < S; ++r) {
987            const float ki = sk[lane * (S + 1) + r];
988#pragma unroll
989            for (int m = 0; m < RW; ++m) {
990                kk[m] = fmaf(sk[(warp + 8 * m) * (S + 1) + r], ki, kk[m]);
991                qk[m] = fmaf(sq[(warp + 8 * m) * (S + 1) + r], ki, qk[m]);
992            }
993        }
994#pragma unroll
995        for (int m = 0; m < RW; ++m) {
996            const int t = warp + 8 * m;
997            skk[t * GTP + lane] = lane <= t ? kk[m] : 0.0f;
998            sqk[t * GTP + lane] = lane <= t ? qk[m] : 0.0f;
999        }
1000    }
1001    __syncthreads();
1002    if (warp >= VPK) return;
1003    const int vh = qh + warp * HK, i = lane;   // warp j: value head j of the key head; lane i: token i (column i)
1004    float* a = sa + warp * GCH * GTP;
1005    const float b = i < n ? beta[(tb + i) * HV + vh] : 0.0f;
1006    float gam = i < n ? gate[(tb + i) * HV + vh] : 0.0f;   // past the end: gate 0, beta 0 (no effect on S)
1007#pragma unroll
1008    for (int o = 1; o < 32; o <<= 1) {
1009        const float u = __shfl_up_sync(0xffffffffu, gam, o);
1010        if (lane >= o) gam += u;
1011    }
1012    for (int t = 0; t < GCH; ++t) {
1013        const float gt = __shfl_sync(0xffffffffu, gam, t), bt = __shfl_sync(0xffffffffu, b, t);
1014        a[t * GTP + i] = i < t ? bt * expf(gt - gam) * skk[t * GTP + i] : (i == t ? 1.0f : 0.0f);
1015    }
1016    __syncwarp();
1017    // T = (I + A)^-1 by forward substitution, row by row in place: T[t][i] = -sum_{k < t} A[t][k] T[k][i] over the
1018    // finished rows (diagonal 1, zeros above it: the terms k < i add an exact 0, so the same bits as summing from k = i)
1019    // - a trip the whole warp shares, so the loads go ahead of the sums
1020    for (int t = 1; t < GCH; ++t) {
1021        float v = 0.0f;
1022#pragma unroll 8
1023        for (int k = 0; k < t; ++k) v = fmaf(-a[t * GTP + k], a[k * GTP + i], v);
1024        __syncwarp();
1025        if (i < t) a[t * GTP + i] = v;
1026        __syncwarp();
1027    }
1028    float* T_ = tm + ((int64_t) ch * HV + vh) * GCH * GCH;
1029    float* P_ = pm + ((int64_t) ch * HV + vh) * GCH * GCH;
1030    for (int t = 0; t < GCH; ++t) {
1031        const float gt = __shfl_sync(0xffffffffu, gam, t);
1032        T_[t * GCH + i] = a[t * GTP + i];
1033        P_[t * GCH + i] = i <= t ? expf(gt - gam) * sqk[t * GTP + i] : 0.0f;
1034    }
1035    gm[((int64_t) ch * HV + vh) * GCH + i] = gam;
1036}
1037
1038__device__ __forceinline__ void gdn_pf_l2(const float* p) { asm volatile("prefetch.global.L2 [%0];" ::"l"(p)); }
1039__device__ __forceinline__ void gdn_cp_wait_all() {
1040#if STRATA_GDN_CP_ASYNC
1041    asm volatile("cp.async.wait_all;\n" ::);
1042#endif
1043}
1044// A block per (key head, 16 value columns): 128 threads for each of the key head's three value heads, which share the
1045// staged k and q rows.  128 blocks, one an SM, in one wave (each walks every chunk: a second wave would double the
1046// time).  A thread owns one token's row of the products (4 columns) and holds that token's T and P rows in registers,
1047// loaded at the chunk's start so they land during the first product; the next chunk's k (a second buffer), q (after
1048// this chunk's last read of q), v, gamma and beta load while this chunk computes.  Three barriers a chunk.
1049__global__ void __launch_bounds__(128 * VPK) gdn_chunk_scan_kernel(float* __restrict__ state, const float* __restrict__ h,
1050                                                                   const float* __restrict__ beta, const float* __restrict__ tm,
1051                                                                   const float* __restrict__ pm, const float* __restrict__ gm,
1052                                                                   float* __restrict__ oc_out, int64_t t0, int nch, int64_t T) {
1053    extern __shared__ __align__(16) float gsm[];
1054    constexpr int NT = 128 * VPK, HEAD = S * GDV + 3 * GCH * GDV;   // threads; a head's shared floats
1055    float* kbuf = gsm;                     // [2][GCH][GKP]  k, double-buffered
1056    float* sq = kbuf + 2 * GCH * GKP;      // [GCH][GKP]
1057    const int qh = blockIdx.x, c0 = blockIdx.y * GDV, j = threadIdx.x / 128, tid = threadIdx.x % 128;
1058    const int vh = qh + j * HK;
1059    float* ss = sq + GCH * GKP + j * HEAD; // [S][GDV]  the state slice at the chunk's start
1060    float* sy = ss + S * GDV;              // [GCH][GDV]  Y
1061    float* sd = sy + GCH * GDV;            // [GCH][GDV]  D
1062    float* sdd = sd + GCH * GDV;           // [GCH][GDV]  exp(gamma_last - gamma_t) D
1063    const int rq = tid >> 2, vq = tid & 3;   // the update's tile: rows 4rq..4rq+3; both tiles: columns 4vq..4vq+3
1064    const int tt = tid >> 2, vv = 4 * vq;    // the products' tile: token tt
1065    const size_t rs = (size_t) HV * S;
1066    auto stage_kq = [&](int64_t c_t0, int n, float* dst, bool isq) {   // k or q rows of a chunk, cp.async
1067        for (int p = threadIdx.x; p < GCH * (S / 4); p += NT) {
1068            const int t = p / (S / 4), r = (p % (S / 4)) * 4;
1069            if (t < n) gdn_cp16(dst + t * GKP + r, h + (c_t0 + t) * C + (isq ? 0 : HK * S) + qh * S + r);
1070            else *reinterpret_cast<float4*>(dst + t * GKP + r) = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
1071        }
1072    };
1073    // this tile's v, gamma, beta and the chunk's last gamma (registers)
1074    auto load_vgb = [&](int ch, int64_t c_t0, int n, float4& v4, float& gam, float& bet, float& glast) {
1075        v4 = tt < n ? __ldg(reinterpret_cast<const float4*>(h + (c_t0 + tt) * C + 2 * HK * S + vh * S + c0 + vv))
1076                    : make_float4(0.0f, 0.0f, 0.0f, 0.0f);
1077        const float* g = gm + ((int64_t) ch * HV + vh) * GCH;
1078        gam = __ldg(g + tt);
1079        glast = __ldg(g + GCH - 1);
1080        bet = tt < n ? __ldg(beta + (c_t0 + tt) * HV + vh) : 0.0f;
1081    };
1082    float s[4][4];
1083#pragma unroll
1084    for (int x = 0; x < 4; ++x) {
1085#pragma unroll
1086        for (int y = 0; y < 4; ++y) s[x][y] = state[(size_t) (4 * rq + x) * rs + (size_t) vh * S + c0 + vv + y];
1087        *reinterpret_cast<float4*>(&ss[(4 * rq + x) * GDV + vv]) = make_float4(s[x][0], s[x][1], s[x][2], s[x][3]);
1088    }
1089    const float out_scale = rsqrtf((float) S);
1090    float4 v4;
1091    float gam, bet, glast;
1092    {
1093        const int n0 = (int) min((int64_t) GCH, T - t0);
1094        stage_kq(t0, n0, kbuf, false);
1095        stage_kq(t0, n0, sq, true);
1096        gdn_cp_commit();
1097        load_vgb(0, t0, n0, v4, gam, bet, glast);
1098        gdn_cp_wait_all();
1099        __syncthreads();
1100    }
1101    for (int ch = 0; ch < nch; ++ch) {
1102        const int64_t c_t0 = t0 + (int64_t) ch * GCH;
1103        const int n = (int) min((int64_t) GCH, T - c_t0);
1104        const bool more = ch + 1 < nch;
1105        const int64_t n_t0 = c_t0 + GCH;
1106        const int nn = more ? (int) min((int64_t) GCH, T - n_t0) : 0;
1107        const float* sk = kbuf + (ch & 1) * GCH * GKP;
1108        // this token's T and P rows into registers now: they land while the first product runs
1109        float tr[GCH], pr[GCH];
1110        {
1111            const float4* T4 = reinterpret_cast<const float4*>(tm + (((int64_t) ch * HV + vh) * GCH + tt) * GCH);
1112            const float4* P4 = reinterpret_cast<const float4*>(pm + (((int64_t) ch * HV + vh) * GCH + tt) * GCH);
1113#pragma unroll
1114            for (int i = 0; i < GCH / 4; ++i) {
1115                const float4 a = __ldg(T4 + i), b = __ldg(P4 + i);
1116                tr[4 * i] = a.x; tr[4 * i + 1] = a.y; tr[4 * i + 2] = a.z; tr[4 * i + 3] = a.w;
1117                pr[4 * i] = b.x; pr[4 * i + 1] = b.y; pr[4 * i + 2] = b.z; pr[4 * i + 3] = b.w;
1118            }
1119        }
1120        float4 nv4 = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
1121        float ngam = 0.0f, nbet = 0.0f, nglast = 0.0f;
1122        if (more) {   // the next chunk's v, gamma and beta; the one after into L2 (its k and q: after barrier A)
1123            load_vgb(ch + 1, n_t0, nn, nv4, ngam, nbet, nglast);
1124            const int64_t f_t0 = n_t0 + GCH;
1125            const int t = threadIdx.x >> 3, l = threadIdx.x & 7;
1126            if (t < GCH && f_t0 + t < T) gdn_pf_l2(h + (f_t0 + t) * C + (l < 4 ? HK * S : 0) + qh * S + 32 * (l & 3));
1127            if (tid < GCH) {
1128                gdn_pf_l2(tm + (((int64_t) (ch + 1) * HV + vh) * GCH + tid) * GCH);
1129                gdn_pf_l2(pm + (((int64_t) (ch + 1) * HV + vh) * GCH + tid) * GCH);
1130            }
1131        }
1132        // X = K S0 and Q S0 for token tt, then Y = beta (V - exp(gamma) X)
1133        float x[4] = {0.f, 0.f, 0.f, 0.f}, qs[4] = {0.f, 0.f, 0.f, 0.f};
1134#pragma unroll 4
1135        for (int r = 0; r < S; r += 4) {
1136            const float4 k4 = *reinterpret_cast<const float4*>(&sk[tt * GKP + r]);
1137            const float4 q4 = *reinterpret_cast<const float4*>(&sq[tt * GKP + r]);
1138            const float kk[4] = {k4.x, k4.y, k4.z, k4.w}, qq[4] = {q4.x, q4.y, q4.z, q4.w};
1139#pragma unroll
1140            for (int jj = 0; jj < 4; ++jj) {
1141                const float4 s4 = *reinterpret_cast<const float4*>(&ss[(r + jj) * GDV + vv]);
1142                x[0] = fmaf(kk[jj], s4.x, x[0]); x[1] = fmaf(kk[jj], s4.y, x[1]);
1143                x[2] = fmaf(kk[jj], s4.z, x[2]); x[3] = fmaf(kk[jj], s4.w, x[3]);
1144                qs[0] = fmaf(qq[jj], s4.x, qs[0]); qs[1] = fmaf(qq[jj], s4.y, qs[1]);
1145                qs[2] = fmaf(qq[jj], s4.z, qs[2]); qs[3] = fmaf(qq[jj], s4.w, qs[3]);
1146            }
1147        }
1148        const float e = expf(gam);
1149        *reinterpret_cast<float4*>(&sy[tt * GDV + vv]) = make_float4(bet * (v4.x - e * x[0]), bet * (v4.y - e * x[1]),
1150                                                                     bet * (v4.z - e * x[2]), bet * (v4.w - e * x[3]));
1151        __syncthreads();   // (A) Y complete; every read of q done
1152        if (more) {        // the next chunk's k into the other buffer, its q into the single q buffer
1153            stage_kq(n_t0, nn, kbuf + ((ch + 1) & 1) * GCH * GKP, false);
1154            stage_kq(n_t0, nn, sq, true);
1155            gdn_cp_commit();
1156        }
1157        // D = T Y (T is zero above its diagonal), and D decayed to the chunk's end for the update
1158        float d[4] = {0.f, 0.f, 0.f, 0.f};
1159#pragma unroll
1160        for (int i = 0; i < GCH; ++i) {
1161            const float4 y4 = *reinterpret_cast<const float4*>(&sy[i * GDV + vv]);
1162            d[0] = fmaf(tr[i], y4.x, d[0]); d[1] = fmaf(tr[i], y4.y, d[1]);
1163            d[2] = fmaf(tr[i], y4.z, d[2]); d[3] = fmaf(tr[i], y4.w, d[3]);
1164        }
1165        const float f = expf(glast - gam);
1166        *reinterpret_cast<float4*>(&sd[tt * GDV + vv]) = make_float4(d[0], d[1], d[2], d[3]);
1167        *reinterpret_cast<float4*>(&sdd[tt * GDV + vv]) = make_float4(f * d[0], f * d[1], f * d[2], f * d[3]);
1168        __syncthreads();   // (B) D complete
1169        // o = exp(gamma) Q S0 + P D (P is zero above its diagonal), the output
1170        float o[4] = {e * qs[0], e * qs[1], e * qs[2], e * qs[3]};
1171#pragma unroll
1172        for (int i = 0; i < GCH; ++i) {
1173            const float4 d4 = *reinterpret_cast<const float4*>(&sd[i * GDV + vv]);
1174            o[0] = fmaf(pr[i], d4.x, o[0]); o[1] = fmaf(pr[i], d4.y, o[1]);
1175            o[2] = fmaf(pr[i], d4.z, o[2]); o[3] = fmaf(pr[i], d4.w, o[3]);
1176        }
1177        if (tt < n)
1178            *reinterpret_cast<float4*>(oc_out + (c_t0 + tt) * HV * S + vh * S + c0 + vv) =
1179                make_float4(o[0] * out_scale, o[1] * out_scale, o[2] * out_scale, o[3] * out_scale);
1180        // S = exp(gamma_last) S0 + K^T (decayed D)
1181        const float gL = expf(glast);
1182#pragma unroll
1183        for (int xx = 0; xx < 4; ++xx)
1184#pragma unroll
1185            for (int y = 0; y < 4; ++y) s[xx][y] *= gL;
1186#pragma unroll 4
1187        for (int t = 0; t < GCH; ++t) {
1188            const float4 k4 = *reinterpret_cast<const float4*>(&sk[t * GKP + 4 * rq]);
1189            const float4 d4 = *reinterpret_cast<const float4*>(&sdd[t * GDV + vv]);
1190            const float kx[4] = {k4.x, k4.y, k4.z, k4.w}, dy[4] = {d4.x, d4.y, d4.z, d4.w};
1191#pragma unroll
1192            for (int xx = 0; xx < 4; ++xx)
1193#pragma unroll
1194                for (int y = 0; y < 4; ++y) s[xx][y] = fmaf(kx[xx], dy[y], s[xx][y]);
1195        }
1196#pragma unroll
1197        for (int xx = 0; xx < 4; ++xx)
1198            *reinterpret_cast<float4*>(&ss[(4 * rq + xx) * GDV + vv]) = make_float4(s[xx][0], s[xx][1], s[xx][2], s[xx][3]);
1199        v4 = nv4; gam = ngam; bet = nbet; glast = nglast;
1200        gdn_cp_wait_all();
1201        __syncthreads();   // (C) the new ss, the next k and q landed; every read of sd, sdd and this k buffer done
1202    }
1203#pragma unroll
1204    for (int xx = 0; xx < 4; ++xx)
1205#pragma unroll
1206        for (int y = 0; y < 4; ++y) state[(size_t) (4 * rq + xx) * rs + (size_t) vh * S + c0 + vv + y] = s[xx][y];
1207}
1208// the same scan on the tensor cores (STRATA_GDN_TC=1, gdn_rec_tc below); src/prefill/gdn_rec_parity.cu includes the
1209// same text
1210#include "gdn_tc.cuh"
1211
1212// The scratch, one a device: allocated on first use at its largest (GSB / GCH chunks of T, P and gamma: 25.6 MB) and
1213// kept (a device runs its prompt on one stream).  A stream-ordered allocation and free per call, even from a pool that
1214// keeps its memory, cost host time the GPU waited for (a 2K prompt's recurrence took 78 ms against 34 ms for
1215// gdn_rec_kh_kernel).
1216float* gdn_chunk_scratch() {
1217    static float* bufs[64] = {};
1218    int dev = 0;
1219    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return nullptr; }
1220    if (bufs[dev] == nullptr) {
1221        const size_t n = (size_t) (GSB / GCH) * HV * (2 * GCH * GCH + GCH);
1222        if (cudaMalloc((void**) &bufs[dev], n * sizeof(float)) != cudaSuccess) {
1223            cudaGetLastError();
1224            bufs[dev] = nullptr;
1225        }
1226    }
1227    return bufs[dev];
1228}
1229
1230// The whole recurrence of T tokens in super-blocks of GSB: a prep and a scan launch each, the scratch (T, P and gamma
1231// of a super-block's chunks: up to GSB / GCH x 48 heads x (2 x 32 x 32 + 32) floats, 25.6 MB) from gdn_chunk_scratch.
1232// y: the [T][HV][S] output.  An error return means nothing was launched (the caller takes another kernel): the scratch
1233// could not be had, or the card has fewer than 128 SMs (a second wave of the scan would double it) or too little
1234// shared memory for it (Turing).
1235cudaError_t gdn_rec_chunked(float* state, const float* h, const float* gate, const float* beta, float* y, int64_t T,
1236                            cudaStream_t s) {
1237    if (T <= 0) return cudaSuccess;
1238    {   // sm_80+ (cp.async), the scan's 128 blocks one an SM in one wave, and its 93.7 KB of shared memory (else:
1239        // another kernel)
1240        int dev = 0, major = 0, sms = 0, smem = 0;
1241        if (cudaGetDevice(&dev) != cudaSuccess ||
1242            cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess ||
1243            cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev) != cudaSuccess ||
1244            cudaDeviceGetAttribute(&smem, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev) != cudaSuccess) {
1245            cudaGetLastError();
1246            return cudaErrorNotSupported;
1247        }
1248        // STRATA_GDN_CHUNKED=2 skips the SM-count test (measurement on a card under 128 SMs: the scan then runs in
1249        // several waves and is expected to be slower than the default kernel; the architecture and shared-memory
1250        // tests stay)
1251        static const bool any_sms_env = [] { const char* v = std::getenv("STRATA_GDN_CHUNKED"); return v != nullptr && std::atoi(v) >= 2; }();
1252        const GdnProbe* pr = gdn_probe_get();   // tests only: the same as =2, per call
1253        const bool any_sms = any_sms_env || (pr != nullptr && pr->any_sms);
1254        if (strata::cc_major_of(major) < 8 || (!any_sms && sms < HK * (S / GDV)) || (size_t) strata::smem_optin_of(smem) < kChunkScanSmem)
1255            return cudaErrorNotSupported;
1256    }
1257    float* scratch = gdn_chunk_scratch();
1258    if (scratch == nullptr) return cudaErrorMemoryAllocation;
1259    // the scratch segment: a test may ask for a smaller one than GSB (a multiple of GCH); production always GSB
1260    int64_t gsb = GSB;
1261    if (const GdnProbe* pr = gdn_probe_get())
1262        if (pr->gsb >= GCH && pr->gsb < GSB) gsb = (pr->gsb / GCH) * GCH;
1263    const int nb = (int) ((std::min<int64_t>(gsb, T) + GCH - 1) / GCH);
1264    const size_t tsz = (size_t) nb * HV * GCH * GCH;
1265    float *tm = scratch, *pm = tm + tsz, *gm = pm + tsz;
1266    {   // once a device
1267        static bool attrs[64] = {};
1268        int dev = 0;
1269        cudaGetDevice(&dev);
1270        if (dev >= 0 && dev < 64 && !attrs[dev]) {
1271            cudaFuncSetAttribute(gdn_chunk_prep_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kChunkPrepSmem);
1272            cudaFuncSetAttribute(gdn_chunk_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kChunkScanSmem);
1273            attrs[dev] = true;
1274        }
1275    }
1276    for (int64_t t0 = 0; t0 < T; t0 += gsb) {
1277        const int nch = (int) ((std::min<int64_t>(gsb, T - t0) + GCH - 1) / GCH);
1278        gdn_chunk_prep_kernel<<<dim3((unsigned) nch, HK), 256, kChunkPrepSmem, s>>>(h, gate, beta, tm, pm, gm, t0, T);
1279        gdn_chunk_scan_kernel<<<dim3(HK, S / GDV), 128 * VPK, kChunkScanSmem, s>>>(state, h, beta, tm, pm, gm, y, t0, nch, T);
1280    }
1281    return cudaSuccess;   // launch errors surface at the caller's check; an error above means nothing ran
1282}
1283// STRATA_GDN_TC=1: gdn_rec_chunked with the scan on the tensor cores (gdn_tc_scan_kernel, gdn_tc.cuh) and the prep
1284// that also writes its f16 images (gdn_tc_prep_kernel, scratch gdn_tc_scratch), 48 blocks of 256 threads in one wave.  An error return means nothing was launched: the card is below
1285// sm_80, has fewer than 48 SMs, or less than 122 KB of shared memory a block.
1286// value tiles a head for the split tensor-core scan: STRATA_GDN_TC_TILES=1|2 (or the probe's tc_tiles) asks; 1 otherwise
1287int gdn_tc_tiles() {
1288    const GdnProbe* pr = gdn_probe_get();
1289    if (pr != nullptr && pr->tc_tiles > 0) return pr->tc_tiles >= 2 ? 2 : 1;
1290    static const int e = [] { const char* v = std::getenv("STRATA_GDN_TC_TILES"); return v ? std::atoi(v) : 0; }();
1291    if (e > 0) return e >= 2 ? 2 : 1;
1292    // automatic: two tiles when all 2 x 48 blocks fit the card in one wave (measured: PRO 5000 / 110 SMs rec 1.47x; A6000 / 84 SMs
1293    // is 1.25x SLOWER with two tiles, its 96 blocks need a second wave)
1294    static int sms_of[64] = {};
1295    int dev = 0;
1296    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return 1; }
1297    if (sms_of[dev] == 0) {
1298        int n = 0;
1299        if (cudaDeviceGetAttribute(&n, cudaDevAttrMultiProcessorCount, dev) != cudaSuccess) { cudaGetLastError(); n = 1; }
1300        sms_of[dev] = n;
1301    }
1302    return sms_of[dev] >= 2 * HV ? 2 : 1;
1303}
1304// the output norm's operands, when the split scan fuses it (see gdn_tc_scan_kernel NORM)
1305struct GdnTcNorm {
1306    const float* z;
1307    const float* gamma;
1308    float eps;
1309    uint16_t* y16;
1310    int64_t ld16;
1311};
1312cudaError_t gdn_rec_tc(float* state, const float* h, const float* gate, const float* beta, float* y, int64_t T,
1313                       cudaStream_t s, bool split = false, int np = 3, const GdnTcNorm* nm = nullptr, int tiles = 1) {
1314    if (T <= 0) return cudaSuccess;
1315    {
1316        int dev = 0, major = 0, sms = 0, smem = 0;
1317        if (cudaGetDevice(&dev) != cudaSuccess ||
1318            cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess ||
1319            cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev) != cudaSuccess ||
1320            cudaDeviceGetAttribute(&smem, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev) != cudaSuccess) {
1321            cudaGetLastError();
1322            return cudaErrorNotSupported;
1323        }
1324        const GdnProbe* pr = gdn_probe_get();   // tests only: fewer SMs than value heads run the 48 blocks in several waves
1325        const bool any_sms = pr != nullptr && pr->any_sms;
1326        if (strata::cc_major_of(major) < 8 || (!any_sms && sms < HV) ||
1327            (size_t) strata::smem_optin_of(smem) < (split ? (nm ? kTcScanSmemSplitNorm : kTcScanSmemSplit) : kTcScanSmem<false>))
1328            return cudaErrorNotSupported;
1329    }
1330    const GtcScratch sc = gdn_tc_scratch();
1331    if (sc.ti == nullptr) return cudaErrorMemoryAllocation;
1332    {   // once a device
1333        static bool attrs[3][64] = {};
1334        const int ai = nm && split ? 2 : (split ? 1 : 0);
1335        int dev = 0;
1336        cudaGetDevice(&dev);
1337        if (dev >= 0 && dev < 64 && !attrs[ai][dev]) {
1338            if (split) cudaFuncSetAttribute(gdn_tc_scan_kernel<false, true, 3, 2>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplit);
1339            if (ai == 2) {
1340                cudaFuncSetAttribute(gdn_tc_scan_kernel<true, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplitNorm);
1341                cudaFuncSetAttribute(gdn_tc_scan_kernel<true, true, 2>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplitNorm);
1342                cudaFuncSetAttribute(gdn_tc_scan_kernel<true, true, 1>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplitNorm);
1343            } else if (split) {
1344                cudaFuncSetAttribute(gdn_tc_scan_kernel<false, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplit);
1345                cudaFuncSetAttribute(gdn_tc_scan_kernel<false, true, 2>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplit);
1346                cudaFuncSetAttribute(gdn_tc_scan_kernel<false, true, 1>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmemSplit);
1347            }
1348            else cudaFuncSetAttribute(gdn_tc_scan_kernel<false>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmem<false>);
1349            attrs[ai][dev] = true;
1350        }
1351    }
1352    for (int64_t t0 = 0; t0 < T; t0 += GSB) {
1353        const int nch = (int) ((std::min<int64_t>(GSB, T - t0) + GCH - 1) / GCH);
1354        gdn_tc_prep_kernel<<<dim3((unsigned) nch, HK), 256, kTcPrepSmem, s>>>(h, gate, beta, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, t0, T);
1355        if (tiles == 2 && split && !nm && np == 3) {
1356            gdn_tc_scan_kernel<false, true, 3, 2><<<HV * 2, GTC_CW * 16, kTcScanSmemSplit, s>>>(state, h, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y, t0, nch, T);
1357        } else if (nm && split) {
1358#define STRATA_TCN(NPV) gdn_tc_scan_kernel<true, true, NPV><<<HV, GTC_CW * 32, kTcScanSmemSplitNorm, s>>>(state, h, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y, t0, nch, T, nm->z, nm->gamma, nm->eps, nm->y16, nm->ld16)
1359            if (np == 2) STRATA_TCN(2);
1360            else if (np == 1) STRATA_TCN(1);
1361            else STRATA_TCN(3);
1362#undef STRATA_TCN
1363        } else if (split && np == 2)
1364            gdn_tc_scan_kernel<false, true, 2><<<HV, GTC_CW * 32, kTcScanSmemSplit, s>>>(state, h, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y, t0, nch, T);
1365        else if (split && np == 1)
1366            gdn_tc_scan_kernel<false, true, 1><<<HV, GTC_CW * 32, kTcScanSmemSplit, s>>>(state, h, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y, t0, nch, T);
1367        else if (split)
1368            gdn_tc_scan_kernel<false, true><<<HV, GTC_CW * 32, kTcScanSmemSplit, s>>>(state, h, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y, t0, nch, T);
1369        else
1370            gdn_tc_scan_kernel<false><<<HV, GTC_CW * 32, kTcScanSmem<false>, s>>>(state, h, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y, t0, nch, T);
1371    }
1372    return cudaSuccess;
1373}
1374// Why gdn_rec_chunked (tc false) or gdn_rec_tc (tc true) launched nothing, in words: the same tests asked again.  Only
1375// the gdn_probe.hpp `reason` uses it (a test says what it timed); the dispatch itself never calls it.
1376const char* gdn_chunk_why(bool tc, cudaError_t e, bool any_sms, bool split = false) {
1377    static thread_local char buf[200];
1378    if (e == cudaErrorMemoryAllocation) return "scratch allocation failed";
1379    int dev = 0, major = 0, sms = 0, smem = 0;
1380    if (cudaGetDevice(&dev) != cudaSuccess ||
1381        cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess ||
1382        cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev) != cudaSuccess ||
1383        cudaDeviceGetAttribute(&smem, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev) != cudaSuccess) {
1384        cudaGetLastError();
1385        return "device attributes unavailable";
1386    }
1387    const int cc = strata::cc_major_of(major);
1388    const size_t need = tc ? (split ? kTcScanSmemSplit : (size_t) kTcScanSmem<false>) : kChunkScanSmem;
1389    const int sm_need = tc ? HV : HK * (S / GDV);
1390    if (cc < 8) std::snprintf(buf, sizeof buf, "compute capability %d < 8 (cp.async)", cc);
1391    else if (!tc && !any_sms && sms < sm_need)
1392        std::snprintf(buf, sizeof buf, "%d SMs < %d: the scan would run in several waves (STRATA_GDN_CHUNKED=2 bypasses)", sms, sm_need);
1393    else if (tc && !any_sms && sms < sm_need) std::snprintf(buf, sizeof buf, "%d SMs < %d (one block per value head)", sms, sm_need);
1394    else if ((size_t) strata::smem_optin_of(smem) < need)
1395        std::snprintf(buf, sizeof buf, "shared memory per block %d B < %zu B needed", strata::smem_optin_of(smem), need);
1396    else std::snprintf(buf, sizeof buf, "not supported (%s)", cudaGetErrorString(e));
1397    return buf;
1398}
1399#endif
1400#if defined(__HIPCC__)   // the Aurora (gfx11) recurrence kernels: AMD builds only
1401// Aurora (S23): the recurrence with the column-split grid of gdn_rec_cols_pipe_kernel (four 32-column blocks per value
1402// head) but FOUR LANES per column, lane g holding the column's state rows 32g .. 32g + 31 in registers - exactly the
1403// row group the old kernel's thread (col, rg = g) held - so a token needs no __syncthreads: the four kv / o partials
1404// meet through wave shuffles and are added in the old order red[0] + red[1] + red[2] + red[3] (the same bits;
1405// tests/hip/gdn_rec_head.cpp).  The q/k rows, v, gate and beta are staged in LDS HT tokens at a time, the next chunk
1406// loaded into registers while this one computes, and a token's k and q rows are read into registers before its
1407// products (one LDS latency per token, not one per load).  The old kernels took ~4 barriers per token and ~3.5 us
1408// per token and layer on the Radeon 8060S; the output norm runs after it in gdn_out_norm_warp_kernel.
1409// STRATA_GDN_HEAD=0: the old kernels.
1410constexpr int HT = 4;                           // tokens per staged chunk (LDS ~10 KB: all 192 blocks resident)
1411constexpr int QCB = 32;                         // columns per block
1412constexpr int QTH = QCB * 4;                    // threads per block: 4 lanes per column
1413constexpr int QRS = 36;                         // staged row-group stride (32 rows + 4 pad: the 4 groups' reads
1414                                                // land in different LDS banks)
1415constexpr int QPF = HT * 2 * S / 4 / QTH;       // float4 of q/k each thread prefetches per chunk (2)
1416__global__ void __launch_bounds__(QTH) gdn_rec_quad_kernel(float* __restrict__ state, const float* __restrict__ h,
1417                                                           const float* __restrict__ gate, const float* __restrict__ beta,
1418                                                           float* __restrict__ oc_out, int64_t T) {
1419    __shared__ __align__(16) float sqk[2][HT][2][4 * QRS];   // [buffer][token][q | k][group][row (padded)]
1420    __shared__ float sgb[2][2][HT];                         // [buffer][gate | beta][token]
1421    __shared__ float sv[2][HT][QCB];                        // [buffer][token][column] v
1422    const int head = blockIdx.x / (S / QCB), cb = blockIdx.x % (S / QCB);
1423    const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
1424    const int g = lane >> 3, cl = wave * 8 + (lane & 7), col = cb * QCB + cl;   // row group, column in block / head
1425    const int qh = head % HK;
1426    float s[32];
1427    {
1428        const float* base = state + ((size_t) (g * 32) * HV + head) * S + col;
1429#pragma unroll
1430        for (int r = 0; r < 32; ++r) s[r] = base[(size_t) r * HV * S];
1431    }
1432    float4 pf[QPF];
1433    float pv[HT], pgb = 0.0f;
1434    // chunk c's inputs into registers: q/k (float4 i of the chunk's [token][q|k][S/4] block), the column's v (lanes of
1435    // group 0) and gate (threads 0..HT-1) / beta (HT..2HT-1) of token `tid % HT`
1436    auto fetch = [&](int64_t c) {
1437        const int64_t t0 = c * HT;
1438#pragma unroll
1439        for (int u = 0; u < QPF; ++u) {
1440            const int i = tid + u * QTH;
1441            const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);
1442            const int64_t t = t0 + tt;
1443            pf[u] = t < T ? *reinterpret_cast<const float4*>(h + t * C + part * HK * S + qh * S + r4 * 4)
1444                          : make_float4(0.f, 0.f, 0.f, 0.f);
1445        }
1446        if (g == 0) {
1447#pragma unroll
1448            for (int tt = 0; tt < HT; ++tt) {
1449                const int64_t t = t0 + tt;
1450                pv[tt] = t < T ? h[t * C + 2 * HK * S + head * S + col] : 0.0f;
1451            }
1452        }
1453        if (tid < 2 * HT) {
1454            const int64_t t = t0 + (tid % HT);
1455            pgb = t < T ? (tid < HT ? gate : beta)[t * HV + head] : 0.0f;
1456        }
1457    };
1458    const float rs_s = rsqrtf((float) S);
1459    const int src0 = lane & 7;                       // lane of group 0 for this column; group j is src0 + 8 j
1460    const int64_t nch = (T + HT - 1) / HT;
1461    if (nch > 0) fetch(0);
1462    for (int64_t c = 0; c < nch; ++c) {
1463        const int b = (int) (c & 1);
1464        if (g == 0) {
1465#pragma unroll
1466            for (int tt = 0; tt < HT; ++tt) sv[b][tt][cl] = pv[tt];
1467        }
1468#pragma unroll
1469        for (int u = 0; u < QPF; ++u) {
1470            const int i = tid + u * QTH;
1471            const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);
1472            const int row = r4 * 4;
1473            *reinterpret_cast<float4*>(&sqk[b][tt][part][(row >> 5) * QRS + (row & 31)]) = pf[u];
1474        }
1475        if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb;
1476        __syncthreads();                               // chunk c staged (buffer b was last read two chunks ago)
1477        if (c + 1 < nch) fetch(c + 1);
1478        const int64_t t0 = c * HT;
1479        const int nt = (int) (T - t0 < HT ? T - t0 : HT);
1480        for (int tt = 0; tt < nt; ++tt) {
1481            float k[32], q[32];
1482            {
1483                const float4* k4 = reinterpret_cast<const float4*>(&sqk[b][tt][1][g * QRS]);
1484                const float4* q4 = reinterpret_cast<const float4*>(&sqk[b][tt][0][g * QRS]);
1485#pragma unroll
1486                for (int j = 0; j < 8; ++j) {
1487                    const float4 kk = k4[j], qq = q4[j];
1488                    k[4 * j] = kk.x; k[4 * j + 1] = kk.y; k[4 * j + 2] = kk.z; k[4 * j + 3] = kk.w;
1489                    q[4 * j] = qq.x; q[4 * j + 1] = qq.y; q[4 * j + 2] = qq.z; q[4 * j + 3] = qq.w;
1490                }
1491            }
1492            const float g_exp = __expf(sgb[b][0][tt]);
1493            float kv = 0.0f;
1494#pragma unroll
1495            for (int r = 0; r < 32; ++r) kv = fmaf(s[r], k[r], kv);
1496            const float p0 = __shfl_sync(0xffffffffu, kv, src0), p1 = __shfl_sync(0xffffffffu, kv, src0 + 8),
1497                        p2 = __shfl_sync(0xffffffffu, kv, src0 + 16), p3 = __shfl_sync(0xffffffffu, kv, src0 + 24);
1498            const float kv_col = p0 + p1 + p2 + p3;
1499            const float cvt = sv[b][tt][cl], cbt = sgb[b][1][tt];
1500            const float delta = (cvt - g_exp * kv_col) * cbt;
1501            float o = 0.0f;
1502#pragma unroll
1503            for (int r = 0; r < 32; ++r) {
1504                s[r] = fmaf(g_exp, s[r], k[r] * delta);
1505                o = fmaf(s[r], q[r], o);
1506            }
1507            const float o0 = __shfl_sync(0xffffffffu, o, src0), o1 = __shfl_sync(0xffffffffu, o, src0 + 8),
1508                        o2 = __shfl_sync(0xffffffffu, o, src0 + 16), o3 = __shfl_sync(0xffffffffu, o, src0 + 24);
1509            if (g == 0) oc_out[(t0 + tt) * HV * S + head * S + col] = (o0 + o1 + o2 + o3) * rs_s;
1510        }
1511    }
1512    {
1513        float* base = state + ((size_t) (g * 32) * HV + head) * S + col;
1514#pragma unroll
1515        for (int r = 0; r < 32; ++r) base[(size_t) r * HV * S] = s[r];
1516    }
1517}
1518// Aurora (S23, opt-in STRATA_GDN_PP=1): gdn_rec_quad_kernel with the same arithmetic in the same order, two changes in
1519// how it is compiled.  (1) The VGPR count: the 32 state-row addresses of the first loads were kept live across the
1520// whole walk to be reused by the final stores (64 VGPRs, 196 in all = 7 waves a SIMD for the 192 blocks of 4 waves
1521// that need 9.6): the stores' lane offset goes through an asm so the addresses are made again, 133 VGPRs, all blocks
1522// resident.  (2) A full chunk's four tokens run with the state alternating between two register sets (the update
1523// writes the other set), so the compiler emits no 32 register copies after the update.
1524__global__ void __launch_bounds__(QTH) gdn_rec_quad_pp_kernel(float* __restrict__ state, const float* __restrict__ h,
1525                                                           const float* __restrict__ gate, const float* __restrict__ beta,
1526                                                           float* __restrict__ oc_out, int64_t T) {
1527    __shared__ __align__(16) float sqk[2][HT][2][4 * QRS];   // [buffer][token][q | k][group][row (padded)]
1528    __shared__ float sgb[2][2][HT];                         // [buffer][gate | beta][token]
1529    __shared__ float sv[2][HT][QCB];                        // [buffer][token][column] v
1530    const int head = blockIdx.x / (S / QCB), cb = blockIdx.x % (S / QCB);
1531    const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
1532    const int g = lane >> 3, cl = wave * 8 + (lane & 7), col = cb * QCB + cl;   // row group, column in block / head
1533    const int qh = head % HK;
1534    float s[32];
1535    {
1536        const float* sb = state + (size_t) head * S;
1537        const uint32_t voff = (uint32_t) ((g * 32) * HV * S + col);
1538#pragma unroll
1539        for (int r = 0; r < 32; ++r) s[r] = sb[(size_t) r * HV * S + voff];
1540    }
1541    float4 pf[QPF];
1542    float pv[HT], pgb = 0.0f;
1543    // chunk c's inputs into registers: q/k (float4 i of the chunk's [token][q|k][S/4] block), the column's v (lanes of
1544    // group 0) and gate (threads 0..HT-1) / beta (HT..2HT-1) of token `tid % HT`
1545    auto fetch = [&](int64_t c) {
1546        const int64_t t0 = c * HT;
1547#pragma unroll
1548        for (int u = 0; u < QPF; ++u) {
1549            const int i = tid + u * QTH;
1550            const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);
1551            const int64_t t = t0 + tt;
1552            pf[u] = t < T ? *reinterpret_cast<const float4*>(h + t * C + part * HK * S + qh * S + r4 * 4)
1553                          : make_float4(0.f, 0.f, 0.f, 0.f);
1554        }
1555        if (g == 0) {
1556#pragma unroll
1557            for (int tt = 0; tt < HT; ++tt) {
1558                const int64_t t = t0 + tt;
1559                pv[tt] = t < T ? h[t * C + 2 * HK * S + head * S + col] : 0.0f;
1560            }
1561        }
1562        if (tid < 2 * HT) {
1563            const int64_t t = t0 + (tid % HT);
1564            pgb = t < T ? (tid < HT ? gate : beta)[t * HV + head] : 0.0f;
1565        }
1566    };
1567    const float rs_s = rsqrtf((float) S);
1568    const int src0 = lane & 7;                       // lane of group 0 for this column; group j is src0 + 8 j
1569    const int64_t nch = (T + HT - 1) / HT;
1570    if (nch > 0) fetch(0);
1571    for (int64_t c = 0; c < nch; ++c) {
1572        const int b = (int) (c & 1);
1573        if (g == 0) {
1574#pragma unroll
1575            for (int tt = 0; tt < HT; ++tt) sv[b][tt][cl] = pv[tt];
1576        }
1577#pragma unroll
1578        for (int u = 0; u < QPF; ++u) {
1579            const int i = tid + u * QTH;
1580            const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);
1581            const int row = r4 * 4;
1582            *reinterpret_cast<float4*>(&sqk[b][tt][part][(row >> 5) * QRS + (row & 31)]) = pf[u];
1583        }
1584        if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb;
1585        __syncthreads();                               // chunk c staged (buffer b was last read two chunks ago)
1586        if (c + 1 < nch) fetch(c + 1);
1587        const int64_t t0 = c * HT;
1588        const int nt = (int) (T - t0 < HT ? T - t0 : HT);
1589        auto token = [&](int tt, float (&sin)[32], float (&sout)[32]) {
1590            float k[32], q[32];
1591            {
1592                const float4* k4 = reinterpret_cast<const float4*>(&sqk[b][tt][1][g * QRS]);
1593                const float4* q4 = reinterpret_cast<const float4*>(&sqk[b][tt][0][g * QRS]);
1594#pragma unroll
1595                for (int j = 0; j < 8; ++j) {
1596                    const float4 kk = k4[j], qq = q4[j];
1597                    k[4 * j] = kk.x; k[4 * j + 1] = kk.y; k[4 * j + 2] = kk.z; k[4 * j + 3] = kk.w;
1598                    q[4 * j] = qq.x; q[4 * j + 1] = qq.y; q[4 * j + 2] = qq.z; q[4 * j + 3] = qq.w;
1599                }
1600            }
1601            const float g_exp = __expf(sgb[b][0][tt]);
1602            float kv = 0.0f;
1603#pragma unroll
1604            for (int r = 0; r < 32; ++r) kv = fmaf(sin[r], k[r], kv);
1605            const float p0 = __shfl_sync(0xffffffffu, kv, src0), p1 = __shfl_sync(0xffffffffu, kv, src0 + 8),
1606                        p2 = __shfl_sync(0xffffffffu, kv, src0 + 16), p3 = __shfl_sync(0xffffffffu, kv, src0 + 24);
1607            const float kv_col = p0 + p1 + p2 + p3;
1608            const float cvt = sv[b][tt][cl], cbt = sgb[b][1][tt];
1609            const float delta = (cvt - g_exp * kv_col) * cbt;
1610            float o = 0.0f;
1611#pragma unroll
1612            for (int r = 0; r < 32; ++r) {
1613                sout[r] = fmaf(g_exp, sin[r], k[r] * delta);
1614                o = fmaf(sout[r], q[r], o);
1615            }
1616            const float o0 = __shfl_sync(0xffffffffu, o, src0), o1 = __shfl_sync(0xffffffffu, o, src0 + 8),
1617                        o2 = __shfl_sync(0xffffffffu, o, src0 + 16), o3 = __shfl_sync(0xffffffffu, o, src0 + 24);
1618            if (g == 0) oc_out[(t0 + tt) * HV * S + head * S + col] = (o0 + o1 + o2 + o3) * rs_s;
1619        };
1620        if (nt == HT) {   // the state alternates between two register sets: no copy after the update
1621            float s2[32];
1622            token(0, s, s2);
1623            token(1, s2, s);
1624            token(2, s, s2);
1625            token(3, s2, s);
1626        } else {
1627            for (int tt = 0; tt < nt; ++tt) {
1628                float s2[32];
1629                token(tt, s, s2);
1630#pragma unroll
1631                for (int r = 0; r < 32; ++r) s[r] = s2[r];
1632            }
1633        }
1634    }
1635    {
1636        float* sb = state + (size_t) head * S;
1637        uint32_t voff = (uint32_t) ((g * 32) * HV * S + col);
1638        asm volatile("" : "+v"(voff));   // (so the loads' 32 addresses are not kept alive across the whole loop)
1639#pragma unroll
1640        for (int r = 0; r < 32; ++r) sb[(size_t) r * HV * S + voff] = s[r];
1641    }
1642}
1643
1644// Aurora (S23, opt-in STRATA_GDN_PP=2): gdn_rec_quad_kernel with two columns per lane (a wave: 4 row groups x 8 lanes x
1645// 2 columns = 16 columns; a block of 4 waves 64 columns, 96 blocks).  A lane's two columns share the k / q rows it
1646// reads from shared memory (half the LDS reads and shuffles per column, the kernel's limit) and give each wave two
1647// independent dependency chains; the 384 waves fit in one round at 230 VGPRs.  Per column the same arithmetic in
1648// the same order (the same bits as gdn_rec_quad_kernel).  The store of the state goes through an asm for the reason
1649// given at gdn_rec_quad_pp_kernel.
1650
1651// ---- C2: two columns per lane (a wave: 4 row groups x 8 lanes x 2 columns = 16 columns; a block of 4 waves 64
1652// columns).  A lane's two columns share the k / q rows it reads from LDS (half the LDS reads and shuffles per column
1653// and two independent dependency chains in each wave).  Per column the same arithmetic in the same order.
1654constexpr int C2CB = 64;                          // columns per block
1655constexpr int C2PF = HT * 2 * S / 4 / QTH;        // float4 of q/k each thread prefetches per chunk (2)
1656__global__ void __launch_bounds__(QTH) gdn_rec_quad2c_kernel(float* __restrict__ state, const float* __restrict__ h,
1657                                                             const float* __restrict__ gate, const float* __restrict__ beta,
1658                                                             float* __restrict__ oc_out, int64_t T) {
1659    __shared__ __align__(16) float sqk[2][HT][2][4 * QRS];
1660    __shared__ float sgb[2][2][HT];
1661    __shared__ float sv[2][HT][C2CB];
1662    const int head = blockIdx.x / (S / C2CB), cb = blockIdx.x % (S / C2CB);
1663    const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
1664    const int g = lane >> 3, cl0 = wave * 16 + (lane & 7), cl1 = cl0 + 8;   // the lane's two columns in the block
1665    const int col0 = cb * C2CB + cl0, col1 = cb * C2CB + cl1;
1666    const int qh = head % HK;
1667    float s0[32], s1[32];
1668    {
1669        const float* sb = state + (size_t) head * S;
1670        const uint32_t voff = (uint32_t) ((g * 32) * HV * S);
1671#pragma unroll
1672        for (int r = 0; r < 32; ++r) { s0[r] = sb[(size_t) r * HV * S + voff + col0]; s1[r] = sb[(size_t) r * HV * S + voff + col1]; }
1673    }
1674    float4 pf[C2PF];
1675    float pv[2][HT], pgb = 0.0f;
1676    auto fetch = [&](int64_t c) {
1677        const int64_t t0 = c * HT;
1678#pragma unroll
1679        for (int u = 0; u < C2PF; ++u) {
1680            const int i = tid + u * QTH;
1681            const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);
1682            const int64_t t = t0 + tt;
1683            pf[u] = t < T ? *reinterpret_cast<const float4*>(h + t * C + part * HK * S + qh * S + r4 * 4)
1684                          : make_float4(0.f, 0.f, 0.f, 0.f);
1685        }
1686        if (g == 0) {
1687#pragma unroll
1688            for (int tt = 0; tt < HT; ++tt) {
1689                const int64_t t = t0 + tt;
1690                pv[0][tt] = t < T ? h[t * C + 2 * HK * S + head * S + col0] : 0.0f;
1691                pv[1][tt] = t < T ? h[t * C + 2 * HK * S + head * S + col1] : 0.0f;
1692            }
1693        }
1694        if (tid < 2 * HT) {
1695            const int64_t t = t0 + (tid % HT);
1696            pgb = t < T ? (tid < HT ? gate : beta)[t * HV + head] : 0.0f;
1697        }
1698    };
1699    const float rs_s = rsqrtf((float) S);
1700    const int src0 = lane & 7;
1701    const int64_t nch = (T + HT - 1) / HT;
1702    if (nch > 0) fetch(0);
1703    for (int64_t c = 0; c < nch; ++c) {
1704        const int b = (int) (c & 1);
1705        if (g == 0) {
1706#pragma unroll
1707            for (int tt = 0; tt < HT; ++tt) { sv[b][tt][cl0] = pv[0][tt]; sv[b][tt][cl1] = pv[1][tt]; }
1708        }
1709#pragma unroll
1710        for (int u = 0; u < C2PF; ++u) {
1711            const int i = tid + u * QTH;
1712            const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);
1713            const int row = r4 * 4;
1714            *reinterpret_cast<float4*>(&sqk[b][tt][part][(row >> 5) * QRS + (row & 31)]) = pf[u];
1715        }
1716        if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb;
1717        __syncthreads();
1718        if (c + 1 < nch) fetch(c + 1);
1719        const int64_t t0 = c * HT;
1720        const int nt = (int) (T - t0 < HT ? T - t0 : HT);
1721        for (int tt = 0; tt < nt; ++tt) {
1722            float k[32], q[32];
1723            {
1724                const float4* k4 = reinterpret_cast<const float4*>(&sqk[b][tt][1][g * QRS]);
1725                const float4* q4 = reinterpret_cast<const float4*>(&sqk[b][tt][0][g * QRS]);
1726#pragma unroll
1727                for (int j = 0; j < 8; ++j) {
1728                    const float4 kk = k4[j], qq = q4[j];
1729                    k[4 * j] = kk.x; k[4 * j + 1] = kk.y; k[4 * j + 2] = kk.z; k[4 * j + 3] = kk.w;
1730                    q[4 * j] = qq.x; q[4 * j + 1] = qq.y; q[4 * j + 2] = qq.z; q[4 * j + 3] = qq.w;
1731                }
1732            }
1733            const float g_exp = __expf(sgb[b][0][tt]);
1734            float kv0 = 0.0f, kv1 = 0.0f;
1735#pragma unroll
1736            for (int r = 0; r < 32; ++r) { kv0 = fmaf(s0[r], k[r], kv0); kv1 = fmaf(s1[r], k[r], kv1); }
1737            const float a0 = __shfl_sync(0xffffffffu, kv0, src0), a1 = __shfl_sync(0xffffffffu, kv0, src0 + 8),
1738                        a2 = __shfl_sync(0xffffffffu, kv0, src0 + 16), a3 = __shfl_sync(0xffffffffu, kv0, src0 + 24);
1739            const float b0 = __shfl_sync(0xffffffffu, kv1, src0), b1 = __shfl_sync(0xffffffffu, kv1, src0 + 8),
1740                        b2 = __shfl_sync(0xffffffffu, kv1, src0 + 16), b3 = __shfl_sync(0xffffffffu, kv1, src0 + 24);
1741            const float kvc0 = a0 + a1 + a2 + a3, kvc1 = b0 + b1 + b2 + b3;
1742            const float cbt = sgb[b][1][tt];
1743            const float d0 = (sv[b][tt][cl0] - g_exp * kvc0) * cbt, d1 = (sv[b][tt][cl1] - g_exp * kvc1) * cbt;
1744            float o0 = 0.0f, o1 = 0.0f;
1745#pragma unroll
1746            for (int r = 0; r < 32; ++r) {
1747                s0[r] = fmaf(g_exp, s0[r], k[r] * d0);
1748                s1[r] = fmaf(g_exp, s1[r], k[r] * d1);
1749                o0 = fmaf(s0[r], q[r], o0);
1750                o1 = fmaf(s1[r], q[r], o1);
1751            }
1752            const float x0 = __shfl_sync(0xffffffffu, o0, src0), x1 = __shfl_sync(0xffffffffu, o0, src0 + 8),
1753                        x2 = __shfl_sync(0xffffffffu, o0, src0 + 16), x3 = __shfl_sync(0xffffffffu, o0, src0 + 24);
1754            const float y0 = __shfl_sync(0xffffffffu, o1, src0), y1 = __shfl_sync(0xffffffffu, o1, src0 + 8),
1755                        y2 = __shfl_sync(0xffffffffu, o1, src0 + 16), y3 = __shfl_sync(0xffffffffu, o1, src0 + 24);
1756            if (g == 0) {
1757                oc_out[(t0 + tt) * HV * S + head * S + col0] = (x0 + x1 + x2 + x3) * rs_s;
1758                oc_out[(t0 + tt) * HV * S + head * S + col1] = (y0 + y1 + y2 + y3) * rs_s;
1759            }
1760        }
1761    }
1762    {
1763        float* sb = state + (size_t) head * S;
1764        uint32_t voff = (uint32_t) ((g * 32) * HV * S);
1765        asm volatile("" : "+v"(voff));
1766#pragma unroll
1767        for (int r = 0; r < 32; ++r) { sb[(size_t) r * HV * S + voff + col0] = s0[r]; sb[(size_t) r * HV * S + voff + col1] = s1[r]; }
1768    }
1769}
1770
1771// gdn_out_norm_kernel's body over a grid-stride walk of the (token, head) rows: the old kernel launched a 128-thread
1772// block per row (T * 48 blocks; ~45 GB/s on the 8060S).  The same code per row (the same compiled arithmetic: a wave
1773// per row with four values per lane rounded differently in its first xor step).
1774template <bool WY>
1775__global__ void __launch_bounds__(S) gdn_out_norm_loop_kernel(const float* __restrict__ z, const float* __restrict__ gamma,
1776                                                              float eps, float* __restrict__ y, uint16_t* __restrict__ y16,
1777                                                              int64_t rows, int64_t ld16) {
1778    __shared__ float wsum[4];
1779    const int col = threadIdx.x;
1780    for (int64_t row = blockIdx.x; row < rows; row += gridDim.x) {
1781        const size_t at = (size_t) row * S + col;
1782        const float oc = y[at];
1783        // (warp_sum as the compiler built it: the first xor step adds the partner's rounded square to an unrounded own
1784        // one, an fma; spelled out so neither instance's contraction can differ)
1785        float sp = __fmaf_rn(oc, oc, __shfl_xor_sync(0xffffffffu, __fmul_rn(oc, oc), 16));
1786#pragma unroll
1787        for (int o = 8; o > 0; o >>= 1) sp = __fadd_rn(sp, __shfl_xor_sync(0xffffffffu, sp, o));
1788        __syncthreads();                               // the previous row's sums are read
1789        if ((col & 31) == 0) wsum[col >> 5] = sp;
1790        __syncthreads();
1791        const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
1792        const float bp = oc * rsqrtf(ss / (float) S + eps) * gamma[col], sg = sigm(z[at]);
1793        const size_t o16 = (size_t) (row / HV) * ld16 + (size_t) (row % HV) * S + col;
1794        if constexpr (WY) {
1795            const float v = bp * sg;
1796            y[at] = v;
1797            y16[o16] = hf(v);
1798        } else {
1799            // STRATA_GDN_NOY=1: nothing reads the FP32 result (403 MB per 16K chunk).  The FP16 value is what the
1800            // compiler makes of hf(v) next to the store: v_fma_mixlo_f16, the product rounded to FP16 once
1801            unsigned r;
1802            asm("v_fma_mixlo_f16 %0, %1, %2, 0" : "=v"(r) : "v"(sg), "v"(bp));
1803            y16[o16] = (uint16_t) r;
1804        }
1805    }
1806}
1807// STRATA_GDN_CHUNKED=1 on the gfx11 matrix cores: the recurrence in chunks of 16 tokens (the WY form of the CUDA
1808// chunked path above), FP16 operands and FP32 accumulation, the output norm fused.  Per value head, gamma_t the
1809// gate's sum from the chunk's start to t (inclusive; the code's sg) and S0 the state before the chunk:
1810//   A[t][i] = beta_t exp(gamma_t - gamma_i) k_t.k_i (i < t),  T = (I + A)^-1,  P[t][i] = exp(gamma_t - gamma_i) q_t.k_i (i <= t),
1811//   Y = beta (V - exp(gamma) K S0),  D = T Y,  o = exp(gamma) Q S0 + P D,
1812//   S = exp(gamma_last) S0 + K^T (exp(gamma_last - gamma) D).
1813// gdn_wmma_prep_kernel computes T and P of every chunk at once (they do not depend on the state); gdn_wmma_scan_kernel
1814// walks the chunks, a block per value head and a wave per 16 value columns, the state in the waves' WMMA accumulators
1815// (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
1816// 2^-11), so the output differs from the FP32 kernels by more than their rounding (tests/hip/gdn_chunked.cpp holds it
1817// to the bounds of its Error::ok).  The norm and the z gate run in the scan.
1818#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || defined(__gfx1150__) || defined(__gfx1151__)
1819#define STRATA_GDN_WMMA 1   // device pass with the gfx11 WMMA intrinsic (the list of gfx_arch_is_gfx11_wmma)
1820#endif
1821constexpr int GW_CK = 16;          // tokens per chunk (a WMMA tile)
1822constexpr int GW_NW = S / 16;      // the scan's waves per block: one per 16 value columns
1823constexpr int GW_VPK = HV / HK;    // value heads per key head: the prep's waves per block
1824constexpr int GW_KP = S + 8;       // the scan's padded FP16 k / q rows
1825constexpr int GW_AHEAD = 3;        // the scan warms the cache this many chunks ahead
1826constexpr int64_t kGdnWmmaMin = 64;   // STRATA_GDN_CHUNKED=1 takes prompt chunks of this many tokens and more
1827// 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
1828// 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
1829// 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
1830// 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 /
1831// 0.0381 max, 55 of 61 tasks, a 30-minute soak clean.  So gfx12 takes it from the same 64 tokens as gfx11.
1832constexpr int64_t kGdnW12MinT = kGdnWmmaMin;
1833// gfx12 (RDNA4) only, STRATA_GDN_CHUNKED unset (owner 11-06, "ok" to a length-gated default): the chunked scan takes prompt chunks of 30,000 tokens or more -
1834// a long prompt (--prefill auto takes chunks up to 32,768 on gfx12, so a 32K prompt is one chunk of about 31,996-32,087 rows, which is why the line is 30,000 and not 32,000; +6.5% prompt speed at 32K, 3 of 3 rounds).  Shorter chunks keep the kernels they ran.
1835// STRATA_GDN_CHUNKED=0 turns it off, =1 takes every chunk of 64 tokens or more (the old opt-in), STRATA_GDN_CHUNKED_MIN=N moves the line.
1836inline int gdn_chunked_env() {   // -1 unset, else the number
1837    static const int v = [] { const char* e = std::getenv("STRATA_GDN_CHUNKED"); return e == nullptr || e[0] == '\0' ? -1 : std::atoi(e); }();
1838    return v;
1839}
1840inline bool gdn_chunked_auto(int64_t T) {   // unset: only on gfx12, only for long chunks (the caller has checked the device)
1841    static const int64_t lo = [] { const char* e = std::getenv("STRATA_GDN_CHUNKED_MIN"); return e != nullptr && e[0] != '\0' ? (int64_t) std::atoll(e) : (int64_t) 30000; }();
1842    static const bool gfx12_defaults = [] { const char* e = std::getenv("STRATA_GFX12_DEFAULTS"); return !(e != nullptr && e[0] == '0'); }();   // (the gfx12 defaults' one off switch)
1843    return gdn_chunked_env() < 0 && gfx12_defaults && T >= lo;
1844}
1845typedef _Float16 gw_h16 __attribute__((ext_vector_type(16)));
1846typedef _Float16 gw_h8 __attribute__((ext_vector_type(8)));
1847typedef _Float16 gw_h2 __attribute__((ext_vector_type(2)));
1848typedef float gw_f8 __attribute__((ext_vector_type(8)));
1849typedef float gw_f4 __attribute__((ext_vector_type(4)));   // (HIP's float4 copies through memcpy, which kept a staged
1850                                                           // copy in scratch: a store that waits for the load)
1851__device__ __forceinline__ gw_f8 gw_mma(gw_h16 a, gw_h16 b, gw_f8 c) {
1852#if defined(STRATA_GDN_WMMA)
1853    return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c);
1854#else
1855    (void) a; (void) b; (void) c;
1856    __builtin_trap();   // not a gfx11 device pass: the runtime gate never launches it
1857#endif
1858}
1859// An accumulator tile (lane l: rows 2v + (l >> 4) for v = 0..7, column l & 15) as a B operand (lane l: column l & 15,
1860// rows 0..15, both halves of the wave alike): pairs of rows rounded to FP16 and packed, the other half's pairs fetched
1861// across (permlanex16), then interleaved by a byte permute whose selector depends on the lane's half (gw_sel).
1862struct GwSel { unsigned even, odd; };
1863__device__ __forceinline__ GwSel gw_sel(int hi) { return hi ? GwSel{0x01000504u, 0x03020706u} : GwSel{0x05040100u, 0x07060302u}; }
1864__device__ __forceinline__ gw_h16 gw_acc_to_b(gw_f8 x, GwSel ps) {
1865    unsigned wd[8];
1866#pragma unroll
1867    for (int m = 0; m < 4; ++m) {
1868        const gw_h2 p = {(_Float16) x[2 * m], (_Float16) x[2 * m + 1]};
1869        const unsigned own = __builtin_bit_cast(unsigned, p);
1870#if defined(STRATA_GDN_WMMA)
1871        const unsigned other = __builtin_amdgcn_permlanex16(own, own, 0x76543210u, 0xfedcba98u, false, false);
1872#else
1873        const unsigned other = own;
1874#endif
1875        wd[2 * m] = __builtin_amdgcn_perm(other, own, ps.even);
1876        wd[2 * m + 1] = __builtin_amdgcn_perm(other, own, ps.odd);
1877    }
1878    return __builtin_bit_cast(gw_h16, wd);
1879}
1880__device__ __forceinline__ gw_h16 gw_ld(const _Float16* p) {   // 32 bytes of LDS, 16-byte aligned
1881    const uint4 a = *reinterpret_cast<const uint4*>(p), b = *reinterpret_cast<const uint4*>(p + 8);
1882    const uint4 ab[2] = {a, b};
1883    return __builtin_bit_cast(gw_h16, ab);
1884}
1885// The wave's own LDS writes complete (read back across its lanes).  A gfx11 instruction: gfx12 device passes never run these kernels.
1886__device__ __forceinline__ void gw_lds_wait() {
1887#if defined(STRATA_GDN_WMMA)
1888    __asm__ volatile("s_waitcnt lgkmcnt(0)" ::: "memory");
1889#endif
1890}
1891// A barrier over LDS only.  __syncthreads() is a workgroup fence over all memory, which on gfx11 also waits for every
1892// global load in flight: the scan's loads of the next chunk would have to land before each barrier.
1893__device__ __forceinline__ void gw_lds_barrier() {
1894#if defined(STRATA_GDN_WMMA)
1895    __asm__ volatile("s_waitcnt lgkmcnt(0)\n\ts_barrier" ::: "memory");
1896#else
1897    __syncthreads();   // the gfx11-only instruction must not reach a gfx12 device pass
1898#endif
1899}
1900
1901// A block per (key head, chunk) - the grid's x the key head, so the blocks in flight read the same token rows (blocks
1902// that walked the key heads' slices of far-apart rows took 14 ms against 2.2 ms for 16K tokens on gfx1151) - and a wave per value head of the key head.
1903// T then P, FP16 row-major (1 KB), at tp[(chunk * HV + value head) * 512].
1904__global__ void __launch_bounds__(32 * GW_VPK) gdn_wmma_prep_kernel(const float* __restrict__ h, const float* __restrict__ gate,
1905                                                                 const float* __restrict__ beta, _Float16* __restrict__ tp,
1906                                                                 int64_t T) {
1907    __shared__ float sa[GW_VPK][GW_CK * GW_CK], sg[GW_VPK][GW_CK], sb[GW_VPK][GW_CK];
1908    const int qh = blockIdx.x, ch = blockIdx.y, w = threadIdx.x >> 5, l = threadIdx.x & 31, c = l & 15, hi = l >> 4;
1909    const int vh = qh + w * HK;
1910    const int64_t t0 = (int64_t) ch * GW_CK;
1911    gw_f8 kk = {}, qk = {};   // k_t.k_i and q_t.k_i (lane: column i = c, rows t = 2v + hi)
1912    {
1913        const bool ok = t0 + c < T;   // past the end: zero rows
1914        const float* ht = h + (ok ? t0 + c : 0) * C;
1915#pragma unroll
1916        for (int j = 0; j < S / 16; ++j) {
1917            gw_h16 ka, qa;
1918#pragma unroll
1919            for (int i = 0; i < 4; ++i) {
1920                const gw_f4 k4 = *reinterpret_cast<const gw_f4*>(ht + HK * S + qh * S + 16 * j + 4 * i);
1921                const gw_f4 q4 = *reinterpret_cast<const gw_f4*>(ht + qh * S + 16 * j + 4 * i);
1922#pragma unroll
1923                for (int e = 0; e < 4; ++e) {
1924                    ka[4 * i + e] = (_Float16) (ok ? k4[e] : 0.0f);
1925                    qa[4 * i + e] = (_Float16) (ok ? q4[e] : 0.0f);
1926                }
1927            }
1928            kk = gw_mma(ka, ka, kk);   // B = K^T: lane i holds column i of K^T, row i of K - the A operand itself
1929            qk = gw_mma(qa, ka, qk);
1930        }
1931    }
1932    if (l < GW_CK) {   // past the end: gate 0, beta 0
1933        const bool ok = t0 + l < T;
1934        float g = ok ? gate[(t0 + l) * HV + vh] : 0.0f;
1935#pragma unroll
1936        for (int o = 1; o < GW_CK; o <<= 1) {
1937            const float u = __shfl_up(g, o, GW_CK);
1938            if (l >= o) g += u;
1939        }
1940        sg[w][l] = g;
1941        sb[w][l] = ok ? beta[(t0 + l) * HV + vh] : 0.0f;
1942    }
1943    gw_lds_wait();   // the wave's own LDS writes, read across its lanes
1944    _Float16* out = tp + ((int64_t) ch * HV + vh) * (2 * GW_CK * GW_CK);
1945#pragma unroll
1946    for (int v = 0; v < 8; ++v) {
1947        const int t = 2 * v + hi;
1948        sa[w][t * GW_CK + c] = c < t ? sb[w][t] * __expf(sg[w][t] - sg[w][c]) * kk[v] : 0.0f;
1949        out[GW_CK * GW_CK + t * GW_CK + c] = (_Float16) (c <= t ? __expf(sg[w][t] - sg[w][c]) * qk[v] : 0.0f);
1950    }
1951    gw_lds_wait();
1952    if (l < GW_CK) {   // lane c: column c of T = (I + A)^-1 by forward substitution
1953        float tc[GW_CK];
1954#pragma unroll
1955        for (int t = 0; t < GW_CK; ++t) {
1956            float v = t == c ? 1.0f : 0.0f;
1957#pragma unroll
1958            for (int k = 0; k < t; ++k) v = fmaf(-sa[w][t * GW_CK + k], tc[k], v);
1959            tc[t] = v;
1960            out[t * GW_CK + c] = (_Float16) v;
1961        }
1962    }
1963}
1964
1965// A thread's slice of a chunk in the scan (token threadIdx / 16, columns (threadIdx % 16) * 8 .. + 7): k, q and v,
1966// loaded a chunk ahead, and one word of the chunk's T and P; lanes 0..15 of wave 0 also gate and beta of token l.
1967// Rows past the end read the last row (finite: their gate and beta become 0 at staging, which keeps them out of the
1968// state, of the real rows' products and of the output) - no select on the loaded values, which would wait for them.
1969struct GwChunk {
1970    gw_f4 k0, k1, q0, q1, v0, v1;
1971    float g, b;
1972    unsigned tp;
1973};
1974__device__ __forceinline__ void gw_load(GwChunk& in, const float* __restrict__ h, const float* __restrict__ gate,
1975                                        const float* __restrict__ beta, const unsigned* __restrict__ tp, int64_t t0,
1976                                        int64_t T, int vh, int qh) {
1977    const int t = threadIdx.x >> 4, r = (threadIdx.x & 15) * 8;
1978    const float* ht = h + std::min<int64_t>(t0 + t, T - 1) * C;
1979    in.tp = tp[((t0 / GW_CK) * HV + vh) * (GW_CK * GW_CK) + threadIdx.x];
1980    in.k0 = *reinterpret_cast<const gw_f4*>(ht + HK * S + qh * S + r);
1981    in.k1 = *reinterpret_cast<const gw_f4*>(ht + HK * S + qh * S + r + 4);
1982    in.q0 = *reinterpret_cast<const gw_f4*>(ht + qh * S + r);
1983    in.q1 = *reinterpret_cast<const gw_f4*>(ht + qh * S + r + 4);
1984    in.v0 = *reinterpret_cast<const gw_f4*>(ht + 2 * HK * S + vh * S + r);
1985    in.v1 = *reinterpret_cast<const gw_f4*>(ht + 2 * HK * S + vh * S + r + 4);
1986    if (threadIdx.x < GW_CK) {
1987        const int64_t tl = std::min<int64_t>(t0 + threadIdx.x, T - 1);
1988        in.g = gate[tl * HV + vh];
1989        in.b = beta[tl * HV + vh];
1990    }
1991}
1992// Brings a later chunk's lines (this block's k, q, v and z rows: 256 lines of 128 bytes, one a thread) into the cache
1993// with a load whose result is not used, so the real loads of that chunk hit the cache.  An ordinary load: the compiler
1994// tracks it, and the result is consumed (by an empty asm) one chunk later, after the store of the previous chunk's output
1995// rows, where the wait for the loads issued before that point also covers it.
1996__device__ __forceinline__ unsigned gw_touch(const float* __restrict__ h, const float* __restrict__ z, int64_t t0,
1997                                             int64_t T, int vh, int qh) {
1998    const int t = threadIdx.x >> 4, part = threadIdx.x & 15, kind = part >> 2;
1999    if (t0 + t >= T) return 0u;
2000    const float* p = kind == 0 ? h + (t0 + t) * C + HK * S + qh * S
2001                   : kind == 1 ? h + (t0 + t) * C + qh * S
2002                   : kind == 2 ? h + (t0 + t) * C + 2 * HK * S + vh * S
2003                               : z + (t0 + t) * HV * S + vh * S;
2004    return __float_as_uint(p[32 * (part & 3)]);
2005}
2006// Per chunk: stage it (k / q FP16, k also transposed, v, the gate's running sum, beta, T and P); barrier (1); store
2007// the previous chunk's output rows (the z gate on its normed output, 16 bytes a thread); X = K S0, QS = Q S0; Y, D,
2008// o and the wave's sums of o^2; the state update; barrier (2); the norm.  LDS is single-buffered: an array written in
2009// the staging of chunk c + 1 or after its barrier (2) was last read before that wave reached barrier (1) of c + 1.
2010__global__ void __launch_bounds__(GW_NW * 32) gdn_wmma_scan_kernel(float* __restrict__ state, const float* __restrict__ h,
2011                                                                   const float* __restrict__ gate, const float* __restrict__ beta,
2012                                                                   const float* __restrict__ z, const float* __restrict__ gamma,
2013                                                                   const unsigned* __restrict__ tp, float eps,
2014                                                                   uint16_t* __restrict__ y16, int64_t T, int64_t ld16) {
2015    __shared__ __attribute__((aligned(16))) _Float16 sk[GW_CK * GW_KP], sq[GW_CK * GW_KP], skt[S * GW_CK],
2016        stp[2 * GW_CK * GW_CK];
2017    __shared__ __attribute__((aligned(16))) float sv[GW_CK * S], so[GW_CK * S], sn[GW_CK * GW_NW];
2018    __shared__ float sg[GW_CK], sb[GW_CK], sgam[S];
2019    const _Float16 *st_ = stp, *sp_ = stp + GW_CK * GW_CK;   // T, P
2020    const int vh = blockIdx.x, qh = vh % HK, w = threadIdx.x >> 5, l = threadIdx.x & 31, c = l & 15, hi = l >> 4;
2021    const int col = 16 * w + c;                                       // this lane's column in the products
2022    const int st = threadIdx.x >> 4, sr = (threadIdx.x & 15) * 8;    // this thread's staging slice
2023    const size_t rs = (size_t) HV * S;
2024    const GwSel ps = gw_sel(hi);
2025    gw_f8 s[S / 16];   // the state: rows 16j + 2v + hi, column col
2026#pragma unroll
2027    for (int j = 0; j < S / 16; ++j)
2028#pragma unroll
2029        for (int v = 0; v < 8; ++v) s[j][v] = state[(size_t) (16 * j + 2 * v + hi) * rs + (size_t) vh * S + col];
2030    if (threadIdx.x < S) sgam[threadIdx.x] = gamma[threadIdx.x];
2031    const float out_scale = rsqrtf((float) S);
2032    GwChunk cur;
2033    gw_load(cur, h, gate, beta, tp, 0, T, vh, qh);
2034    unsigned touched = 0;
2035    gw_f4 z0 = {}, z1 = {};   // the z slice of the chunk whose output rows are stored next
2036    auto store_rows = [&](int64_t c0) {   // the output rows of the chunk at c0 (its norm in so): z gate, FP16
2037        if (c0 + st >= T) return;
2038        const float* o = &so[st * S + sr];
2039        gw_h8 r;
2040#pragma unroll
2041        for (int i = 0; i < 8; ++i) r[i] = (_Float16) (o[i] * sigm(i < 4 ? z0[i] : z1[i - 4]));
2042        *reinterpret_cast<uint4*>(y16 + (c0 + st) * ld16 + vh * S + sr) = __builtin_bit_cast(uint4, r);
2043    };
2044    for (int64_t t0 = 0; t0 < T; t0 += GW_CK) {
2045        {   // stage this chunk
2046            gw_h8 kh, qq;
2047#pragma unroll
2048            for (int i = 0; i < 8; ++i) {
2049                kh[i] = (_Float16) (i < 4 ? cur.k0[i] : cur.k1[i - 4]);
2050                qq[i] = (_Float16) (i < 4 ? cur.q0[i] : cur.q1[i - 4]);
2051                skt[(sr + i) * GW_CK + st] = kh[i];
2052            }
2053            *reinterpret_cast<uint4*>(&sk[st * GW_KP + sr]) = __builtin_bit_cast(uint4, kh);
2054            *reinterpret_cast<uint4*>(&sq[st * GW_KP + sr]) = __builtin_bit_cast(uint4, qq);
2055            *reinterpret_cast<gw_f4*>(&sv[st * S + sr]) = cur.v0;
2056            *reinterpret_cast<gw_f4*>(&sv[st * S + sr + 4]) = cur.v1;
2057            reinterpret_cast<unsigned*>(stp)[threadIdx.x] = cur.tp;
2058            if (threadIdx.x < GW_CK) {   // past the end: gate 0, beta 0
2059                const bool ok = t0 + l < T;
2060                float g = ok ? cur.g : 0.0f;
2061#pragma unroll
2062                for (int o = 1; o < GW_CK; o <<= 1) {
2063                    const float u = __shfl_up(g, o, GW_CK);
2064                    if (l >= o) g += u;
2065                }
2066                sg[l] = g;
2067                sb[l] = ok ? cur.b : 0.0f;
2068            }
2069        }
2070        if (t0 + GW_CK < T) gw_load(cur, h, gate, beta, tp, t0 + GW_CK, T, vh, qh);   // lands during this chunk
2071        const unsigned touch_now = gw_touch(h, z, t0 + GW_AHEAD * GW_CK, T, vh, qh);
2072        gw_lds_barrier();   // (1) this chunk staged; the previous chunk's norm in so
2073        if (t0 > 0) store_rows(t0 - GW_CK);
2074        __asm__ volatile("" ::"v"(touched));   // the previous touch, consumed here
2075        touched = touch_now;
2076        {   // this chunk's z slice, for its output rows after barrier (1) of the next chunk
2077            const int64_t tz = std::min<int64_t>(t0 + st, T - 1);
2078            z0 = *reinterpret_cast<const gw_f4*>(z + tz * HV * S + vh * S + sr);
2079            z1 = *reinterpret_cast<const gw_f4*>(z + tz * HV * S + vh * S + sr + 4);
2080        }
2081        gw_f8 x = {}, qs = {};   // K S0 and Q S0, this wave's columns
2082#pragma unroll
2083        for (int j = 0; j < S / 16; ++j) {
2084            const gw_h16 b = gw_acc_to_b(s[j], ps);
2085            x = gw_mma(gw_ld(sk + c * GW_KP + 16 * j), b, x);
2086            qs = gw_mma(gw_ld(sq + c * GW_KP + 16 * j), b, qs);
2087        }
2088        gw_f8 y;
2089#pragma unroll
2090        for (int v = 0; v < 8; ++v) {
2091            const int t = 2 * v + hi;
2092            y[v] = sb[t] * (sv[t * S + col] - __expf(sg[t]) * x[v]);
2093        }
2094        const gw_f8 d = gw_mma(gw_ld(st_ + c * GW_CK), gw_acc_to_b(y, ps), gw_f8{});
2095        gw_f8 o;
2096#pragma unroll
2097        for (int v = 0; v < 8; ++v) o[v] = __expf(sg[2 * v + hi]) * qs[v];
2098        o = gw_mma(gw_ld(sp_ + c * GW_CK), gw_acc_to_b(d, ps), o);
2099#pragma unroll
2100        for (int v = 0; v < 8; ++v) {   // the wave's 16 columns of o^2 per token, then the 8 waves' through LDS
2101            o[v] *= out_scale;
2102            float p = o[v] * o[v];
2103#pragma unroll
2104            for (int m = 1; m < 16; m <<= 1) p += __shfl_xor(p, m);
2105            if (c == 0) sn[(2 * v + hi) * GW_NW + w] = p;
2106        }
2107        const float gl = sg[GW_CK - 1];
2108        gw_f8 dd;
2109#pragma unroll
2110        for (int v = 0; v < 8; ++v) dd[v] = __expf(gl - sg[2 * v + hi]) * d[v];
2111        const gw_h16 db = gw_acc_to_b(dd, ps);
2112        const float eg = __expf(gl);
2113#pragma unroll
2114        for (int j = 0; j < S / 16; ++j) s[j] = gw_mma(gw_ld(skt + (16 * j + c) * GW_CK), db, s[j] * eg);
2115        gw_lds_barrier();   // (2) the sums of o^2
2116        const float g_col = sgam[col];
2117#pragma unroll
2118        for (int v = 0; v < 8; ++v) {
2119            const int t = 2 * v + hi;
2120            const gw_f4 n0 = *reinterpret_cast<const gw_f4*>(&sn[t * GW_NW]), n1 = *reinterpret_cast<const gw_f4*>(&sn[t * GW_NW + 4]);
2121            const float ss = n0[0] + n0[1] + n0[2] + n0[3] + n1[0] + n1[1] + n1[2] + n1[3];
2122            so[t * S + col] = o[v] * rsqrtf(ss * (1.0f / S) + eps) * g_col;
2123        }
2124    }
2125    __asm__ volatile("" ::"v"(touched));
2126    gw_lds_barrier();
2127    store_rows((T - 1) / GW_CK * GW_CK);
2128    __asm__ volatile("" : "+s"(state));   // the state's addresses recomputed here, not kept (spilled) since the start
2129#pragma unroll
2130    for (int j = 0; j < S / 16; ++j)
2131#pragma unroll
2132        for (int v = 0; v < 8; ++v) state[(size_t) (16 * j + 2 * v + hi) * rs + (size_t) vh * S + col] = s[j][v];
2133}
2134#include "gdn_wmma12.inc"
2135// The opt-in chunked recurrence on gfx11 and gfx12 (STRATA_GDN_CHUNKED=1): false (nothing launched) on another part.  y, the
2136// 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).
2137bool gdn_rec_wmma(float* state, const float* h, const float* gate, const float* beta, const float* z, const float* gamma,
2138                  float eps, float* y, uint16_t* y16, int64_t T, cudaStream_t s, int64_t ld16) {
2139    if (T < kGdnWmmaMin || ld16 % 8 != 0) return false;   // the rows are stored 16 bytes at a time
2140    // A layer-split worker can change devices: a process-wide answer for the first card can launch a trapping
2141    // gfx11 kernel on a later gfx12 card.  Cache only the current thread's last device, as properties are not cheap.
2142    static thread_local int last_device = -1;
2143    static thread_local bool gfx11 = false, gfx12 = false;
2144    int dev = 0;
2145    if (cudaGetDevice(&dev) != cudaSuccess) return false;
2146    if (dev != last_device) {
2147        cudaDeviceProp p{};
2148        if (cudaGetDeviceProperties(&p, dev) != cudaSuccess) return false;
2149        gfx11 = strata::kernels::gfx_arch_is_gfx11_wmma(p.gcnArchName);
2150        gfx12 = strata::kernels::gfx_arch_is_gfx12_wmma(p.gcnArchName);
2151        last_device = dev;
2152    }
2153    if (!gfx11 && !gfx12) return false;
2154    if (gfx12 && T < kGdnW12MinT) return false;
2155    if (gdn_chunked_env() < 0 && !(gfx12 && gdn_chunked_auto(T))) return false;   // unset: gfx12, long chunks only
2156    const int64_t nch = (T + GW_CK - 1) / GW_CK;
2157    _Float16* tp = reinterpret_cast<_Float16*>(y);
2158    if (gfx12) {
2159        gdn_w12_prep_kernel<false><<<dim3(HK, (unsigned) nch), 32 * GW_VPK, 0, s>>>(h, nullptr, gate, beta, tp, T);
2160        static const bool lb = [] { const char* v = std::getenv("STRATA_GDN_W12_LB"); return v == nullptr || std::atoi(v) != 0; }();
2161        if (lb)
2162            gdn_w12_scan_kernel<true, false><<<HV, GW_NW * 32, 0, s>>>(state, h, nullptr, gate, beta, z, gamma,
2163                                                                       reinterpret_cast<const unsigned*>(tp), eps, y16, T, ld16);
2164        else
2165            gdn_w12_scan_kernel<false, false><<<HV, GW_NW * 32, 0, s>>>(state, h, nullptr, gate, beta, z, gamma,
2166                                                                        reinterpret_cast<const unsigned*>(tp), eps, y16, T, ld16);
2167        return true;
2168    }
2169    gdn_wmma_prep_kernel<<<dim3(HK, (unsigned) nch), 32 * GW_VPK, 0, s>>>(h, gate, beta, tp, T);
2170    gdn_wmma_scan_kernel<<<HV, GW_NW * 32, 0, s>>>(state, h, gate, beta, z, gamma, reinterpret_cast<const unsigned*>(tp),
2171                                                   eps, y16, T, ld16);
2172    return true;
2173}
2174// STRATA_GDN_CHUNKED=1 on gfx12 with the conv folded in (gdn_wmma12f.inc; STRATA_GDN_FUSE=0 keeps conv and recurrence apart):
2175// the work of gdn_conv + gdn_recurrence in three launches, no h buffer.  False (nothing launched) when the chunked path or
2176// the fusion is off, the device is not gfx12, or the call is short / unaligned: the caller then runs the two entry points.
2177bool gdn_fused_impl(float* history, const float* qkv, const float* conv_w, float* hbuf, float* state, const float* gate,
2178                    const float* beta, const float* z, const float* gamma, float eps, float l2eps, float* y, uint16_t* y16,
2179                    int64_t T, void* stream, int64_t ld16) {
2180    static const bool on = [] {
2181        const char* f = std::getenv("STRATA_GDN_FUSE");
2182        return gdn_chunked_env() != 0 && (f == nullptr || std::atoi(f) != 0);   // (unset: the length gate below, gfx12 only)
2183    }();
2184    if (!on || T < kGdnWmmaMin) return false;
2185    if (ld16 <= 0) ld16 = (int64_t) HV * S;
2186    if (ld16 % 8 != 0) return false;
2187    static thread_local int last_device = -1;
2188    static thread_local bool gfx12 = false;
2189    int dev = 0;
2190    if (cudaGetDevice(&dev) != cudaSuccess) return false;
2191    if (dev != last_device) {
2192        cudaDeviceProp p{};
2193        if (cudaGetDeviceProperties(&p, dev) != cudaSuccess) return false;
2194        gfx12 = strata::kernels::gfx_arch_is_gfx12_wmma(p.gcnArchName);
2195        last_device = dev;
2196    }
2197    if (!gfx12 || T < kGdnW12MinT) return false;
2198    if (gdn_chunked_env() < 0 && !gdn_chunked_auto(T)) return false;   // unset: long chunks only
2199    cudaStream_t s = (cudaStream_t) stream;
2200    const int64_t nch = (T + GW_CK - 1) / GW_CK;
2201    _Float16* tp = reinterpret_cast<_Float16*>(y);
2202    _Float16* h16 = reinterpret_cast<_Float16*>(hbuf);   // the FP32 h buffer holds the FP16 one
2203    gdn_conv_l2_h16_kernel<<<dim3(C / 128, (unsigned) ((T + CONV_TILE - 1) / CONV_TILE)), 128, 0, s>>>(history, qkv, conv_w, h16, T, l2eps);
2204    gdn_conv_hist_kernel<<<C / 128, 128, 0, s>>>(history, qkv, T);   // the history after the chunk (the conv above read the old one)
2205    gdn_w12_prep_kernel<true><<<dim3(HK, (unsigned) nch), 32 * GW_VPK, 0, s>>>(nullptr, h16, gate, beta, tp, T);
2206    static const bool lb = [] { const char* v = std::getenv("STRATA_GDN_W12_LB"); return v == nullptr || std::atoi(v) != 0; }();
2207    if (lb)
2208        gdn_w12_scan_kernel<true, true><<<HV, GW_NW * 32, 0, s>>>(state, nullptr, h16, gate, beta, z, gamma,
2209                                                                  reinterpret_cast<const unsigned*>(tp), eps, y16, T, ld16);
2210    else
2211        gdn_w12_scan_kernel<false, true><<<HV, GW_NW * 32, 0, s>>>(state, nullptr, h16, gate, beta, z, gamma,
2212                                                                   reinterpret_cast<const unsigned*>(tp), eps, y16, T, ld16);
2213    check("gdn_conv_recurrence_fused");
2214    return true;
2215}
2216#endif   // __HIPCC__
2217__global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma,
2218                                                         float eps, float* __restrict__ y, uint16_t* __restrict__ y16,
2219                                                         int64_t ld16) {
2220    __shared__ float wsum[4];
2221    const int64_t t = blockIdx.x;
2222    const int head = blockIdx.y, col = threadIdx.x;
2223    const size_t at = (size_t) t * HV * S + (size_t) head * S + col;
2224    const float oc = y[at];
2225    float sp = warp_sum(oc * oc);
2226    if ((col & 31) == 0) wsum[col >> 5] = sp;
2227    __syncthreads();
2228    const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
2229    const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * sigm(z[t * HV * S + head * S + col]);
2230    y16[(size_t) t * ld16 + (size_t) head * S + col] = hf(v);   // (the FP32 normalized value is not stored: nothing reads it)
2231}
2232
2233// ---------------------------------------------------------------- MoE
2234template <int REG>
2235__global__ void route_kernel(const float* __restrict__ logits, int32_t* __restrict__ ids, float* __restrict__ wout,
2236                             int64_t T) {
2237    const int64_t t = (int64_t) blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5);
2238    if (t >= T) return;
2239    const int lane = threadIdx.x & 31;
2240    const float* lg = logits + t * (REG * 32);
2241    float v[REG];
2242#pragma unroll
2243    for (int i = 0; i < REG; ++i) v[i] = lg[lane + i * 32];
2244    float mx = -INFINITY;
2245#pragma unroll
2246    for (int i = 0; i < REG; ++i) mx = fmaxf(mx, v[i]);
2247    mx = warp_max(mx);
2248    float sum = 0.0f;
2249#pragma unroll
2250    for (int i = 0; i < REG; ++i) { v[i] = expf(v[i] - mx); sum += v[i]; }
2251    const float rcp = 1.0f / warp_sum(sum);
2252#pragma unroll
2253    for (int i = 0; i < REG; ++i) { v[i] *= rcp; if (isnan(v[i])) v[i] = -FLT_MAX; }
2254    float selected = 0.0f, selected_sum = 0.0f;
2255    for (int rank = 0; rank < KU; ++rank) {
2256        float best = v[0];
2257        int ex = lane;
2258#pragma unroll
2259        for (int i = 1; i < REG; ++i) if (v[i] > best) { best = v[i]; ex = lane + i * 32; }
2260#pragma unroll
2261        for (int m = 16; m; m >>= 1) {
2262            const float ob = __shfl_xor_sync(0xffffffffu, best, m);
2263            const int oi = __shfl_xor_sync(0xffffffffu, ex, m);
2264            if (ob > best || (ob == best && oi < ex)) { best = ob; ex = oi; }
2265        }
2266        if ((ex & 31) == lane) { v[ex / 32] = -INFINITY; selected_sum += best; }
2267        if (lane == 0) ids[t * KU + rank] = ex;
2268        if (rank == lane) selected = best;
2269    }
2270    selected_sum = fmaxf(warp_sum(selected_sum), 6.103515625e-5f);
2271    if (lane < KU) wout[t * KU + lane] = selected / selected_sum;
2272}
2273// Strata blob: gate/up codes [2 F][E / 4 B], down codes [E][F / 4 B], gate/up scales [2 F][E / 64] f16, down scales [E][F / 64] f16
2274// (E = N, F = FFC: the compiled geometry's; Flash-Next 2560 and 640: [1280][640 B], [2560][160 B], [1280][40], [2560][10])
2275constexpr int BLOB_GU_ROWS = 2 * (int) FFC, BLOB_ROW_GU = N / 4, BLOB_ROW_D = (int) FFC / 4, BLOB_SC_GU = N / 64, BLOB_SC_D = (int) FFC / 64;
2276static_assert(N % 64 == 0 && FFC % 64 == 0, "the Strata Q2 blob holds whole 64-weight blocks");
2277template <bool HALF>
2278__global__ void blob_dequant_kernel(const uint8_t* __restrict__ blob, uint16_t* __restrict__ gu16,
2279                                    uint16_t* __restrict__ d16) {
2280    constexpr size_t O_D_CODES = (size_t) BLOB_GU_ROWS * BLOB_ROW_GU, O_GU_SC = O_D_CODES + (size_t) N * BLOB_ROW_D,
2281                     O_D_SC = O_GU_SC + (size_t) BLOB_GU_ROWS * BLOB_SC_GU * 2;
2282    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;   // one thread per 4 weights (one code byte)
2283    const int64_t n_gu = (int64_t) BLOB_GU_ROWS * BLOB_ROW_GU, n_d = (int64_t) N * BLOB_ROW_D;
2284    if (i < n_gu) {
2285        const int64_t row = i / BLOB_ROW_GU, byte = i % BLOB_ROW_GU;
2286        const uint8_t c = blob[row * BLOB_ROW_GU + byte];
2287        const uint8_t* sp = blob + O_GU_SC + (size_t) (row * BLOB_SC_GU + (byte * 4) / 64) * 2;
2288        const float d = __half2float(__ushort_as_half((uint16_t) (sp[0] | (sp[1] << 8))));
2289        uint16_t* o = gu16 + row * N + byte * 4;
2290#pragma unroll
2291        for (int k = 0; k < 4; ++k) { const float v = (float) (((c >> (2 * k)) & 3) - 1) * d; o[k] = HALF ? hf(v) : bf(v); }
2292    } else if (i < n_gu + n_d) {
2293        const int64_t j = i - n_gu, row = j / BLOB_ROW_D, byte = j % BLOB_ROW_D;
2294        const uint8_t c = blob[O_D_CODES + row * BLOB_ROW_D + byte];
2295        const uint8_t* sp = blob + O_D_SC + (size_t) (row * BLOB_SC_D + (byte * 4) / 64) * 2;
2296        const float d = __half2float(__ushort_as_half((uint16_t) (sp[0] | (sp[1] << 8))));
2297        uint16_t* o = d16 + row * FFC + byte * 4;
2298#pragma unroll
2299        for (int k = 0; k < 4; ++k) { const float v = (float) (((c >> (2 * k)) & 3) - 1) * d; o[k] = HALF ? hf(v) : bf(v); }
2300    }
2301}
2302__global__ void swiglu_il_kernel(const float* __restrict__ gu, uint16_t* __restrict__ h16, int64_t n) {
2303    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
2304    if (i >= n * FFC) return;
2305    const int64_t r = i / FFC, k = i % FFC;
2306    const float g = gu[r * (2 * FFC) + 2 * k], u = gu[r * (2 * FFC) + 2 * k + 1];
2307    h16[i] = hf_sat(g / (1.0f + __expf(-g)) * u);
2308}
2309// The Volta prompt experts (gemm_iq_f16_grouped): SwiGLU of the gate/up product's rows (gate 0..n_ff, up n_ff..2 n_ff,
2310// or interleaved) to the FP16 input of the down product, saturated as swiglu_il_kernel
2311__global__ void swiglu_split_f16_kernel(const float* __restrict__ gu, uint16_t* __restrict__ h16, int64_t rows, int n_ff,
2312                                        bool interleaved) {
2313    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
2314    if (i >= rows * n_ff) return;
2315    const int64_t r = i / n_ff, k = i % n_ff;
2316    const float* row = gu + r * 2 * n_ff;
2317    const float g = interleaved ? row[2 * k] : row[k], u = interleaved ? row[2 * k + 1] : row[n_ff + k];
2318    h16[i] = hf_sat(g / (1.0f + __expf(-g)) * u);
2319}
2320__global__ void swiglu_pair_kernel(const float* __restrict__ g, const float* __restrict__ u, uint16_t* __restrict__ h16,
2321                                   int64_t n) {
2322    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
2323    if (i >= n * FFC) return;
2324    const float a = g[i];
2325    h16[i] = hf_sat(a / (1.0f + __expf(-a)) * u[i]);
2326}
2327__global__ void gather_rows16_kernel(const uint16_t* __restrict__ x, const int32_t* __restrict__ src,
2328                                     uint16_t* __restrict__ dst, int64_t n, int64_t width) {
2329    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;   // one uint4 (8 bf16)
2330    const int64_t per = width / 8;
2331    if (i >= n * per) return;
2332    const int64_t r = i / per, j = i % per;
2333    reinterpret_cast<uint4*>(dst)[r * per + j] = reinterpret_cast<const uint4*>(x)[(int64_t) src[r] * per + j];
2334}
2335__global__ void moe_combine_kernel(const float* __restrict__ Dm, const int32_t* __restrict__ slot,
2336                                   const float* __restrict__ w, const float* __restrict__ shared,
2337                                   const float* __restrict__ sg, float* __restrict__ bo, int64_t T,
2338                                   const float* __restrict__ row_sd) {
2339    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
2340    if (i >= T * N) return;
2341    const int64_t t = i / N, d = i % N;
2342    float s = 0.0f;
2343#pragma unroll
2344    for (int k = 0; k < KU; ++k) {
2345        const int64_t r = slot[t * KU + k];
2346        const float v = row_sd ? Dm[r * N + d] * row_sd[r] : Dm[r * N + d];   // the product scale_down_rows stored
2347        s = fmaf(w[t * KU + k], v, s);
2348    }
2349    bo[i] = s + shared[i] * sigm(sg[t]);
2350}
2351
2352// W (X5): four columns per thread, one float4 load per slot; the per-element expression and the k order are unchanged
2353// (bitwise equal to moe_combine_kernel). Needs 16-byte aligned Dm / shared / bo (N * 4 bytes per row is a multiple of 16).
2354__global__ void moe_combine4_kernel(const float* __restrict__ Dm, const int32_t* __restrict__ slot,
2355                                    const float* __restrict__ w, const float4* __restrict__ shared,
2356                                    const float* __restrict__ sg, float4* __restrict__ bo, int64_t T,
2357                                    const float* __restrict__ row_sd) {
2358    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;   // float4 index
2359    if (i >= T * (N / 4)) return;
2360    const int64_t t = i / (N / 4), d = (i % (N / 4)) * 4;
2361    float4 s = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
2362    float4 v[KU];
2363    float ww[KU];
2364#pragma unroll
2365    for (int k = 0; k < KU; ++k) {
2366        ww[k] = w[t * KU + k];
2367        const int64_t r = slot[t * KU + k];
2368        v[k] = *reinterpret_cast<const float4*>(Dm + r * N + d);
2369        if (row_sd) {   // NVFP4 in MMQ: the row's s_down, as moe_combine_kernel applies it
2370            const float sd = row_sd[r];
2371            v[k] = make_float4(v[k].x * sd, v[k].y * sd, v[k].z * sd, v[k].w * sd);
2372        }
2373    }
2374#pragma unroll
2375    for (int k = 0; k < KU; ++k) {
2376        s.x = fmaf(ww[k], v[k].x, s.x); s.y = fmaf(ww[k], v[k].y, s.y);
2377        s.z = fmaf(ww[k], v[k].z, s.z); s.w = fmaf(ww[k], v[k].w, s.w);
2378    }
2379    const float g = sigm(sg[t]);
2380    const float4 sh = shared[i];
2381    bo[i] = make_float4(s.x + sh.x * g, s.y + sh.y * g, s.z + sh.z * g, s.w + sh.w * g);
2382}
2383
2384// moe_combine4_kernel with the expert rows as FP16 (fused::dm_f16_used(): the down kernels wrote 2,560 halves a row): the same fmaf order, the rows
2385// widened to FP32 first.  Half the bytes of the layer's rows, read once.  (Round 0215, from the Strix dm16 patch.)
2386__global__ void moe_combine16_kernel(const uint16_t* __restrict__ Dm, const int32_t* __restrict__ slot,
2387                                     const float* __restrict__ w, const float4* __restrict__ shared,
2388                                     const float* __restrict__ sg, float4* __restrict__ bo, int64_t T) {
2389    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;   // float4 index
2390    if (i >= T * (N / 4)) return;
2391    const int64_t t = i / (N / 4), d = (i % (N / 4)) * 4;
2392    uint2 raw[KU];
2393    float ww[KU];
2394#pragma unroll
2395    for (int k = 0; k < KU; ++k) {
2396        ww[k] = w[t * KU + k];
2397        const int64_t r = slot[t * KU + k];
2398        raw[k] = *reinterpret_cast<const uint2*>(Dm + r * N + d);
2399    }
2400    float4 s = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
2401#pragma unroll
2402    for (int k = 0; k < KU; ++k) {
2403        const float a = __half2float(__ushort_as_half((unsigned short) (raw[k].x & 0xffffu))), b = __half2float(__ushort_as_half((unsigned short) (raw[k].x >> 16)));
2404        const float c = __half2float(__ushort_as_half((unsigned short) (raw[k].y & 0xffffu))), e = __half2float(__ushort_as_half((unsigned short) (raw[k].y >> 16)));
2405        s.x = fmaf(ww[k], a, s.x); s.y = fmaf(ww[k], b, s.y);
2406        s.z = fmaf(ww[k], c, s.z); s.w = fmaf(ww[k], e, s.w);
2407    }
2408    const float g = sigm(sg[t]);
2409    const float4 sh = shared[i];
2410    bo[i] = make_float4(s.x + sh.x * g, s.y + sh.y * g, s.z + sh.z * g, s.w + sh.w * g);
2411}
2412
2413__global__ void moe_shared_init_kernel(const float* __restrict__ shared, const float* __restrict__ sg,
2414                                       float* __restrict__ acc, int64_t T) {
2415    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
2416    if (i >= T * N) return;
2417    acc[i] = shared[i] * sigm(sg[i / N]);
2418}
2419// grid (n_u, ceil(N / 256)): one token of the group per block row, its rows summed in order
2420__global__ void moe_scatter_add_kernel(const float* __restrict__ Dm, const int32_t* __restrict__ u_tok,
2421                                       const int32_t* __restrict__ u_off, const int32_t* __restrict__ u_rows,
2422                                       const float* __restrict__ u_w, float* __restrict__ acc) {
2423    const int64_t u = blockIdx.x;
2424    const int64_t d = (int64_t) blockIdx.y * blockDim.x + threadIdx.x;
2425    if (d >= N) return;
2426    float s = 0.0f;
2427    for (int32_t j = u_off[u]; j < u_off[u + 1]; ++j) s = fmaf(u_w[j], Dm[(int64_t) u_rows[j] * N + d], s);
2428    acc[(int64_t) u_tok[u] * N + d] += s;
2429}
2430
2431// ---------------------------------------------------------------- QSA helpers
2432__global__ void rms_rows_kernel(float* __restrict__ x, const float* __restrict__ w, int64_t cols, int64_t ld, float eps) {
2433    __shared__ float sh[32];
2434    float* r = x + (int64_t) blockIdx.x * ld;
2435    float ss = 0.0f;
2436    for (int64_t c = threadIdx.x; c < cols; c += blockDim.x) ss += r[c] * r[c];
2437    const float s = rsqrtf(block_sum(ss, sh) / (float) cols + eps);
2438    __syncthreads();
2439    for (int64_t c = threadIdx.x; c < cols; c += blockDim.x) r[c] = s * r[c] * w[c];
2440}
2441// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table.  The host launches <false> whenever
2442// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it;
2443// with it merely skipped at run time, the compiled default path changed its results).
2444template <bool TAB>
2445__global__ void rope_kernel(float* __restrict__ x, int64_t heads, int64_t dim, int64_t ld, int64_t pos0,
2446                            float theta_scale, float freq_scale, float corr_low, float corr_high,
2447                            float ext_factor, float mscale, const int32_t* __restrict__ mtab,
2448                            strata::kernels::RopeTab rt) {
2449    const int64_t row = blockIdx.x;             // t * heads + h
2450    const int pair = threadIdx.x;               // 0..31
2451    const int64_t t = row / heads, h = row % heads;
2452    float* p = x + t * ld + h * dim;
2453    float c, s;
2454    if (!(TAB && strata::kernels::rope_tab_cs(rt, strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair), pair, c,
2455                                              s))) {
2456        const float theta_extrap =
2457            (float) strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair) * powf(theta_scale, (float) pair);
2458        strata::kernels::rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale,
2459                                           pair, c, s);
2460    }
2461    const float a = p[pair], b = p[pair + 32];
2462    p[pair] = a * c - b * s;
2463    p[pair + 32] = a * s + b * c;
2464}
2465// STRATA_QSA_FUSE_NR (default on, =0 runs the chain below as before): rms_rows_kernel + rope_kernel (+ split_q_kernel for
2466// the query) in ONE pass over a head's row.  The same arithmetic in the same order as the pair: the sum of squares goes
2467// through the same block_sum, the scaled value is (s * x) * w as a float (the pair stored it and reloaded it), and a
2468// rotated pair is rotated with rope_kernel's own expressions.  What changes is the traffic: the q chain read and wrote
2469// the 24 heads' rows four times (split, norm read, norm write, rope read/write), this reads the source once and writes
2470// the result once, and the rope runs in the block that already holds the row instead of 32-thread blocks.
2471// Idea: halo-box/strix-llama.cpp #213 ("fused RMS norm + multi-section RoPE", MIT, The ggml authors); the kernel is ours.
2472// in[t * in_ts + h * in_hs + d] -> out[t * out_ts + h * dim + d]; in and out may be the same buffer (a block reads its whole
2473// row before it writes).  dim <= 256 and >= 64; the first 64 dims are rotated (pair, pair + 32).
2474template <bool TAB>
2475__global__ void __launch_bounds__(256) rms_rope_rows_kernel(const float* in, int64_t in_ts, int64_t in_hs, float* out,
2476                                                            int64_t out_ts, const float* __restrict__ w, int64_t heads,
2477                                                            int64_t dim, float eps, int64_t pos0, float theta_scale,
2478                                                            float freq_scale, float corr_low, float corr_high,
2479                                                            float ext_factor, float mscale, const int32_t* __restrict__ mtab,
2480                                                            strata::kernels::RopeTab rt) {
2481    __shared__ float sh[32];
2482    __shared__ float sv[256];
2483    const int64_t row = blockIdx.x;             // t * heads + h
2484    const int64_t t = row / heads, h = row % heads;
2485    const int tid = threadIdx.x;
2486    const float x = tid < dim ? in[t * in_ts + h * in_hs + tid] : 0.0f;
2487    // rms_rows_kernel: ss += r[c] * r[c] from 0, one column a thread (dim <= 256) = the rounded square.  The empty asm makes the
2488    // square a value the compiler cannot fold into the first add of block_sum's butterfly (it did: fma(x, x, other lane's
2489    // square) is another rounding than the sum of two rounded squares; hip_qsa_nr_parity found it on gfx1151, and __fmul_rn
2490    // does not stop it: it compiles to the same v_fmac).
2491    float ss = x * x;
2492#if defined(__HIP_DEVICE_COMPILE__)
2493    asm volatile("" : "+v"(ss));
2494#endif
2495    const float sc = rsqrtf(block_sum(ss, sh) / (float) dim + eps);
2496    if (tid < dim) sv[tid] = sc * x * w[tid];
2497    __syncthreads();
2498    float* o = out + t * out_ts + h * dim;
2499    if (tid < 32) {                             // rope_kernel: one thread a (pair, pair + 32)
2500        const int pair = tid;
2501        float c, s;
2502        if (!(TAB && strata::kernels::rope_tab_cs(rt, strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair), pair, c,
2503                                                  s))) {
2504            const float theta_extrap =
2505                (float) strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair) * powf(theta_scale, (float) pair);
2506            strata::kernels::rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale,
2507                                               pair, c, s);
2508        }
2509        const float a = sv[pair], b = sv[pair + 32];
2510        o[pair] = a * c - b * s;
2511        o[pair + 32] = a * s + b * c;
2512    } else if (tid >= 64 && tid < dim) {
2513        o[tid] = sv[tid];
2514    }
2515}
2516__global__ void split_q_kernel(const float* __restrict__ qf, float* __restrict__ q, int64_t T) {
2517    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
2518    if (i >= T * 24 * 256) return;
2519    const int64_t t = i / (24 * 256), h = (i / 256) % 24, d = i % 256;
2520    q[i] = qf[t * 24 * 512 + h * 512 + d];
2521}
2522__global__ void gate_attn_kernel(const float* __restrict__ a, const float* __restrict__ qf, uint16_t* __restrict__ o16,
2523                                 int64_t T, int64_t ld16) {
2524    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
2525    if (i >= T * 24 * 256) return;
2526    const int64_t t = i / (24 * 256), h = (i / 256) % 24, d = i % 256;
2527    o16[t * ld16 + h * 256 + d] = hf(a[i] * (1.0f / (1.0f + expf(-qf[t * 24 * 512 + h * 512 + 256 + d]))));
2528}
2529
2530// one block per (token, kv head, 64-value group); 64 threads. KV streaming: the pool page only if the block is
2531// resident (table >= 0), and the host copy and the prompt path's staging pool (both identity layout) when given.
2532__global__ void kv_append_kernel(const float* __restrict__ K, const float* __restrict__ V, int64_t pos0,
2533                                 const int32_t* __restrict__ table, int64_t page_size, uint16_t* k_pool,
2534                                 uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale,
2535                                 strata::kernels::KvHostPools host, strata::kernels::KvHostPools stage) {
2536    const int64_t t = blockIdx.x;
2537    const int kvh = blockIdx.y, g = blockIdx.z >> 1;
2538    const bool is_v = (blockIdx.z & 1) != 0;
2539    const int d = g * 64 + threadIdx.x;
2540    const float x = (is_v ? V : K)[t * 512 + kvh * 256 + d];
2541    const int64_t pos = pos0 + t;
2542    const int64_t page = table[pos / page_size];
2543    const int64_t row = (page * 2 + kvh) * page_size + pos % page_size;
2544    const int64_t row_id = ((pos / page_size) * 2 + kvh) * page_size + pos % page_size;
2545    if (k_pool != nullptr) {
2546        const uint16_t h = hf(x);
2547        if (page >= 0) (is_v ? v_pool : k_pool)[row * 256 + d] = h;
2548        if (host.k_pool != nullptr) (is_v ? host.v_pool : host.k_pool)[row_id * 256 + d] = h;
2549        if (stage.k_pool != nullptr) (is_v ? stage.v_pool : stage.k_pool)[row_id * 256 + d] = h;
2550        return;
2551    }
2552    float a = fabsf(x);
2553    for (int o = 16; o > 0; o >>= 1) a = fmaxf(a, __shfl_xor_sync(0xffffffffu, a, o));
2554    __shared__ float wm[2];
2555    if ((threadIdx.x & 31) == 0) wm[threadIdx.x >> 5] = a;
2556    __syncthreads();
2557    const float amax = fmaxf(wm[0], wm[1]);
2558    const uint16_t sb = hf(amax / 127.0f);
2559    const float sf = __half2float(__ushort_as_half(sb));
2560    int q = 0;
2561    if (sf > 0.0f) { q = __float2int_rn(x / sf); q = q < -127 ? -127 : (q > 127 ? 127 : q); }
2562    if (page >= 0) {
2563        (is_v ? v_q : k_q)[row * 256 + d] = (int8_t) q;
2564        if (threadIdx.x == 0) (is_v ? v_scale : k_scale)[row * 4 + g] = sb;
2565    }
2566    if (host.k_q != nullptr) {
2567        (is_v ? host.v_q : host.k_q)[row_id * 256 + d] = (int8_t) q;
2568        if (threadIdx.x == 0) (is_v ? host.v_scale : host.k_scale)[row_id * 4 + g] = sb;
2569    }
2570    if (stage.k_q != nullptr) {
2571        (is_v ? stage.v_q : stage.k_q)[row_id * 256 + d] = (int8_t) q;
2572        if (threadIdx.x == 0) (is_v ? stage.v_scale : stage.k_scale)[row_id * 4 + g] = sb;
2573    }
2574}
2575__global__ void to_f16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, int64_t n) {
2576    for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x)
2577#if defined(__HIPCC__)
2578        y[i] = hf_sat(x[i]);   // saturated and counted like every other FP16 image (the hc / embedding image on gfx103x)
2579#else
2580        y[i] = hf(x[i]);       // CUDA: as it was
2581#endif
2582}
2583__global__ void round_f16_kernel(const float* __restrict__ x, float* __restrict__ y, int64_t n) {
2584    for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x)
2585        y[i] = __half2float(__float2half_rn(x[i]));
2586}
2587__global__ void to_bf16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, uint16_t* __restrict__ ylo,
2588                               int64_t n) {
2589    for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) {
2590        const uint16_t h = act16(x[i]);
2591        y[i] = h;
2592        if (ylo) ylo[i] = bf_lo(x[i], h);
2593    }
2594}
2595
2596// S23 (opt-in STRATA_HC_UPMIX=1, gfx11): the hyper-connection read's up projection with gr_mix_r as its epilogue.  The
2597// up GEMM's FP32 output `gated` (T x 10240: 671 MB per 16K chunk) is never written or read back: a block computes a
2598// tile of 64 tokens x 64 columns for all 4 streams on the matrix cores (BF16 in, FP32 accumulate over K = 320; the
2599// lo16 and w_up tiles staged in LDS), and each lane already holds the 4 streams' values of its (token, column) - the
2600// mix (x_c = R * rs * w, sum of x_c * sigmoid(gated_c), / 4) runs in registers, in gr_mix_r_kernel's order.  The
2601// GEMM sums K in another order than hipBLASLt: rounding-level, hence opt-in and quality-gated.
2602#if defined(__HIPCC__)
2603typedef __bf16 um_b16 __attribute__((ext_vector_type(16)));
2604typedef float um_f8 __attribute__((ext_vector_type(8)));
2605__device__ __forceinline__ um_f8 um_wmma(um_b16 a, um_b16 b, um_f8 c) {
2606#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || defined(__gfx1150__) || defined(__gfx1151__)
2607    return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c);
2608#else
2609    (void) a; (void) b; return c;   // not a gfx11 device pass: never launched (runtime gate)
2610#endif
2611}
2612constexpr int UM_T = 256, UM_D = 16, UM_LD = LR + 8;   // a block: 256 tokens x 16 columns x the 4 streams
2613__device__ __forceinline__ um_b16 um_frag(const uint16_t* p) {   // 16 BF16 (32 bytes, 16-byte aligned)
2614    const uint4 a = *reinterpret_cast<const uint4*>(p), b = *reinterpret_cast<const uint4*>(p + 8);
2615    const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w};
2616    return __builtin_bit_cast(um_b16, w);
2617}
2618// The FP16 prompt path (g_act_f16, STRATA_HIP_PROMPT_F16=1): lo16 holds FP16 bits, so the same product runs on the FP16 matrix-core
2619// builtin; the BF16 w_up rows are converted to FP16 while they are staged (bf_to_hf_conv, the conversion the FP16 GEMM route applies;
2620// a BF16 value is exact in FP16 above 6e-5).  FP32 accumulate, same K order as the BF16 kernel.
2621typedef _Float16 um_h16 __attribute__((ext_vector_type(16)));
2622__device__ __forceinline__ um_f8 um_wmma_h(um_h16 a, um_h16 b, um_f8 c) {
2623#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || defined(__gfx1150__) || defined(__gfx1151__)
2624    return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c);
2625#else
2626    (void) a; (void) b; return c;   // not a gfx11 device pass: never launched (runtime gate)
2627#endif
2628}
2629__device__ __forceinline__ um_h16 um_frag_h(const uint16_t* p) {   // 16 FP16 (32 bytes, 16-byte aligned)
2630    const uint4 a = *reinterpret_cast<const uint4*>(p), b = *reinterpret_cast<const uint4*>(p + 8);
2631    const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w};
2632    return __builtin_bit_cast(um_h16, w);
2633}
2634// The block's w_up rows (16 columns x 4 streams x all 320 k) are staged in LDS once; each wave streams its own 16
2635// tokens' lo16 rows from global memory (every A fragment feeds the 4 streams' WMMAs) - one barrier per block.
2636__global__ void __launch_bounds__(512) gr_upmix_kernel(const uint16_t* __restrict__ lo16, const uint16_t* __restrict__ wu,
2637                                                       const float* __restrict__ R, const float* __restrict__ rs,
2638                                                       const float* __restrict__ w, float* __restrict__ mixed,
2639                                                       uint16_t* __restrict__ mixed16, uint16_t* __restrict__ mixed_h,
2640                                                       int64_t T) {
2641    __shared__ __align__(16) uint16_t sB[HC * UM_D][UM_LD];
2642    const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, l16 = lane & 15, hi = lane >> 4;
2643    // blocks ordered column-tile fastest: the blocks in flight share a token tile, so the epilogue's R reads run
2644    // along rows (token-tile fastest scattered them over 512 rows x 40 KB per block: 28 ms instead of 3.7 at 8K)
2645    const int64_t t0 = (int64_t) blockIdx.y * UM_T + 16 * wave;
2646    const int d0 = blockIdx.x * UM_D;
2647    const bool f16 = g_act_f16 != 0;   // uniform: the FP16 prompt path
2648    for (int i = tid; i < HC * UM_D * (LR / 8); i += 512) {
2649        const int rr = i / (LR / 8), q = i % (LR / 8);
2650        const int c = rr / UM_D, dd = rr % UM_D;
2651        uint4 v = *reinterpret_cast<const uint4*>(wu + (size_t) (c * N + d0 + dd) * LR + 8 * q);
2652        if (f16) {
2653            uint32_t* w32 = reinterpret_cast<uint32_t*>(&v);
2654#pragma unroll
2655            for (int j = 0; j < 4; ++j)
2656                w32[j] = (uint32_t) bf_to_hf_conv((uint16_t) (w32[j] & 0xffffu)) | ((uint32_t) bf_to_hf_conv((uint16_t) (w32[j] >> 16)) << 16);
2657        }
2658        *reinterpret_cast<uint4*>(&sB[rr][8 * q]) = v;
2659    }
2660    __syncthreads();
2661    if (t0 >= T) return;
2662    const int64_t ta = t0 + l16 < T ? t0 + l16 : T - 1;
2663    const uint16_t* arow = lo16 + ta * LR;
2664    um_f8 acc[HC];
2665#pragma unroll
2666    for (int c = 0; c < HC; ++c) acc[c] = um_f8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
2667    if (f16) {
2668#pragma unroll
2669        for (int ks = 0; ks < LR; ks += 16) {
2670            const um_h16 a = um_frag_h(arow + ks);
2671#pragma unroll
2672            for (int c = 0; c < HC; ++c) acc[c] = um_wmma_h(a, um_frag_h(&sB[c * UM_D + l16][ks]), acc[c]);
2673        }
2674    } else {
2675#pragma unroll
2676        for (int ks = 0; ks < LR; ks += 16) {
2677            const um_b16 a = um_frag(arow + ks);
2678#pragma unroll
2679            for (int c = 0; c < HC; ++c) acc[c] = um_wmma(a, um_frag(&sB[c * UM_D + l16][ks]), acc[c]);
2680        }
2681    }
2682    const int d = d0 + l16;
2683#pragma unroll
2684    for (int i = 0; i < 8; ++i) {
2685        const int64_t t = t0 + 2 * i + hi;
2686        if (t >= T) continue;
2687        float s = 0.0f;
2688#pragma unroll
2689        for (int c = 0; c < HC; ++c) {
2690            const float x = R[t * D + c * N + d] * rs[t * HC + c] * w[c * N + d];   // gr_mix_r_kernel's order
2691            s = fmaf(x, sigm(acc[c][i]), s);
2692        }
2693        s /= (float) HC;
2694        mixed[t * N + d] = s;
2695        if (mixed16) mixed16[t * N + d] = act16(s);
2696        if (mixed_h) mixed_h[t * N + d] = hf(s);
2697    }
2698}
2699#endif
2700#if !defined(__HIPCC__)
2701// S23 on CUDA (sm_80+; opt-in STRATA_HC_UPMIX=1, see hc_upmix in prefill.cpp): the hyper-connection read's up
2702// projection (lo16 x w_up^T, BF16 in, FP32 accumulate over K = 320) with gr_mix_r as its epilogue, so `gated`
2703// (T x 10240 FP32, 336 MB for an 8,192-token chunk) is neither written by the GEMM nor read back by the mix - gr_mix_r
2704// reads R and `gated` at ~96% of the bandwidth already, so only fewer bytes make the read faster.  A block: 128 tokens
2705// x 32 columns x the 4 streams (128 output columns), K staged in 32-deep slices (cp.async, double-buffered), 8 warps of
2706// 32 tokens x 16 columns x 4 streams on mma.m16n8k16 (ldmatrix); a lane then holds its (token, column) pairs for all 4
2707// streams, and the mix runs in registers in gr_mix_r_kernel's order (x_c = R * rs * w; s = fmaf(x_c, sigm(g_c), s);
2708// s / 4) with the BF16 / FP16 images.  The epilogue's R rows are asked into L2 at the start.  With cuBLAS's up GEMM
2709// summing K in the same order (CUDA 13.3 on an RTX 5090 from 33 tokens: gr_upmix_parity) `mixed` is the default pair's
2710// bits.
2711constexpr int UC_BM = 128, UC_BD = 32;   // tokens, columns a stream
2712#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800   // cp.async, bf16 mma: the kernel is empty before sm_80
2713constexpr int UC_KC = 32, UC_LD = UC_KC + 8;   // k a slice, a staged row
2714__device__ __forceinline__ void uc_pf_l2(const float* p) { asm volatile("prefetch.global.L2 [%0];" ::"l"(p)); }
2715__device__ __forceinline__ void uc_cp16(void* s, const void* g) {
2716    asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"((unsigned) __cvta_generic_to_shared(s)), "l"(g));
2717}
2718__device__ __forceinline__ void uc_ldm4(unsigned (&r)[4], const void* p) {
2719    asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n"
2720                 : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3])
2721                 : "r"((unsigned) __cvta_generic_to_shared(p)));
2722}
2723__device__ __forceinline__ void uc_mma(float (&d)[4], const unsigned (&a)[4], unsigned b0, unsigned b1) {
2724    asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, "
2725                 "{%0,%1,%2,%3};\n"
2726                 : "+f"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3])
2727                 : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1));
2728}
2729#endif
2730__global__ void __launch_bounds__(256, 2) gr_upmix_cuda_kernel(const uint16_t* __restrict__ lo16,
2731                                                              const uint16_t* __restrict__ wu,
2732                                                              const float* __restrict__ R, const float* __restrict__ rs,
2733                                                              const float* __restrict__ w, float* __restrict__ mixed,
2734                                                              uint16_t* __restrict__ mixed16,
2735                                                              uint16_t* __restrict__ mixed_h,
2736                                                              int64_t T) {
2737#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
2738    __shared__ __align__(16) uint16_t sA[2][UC_BM][UC_LD];
2739    __shared__ __align__(16) uint16_t sB[2][HC * UC_BD][UC_LD];
2740    const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5, wm = warp >> 1, wn = warp & 1;
2741    // blocks column-tile fastest: the blocks in flight share a token tile (its lo16 rows stay in L2, the epilogue's R
2742    // reads run along rows)
2743    const int64_t t0 = (int64_t) blockIdx.y * UC_BM;
2744    const int d0 = blockIdx.x * UC_BD;
2745    // the epilogue's R rows (128 tokens x 4 streams x 128 bytes) asked into L2 now, so they arrive under the GEMM
2746    for (int i = tid; i < UC_BM * HC; i += 256) {
2747        const int64_t t = t0 + i / HC;
2748        if (t < T) uc_pf_l2(R + t * D + (i % HC) * N + d0);
2749    }
2750    auto stage = [&](int kc, int buf) {
2751        for (int i = tid; i < UC_BM * (UC_KC / 8); i += 256) {
2752            const int r = i / (UC_KC / 8), q = i % (UC_KC / 8);
2753            const int64_t t = t0 + r < T ? t0 + r : T - 1;   // the last tile's missing rows read a real row, unused
2754            uc_cp16(&sA[buf][r][q * 8], lo16 + t * LR + kc * UC_KC + q * 8);
2755        }
2756        for (int i = tid; i < HC * UC_BD * (UC_KC / 8); i += 256) {
2757            const int r = i / (UC_KC / 8), q = i % (UC_KC / 8);
2758            uc_cp16(&sB[buf][r][q * 8], wu + ((int64_t) (r / UC_BD) * N + d0 + r % UC_BD) * LR + kc * UC_KC + q * 8);
2759        }
2760        asm volatile("cp.async.commit_group;\n" ::);
2761    };
2762    float acc[2][HC][2][4];
2763#pragma unroll
2764    for (int mt = 0; mt < 2; ++mt)
2765#pragma unroll
2766        for (int c = 0; c < HC; ++c)
2767#pragma unroll
2768            for (int s = 0; s < 2; ++s)
2769#pragma unroll
2770                for (int i = 0; i < 4; ++i) acc[mt][c][s][i] = 0.0f;
2771    constexpr int NK = LR / UC_KC;
2772    stage(0, 0);
2773    for (int kc = 0; kc < NK; ++kc) {
2774        const int buf = kc & 1;
2775        if (kc + 1 < NK) {
2776            stage(kc + 1, buf ^ 1);
2777            asm volatile("cp.async.wait_group 1;\n" ::);
2778        } else {
2779            asm volatile("cp.async.wait_group 0;\n" ::);
2780        }
2781        __syncthreads();
2782#pragma unroll
2783        for (int ks = 0; ks < UC_KC / 16; ++ks) {
2784            unsigned a[2][4];
2785#pragma unroll
2786            for (int mt = 0; mt < 2; ++mt) uc_ldm4(a[mt], &sA[buf][wm * 32 + mt * 16 + (lane & 15)][ks * 16 + (lane >> 4) * 8]);
2787#pragma unroll
2788            for (int c = 0; c < HC; ++c) {
2789                unsigned b[4];   // b[0..1]: columns 0-7 of this warp's 16, b[2..3]: 8-15 (k 0-7, 8-15 each)
2790                uc_ldm4(b, &sB[buf][c * UC_BD + wn * 16 + (lane & 7) + ((lane >> 4) << 3)][ks * 16 + ((lane >> 3) & 1) * 8]);
2791#pragma unroll
2792                for (int mt = 0; mt < 2; ++mt) {
2793                    uc_mma(acc[mt][c][0], a[mt], b[0], b[1]);
2794                    uc_mma(acc[mt][c][1], a[mt], b[2], b[3]);
2795                }
2796            }
2797        }
2798        __syncthreads();   // every read of `buf` before stage(kc + 2) refills it
2799    }
2800#pragma unroll
2801    for (int mt = 0; mt < 2; ++mt)
2802#pragma unroll
2803        for (int h = 0; h < 2; ++h) {
2804            const int64_t t = t0 + wm * 32 + mt * 16 + (lane >> 2) + h * 8;
2805            if (t >= T) continue;
2806#pragma unroll
2807            for (int s = 0; s < 2; ++s) {
2808                const int d = d0 + wn * 16 + s * 8 + (lane & 3) * 2;
2809                float sm[2] = {0.0f, 0.0f};
2810#pragma unroll
2811                for (int c = 0; c < HC; ++c) {
2812                    const float2 r2 = *reinterpret_cast<const float2*>(R + t * D + c * N + d);
2813                    const float2 w2 = *reinterpret_cast<const float2*>(w + c * N + d);
2814                    const float rsc = rs[t * HC + c];
2815                    const float x0 = r2.x * rsc * w2.x, x1 = r2.y * rsc * w2.y;   // gr_mix_r_kernel's order
2816                    sm[0] = fmaf(x0, sigm(acc[mt][c][s][h * 2 + 0]), sm[0]);
2817                    sm[1] = fmaf(x1, sigm(acc[mt][c][s][h * 2 + 1]), sm[1]);
2818                }
2819                sm[0] /= (float) HC;
2820                sm[1] /= (float) HC;
2821                *reinterpret_cast<float2*>(mixed + t * N + d) = make_float2(sm[0], sm[1]);
2822                if (mixed16)
2823                    *reinterpret_cast<uint32_t*>(mixed16 + t * N + d) =
2824                        (uint32_t) act16(sm[0]) | ((uint32_t) act16(sm[1]) << 16);
2825                if (mixed_h)
2826                    *reinterpret_cast<uint32_t*>(mixed_h + t * N + d) = (uint32_t) hf(sm[0]) | ((uint32_t) hf(sm[1]) << 16);
2827            }
2828        }
2829#endif
2830}
2831#endif
2832}  // namespace
2833
2834void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const int32_t* page_table, int64_t page_size,
2835               uint16_t* k_pool, uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale,
2836               void* stream, const strata::kernels::KvHostPools* host, const strata::kernels::KvHostPools* stage) {
2837    if (T <= 0) return;
2838    kv_append_kernel<<<dim3((unsigned) T, 2, 8), 64, 0, (cudaStream_t) stream>>>(
2839        K, V, pos0, page_table, page_size, k_pool, v_pool, k_q, v_q, k_scale, v_scale,
2840        host ? *host : strata::kernels::KvHostPools{}, stage ? *stage : strata::kernels::KvHostPools{});
2841    check("kv_append");
2842}
2843void set_act_f16(bool on) {
2844#if !defined(__HIPCC__)
2845    (void) on;   // CUDA: the activation image is always BF16
2846    return;
2847#else
2848    const int v = on ? 1 : 0;
2849    if (cudaMemcpyToSymbol(g_act_f16, &v, sizeof v) != cudaSuccess) {
2850        std::fprintf(stderr, "prefill: setting the FP16 activation image failed: %s\n", cudaGetErrorString(cudaGetLastError()));
2851        std::exit(1);
2852    }
2853#endif
2854}
2855void set_f16_range(bool on) {
2856#if defined(__HIPCC__)
2857    const int v = on ? 1 : 0;
2858    if (cudaMemcpyToSymbol(g_f16_range_on, &v, sizeof v) != cudaSuccess) {
2859        std::fprintf(stderr, "prefill: setting the FP16 range check failed: %s\n", cudaGetErrorString(cudaGetLastError()));
2860        std::exit(1);
2861    }
2862#else
2863    (void) on;
2864#endif
2865}
2866bool f16_range_read(float& max_abs, unsigned long long& over, bool reset) {
2867#if !defined(__HIPCC__)
2868    (void) max_abs; (void) over; (void) reset;
2869    return false;
2870#else
2871    unsigned bits = 0; unsigned long long o = 0;
2872    if (cudaMemcpyFromSymbol(&bits, g_f16_range_max, sizeof bits) != cudaSuccess ||
2873        cudaMemcpyFromSymbol(&o, g_f16_range_over, sizeof o) != cudaSuccess) { cudaGetLastError(); return false; }
2874    union { unsigned u; float f; } c; c.u = bits; max_abs = c.f; over = o;
2875    if (reset) {
2876        const unsigned z = 0; const unsigned long long zz = 0;
2877        cudaMemcpyToSymbol(g_f16_range_max, &z, sizeof z); cudaMemcpyToSymbol(g_f16_range_over, &zz, sizeof zz);
2878    }
2879    return true;
2880#endif
2881}
2882void to_f16(const float* x, uint16_t* y, int64_t n, void* stream) {
2883    if (n <= 0) return;
2884    to_f16_kernel<<<(unsigned) ((n + 255) / 256 < 4096 ? (n + 255) / 256 : 4096), 256, 0, (cudaStream_t) stream>>>(x, y, n);
2885    check("to_f16");
2886}
2887void round_f16(const float* x, float* y, int64_t n, void* stream) {
2888    if (n <= 0) return;
2889    round_f16_kernel<<<(unsigned) ((n + 255) / 256 < 4096 ? (n + 255) / 256 : 4096), 256, 0, (cudaStream_t) stream>>>(x, y, n);
2890    check("round_f16");
2891}
2892void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream, uint16_t* ylo) {
2893    if (n <= 0) return;
2894    to_bf16_kernel<<<(unsigned) ((n + 255) / 256 < 4096 ? (n + 255) / 256 : 4096), 256, 0, (cudaStream_t) stream>>>(x, y, ylo, n);
2895    check("to_bf16");
2896}
2897
2898void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream,
2899             uint16_t* xn16_lo, bool f16img) {
2900    gr_norm_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, xn, xn16, xn16_lo, f16img ? 1 : 0);
2901    check("gr_norm");
2902}
2903void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream,
2904                uint16_t* xn16_lo, int64_t ldx, bool f16img) {
2905    gr_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, rs, xn16, xn16_lo,
2906                                                                                ldx > 0 ? ldx : D, f16img ? 1 : 0);
2907    check("gr_norm_rs");
2908}
2909void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16,
2910              int64_t T, void* stream, uint16_t* mixed_h, uint16_t* mixed16_lo) {
2911    gr_mix_r_kernel<<<blocks_for(T * N), 256, 0, (cudaStream_t) stream>>>(R, rs, w_norm, gated, mixed, mixed16, T,
2912                                                                          mixed_h, mixed16_lo);
2913    check("gr_mix_r");
2914}
2915bool gr_upmix(const uint16_t* lo16, const uint16_t* w_up, const float* R, const float* rs, const float* w_norm,
2916              float* mixed, uint16_t* mixed16, uint16_t* mixed_h, int64_t T, void* stream) {
2917#if defined(__HIPCC__)
2918    static const bool gfx11 = [] {
2919        int dev = 0;
2920        cudaDeviceProp p;
2921        if (cudaGetDevice(&dev) != cudaSuccess || cudaGetDeviceProperties(&p, dev) != cudaSuccess) return false;
2922        return strata::kernels::gfx_arch_is_gfx11_wmma(p.gcnArchName);
2923    }();
2924    if (!gfx11 || T <= 0) return false;
2925    gr_upmix_kernel<<<dim3(N / UM_D, (unsigned) ((T + UM_T - 1) / UM_T)), 512, 0, (cudaStream_t) stream>>>(
2926        lo16, w_up, R, rs, w_norm, mixed, mixed16, mixed_h, T);
2927    check("gr_upmix");
2928    return true;
2929#else
2930    static int ok_dev[64] = {};   // per device: 0 not asked yet, 1 sm_80+, 2 no
2931    int dev = 0;
2932    if (T <= 0 || cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
2933    if (ok_dev[dev] == 0) {
2934        int major = 0;
2935        ok_dev[dev] = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
2936                      strata::cc_major_of(major) >= 8 ? 1 : 2;
2937        cudaGetLastError();
2938    }
2939    if (ok_dev[dev] != 1) return false;
2940    gr_upmix_cuda_kernel<<<dim3(N / UC_BD, (unsigned) ((T + UC_BM - 1) / UC_BM)), 256, 0, (cudaStream_t) stream>>>(
2941        lo16, w_up, R, rs, w_norm, mixed, mixed16, mixed_h, T);
2942    check("gr_upmix");
2943    return true;
2944#endif
2945}
2946void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps,
2947                      float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo, int64_t ldx, bool f16img) {
2948    gr_write_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, bo, inj, inj_ld, w_norm_next, eps,
2949                                                                                      rs, xn16, xn16_lo,
2950                                                                                      ldx > 0 ? ldx : D, f16img ? 1 : 0);
2951    check("gr_write_norm_rs");
2952}
2953void gr_write_cvec_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* v_l,
2954                           const float* s_l, const int* on, int mode, const float* w_norm_next, float eps, float* rs,
2955                           uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo, int64_t ldx, bool f16img) {
2956    gr_write_cvec_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(
2957        R, bo, inj, inj_ld, v_l, s_l, on, mode, w_norm_next, eps, rs, xn16, xn16_lo, ldx > 0 ? ldx : D, f16img ? 1 : 0);
2958    check("gr_write_cvec_norm_rs");
2959}
2960void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo) {
2961    gr_silu_kernel<<<blocks_for(T * LR), 256, 0, (cudaStream_t) stream>>>(lo, lo16, lo16_lo, T * LR);
2962    check("gr_silu");
2963}
2964void gr_mix(const float* xn, const float* gated, float* mixed, uint16_t* mixed16, int64_t T, void* stream,
2965            uint16_t* mixed_h, uint16_t* mixed16_lo) {
2966    gr_mix_kernel<<<blocks_for(T * N), 256, 0, (cudaStream_t) stream>>>(xn, gated, mixed, mixed16, T, mixed_h, mixed16_lo);
2967    check("gr_mix");
2968}
2969void gr_write(float* R, const float* bo, const float* inj, int64_t inj_ld, int64_t T, void* stream) {
2970    gr_write_kernel<<<blocks_for(T * D), 256, 0, (cudaStream_t) stream>>>(R, bo, inj, inj_ld, T);
2971    check("gr_write");
2972}
2973void gr_broadcast(const float* e, float* R, int64_t T, void* stream) {
2974    gr_broadcast_kernel<<<blocks_for(T * D), 256, 0, (cudaStream_t) stream>>>(e, R, T);
2975    check("gr_broadcast");
2976}
2977void gdn_gates(const float* ab, const float* dt, const float* ssm_a, float* gate, float* beta, int64_t T, void* stream) {
2978    gdn_gates_kernel<<<blocks_for(T * HV), 256, 0, (cudaStream_t) stream>>>(ab, dt, ssm_a, gate, beta, T);
2979    check("gdn_gates");
2980}
2981void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, int64_t T, float eps, void* stream) {
2982    static const bool serial = std::getenv("STRATA_GDN_CONV_SERIAL") != nullptr;   // the old walk (A/B)
2983    if (serial || T <= CONV_TILE) {
2984        gdn_conv_kernel<<<C / 128, 128, 0, (cudaStream_t) stream>>>(history, qkv, conv_w, h, T);
2985    } else {
2986        static const int fused_mode = [] { const char* v = std::getenv("STRATA_GDN_CONVL2"); return v ? std::atoi(v) : 0; }();
2987        const bool fused = fused_mode != 0;
2988        if (fused_mode >= 2) {
2989            gdn_conv_w_kernel<<<dim3(C / 128, (unsigned) ((T + 4 * CONVW_TOK - 1) / (4 * CONVW_TOK))), 128, 0,
2990                                (cudaStream_t) stream>>>(history, qkv, conv_w, h, T, eps);
2991            gdn_conv_hist_kernel<<<C / 128, 128, 0, (cudaStream_t) stream>>>(history, qkv, T);
2992            check("gdn_conv");
2993            return;
2994        }
2995        if (fused) {
2996            gdn_conv_l2_kernel<<<dim3(C / 128, (unsigned) ((T + CONV_TILE - 1) / CONV_TILE)), 128, 0,
2997                                 (cudaStream_t) stream>>>(history, qkv, conv_w, h, T, eps);
2998            gdn_conv_hist_kernel<<<C / 128, 128, 0, (cudaStream_t) stream>>>(history, qkv, T);
2999            check("gdn_conv");
3000            return;
3001        }
3002        gdn_conv_tiled_kernel<<<dim3(C / 128, (unsigned) ((T + CONV_TILE - 1) / CONV_TILE)), 128, 0,
3003                                (cudaStream_t) stream>>>(history, qkv, conv_w, h, T);
3004        gdn_conv_hist_kernel<<<C / 128, 128, 0, (cudaStream_t) stream>>>(history, qkv, T);
3005    }
3006    gdn_l2_kernel<<<dim3(2 * HK, (unsigned) T), S, 0, (cudaStream_t) stream>>>(h, eps);
3007    check("gdn_conv");
3008}
3009// The recurrence dispatch, shared by the two entry points below so the state-only form cannot drift from the full
3010// one.  `with_out` false runs exactly the same kernels minus the output normalization (the CUDA-only KVA path).
3011static void gdn_recurrence_impl(int variant, float* state, const float* h, const float* gate, const float* beta,
3012                                const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T,
3013                                void* stream, int64_t ld16, bool with_out) {
3014    if (ld16 <= 0) ld16 = (int64_t) HV * S;
3015    static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr;   // the one-block-per-head kernel (A/B)
3016#if defined(__HIPCC__)
3017    if (variant == 0 || variant == 1) {
3018        // STRATA_GDN_CHUNKED=1 (opt-in): the chunked recurrence on the gfx11 matrix cores, FP16 operands (other bits;
3019        // a shorter chunk or another part takes the kernels below)
3020        static const bool chunked = gdn_chunked_env() != 0;   // (unset: gdn_rec_wmma applies the gfx12 length gate)
3021        if (chunked && !serial && gdn_rec_wmma(state, h, gate, beta, z, gamma, eps, y, y16, T, (cudaStream_t) stream, ld16)) {
3022            check("gdn_recurrence (chunked, WMMA)");
3023            return;
3024        }
3025    }
3026    if (variant == 3) {   // diagnostics: the quad recurrence + the old norm kernel
3027        if (T > 0) {
3028            gdn_rec_quad_kernel<<<HV * (S / QCB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
3029            if (with_out)
3030                gdn_out_norm_kernel<<<dim3((unsigned) T, HV), S, 0, (cudaStream_t) stream>>>(z, gamma, eps, y, y16, ld16);
3031        }
3032        return;
3033    }
3034    if (variant == 4 || variant == 5) {   // diagnostics: the quad recurrence's PP / two-column kernels + the norm
3035        if (T > 0) {
3036            if (variant == 5)
3037                gdn_rec_quad2c_kernel<<<HV * (S / C2CB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
3038            else
3039                gdn_rec_quad_pp_kernel<<<HV * (S / QCB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
3040            if (with_out)
3041                gdn_out_norm_loop_kernel<true><<<(unsigned) std::min<int64_t>(T * HV, 4096), S, 0, (cudaStream_t) stream>>>(
3042                    z, gamma, eps, y, y16, T * HV, ld16);
3043        }
3044        check("gdn_recurrence (quad pp)");
3045        return;
3046    }
3047    if (variant == 1) {
3048        if (T > 0) {
3049            static const int pp = [] { const char* v = std::getenv("STRATA_GDN_PP"); return v ? std::atoi(v) : 0; }();
3050            if (pp == 2)
3051                gdn_rec_quad2c_kernel<<<HV * (S / C2CB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
3052            else if (pp)
3053                gdn_rec_quad_pp_kernel<<<HV * (S / QCB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
3054            else
3055                gdn_rec_quad_kernel<<<HV * (S / QCB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
3056            static const bool noy = [] { const char* v = std::getenv("STRATA_GDN_NOY"); return v && std::atoi(v) != 0; }();
3057            if (with_out && noy)
3058                gdn_out_norm_loop_kernel<false><<<(unsigned) std::min<int64_t>(T * HV, 4096), S, 0, (cudaStream_t) stream>>>(
3059                    z, gamma, eps, y, y16, T * HV, ld16);
3060            else if (with_out)
3061                gdn_out_norm_loop_kernel<true><<<(unsigned) std::min<int64_t>(T * HV, 4096), S, 0, (cudaStream_t) stream>>>(
3062                    z, gamma, eps, y, y16, T * HV, ld16);
3063        }
3064        check("gdn_recurrence (quad)");
3065        return;
3066    }
3067#else
3068    (void) variant;   // the quad recurrence kernels are AMD-only
3069#endif
3070#if defined(STRATA_EXPERIMENTAL_SM60)
3071    // v100/gdn-chunk: the chunked recurrence (src/prefill/gdn_chunk.cu) on Volta, where the token chain is the
3072    // cost.  STRATA_GDN_CHUNK=0 forces the recurrence, =1 forces the chunked path (the parity test's A/B switch);
3073    // unset: cc == 7.0 only, every other architecture keeps the recurrence bit-for-bit as before.  Read per call
3074    // on purpose - cheap next to the work, and the tests flip it between two launches.
3075    const char* chunk_v = std::getenv("STRATA_GDN_CHUNK");
3076    const int chunk_env = chunk_v && *chunk_v ? std::atoi(chunk_v) : -1;
3077    static const bool volta = gdn_chunk_available();   // runtime cc == 7.0 (the kernels are compiled for sm_70 only)
3078    const bool chunked = !serial && T > 0 && (chunk_env >= 0 ? chunk_env != 0 : false);
3079    // v100/gdn-chunk: the sync-free warp-reduction recurrence (bit-exact vs gdn_rec_cols_pipe) is the
3080    // measured-fast path on Volta; the chunked recurrence is opt-in (STRATA_GDN_CHUNK=1/2) - correct and
3081    // measured, but slower than this on the V100 (bench/gdn_chunk_bench).  STRATA_GDN_REC_WARP=0 restores
3082    // the old pipelined kernel bit-for-bit.
3083    // STRATA_GDN_REC_WARP (Volta only, opt-in): unset or 0 -> the pipelined kernel (the default; the chain split changes the
3084    // summation order, so it is not the default without a V100 check here), 2 -> the chain-split kernel (measured +6..9%, FP32-level), the
3085    // old pipelined kernel bit-for-bit is 0, 1 -> the sync-free bit-exact control.
3086    const char* warp_v = std::getenv("STRATA_GDN_REC_WARP");
3087    const int warp_env = warp_v && *warp_v ? std::atoi(warp_v) : 0;
3088    const bool warp_rec = !serial && !chunked && T > 0 && volta && warp_env != 0;
3089    if (chunked && T >= 64) {
3090        // the chunked prefix + the recurrence over the tail (< 64 tokens), then the out norm over all of T
3091        const int64_t T64 = T - T % 64;
3092        gdn_chunk_recurrence(state, h, gate, beta, y, T64, stream);
3093        if (T > T64)
3094            gdn_rec_cols_pipe_kernel<<<HV * NCB, dim3(CB, RG), 0, (cudaStream_t) stream>>>(
3095                state, h + T64 * C, gate + T64 * HV, beta + T64 * HV, y + T64 * (size_t) HV * S, T - T64);
3096        if (with_out)
3097            gdn_out_norm_kernel<<<dim3((unsigned) T, HV), S, 0, (cudaStream_t) stream>>>(z, gamma, eps, y, y16, ld16);
3098    } else if (warp_rec) {
3099        // =2: the 4-accumulator chain split on the pipelined structure (FP32-level, not bit-exact);
3100        // =1: the sync-free bit-exact warp reduction (measured slower - kept as the bitwise control)
3101        if (warp_env == 2)
3102            gdn_rec_cols_pipe_fast_kernel<<<HV * NCB, dim3(CB, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta,
3103                                                                                                y, T);
3104        else
3105            gdn_rec_cols_warp_kernel<<<HV * NCB, S, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
3106        if (with_out)
3107            gdn_out_norm_kernel<<<dim3((unsigned) T, HV), S, 0, (cudaStream_t) stream>>>(z, gamma, eps, y, y16, ld16);
3108    } else
3109#endif
3110    if ((serial && with_out) || T <= 0 || variant == 2) {   // the fused kernel needs z/gamma: only with the output
3111        gdn_rec_kernel<<<HV, dim3(S, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, z, gamma, eps, y, y16, T, ld16);
3112    } else {
3113        static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }();
3114        bool normed_any = false;   // the tensor-core scan wrote y16 (the norm kernel below is skipped)
3115#if !defined(__HIPCC__)
3116        // STRATA_GDN_CHUNKED=1 (opt-in): the recurrence in chunks for prompt chunks of kGdnChunkedMin+ tokens (other
3117        // bits; a shorter chunk, a card it does not fit or a failed scratch allocation takes the kernels below)
3118        static const bool chunked = [] { const char* v = std::getenv("STRATA_GDN_CHUNKED"); return v != nullptr && std::atoi(v) != 0; }();
3119        // STRATA_GDN_TC=1 (opt-in): the chunked recurrence with the scan on the tensor cores (gdn_tc.cuh) for prompt
3120        // chunks of kGdnTcMin+ tokens: within 1e-4 of the kernels below (gdn_rec_parity), 3.75x gdn_rec_kh_kernel on a
3121        // CMP 170HX; a shorter chunk, a card it does not fit or a failed scratch allocation takes the kernels below
3122        static const bool tc = [] { const char* v = std::getenv("STRATA_GDN_TC"); return v != nullptr && std::atoi(v) != 0; }();
3123        // A test's probe (gdn_probe.hpp) reads back the path that ran and may force one; without a probe this is the
3124        // dispatch it was.  A forced path that cannot run launches nothing (selected = none, reason says why).
3125        GdnProbe* pr = gdn_probe_get();
3126        const int force = pr ? pr->force : (int) kGdnAuto;
3127        int sel = kGdnNone, wanted = force;
3128        bool normed = false;   // the scan wrote y16 itself
3129        const char* why = "";
3130        const cudaStream_t cs = (cudaStream_t) stream;
3131        // the split tensor-core scan can write y16 itself (STRATA_GDN_TC_FUSE=0 off): then the norm kernel below is skipped
3132        static const bool tc_fuse = [] { const char* v = std::getenv("STRATA_GDN_TC_FUSE"); return v == nullptr || std::atoi(v) != 0; }();
3133        const GdnTcNorm tcn = {z, gamma, eps, y16, ld16};
3134        const int tcl = gdn_tc_tiles();
3135        const GdnTcNorm* tcnp = with_out && tc_fuse && tcl == 1 ? &tcn : nullptr;   // 2 tiles a head: the norm kernel (a head's norm spans both)
3136        if (force != kGdnAuto) {
3137            if (force == kGdnTc || force == kGdnTcSplit || force == kGdnTcS2 || force == kGdnTcS1) {
3138                const bool sp = force != kGdnTc;
3139                const int np = force == kGdnTcS2 ? 2 : force == kGdnTcS1 ? 1 : 3;
3140                cudaError_t e = T >= kGdnTcMin ? gdn_rec_tc(state, h, gate, beta, y, T, cs, sp, np, sp ? tcnp : nullptr, sp ? tcl : 1) : cudaErrorInvalidValue;
3141                if (e == cudaSuccess) { sel = force; normed = sp && tcnp != nullptr; }
3142                else why = T < kGdnTcMin ? "T below the tc minimum (128)" : gdn_chunk_why(true, e, false, sp);
3143            } else if (force == kGdnChunked) {
3144                cudaError_t e = T >= kGdnChunkedMin ? gdn_rec_chunked(state, h, gate, beta, y, T, cs) : cudaErrorInvalidValue;
3145                if (e == cudaSuccess) sel = kGdnChunked;
3146                else why = T < kGdnChunkedMin ? "T below the chunked minimum (128)" : gdn_chunk_why(false, e, pr->any_sms);
3147            } else if (force == kGdnKeyHead) {
3148                if (gdn_keyhead_ok()) {
3149                    gdn_rec_kh_kernel<<<HK * NCB, dim3(CB, RG), 0, cs>>>(state, h, gate, beta, y, T);
3150                    sel = kGdnKeyHead;
3151                } else why = "keyhead kernel not eligible here (needs sm_80+ with all 64 blocks resident, or STRATA_GDN_KEYHEAD=0 is set)";
3152            } else if (force == kGdnPipe) {
3153                gdn_rec_cols_pipe_kernel<<<HV * NCB, dim3(CB, RG), 0, cs>>>(state, h, gate, beta, y, T);
3154                sel = kGdnPipe;
3155            } else if (force == kGdnCols) {
3156                gdn_rec_cols_kernel<<<HV * NCB, dim3(CB, RG), 0, cs>>>(state, h, gate, beta, y, T);
3157                sel = kGdnCols;
3158            } else why = "unknown path";
3159        } else {
3160            if (tc && T >= kGdnTcMin) {
3161                wanted = kGdnTc;
3162                cudaError_t e = gdn_rec_tc(state, h, gate, beta, y, T, cs);
3163                if (e == cudaSuccess) sel = kGdnTc;
3164                else {   // the 99-KB cards (sm_86 / 89 / 120): the single-buffered v / T / P plan
3165                    if (pr) why = gdn_chunk_why(true, e, false);
3166                    // STRATA_GDN_TC_NP=1|2 (experiment, not a default): fewer split passes a product on this plan, other bits
3167                    static const int tc_np = [] { const char* v = std::getenv("STRATA_GDN_TC_NP"); const int x = v ? std::atoi(v) : 3; return x == 1 || x == 2 ? x : 3; }();
3168                    e = gdn_rec_tc(state, h, gate, beta, y, T, cs, true, tc_np, tcnp, tcl);
3169                    if (e == cudaSuccess) { sel = kGdnTcSplit; why = ""; normed = tcnp != nullptr; }
3170                }
3171            }
3172            if (sel == kGdnNone && chunked && T >= kGdnChunkedMin) {
3173                if (wanted == kGdnAuto) wanted = kGdnChunked;
3174                const cudaError_t e = gdn_rec_chunked(state, h, gate, beta, y, T, cs);
3175                if (e == cudaSuccess) sel = kGdnChunked;
3176                else if (pr && wanted == kGdnChunked) why = gdn_chunk_why(false, e, false);
3177            }
3178            if (sel == kGdnNone) {
3179                if (pipe && gdn_keyhead_ok()) {   // the value heads of a key head in one thread (same bits)
3180                    gdn_rec_kh_kernel<<<HK * NCB, dim3(CB, RG), 0, cs>>>(state, h, gate, beta, y, T);
3181                    sel = kGdnKeyHead;
3182                } else if (pipe) {   // the software-pipelined loads (same bits)
3183                    gdn_rec_cols_pipe_kernel<<<HV * NCB, dim3(CB, RG), 0, cs>>>(state, h, gate, beta, y, T);
3184                    sel = kGdnPipe;
3185                } else {
3186                    gdn_rec_cols_kernel<<<HV * NCB, dim3(CB, RG), 0, cs>>>(state, h, gate, beta, y, T);
3187                    sel = kGdnCols;
3188                }
3189                if (wanted == kGdnAuto) wanted = sel;
3190            }
3191        }
3192        if (pr) { pr->selected = sel; pr->wanted = wanted == kGdnAuto ? sel : wanted; pr->reason = why; ++pr->calls; }
3193        normed_any = normed;
3194        if (sel == kGdnNone) { check("gdn_recurrence (forced path not eligible: nothing launched)"); return; }
3195#else
3196        if (pipe)   // the software-pipelined loads (same bits)
3197            gdn_rec_cols_pipe_kernel<<<HV * NCB, dim3(CB, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
3198        else
3199            gdn_rec_cols_kernel<<<HV * NCB, dim3(CB, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
3200#endif
3201        if (with_out && !normed_any)
3202            gdn_out_norm_kernel<<<dim3((unsigned) T, HV), S, 0, (cudaStream_t) stream>>>(z, gamma, eps, y, y16, ld16);
3203    }
3204    check("gdn_recurrence");
3205}
3206void gdn_recurrence_variant(int variant, float* state, const float* h, const float* gate, const float* beta,
3207                            const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T,
3208                            void* stream, int64_t ld16) {
3209    gdn_recurrence_impl(variant, state, h, gate, beta, z, gamma, eps, y, y16, T, stream, ld16, /*with_out=*/true);
3210}
3211void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z,
3212                    const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream, int64_t ld16) {
3213    // Aurora (S23): four lanes per column + the grid-stride norm, the same bits (tests/hip/gdn_rec_head.cpp);
3214    // STRATA_GDN_HEAD=1 (on by default on gfx1151; off with STRATA_GDN_HEAD=0 or STRATA_GDN_REC_HEADS) takes them
3215    // (AMD builds only; the arch defaults set STRATA_GDN_HEAD=1 on gfx1151 and leave other cards on the earlier kernels)
3216    static const bool head = [] { const char* v = std::getenv("STRATA_GDN_HEAD"); return v != nullptr && std::atoi(v) != 0; }();
3217    static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr;
3218    gdn_recurrence_impl(head && !serial ? 1 : 0, state, h, gate, beta, z, gamma, eps, y, y16, T, stream, ld16, true);
3219}
3220/// KVA: the same recurrence, bit for bit, without the output normalisation (its readers - the output projection
3221/// and the gated residual write - have no consumer when only the state advances).  `y` is still the scratch the
3222/// recurrence kernels write; `z`/`gamma` are not read.
3223bool gdn_conv_recurrence_fused(float* history, const float* qkv, const float* conv_w, float* hbuf, float* state, const float* gate,
3224                               const float* beta, const float* z, const float* gamma, float eps, float l2eps, float* y,
3225                               uint16_t* y16, int64_t T, void* stream, int64_t ld16) {
3226#if defined(__HIPCC__)
3227    return gdn_fused_impl(history, qkv, conv_w, hbuf, state, gate, beta, z, gamma, eps, l2eps, y, y16, T, stream, ld16);
3228#else
3229    (void) history; (void) qkv; (void) conv_w; (void) hbuf; (void) state; (void) gate; (void) beta; (void) z; (void) gamma; (void) eps;
3230    (void) l2eps; (void) y; (void) y16; (void) T; (void) stream; (void) ld16;
3231    return false;
3232#endif
3233}
3234void gdn_recurrence_state_only(float* state, const float* h, const float* gate, const float* beta, float* y,
3235                               int64_t T, void* stream) {
3236    static const bool head = [] { const char* v = std::getenv("STRATA_GDN_HEAD"); return v != nullptr && std::atoi(v) != 0; }();
3237    static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr;
3238    gdn_recurrence_impl(head && !serial ? 1 : 0, state, h, gate, beta, nullptr, nullptr, 0.0f, y, nullptr, T,
3239                        stream, 0, /*with_out=*/false);
3240}
3241void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, void* stream) {
3242    if (n_expert == 512)
3243        route_kernel<16><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T);
3244    else if (n_expert == 256)
3245        route_kernel<8><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T);
3246    else
3247        strata::kernels::router_top10(logits, (int) T, (int) n_expert, KU, ids, weights, stream);
3248    check("route");
3249}
3250void blob_dequant(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream) {
3251    blob_dequant_kernel<false><<<blocks_for((int64_t) BLOB_GU_ROWS * BLOB_ROW_GU + (int64_t) N * BLOB_ROW_D), 256, 0, (cudaStream_t) stream>>>(blob, gu16, down16);
3252    check("blob_dequant");
3253}
3254void blob_dequant_f16(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream) {
3255    blob_dequant_kernel<true><<<blocks_for((int64_t) BLOB_GU_ROWS * BLOB_ROW_GU + (int64_t) N * BLOB_ROW_D), 256, 0, (cudaStream_t) stream>>>(blob, gu16, down16);
3256    check("blob_dequant_f16");
3257}
3258__global__ void fewrows_record_kernel(uint8_t* rec, unsigned long long blob, int ne, int o0) {
3259    const int i = threadIdx.x;
3260    int32_t* r = reinterpret_cast<int32_t*>(rec + 8);
3261    if (i == 0) {
3262        *reinterpret_cast<unsigned long long*>(rec) = blob;
3263        r[0] = 0;
3264        r[1] = ne;
3265        r[2] = 1;
3266        r[3] = 0;
3267    }
3268    if (i < ne) r[4 + i] = o0 + i;
3269}
3270void fewrows_record(void* rec, const void* blob, int ne, int o0, void* stream) {
3271    fewrows_record_kernel<<<1, 32, 0, (cudaStream_t) stream>>>((uint8_t*) rec, (unsigned long long) (uintptr_t) blob, ne, o0);
3272    check("fewrows_record");
3273}
3274void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, void* stream) {
3275    if (n <= 0) return;
3276    swiglu_il_kernel<<<blocks_for(n * FFC), 256, 0, (cudaStream_t) stream>>>(gu, h16, n);
3277    check("swiglu_interleaved");
3278}
3279void swiglu_split_f16(const float* gu, uint16_t* h16, int64_t rows, int n_ff, bool interleaved, void* stream) {
3280    if (rows <= 0) return;
3281    swiglu_split_f16_kernel<<<blocks_for(rows * n_ff), 256, 0, (cudaStream_t) stream>>>(gu, h16, rows, n_ff, interleaved);
3282    check("swiglu_split_f16");
3283}
3284void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, void* stream) {
3285    swiglu_pair_kernel<<<blocks_for(n * FFC), 256, 0, (cudaStream_t) stream>>>(g, u, h16, n);
3286    check("swiglu_pair");
3287}
3288namespace {
3289__global__ void copy_i32_kernel(int32_t* __restrict__ dst, const int32_t* __restrict__ src, int64_t n) {
3290    for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x)
3291        dst[i] = src[i];
3292}
3293}  // namespace
3294namespace {
3295__global__ void copy_f4_kernel(float4* __restrict__ dst, const float4* __restrict__ src, int64_t n4) {
3296    for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n4; i += (int64_t) gridDim.x * blockDim.x)
3297        dst[i] = src[i];
3298}
3299}  // namespace
3300void copy_f32_wide(float* dst, const float* src, int64_t n, void* stream) {
3301    if (n <= 0) return;
3302    const int64_t n4 = n / 4, b = std::min<int64_t>((n4 + 255) / 256, 4096);
3303    if (n4 > 0) copy_f4_kernel<<<(unsigned) b, 256, 0, (cudaStream_t) stream>>>((float4*) dst, (const float4*) src, n4);
3304    if (n % 4) copy_i32((int32_t*) dst + n4 * 4, (const int32_t*) src + n4 * 4, n % 4, stream);
3305    check("copy_f32_wide");
3306}
3307void copy_i32(int32_t* dst, const int32_t* src, int64_t n, void* stream) {
3308    if (n <= 0) return;
3309    const int64_t b = (n + 255) / 256;
3310    copy_i32_kernel<<<(unsigned) (b < 256 ? b : 256), 256, 0, (cudaStream_t) stream>>>(dst, src, n);
3311    check("copy_i32");
3312}
3313void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, int64_t n, int64_t width, void* stream) {
3314    if (n <= 0) return;
3315    gather_rows16_kernel<<<blocks_for(n * (width / 8)), 256, 0, (cudaStream_t) stream>>>(x16, src, dst16, n, width);
3316    check("gather_rows16");
3317}
3318namespace {
3319__global__ void moe_combine_peer_kernel(const float* __restrict__ Dm, const int32_t* __restrict__ slot,
3320                                        const float* __restrict__ w, const float* __restrict__ shared,
3321                                        const float* __restrict__ sg, const float* __restrict__ peer, int64_t rows_local,
3322                                        float* __restrict__ bo, int64_t T) {
3323    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
3324    if (i >= T * N) return;
3325    const int64_t t = i / N, d = i % N;
3326    float s = 0.0f;
3327#pragma unroll
3328    for (int k = 0; k < KU; ++k) {
3329        const int32_t r = slot[t * KU + k];
3330        if (r < rows_local) s = fmaf(w[t * KU + k], Dm[(int64_t) r * N + d], s);
3331    }
3332    bo[i] = (s + peer[i]) + shared[i] * sigm(sg[t]);
3333}
3334__global__ void peer_scatter_add_kernel(float* __restrict__ sum, const float* __restrict__ rows,
3335                                        const float* __restrict__ wk, const int32_t* __restrict__ pair, int64_t n) {
3336    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
3337    if (i >= n * N) return;
3338    const int64_t r = i / N, d = i % N;
3339    const int32_t p = pair[r];
3340    float* o = sum + (int64_t) (p / KU) * N + d;
3341    *o = fmaf(wk[p], rows[i], *o);
3342}
3343__global__ void moe_combine_peer16_kernel(const float* __restrict__ Dm, const int32_t* __restrict__ slot,
3344                                          const float* __restrict__ w, const float* __restrict__ shared,
3345                                          const float* __restrict__ sg, const uint16_t* __restrict__ peer16,
3346                                          int64_t rows_local, float* __restrict__ bo, int64_t T) {
3347    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
3348    if (i >= T * N) return;
3349    const int64_t t = i / N, d = i % N;
3350    float s = 0.0f;
3351#pragma unroll
3352    for (int k = 0; k < KU; ++k) {
3353        const int32_t r = slot[t * KU + k];
3354        if (r < rows_local) s = fmaf(w[t * KU + k], Dm[(int64_t) r * N + d], s);
3355    }
3356    bo[i] = (s + __half2float(__ushort_as_half(peer16[i]))) + shared[i] * sigm(sg[t]);
3357}
3358__global__ void peer_gather_add_kernel(float* __restrict__ sum, const float* __restrict__ rows, int64_t r0,
3359                                       const float* __restrict__ wk, const int32_t* __restrict__ pair,
3360                                       const int32_t* __restrict__ tok, const int32_t* __restrict__ start,
3361                                       const int32_t* __restrict__ list) {
3362    const int64_t d = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
3363    if (d >= N) return;
3364    const int b = blockIdx.y;
3365    float* o = sum + (int64_t) tok[b] * N + d;
3366    float s = *o;
3367    for (int i = start[b]; i < start[b + 1]; ++i) {
3368        const int r = list[i];
3369        s = fmaf(wk[pair[r]], rows[(r - r0) * N + d], s);
3370    }
3371    *o = s;
3372}
3373__global__ void sums_to_f16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, int64_t n) {
3374    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
3375    if (i < n) y[i] = hf_sat(x[i]);
3376}
3377__global__ void f16_to_f32_wide_kernel(float4* __restrict__ dst, const uint4* __restrict__ src, int64_t n8) {
3378    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;   // eight values
3379    if (i >= n8) return;
3380    const uint4 v = src[i];
3381    const __half2* h = reinterpret_cast<const __half2*>(&v);
3382    const float2 a = __half22float2(h[0]), b = __half22float2(h[1]), c = __half22float2(h[2]), e = __half22float2(h[3]);
3383    dst[2 * i] = make_float4(a.x, a.y, b.x, b.y);
3384    dst[2 * i + 1] = make_float4(c.x, c.y, e.x, e.y);
3385}
3386}  // namespace
3387void moe_combine_peer16(const float* Dm, const int32_t* slot, const float* w, const float* shared, const float* sg,
3388                        const uint16_t* peer16, int64_t rows_local, float* bo, int64_t T, void* stream) {
3389    moe_combine_peer16_kernel<<<blocks_for(T * N), 256, 0, (cudaStream_t) stream>>>(Dm, slot, w, shared, sg, peer16,
3390                                                                                      rows_local, bo, T);
3391    check("moe_combine_peer16");
3392}
3393void peer_gather_add(float* sum, const float* rows, int64_t r0, const float* wk, const int32_t* pair, const int32_t* tok,
3394                     const int32_t* start, const int32_t* list, int64_t n_tok, void* stream) {
3395    if (n_tok <= 0) return;
3396    peer_gather_add_kernel<<<dim3((unsigned) ((N + 255) / 256), (unsigned) n_tok), 256, 0, (cudaStream_t) stream>>>(
3397        sum, rows, r0, wk, pair, tok, start, list);
3398    check("peer_gather_add");
3399}
3400void sums_to_f16(const float* x, uint16_t* y, int64_t n, void* stream) {
3401    if (n <= 0) return;
3402    sums_to_f16_kernel<<<blocks_for(n), 256, 0, (cudaStream_t) stream>>>(x, y, n);
3403    check("sums_to_f16");
3404}
3405void f16_to_f32_wide(float* dst, const uint16_t* src, int64_t n, void* stream) {
3406    if (n <= 0) return;
3407    f16_to_f32_wide_kernel<<<blocks_for(n / 8), 256, 0, (cudaStream_t) stream>>>(reinterpret_cast<float4*>(dst),
3408                                                                                    reinterpret_cast<const uint4*>(src), n / 8);
3409    check("f16_to_f32_wide");
3410}
3411void moe_combine_peer(const float* Dm, const int32_t* slot, const float* w, const float* shared, const float* sg,
3412                      const float* peer, int64_t rows_local, float* bo, int64_t T, void* stream) {
3413    moe_combine_peer_kernel<<<blocks_for(T * N), 256, 0, (cudaStream_t) stream>>>(Dm, slot, w, shared, sg, peer, rows_local,
3414                                                                                    bo, T);
3415    check("moe_combine_peer");
3416}
3417void peer_scatter_add(float* sum, const float* rows, const float* wk, const int32_t* pair, int64_t n, void* stream) {
3418    if (n <= 0) return;
3419    peer_scatter_add_kernel<<<blocks_for(n * N), 256, 0, (cudaStream_t) stream>>>(sum, rows, wk, pair, n);
3420    check("peer_scatter_add");
3421}
3422void moe_combine(const float* Dm, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo,
3423                 int64_t T, void* stream, const float* row_sd) {
3424#ifndef STRATA_W_NO_COMB
3425    if (((reinterpret_cast<uintptr_t>(Dm) | reinterpret_cast<uintptr_t>(shared) | reinterpret_cast<uintptr_t>(bo)) & 15) == 0) {
3426        moe_combine4_kernel<<<blocks_for(T * (N / 4)), 256, 0, (cudaStream_t) stream>>>(
3427            Dm, slot, w, reinterpret_cast<const float4*>(shared), sg, reinterpret_cast<float4*>(bo), T, row_sd);
3428        check("moe_combine");
3429        return;
3430    }
3431#endif
3432    moe_combine_kernel<<<blocks_for(T * N), 256, 0, (cudaStream_t) stream>>>(Dm, slot, w, shared, sg, bo, T, row_sd);
3433    check("moe_combine");
3434}
3435void moe_combine16(const uint16_t* Dm16, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo, int64_t T,
3436                   void* stream) {
3437    if (T <= 0) return;
3438    moe_combine16_kernel<<<blocks_for(T * (N / 4)), 256, 0, (cudaStream_t) stream>>>(
3439        Dm16, slot, w, reinterpret_cast<const float4*>(shared), sg, reinterpret_cast<float4*>(bo), T);
3440    check("moe_combine16");
3441}
3442void moe_shared_init(const float* shared, const float* sg, float* acc, int64_t T, void* stream) {
3443    if (T <= 0) return;
3444    moe_shared_init_kernel<<<blocks_for(T * N), 256, 0, (cudaStream_t) stream>>>(shared, sg, acc, T);
3445    check("moe_shared_init");
3446}
3447void moe_scatter_add(const float* Dm, const int32_t* u_tok, const int32_t* u_off, const int32_t* u_rows,
3448                     const float* u_w, int64_t n_u, float* acc, void* stream) {
3449    if (n_u <= 0) return;
3450    const dim3 grid((unsigned) n_u, (unsigned) ((N + 255) / 256));
3451    moe_scatter_add_kernel<<<grid, 256, 0, (cudaStream_t) stream>>>(Dm, u_tok, u_off, u_rows, u_w, acc);
3452    check("moe_scatter_add");
3453}
3454void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld, float eps, void* stream) {
3455    if (rows <= 0) return;
3456    rms_rows_kernel<<<(unsigned) rows, 256, 0, (cudaStream_t) stream>>>(x, w, cols, ld, eps);
3457    check("rms_rows");
3458}
3459void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t pos0,
3460          const strata::kernels::RopeScaling& scaling, void* stream) {
3461    // The engine validates the resolved config at startup with the same rule (generate.cpp), so this only
3462    // fires for a caller that bypassed it; the prompt path has no error return here, so it stops the process.
3463    if (const char* why = strata::kernels::rope_scaling_invalid(scaling)) {
3464        std::fprintf(stderr, "prefill rope: invalid rope scaling: %s\n", why);
3465        std::exit(1);
3466    }
3467    const float theta_scale = powf((float) scaling.freq_base, -2.0f / 64.0f);
3468    const strata::kernels::RopeKernelArgs k = scaling.kernel_args(64);   // none: the identity constants
3469    const strata::kernels::RopeTab rt = strata::kernels::rope_table_for(scaling);
3470    if (rt.cos != nullptr)
3471        rope_kernel<true><<<(unsigned) (T * heads), 32, 0, (cudaStream_t) stream>>>(
3472            x, heads, dim, ld, pos0, theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor,
3473            strata::kernels::mrope_table(), rt);
3474    else
3475        rope_kernel<false><<<(unsigned) (T * heads), 32, 0, (cudaStream_t) stream>>>(
3476            x, heads, dim, ld, pos0, theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor,
3477            strata::kernels::mrope_table(), rt);
3478    check("rope");
3479}
3480void rms_rope_rows(const float* in, int64_t in_ts, int64_t in_hs, float* out, int64_t out_ts, const float* w, int64_t T,
3481                   int64_t heads, int64_t dim, float eps, int64_t pos0, const strata::kernels::RopeScaling& scaling,
3482                   void* stream) {
3483    if (T <= 0) return;
3484    if (dim < 64 || dim > 256) {
3485        std::fprintf(stderr, "prefill rms_rope_rows: dim %lld is outside 64..256\n", (long long) dim);
3486        std::exit(1);
3487    }
3488    if (const char* why = strata::kernels::rope_scaling_invalid(scaling)) {
3489        std::fprintf(stderr, "prefill rope: invalid rope scaling: %s\n", why);
3490        std::exit(1);
3491    }
3492    const float theta_scale = powf((float) scaling.freq_base, -2.0f / 64.0f);
3493    const strata::kernels::RopeKernelArgs k = scaling.kernel_args(64);
3494    const strata::kernels::RopeTab rt = strata::kernels::rope_table_for(scaling);
3495    if (rt.cos != nullptr)
3496        rms_rope_rows_kernel<true><<<(unsigned) (T * heads), 256, 0, (cudaStream_t) stream>>>(
3497            in, in_ts, in_hs, out, out_ts, w, heads, dim, eps, pos0, theta_scale, k.freq_scale, k.corr_low, k.corr_high,
3498            k.ext_factor, k.attn_factor, strata::kernels::mrope_table(), rt);
3499    else
3500        rms_rope_rows_kernel<false><<<(unsigned) (T * heads), 256, 0, (cudaStream_t) stream>>>(
3501            in, in_ts, in_hs, out, out_ts, w, heads, dim, eps, pos0, theta_scale, k.freq_scale, k.corr_low, k.corr_high,
3502            k.ext_factor, k.attn_factor, strata::kernels::mrope_table(), rt);
3503    check("rms_rope_rows");
3504}
3505void split_q(const float* q_full, float* q, int64_t T, void* stream) {
3506    split_q_kernel<<<blocks_for(T * 24 * 256), 256, 0, (cudaStream_t) stream>>>(q_full, q, T);
3507    check("split_q");
3508}
3509void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream, int64_t ld16) {
3510    gate_attn_kernel<<<blocks_for(T * 24 * 256), 256, 0, (cudaStream_t) stream>>>(attn, q_full, out16, T,
3511                                                                                ld16 > 0 ? ld16 : 24 * 256);
3512    check("gate_attn");
3513}
3514
3515}  // namespace strata::prefill