okami.mom/strata

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

Niko1221Merge f-027-gh-eng: GitHub engine items for 0.2.76ca60e9a0

main
93.6 KiB1756 linesraw
1// src/prefill/gdn_rec_parity.cu - the prompt path's DeltaNet recurrence, bit for bit and timed.
2//
3// src/prefill/kernels.cu runs gdn_rec_kh_kernel (the three value heads that share a key head in one thread, the
4// inputs staged in blocks of 8 tokens) on CUDA sm_80+ cards that hold all 64 of its blocks at once, and
5// gdn_rec_cols_pipe_kernel elsewhere and with STRATA_GDN_KEYHEAD=0.  Both are copied below verbatim, with the output
6// norm (gdn_out_norm_kernel) and the norm as it was before, which also stored the normalized value in FP32 although
7// nothing reads it.  The two recurrences do the same arithmetic in the same order per value head and column, so the
8// output, the state after it and the FP16 output must be the same bits.  STRATA_GDN_CHUNKED=1's recurrence in chunks
9// (copied below too) sums in another order: it must stay within 1e-4 of gdn_rec_kh_kernel (largest |difference| over
10// largest |value|, the output and the state), also at T = 8192 and 32768; up to 8192 both are also measured against
11// the recurrence in FP64.  STRATA_GDN_TC=1's tensor-core scan (gdn_tc.cuh, included below) is held to the same 1e-4,
12// also on stress inputs (the state 100x smaller, 50x larger or zero, v 50x larger, slow gates, coherent keys).
13//
14// Synthetic inputs of the model's shape (q/k L2-normalized per key head as gdn_l2_kernel leaves them), no model.
15//   gdn_rec_parity            the bit checks (T from 1 to 4099, a non-zero state as after an earlier chunk)
16//   gdn_rec_parity --long     and the tensor-core scan at T = 51820 (needs ~7 GB)
17//   gdn_rec_parity --selftest-frag   the tensor-core scan's fragment helpers alone, one warp each, against FP64
18//   gdn_rec_parity --bench-tc the tensor-core series alone (gdn_rec_kh_kernel and the scan alternating, nothing else:
19//                             for A / B runs of two builds back to back)
20//   gdn_rec_parity --bench    and the timings at T = 2048, 8192 and 32768 (one layer, all 48 value heads); the two
21//                             variants' launches alternate, since a card under load steps its clock down after a
22//                             fraction of a second (see native_grouped_parity); then both at 1 to 6 blocks per
23//                             SM, as on cards with more or fewer SMs (scale), and both with the engine's grids on
24//                             32 to all of this card's SMs, the others held by a sleeping kernel (fewer_sms)
25#include <cuda_fp16.h>
26#include <cuda_runtime.h>
27
28#include <algorithm>
29#include <cmath>
30#include <cstdint>
31#include <cstdio>
32#include <cstdlib>
33#include <cstring>
34#include <map>
35#include <vector>
36
37namespace {
38
39constexpr int S = 128, HK = 16, HV = 48, C = 10240;   // as kernels.cu: head size, key heads, value heads, q|k|v width
40constexpr int RG = 4, RPG = S / RG;
41constexpr int CB = 32, NCB = S / CB;
42
43void ck(cudaError_t e, const char* what) {
44    if (e != cudaSuccess) {
45        std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
46        std::exit(2);
47    }
48}
49
50__device__ __forceinline__ float warp_sum(float v) {
51#pragma unroll
52    for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
53    return v;
54}
55__device__ __forceinline__ float sigm(float x) { return 1.0f / (1.0f + __expf(-x)); }
56__device__ __forceinline__ uint16_t hf(float f) { return __half_as_ushort(__float2half_rn(f)); }
57
58// ------------------------------------------------------------------ the engine's kernels (src/prefill/kernels.cu)
59// gdn_rec_cols_kernel with the next token's inputs (q/k rows, v, gate, beta) loaded into registers while this token
60// computes (software pipelining).  The same arithmetic in the same order: the same bits, and the same CB-column split.
61// STRATA_GDN_PIPELINE=0: gdn_rec_cols_kernel.
62__global__ void __launch_bounds__(CB * RG) gdn_rec_cols_pipe_kernel(float* __restrict__ state, const float* __restrict__ h,
63                                                                      const float* __restrict__ gate,
64                                                                      const float* __restrict__ beta,
65                                                                      float* __restrict__ oc_out, int64_t T) {
66    constexpr int NT = CB * RG, LPT = S / NT;   // threads, q/k rows loaded per thread
67    __shared__ float sk[S], sq[S], red[RG][CB];
68    const int head = blockIdx.x / NCB, cb = blockIdx.x % NCB;
69    const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c;
70    const int qh = head % HK;
71    float s[RPG];
72    float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col;
73    const size_t rs = (size_t) HV * S;
74#pragma unroll
75    for (int r = 0; r < RPG; ++r) s[r] = base[r * rs];
76    float nq[LPT], nk[LPT], nv = 0.0f, ng = 0.0f, nb = 0.0f;
77    auto fetch = [&](int64_t t) {
78        const float* ht = h + t * C;
79#pragma unroll
80        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]; }
81        nv = ht[2 * HK * S + head * S + col];
82        ng = gate[t * HV + head];
83        nb = beta[t * HV + head];
84    };
85    if (T > 0) fetch(0);
86    for (int64_t t = 0; t < T; ++t) {
87        float cq[LPT], ck[LPT];
88#pragma unroll
89        for (int u = 0; u < LPT; ++u) { cq[u] = nq[u]; ck[u] = nk[u]; }
90        const float cv = nv, cg = ng, cbt = nb;
91        __syncthreads();
92#pragma unroll
93        for (int u = 0; u < LPT; ++u) { sq[tid + u * NT] = cq[u]; sk[tid + u * NT] = ck[u]; }
94        __syncthreads();
95        if (t + 1 < T) fetch(t + 1);
96        const float g = __expf(cg);
97        float kv = 0.0f;
98#pragma unroll
99        for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv);
100        red[rg][c] = kv;
101        __syncthreads();
102        const float kv_col = red[0][c] + red[1][c] + red[2][c] + red[3][c];
103        const float delta = (cv - g * kv_col) * cbt;
104        float o = 0.0f;
105#pragma unroll
106        for (int r = 0; r < RPG; ++r) {
107            s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta);
108            o = fmaf(s[r], sq[rg * RPG + r], o);
109        }
110        __syncthreads();
111        red[rg][c] = o;
112        __syncthreads();
113        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);
114    }
115#pragma unroll
116    for (int r = 0; r < RPG; ++r) base[r * rs] = s[r];
117}
118// The recurrence with one thread for the three value heads that share a key head (head % HK): column c of heads
119// qh, qh + 16 and qh + 32, row group rg.  gdn_rec_cols_pipe_kernel spends its time in shared memory, not in
120// arithmetic: every thread of a warp needs the same 32 q and k values per token (the k twice), and a warp receives one
121// such broadcast value per clock however wide the load.  Here every q/k value a thread loads feeds three heads, and a
122// token's k row goes into registers once for both of its uses.  The inputs come in blocks of GDN_TB tokens, copied to
123// shared memory by cp.async while the block before computes (one token ahead is shorter than a load from L2 takes),
124// and the two cross-row-group sums have their own arrays, so a token needs 2 __syncthreads instead of 5: the second
125// 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
126// before the writes after it.  64 blocks instead of 192.  Per value head and column the same arithmetic in the same
127// order: the same bits (src/prefill/gdn_rec_parity.cu checks them and times the variants: 1.41x on a 4080 Super).
128// sm_80+ (gdn_keyhead_ok); STRATA_GDN_KEYHEAD=0: gdn_rec_cols_pipe_kernel.
129#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
130#define STRATA_GDN_CP_ASYNC 0   // Turing builds: plain copies (never launched there, see gdn_keyhead_ok)
131#else
132#define STRATA_GDN_CP_ASYNC 1
133#endif
134__device__ __forceinline__ void gdn_cp4(float* smem, const float* gmem) {
135#if STRATA_GDN_CP_ASYNC
136    asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem));
137#else
138    *smem = *gmem;
139#endif
140}
141__device__ __forceinline__ void gdn_cp16(float* smem, const float* gmem) {
142#if STRATA_GDN_CP_ASYNC
143    asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem));
144#else
145    *reinterpret_cast<float4*>(smem) = *reinterpret_cast<const float4*>(gmem);
146#endif
147}
148__device__ __forceinline__ void gdn_cp_commit() {
149#if STRATA_GDN_CP_ASYNC
150    asm volatile("cp.async.commit_group;\n" ::);
151#endif
152}
153__device__ __forceinline__ void gdn_cp_wait_prev() {   // every group but the newest has landed
154#if STRATA_GDN_CP_ASYNC
155    asm volatile("cp.async.wait_group 1;\n" ::);
156#endif
157}
158constexpr int GDN_TB = 8, VPK = HV / HK;   // tokens per staged block, value heads per key head
159__global__ void __launch_bounds__(CB * RG) gdn_rec_kh_kernel(float* __restrict__ state, const float* __restrict__ h,
160                                                               const float* __restrict__ gate,
161                                                               const float* __restrict__ beta,
162                                                               float* __restrict__ oc_out, int64_t T) {
163    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
164    __shared__ __align__(16) float sq[2][TB][S];
165    __shared__ __align__(16) float sk[2][TB][S];
166    __shared__ __align__(16) float sv[2][TB][VPK][CB];
167    __shared__ float sg[2][TB][VPK], sb[2][TB][VPK], rkv[VPK][RG][CB], ro[VPK][RG][CB];
168    const int qh = blockIdx.x / NCB, cb = blockIdx.x % NCB;
169    const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c;
170    float s[VPK][RPG];
171    const size_t rs = (size_t) HV * S;
172#pragma unroll
173    for (int j = 0; j < VPK; ++j) {
174        const float* base = state + ((size_t) (rg * RPG) * HV + qh + j * HK) * S + col;
175#pragma unroll
176        for (int r = 0; r < RPG; ++r) s[j][r] = base[r * rs];
177    }
178    const int64_t nblk = (T + TB - 1) / TB;
179    auto stage = [&](int64_t k) {   // tokens [k * TB, k * TB + TB) into buffer k & 1
180        const int bb = (int) (k & 1);
181        const int64_t t0 = k * TB;
182        for (int p = tid; p < TB * 2 * QKP; p += NT) {
183            const int i = p / (2 * QKP), w = p % (2 * QKP), isk = w / QKP, jj = (w % QKP) * 4;
184            if (t0 + i < T)
185                gdn_cp16(isk ? &sk[bb][i][jj] : &sq[bb][i][jj], h + (t0 + i) * C + (isk ? HK * S : 0) + qh * S + jj);
186        }
187        for (int p = tid; p < TB * VPK * VP; p += NT) {
188            const int i = p / (VPK * VP), w = p % (VPK * VP), j = w / VP, jj = (w % VP) * 4;
189            if (t0 + i < T)
190                gdn_cp16(&sv[bb][i][j][jj], h + (t0 + i) * C + 2 * HK * S + (qh + j * HK) * S + cb * CB + jj);
191        }
192        for (int p = tid; p < 2 * TB * VPK; p += NT) {
193            const int isb = p / (TB * VPK), w = p % (TB * VPK), i = w / VPK, j = w % VPK;
194            if (t0 + i < T)
195                gdn_cp4(isb ? &sb[bb][i][j] : &sg[bb][i][j], (isb ? beta : gate) + (t0 + i) * HV + qh + j * HK);
196        }
197    };
198    if (nblk > 0) stage(0);
199    gdn_cp_commit();
200    for (int64_t k = 0; k < nblk; ++k) {
201        // buffer (k + 1) & 1 was read by block k - 1, whose last token's second __syncthreads every thread has passed
202        if (k + 1 < nblk) stage(k + 1);
203        gdn_cp_commit();
204        gdn_cp_wait_prev();
205        __syncthreads();
206        const int bb = (int) (k & 1);
207        const int n = (int) ((T - k * TB) < TB ? (T - k * TB) : TB);
208        for (int i = 0; i < n; ++i) {
209            const int64_t t = k * TB + i;
210            float kc[RPG];
211#pragma unroll
212            for (int r = 0; r < RPG; ++r) kc[r] = sk[bb][i][rg * RPG + r];
213            float g[VPK], kv[VPK], delta[VPK], o[VPK];
214#pragma unroll
215            for (int j = 0; j < VPK; ++j) { g[j] = __expf(sg[bb][i][j]); kv[j] = 0.0f; o[j] = 0.0f; }
216#pragma unroll
217            for (int r = 0; r < RPG; ++r)
218#pragma unroll
219                for (int j = 0; j < VPK; ++j) kv[j] = fmaf(s[j][r], kc[r], kv[j]);
220#pragma unroll
221            for (int j = 0; j < VPK; ++j) rkv[j][rg][c] = kv[j];
222            __syncthreads();
223#pragma unroll
224            for (int j = 0; j < VPK; ++j) {
225                const float kv_col = rkv[j][0][c] + rkv[j][1][c] + rkv[j][2][c] + rkv[j][3][c];
226                delta[j] = (sv[bb][i][j][c] - g[j] * kv_col) * sb[bb][i][j];
227            }
228#pragma unroll
229            for (int r = 0; r < RPG; ++r) {
230                const float qr = sq[bb][i][rg * RPG + r];
231#pragma unroll
232                for (int j = 0; j < VPK; ++j) {
233                    s[j][r] = fmaf(g[j], s[j][r], kc[r] * delta[j]);
234                    o[j] = fmaf(s[j][r], qr, o[j]);
235                }
236            }
237#pragma unroll
238            for (int j = 0; j < VPK; ++j) ro[j][rg][c] = o[j];
239            __syncthreads();
240            if (rg < VPK)   // row group j writes head j's output
241                oc_out[t * HV * S + (qh + rg * HK) * S + col] =
242                    (ro[rg][0][c] + ro[rg][1][c] + ro[rg][2][c] + ro[rg][3][c]) * rsqrtf((float) S);
243        }
244    }
245#pragma unroll
246    for (int j = 0; j < VPK; ++j) {
247        float* base = state + ((size_t) (rg * RPG) * HV + qh + j * HK) * S + col;
248#pragma unroll
249        for (int r = 0; r < RPG; ++r) base[r * rs] = s[j][r];
250    }
251}
252
253// src/prefill/kernels.cu's chunked recurrence (STRATA_GDN_CHUNKED=1), copied as it is there
254// STRATA_GDN_CHUNKED=1 (opt-in): the recurrence in chunks of GCH tokens (the WY form of the gated delta rule, as
255// flash-linear-attention computes it), all in FP32.  Per value head, with g_t = exp(gate_t), gamma_t the gate's sum
256// from the chunk's start to t (inclusive) and S0 the state before the chunk:
257//   A[t][i] = beta_t exp(gamma_t - gamma_i) k_t.k_i (i < t),   T = (I + A)^-1 (unit lower triangular),
258//   Y_t = beta_t (v_t - exp(gamma_t) S0^T k_t),   D = T Y (the delta rule's corrections, one per token),
259//   o_t = exp(gamma_t) S0^T q_t + sum_{i <= t} exp(gamma_t - gamma_i) (q_t.k_i) D_i,
260//   S = exp(gamma_last) S0 + sum_t exp(gamma_last - gamma_t) k_t D_t^T,
261// the same state and outputs as the token-by-token kernels up to FP32 rounding (another order of the sums).
262// 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
263// super-block at once (a block per chunk and key head: its three value heads share k and q); gdn_chunk_scan_kernel then
264// walks the super-block's chunks per (value head, 16 columns): the state slice in registers, the products as small
265// register-tiled matmuls from shared memory.  Every exponent is <= 0 (gates are negative), so nothing overflows.
266constexpr int GCH = 32;            // tokens per chunk (the prep's solve is a lane per token)
267constexpr int GSB = 2048;          // tokens per super-block: the prep's scratch is GSB / GCH chunks of T, P and gamma
268constexpr int GDV = 16;            // value columns per scan block
269constexpr int GKP = S + 4;         // the scan's padded q / k rows (8 rows of a warp land on 8 banks)
270constexpr int GTP = GCH + 1;       // padded T / P rows
271static_assert(GCH == 32, "gdn_chunk_prep_kernel: a lane per token of the chunk");
272constexpr size_t kChunkPrepSmem = sizeof(float) * (2 * GCH * (S + 1) + 2 * GCH * GTP);   // A over k / q
273static_assert(VPK * GCH * GTP <= 2 * GCH * (S + 1), "gdn_chunk_prep_kernel: A fits where k and q were");
274constexpr size_t kChunkScanSmem = sizeof(float) * (3 * GCH * GKP + VPK * (S * GDV + 3 * GCH * GDV));
275
276__global__ void __launch_bounds__(256) gdn_chunk_prep_kernel(const float* __restrict__ h, const float* __restrict__ gate,
277                                                             const float* __restrict__ beta, float* __restrict__ tm,
278                                                             float* __restrict__ pm, float* __restrict__ gm, int64_t t0,
279                                                             int64_t T) {
280    extern __shared__ __align__(16) float gsm[];
281    float* sk = gsm;                       // [GCH][S + 1]
282    float* sq = sk + GCH * (S + 1);        // [GCH][S + 1]
283    float* skk = sq + GCH * (S + 1);       // [GCH][GTP]  k_t.k_i
284    float* sqk = skk + GCH * GTP;          // [GCH][GTP]  q_t.k_i
285    float* sa = gsm;                       // [VPK][GCH][GTP]  A, then T below the diagonal (over k and q:
286                                           // read by then, so two blocks share an SM)
287    const int qh = blockIdx.y, ch = blockIdx.x, tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
288    const int64_t tb = t0 + (int64_t) ch * GCH;
289    const int n = (int) min((int64_t) GCH, T - tb);
290    {   // k and q as float4, every load issued before the first store
291        constexpr int NP = GCH * S / 4 / 256;   // float4 a thread, each of k and q
292        float4 kv[NP], qv[NP];
293#pragma unroll
294        for (int m = 0; m < NP; ++m) {
295            const int p = tid + 256 * m, t = p / (S / 4), r = (p % (S / 4)) * 4;
296            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);
297            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);
298        }
299#pragma unroll
300        for (int m = 0; m < NP; ++m) {
301            const int p = tid + 256 * m, t = p / (S / 4), r = (p % (S / 4)) * 4;
302            float* dk = sk + t * (S + 1) + r;
303            float* dq = sq + t * (S + 1) + r;
304            dk[0] = kv[m].x; dk[1] = kv[m].y; dk[2] = kv[m].z; dk[3] = kv[m].w;
305            dq[0] = qv[m].x; dq[1] = qv[m].y; dq[2] = qv[m].z; dq[3] = qv[m].w;
306        }
307    }
308    __syncthreads();
309    {   // lane i, rows warp + 8m: k_t.k_i and q_t.k_i on eight independent sums (rows 129 apart: 32 banks)
310        constexpr int RW = GCH / 8;
311        float kk[RW] = {}, qk[RW] = {};
312        for (int r = 0; r < S; ++r) {
313            const float ki = sk[lane * (S + 1) + r];
314#pragma unroll
315            for (int m = 0; m < RW; ++m) {
316                kk[m] = fmaf(sk[(warp + 8 * m) * (S + 1) + r], ki, kk[m]);
317                qk[m] = fmaf(sq[(warp + 8 * m) * (S + 1) + r], ki, qk[m]);
318            }
319        }
320#pragma unroll
321        for (int m = 0; m < RW; ++m) {
322            const int t = warp + 8 * m;
323            skk[t * GTP + lane] = lane <= t ? kk[m] : 0.0f;
324            sqk[t * GTP + lane] = lane <= t ? qk[m] : 0.0f;
325        }
326    }
327    __syncthreads();
328    if (warp >= VPK) return;
329    const int vh = qh + warp * HK, i = lane;   // warp j: value head j of the key head; lane i: token i (column i)
330    float* a = sa + warp * GCH * GTP;
331    const float b = i < n ? beta[(tb + i) * HV + vh] : 0.0f;
332    float gam = i < n ? gate[(tb + i) * HV + vh] : 0.0f;   // past the end: gate 0, beta 0 (no effect on S)
333#pragma unroll
334    for (int o = 1; o < 32; o <<= 1) {
335        const float u = __shfl_up_sync(0xffffffffu, gam, o);
336        if (lane >= o) gam += u;
337    }
338    for (int t = 0; t < GCH; ++t) {
339        const float gt = __shfl_sync(0xffffffffu, gam, t), bt = __shfl_sync(0xffffffffu, b, t);
340        a[t * GTP + i] = i < t ? bt * expf(gt - gam) * skk[t * GTP + i] : (i == t ? 1.0f : 0.0f);
341    }
342    __syncwarp();
343    // 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
344    // finished rows (diagonal 1, zeros above it: the terms k < i add an exact 0, so the same bits as summing from k = i)
345    // - a trip the whole warp shares, so the loads go ahead of the sums
346    for (int t = 1; t < GCH; ++t) {
347        float v = 0.0f;
348#pragma unroll 8
349        for (int k = 0; k < t; ++k) v = fmaf(-a[t * GTP + k], a[k * GTP + i], v);
350        __syncwarp();
351        if (i < t) a[t * GTP + i] = v;
352        __syncwarp();
353    }
354    float* T_ = tm + ((int64_t) ch * HV + vh) * GCH * GCH;
355    float* P_ = pm + ((int64_t) ch * HV + vh) * GCH * GCH;
356    for (int t = 0; t < GCH; ++t) {
357        const float gt = __shfl_sync(0xffffffffu, gam, t);
358        T_[t * GCH + i] = a[t * GTP + i];
359        P_[t * GCH + i] = i <= t ? expf(gt - gam) * sqk[t * GTP + i] : 0.0f;
360    }
361    gm[((int64_t) ch * HV + vh) * GCH + i] = gam;
362}
363
364__device__ __forceinline__ void gdn_pf_l2(const float* p) { asm volatile("prefetch.global.L2 [%0];" ::"l"(p)); }
365__device__ __forceinline__ void gdn_cp_wait_all() {
366#if STRATA_GDN_CP_ASYNC
367    asm volatile("cp.async.wait_all;\n" ::);
368#endif
369}
370// A block per (key head, 16 value columns): 128 threads for each of the key head's three value heads, which share the
371// staged k and q rows.  128 blocks, one an SM, in one wave (each walks every chunk: a second wave would double the
372// time).  A thread owns one token's row of the products (4 columns) and holds that token's T and P rows in registers,
373// loaded at the chunk's start so they land during the first product; the next chunk's k (a second buffer), q (after
374// this chunk's last read of q), v, gamma and beta load while this chunk computes.  Three barriers a chunk.
375__global__ void __launch_bounds__(128 * VPK) gdn_chunk_scan_kernel(float* __restrict__ state, const float* __restrict__ h,
376                                                                   const float* __restrict__ beta, const float* __restrict__ tm,
377                                                                   const float* __restrict__ pm, const float* __restrict__ gm,
378                                                                   float* __restrict__ oc_out, int64_t t0, int nch, int64_t T) {
379    extern __shared__ __align__(16) float gsm[];
380    constexpr int NT = 128 * VPK, HEAD = S * GDV + 3 * GCH * GDV;   // threads; a head's shared floats
381    float* kbuf = gsm;                     // [2][GCH][GKP]  k, double-buffered
382    float* sq = kbuf + 2 * GCH * GKP;      // [GCH][GKP]
383    const int qh = blockIdx.x, c0 = blockIdx.y * GDV, j = threadIdx.x / 128, tid = threadIdx.x % 128;
384    const int vh = qh + j * HK;
385    float* ss = sq + GCH * GKP + j * HEAD; // [S][GDV]  the state slice at the chunk's start
386    float* sy = ss + S * GDV;              // [GCH][GDV]  Y
387    float* sd = sy + GCH * GDV;            // [GCH][GDV]  D
388    float* sdd = sd + GCH * GDV;           // [GCH][GDV]  exp(gamma_last - gamma_t) D
389    const int rq = tid >> 2, vq = tid & 3;   // the update's tile: rows 4rq..4rq+3; both tiles: columns 4vq..4vq+3
390    const int tt = tid >> 2, vv = 4 * vq;    // the products' tile: token tt
391    const size_t rs = (size_t) HV * S;
392    auto stage_kq = [&](int64_t c_t0, int n, float* dst, bool isq) {   // k or q rows of a chunk, cp.async
393        for (int p = threadIdx.x; p < GCH * (S / 4); p += NT) {
394            const int t = p / (S / 4), r = (p % (S / 4)) * 4;
395            if (t < n) gdn_cp16(dst + t * GKP + r, h + (c_t0 + t) * C + (isq ? 0 : HK * S) + qh * S + r);
396            else *reinterpret_cast<float4*>(dst + t * GKP + r) = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
397        }
398    };
399    // this tile's v, gamma, beta and the chunk's last gamma (registers)
400    auto load_vgb = [&](int ch, int64_t c_t0, int n, float4& v4, float& gam, float& bet, float& glast) {
401        v4 = tt < n ? __ldg(reinterpret_cast<const float4*>(h + (c_t0 + tt) * C + 2 * HK * S + vh * S + c0 + vv))
402                    : make_float4(0.0f, 0.0f, 0.0f, 0.0f);
403        const float* g = gm + ((int64_t) ch * HV + vh) * GCH;
404        gam = __ldg(g + tt);
405        glast = __ldg(g + GCH - 1);
406        bet = tt < n ? __ldg(beta + (c_t0 + tt) * HV + vh) : 0.0f;
407    };
408    float s[4][4];
409#pragma unroll
410    for (int x = 0; x < 4; ++x) {
411#pragma unroll
412        for (int y = 0; y < 4; ++y) s[x][y] = state[(size_t) (4 * rq + x) * rs + (size_t) vh * S + c0 + vv + y];
413        *reinterpret_cast<float4*>(&ss[(4 * rq + x) * GDV + vv]) = make_float4(s[x][0], s[x][1], s[x][2], s[x][3]);
414    }
415    const float out_scale = rsqrtf((float) S);
416    float4 v4;
417    float gam, bet, glast;
418    {
419        const int n0 = (int) min((int64_t) GCH, T - t0);
420        stage_kq(t0, n0, kbuf, false);
421        stage_kq(t0, n0, sq, true);
422        gdn_cp_commit();
423        load_vgb(0, t0, n0, v4, gam, bet, glast);
424        gdn_cp_wait_all();
425        __syncthreads();
426    }
427    for (int ch = 0; ch < nch; ++ch) {
428        const int64_t c_t0 = t0 + (int64_t) ch * GCH;
429        const int n = (int) min((int64_t) GCH, T - c_t0);
430        const bool more = ch + 1 < nch;
431        const int64_t n_t0 = c_t0 + GCH;
432        const int nn = more ? (int) min((int64_t) GCH, T - n_t0) : 0;
433        const float* sk = kbuf + (ch & 1) * GCH * GKP;
434        // this token's T and P rows into registers now: they land while the first product runs
435        float tr[GCH], pr[GCH];
436        {
437            const float4* T4 = reinterpret_cast<const float4*>(tm + (((int64_t) ch * HV + vh) * GCH + tt) * GCH);
438            const float4* P4 = reinterpret_cast<const float4*>(pm + (((int64_t) ch * HV + vh) * GCH + tt) * GCH);
439#pragma unroll
440            for (int i = 0; i < GCH / 4; ++i) {
441                const float4 a = __ldg(T4 + i), b = __ldg(P4 + i);
442                tr[4 * i] = a.x; tr[4 * i + 1] = a.y; tr[4 * i + 2] = a.z; tr[4 * i + 3] = a.w;
443                pr[4 * i] = b.x; pr[4 * i + 1] = b.y; pr[4 * i + 2] = b.z; pr[4 * i + 3] = b.w;
444            }
445        }
446        float4 nv4 = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
447        float ngam = 0.0f, nbet = 0.0f, nglast = 0.0f;
448        if (more) {   // the next chunk's v, gamma and beta; the one after into L2 (its k and q: after barrier A)
449            load_vgb(ch + 1, n_t0, nn, nv4, ngam, nbet, nglast);
450            const int64_t f_t0 = n_t0 + GCH;
451            const int t = threadIdx.x >> 3, l = threadIdx.x & 7;
452            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));
453            if (tid < GCH) {
454                gdn_pf_l2(tm + (((int64_t) (ch + 1) * HV + vh) * GCH + tid) * GCH);
455                gdn_pf_l2(pm + (((int64_t) (ch + 1) * HV + vh) * GCH + tid) * GCH);
456            }
457        }
458        // X = K S0 and Q S0 for token tt, then Y = beta (V - exp(gamma) X)
459        float x[4] = {0.f, 0.f, 0.f, 0.f}, qs[4] = {0.f, 0.f, 0.f, 0.f};
460#pragma unroll 4
461        for (int r = 0; r < S; r += 4) {
462            const float4 k4 = *reinterpret_cast<const float4*>(&sk[tt * GKP + r]);
463            const float4 q4 = *reinterpret_cast<const float4*>(&sq[tt * GKP + r]);
464            const float kk[4] = {k4.x, k4.y, k4.z, k4.w}, qq[4] = {q4.x, q4.y, q4.z, q4.w};
465#pragma unroll
466            for (int jj = 0; jj < 4; ++jj) {
467                const float4 s4 = *reinterpret_cast<const float4*>(&ss[(r + jj) * GDV + vv]);
468                x[0] = fmaf(kk[jj], s4.x, x[0]); x[1] = fmaf(kk[jj], s4.y, x[1]);
469                x[2] = fmaf(kk[jj], s4.z, x[2]); x[3] = fmaf(kk[jj], s4.w, x[3]);
470                qs[0] = fmaf(qq[jj], s4.x, qs[0]); qs[1] = fmaf(qq[jj], s4.y, qs[1]);
471                qs[2] = fmaf(qq[jj], s4.z, qs[2]); qs[3] = fmaf(qq[jj], s4.w, qs[3]);
472            }
473        }
474        const float e = expf(gam);
475        *reinterpret_cast<float4*>(&sy[tt * GDV + vv]) = make_float4(bet * (v4.x - e * x[0]), bet * (v4.y - e * x[1]),
476                                                                     bet * (v4.z - e * x[2]), bet * (v4.w - e * x[3]));
477        __syncthreads();   // (A) Y complete; every read of q done
478        if (more) {        // the next chunk's k into the other buffer, its q into the single q buffer
479            stage_kq(n_t0, nn, kbuf + ((ch + 1) & 1) * GCH * GKP, false);
480            stage_kq(n_t0, nn, sq, true);
481            gdn_cp_commit();
482        }
483        // D = T Y (T is zero above its diagonal), and D decayed to the chunk's end for the update
484        float d[4] = {0.f, 0.f, 0.f, 0.f};
485#pragma unroll
486        for (int i = 0; i < GCH; ++i) {
487            const float4 y4 = *reinterpret_cast<const float4*>(&sy[i * GDV + vv]);
488            d[0] = fmaf(tr[i], y4.x, d[0]); d[1] = fmaf(tr[i], y4.y, d[1]);
489            d[2] = fmaf(tr[i], y4.z, d[2]); d[3] = fmaf(tr[i], y4.w, d[3]);
490        }
491        const float f = expf(glast - gam);
492        *reinterpret_cast<float4*>(&sd[tt * GDV + vv]) = make_float4(d[0], d[1], d[2], d[3]);
493        *reinterpret_cast<float4*>(&sdd[tt * GDV + vv]) = make_float4(f * d[0], f * d[1], f * d[2], f * d[3]);
494        __syncthreads();   // (B) D complete
495        // o = exp(gamma) Q S0 + P D (P is zero above its diagonal), the output
496        float o[4] = {e * qs[0], e * qs[1], e * qs[2], e * qs[3]};
497#pragma unroll
498        for (int i = 0; i < GCH; ++i) {
499            const float4 d4 = *reinterpret_cast<const float4*>(&sd[i * GDV + vv]);
500            o[0] = fmaf(pr[i], d4.x, o[0]); o[1] = fmaf(pr[i], d4.y, o[1]);
501            o[2] = fmaf(pr[i], d4.z, o[2]); o[3] = fmaf(pr[i], d4.w, o[3]);
502        }
503        if (tt < n)
504            *reinterpret_cast<float4*>(oc_out + (c_t0 + tt) * HV * S + vh * S + c0 + vv) =
505                make_float4(o[0] * out_scale, o[1] * out_scale, o[2] * out_scale, o[3] * out_scale);
506        // S = exp(gamma_last) S0 + K^T (decayed D)
507        const float gL = expf(glast);
508#pragma unroll
509        for (int xx = 0; xx < 4; ++xx)
510#pragma unroll
511            for (int y = 0; y < 4; ++y) s[xx][y] *= gL;
512#pragma unroll 4
513        for (int t = 0; t < GCH; ++t) {
514            const float4 k4 = *reinterpret_cast<const float4*>(&sk[t * GKP + 4 * rq]);
515            const float4 d4 = *reinterpret_cast<const float4*>(&sdd[t * GDV + vv]);
516            const float kx[4] = {k4.x, k4.y, k4.z, k4.w}, dy[4] = {d4.x, d4.y, d4.z, d4.w};
517#pragma unroll
518            for (int xx = 0; xx < 4; ++xx)
519#pragma unroll
520                for (int y = 0; y < 4; ++y) s[xx][y] = fmaf(kx[xx], dy[y], s[xx][y]);
521        }
522#pragma unroll
523        for (int xx = 0; xx < 4; ++xx)
524            *reinterpret_cast<float4*>(&ss[(4 * rq + xx) * GDV + vv]) = make_float4(s[xx][0], s[xx][1], s[xx][2], s[xx][3]);
525        v4 = nv4; gam = ngam; bet = nbet; glast = nglast;
526        gdn_cp_wait_all();
527        __syncthreads();   // (C) the new ss, the next k and q landed; every read of sd, sdd and this k buffer done
528    }
529#pragma unroll
530    for (int xx = 0; xx < 4; ++xx)
531#pragma unroll
532        for (int y = 0; y < 4; ++y) state[(size_t) (4 * rq + xx) * rs + (size_t) vh * S + c0 + vv + y] = s[xx][y];
533}
534
535// The scratch, one a device: allocated on first use at its largest (GSB / GCH chunks of T, P and gamma: 25.6 MB) and
536// kept (a device runs its prompt on one stream).  A stream-ordered allocation and free per call, even from a pool that
537// keeps its memory, cost host time the GPU waited for (a 2K prompt's recurrence took 78 ms against 34 ms for
538// gdn_rec_kh_kernel).
539float* gdn_chunk_scratch() {
540    static float* bufs[64] = {};
541    int dev = 0;
542    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return nullptr; }
543    if (bufs[dev] == nullptr) {
544        const size_t n = (size_t) (GSB / GCH) * HV * (2 * GCH * GCH + GCH);
545        if (cudaMalloc((void**) &bufs[dev], n * sizeof(float)) != cudaSuccess) {
546            cudaGetLastError();
547            bufs[dev] = nullptr;
548        }
549    }
550    return bufs[dev];
551}
552
553// The whole recurrence of T tokens in super-blocks of GSB: a prep and a scan launch each, the scratch (T, P and gamma
554// 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.
555// y: the [T][HV][S] output.  An error return means nothing was launched (the caller takes another kernel): the scratch
556// could not be had, or the card has fewer than 128 SMs (a second wave of the scan would double it) or too little
557// shared memory for it (Turing).
558cudaError_t gdn_rec_chunked(float* state, const float* h, const float* gate, const float* beta, float* y, int64_t T,
559                            cudaStream_t s) {
560    if (T <= 0) return cudaSuccess;
561    {   // sm_80+ (cp.async), the scan's 128 blocks one an SM in one wave, and its 93.7 KB of shared memory (else:
562        // another kernel)
563        int dev = 0, major = 0, sms = 0, smem = 0;
564        if (cudaGetDevice(&dev) != cudaSuccess ||
565            cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess ||
566            cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev) != cudaSuccess ||
567            cudaDeviceGetAttribute(&smem, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev) != cudaSuccess) {
568            cudaGetLastError();
569            return cudaErrorNotSupported;
570        }
571        // as in kernels.cu: STRATA_GDN_CHUNKED=2 skips the SM-count test (to measure a card under 128 SMs)
572        static const bool any_sms = [] { const char* v = std::getenv("STRATA_GDN_CHUNKED"); return v != nullptr && std::atoi(v) >= 2; }();
573        if (major < 8 || (!any_sms && sms < HK * (S / GDV)) || (size_t) smem < kChunkScanSmem)
574            return cudaErrorNotSupported;
575    }
576    float* scratch = gdn_chunk_scratch();
577    if (scratch == nullptr) return cudaErrorMemoryAllocation;
578    const int nb = (int) ((std::min<int64_t>(GSB, T) + GCH - 1) / GCH);
579    const size_t tsz = (size_t) nb * HV * GCH * GCH;
580    float *tm = scratch, *pm = tm + tsz, *gm = pm + tsz;
581    {   // once a device
582        static bool attrs[64] = {};
583        int dev = 0;
584        cudaGetDevice(&dev);
585        if (dev >= 0 && dev < 64 && !attrs[dev]) {
586            cudaFuncSetAttribute(gdn_chunk_prep_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kChunkPrepSmem);
587            cudaFuncSetAttribute(gdn_chunk_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kChunkScanSmem);
588            attrs[dev] = true;
589        }
590    }
591    for (int64_t t0 = 0; t0 < T; t0 += GSB) {
592        const int nch = (int) ((std::min<int64_t>(GSB, T - t0) + GCH - 1) / GCH);
593        gdn_chunk_prep_kernel<<<dim3((unsigned) nch, HK), 256, kChunkPrepSmem, s>>>(h, gate, beta, tm, pm, gm, t0, T);
594        gdn_chunk_scan_kernel<<<dim3(HK, S / GDV), 128 * VPK, kChunkScanSmem, s>>>(state, h, beta, tm, pm, gm, y, t0, nch, T);
595    }
596    return cudaSuccess;   // launch errors surface at the caller's check; an error above means nothing ran
597}
598// src/prefill/kernels.cu's tensor-core scan (STRATA_GDN_TC=1): the same text, included there too
599#include "gdn_tc.cuh"
600// src/prefill/kernels.cu's gdn_rec_tc, copied as it is there (with the raw device attributes, as gdn_rec_chunked above)
601cudaError_t gdn_rec_tc(float* state, const float* h, const float* gate, const float* beta, float* y, int64_t T,
602                       cudaStream_t s) {
603    if (T <= 0) return cudaSuccess;
604    {
605        int dev = 0, major = 0, sms = 0, smem = 0;
606        if (cudaGetDevice(&dev) != cudaSuccess ||
607            cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess ||
608            cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev) != cudaSuccess ||
609            cudaDeviceGetAttribute(&smem, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev) != cudaSuccess) {
610            cudaGetLastError();
611            return cudaErrorNotSupported;
612        }
613        if (major < 8 || sms < HV || (size_t) smem < kTcScanSmem<false>) return cudaErrorNotSupported;
614    }
615    const GtcScratch sc = gdn_tc_scratch();
616    if (sc.ti == nullptr) return cudaErrorMemoryAllocation;
617    {   // once a device
618        static bool attrs[64] = {};
619        int dev = 0;
620        cudaGetDevice(&dev);
621        if (dev >= 0 && dev < 64 && !attrs[dev]) {
622            cudaFuncSetAttribute(gdn_tc_scan_kernel<false>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmem<false>);
623            attrs[dev] = true;
624        }
625    }
626    for (int64_t t0 = 0; t0 < T; t0 += GSB) {
627        const int nch = (int) ((std::min<int64_t>(GSB, T - t0) + GCH - 1) / GCH);
628        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);
629        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);
630    }
631    return cudaSuccess;
632}
633// the output norm over a head's 128 columns, into the FP16 copy the out projection reads (the FP32 output before the
634// norm stays in its scratch buffer)
635__global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma,
636                                                         float eps, const float* __restrict__ y,
637                                                         uint16_t* __restrict__ y16) {
638    __shared__ float wsum[4];
639    const int64_t t = blockIdx.x;
640    const int head = blockIdx.y, col = threadIdx.x;
641    const size_t at = (size_t) t * HV * S + (size_t) head * S + col;
642    const float oc = y[at];
643    float sp = warp_sum(oc * oc);
644    if ((col & 31) == 0) wsum[col >> 5] = sp;
645    __syncthreads();
646    const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
647    const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * sigm(z[t * HV * S + head * S + col]);
648    y16[at] = hf(v);
649}
650
651// ------------------------------------------------------------------ the output norm before (0.1.31)
652__global__ void __launch_bounds__(S) gdn_out_norm_old_kernel(const float* __restrict__ z, const float* __restrict__ gamma,
653                                                             float eps, float* __restrict__ y,
654                                                             uint16_t* __restrict__ y16) {
655    __shared__ float wsum[4];
656    const int64_t t = blockIdx.x;
657    const int head = blockIdx.y, col = threadIdx.x;
658    const size_t at = (size_t) t * HV * S + (size_t) head * S + col;
659    const float oc = y[at];
660    float sp = warp_sum(oc * oc);
661    if ((col & 31) == 0) wsum[col >> 5] = sp;
662    __syncthreads();
663    const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
664    const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * sigm(z[t * HV * S + head * S + col]);
665    y[at] = v;
666    y16[at] = hf(v);
667}
668
669// ------------------------------------------------------------------ synthetic inputs
670__device__ __forceinline__ uint32_t mix(uint64_t x) {
671    x ^= x >> 33; x *= 0xff51afd7ed558ccdULL; x ^= x >> 33; x *= 0xc4ceb9fe1a85ec53ULL; x ^= x >> 33;
672    return (uint32_t) x;
673}
674__device__ __forceinline__ float uni(uint64_t key) { return ((mix(key) >> 8) + 0.5f) * (1.0f / 16777216.0f); }
675__device__ __forceinline__ float gauss(uint64_t key) {
676    const float u1 = uni(key * 2 + 1), u2 = uni(key * 2 + 2);
677    return sqrtf(-2.0f * logf(u1)) * cosf(6.2831853f * u2);
678}
679__global__ void fill_gauss(float* x, int64_t n, float scale, uint64_t seed, float offset = 0.0f) {
680    for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x)
681        x[i] = offset + scale * gauss(seed * 0x9E3779B97F4A7C15ULL + (uint64_t) i);
682}
683// the q and k rows L2-normalized per key head, as gdn_l2_kernel leaves them for the recurrence
684__global__ void l2_rows(float* h, float eps) {
685    float* x = h + (int64_t) blockIdx.y * C + (int64_t) blockIdx.x * S;
686    const float v = x[threadIdx.x];
687    __shared__ float part[4];
688    const float sq = warp_sum(v * v);
689    if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sq;
690    __syncthreads();
691    x[threadIdx.x] = v * rsqrtf(part[0] + part[1] + part[2] + part[3] + eps);
692}
693// gate = log of the decay (mostly near 1, some strong; slow: -0.001 u, so the state grows for long), beta in (0, 1)
694__global__ void fill_gates(float* gate, float* beta, int64_t n, uint64_t seed, bool slow = false) {
695    for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) {
696        const float u = uni(seed * 0x9E3779B97F4A7C15ULL + 7 * (uint64_t) i);
697        gate[i] = slow ? -0.001f * u : -0.02f - 0.8f * u * u * u;
698        beta[i] = 1.0f / (1.0f + expf(-gauss(seed * 0xD1B54A32D192ED03ULL + (uint64_t) i)));
699    }
700}
701// coherent keys: every token's k row = a key head's k_0 + 0.05 x the row that was there (before l2_rows): the
702// chunk's T = (I + A)^-1 then carries large entries, the reason the prep scales its T images by a power of two of their own
703__global__ void coherent_k(float* h, uint64_t seed) {
704    float* x = h + (int64_t) blockIdx.y * C + HK * S + (int64_t) blockIdx.x * S;
705    x[threadIdx.x] = gauss(seed * 0x9E3779B97F4A7C15ULL + (uint64_t) (blockIdx.x * S + threadIdx.x)) + 0.05f * x[threadIdx.x];
706}
707__global__ void scale_v(float* h, int64_t T, float scale) {
708    for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < T * HV * S; i += (int64_t) gridDim.x * blockDim.x)
709        h[(i / (HV * S)) * C + 2 * HK * S + i % (HV * S)] *= scale;
710}
711__global__ void count_diff(const uint32_t* a, const uint32_t* b, int64_t n, unsigned long long* out) {
712    unsigned long long d = 0;
713    for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x)
714        d += a[i] != b[i];
715    if (d) atomicAdd(out, d);
716}
717
718// ------------------------------------------------------------------ holding SMs (fewer_sms)
719__device__ __forceinline__ uint64_t gtime() {
720    uint64_t t;
721    asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t));
722    return t;
723}
724__device__ __forceinline__ int sm_id() {
725    unsigned id;
726    asm volatile("mov.u32 %0, %%smid;" : "=r"(id));
727    return (int) id;
728}
729__device__ __forceinline__ void nap(unsigned ns) {
730#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700
731    __nanosleep(ns);
732#else
733    (void) ns;
734#endif
735}
736// limits that a run that works never reaches (a launch here takes milliseconds); they keep a run that does not work
737// from waiting forever, and the host drops its time
738constexpr uint64_t kHoldLimitNs = 1000000000ull, kWaitLimitNs = 500000000ull;
739// One block per SM: it asks for all the shared memory a block may have (launched with that much dynamic shared
740// memory), so no block of another kernel fits beside it.  It notes its SM and sleeps until release says gen.
741__global__ void hold_sm(unsigned long long* sitting, const volatile unsigned* release, unsigned gen, int* where,
742                        unsigned* late) {
743    where[blockIdx.x] = sm_id();
744    __threadfence();
745    atomicAdd(sitting, 1ull);
746    const uint64_t t0 = gtime();
747    while (*release != gen) {
748        if (gtime() - t0 > kHoldLimitNs) { atomicAdd(late, 1u); return; }
749        nap(20000);
750    }
751}
752// on the timed launch's stream, before it: returns once all holding blocks so far sit on their SMs
753__global__ void wait_sitting(const volatile unsigned long long* sitting, unsigned long long all, unsigned* late) {
754    const uint64_t t0 = gtime();
755    while (*sitting < all) {
756        if (gtime() - t0 > kWaitLimitNs) { atomicAdd(late, 1u); return; }
757        nap(1000);
758    }
759}
760__global__ void release_sms(volatile unsigned* release, unsigned gen) { *release = gen; }
761// Where the blocks of a grid land: launched like the recurrence it stands for (the same grid and block size, and as
762// much dynamic shared memory as lets as many blocks share an SM), every block notes its SM and stays until all of them
763// have landed, so they all sit at once as the recurrence's blocks do for the whole chunk.
764__global__ void land(int* where, unsigned* landed, unsigned* apart) {
765    extern __shared__ unsigned char land_smem[];   // only its size matters
766    if (threadIdx.x != 0 || threadIdx.y != 0) return;
767    where[blockIdx.x] = sm_id();
768    atomicAdd(landed, 1u);
769    const uint64_t t0 = gtime();
770    while (*(volatile unsigned*) landed < gridDim.x) {
771        if (gtime() - t0 > kWaitLimitNs) { atomicAdd(apart, 1u); return; }   // they did not all fit at once
772        nap(1000);
773    }
774    (void) land_smem;
775}
776
777template <typename T> T* dalloc(size_t n) {
778    T* p = nullptr;
779    ck(cudaMalloc((void**) &p, n * sizeof(T) + 16), "cudaMalloc");
780    return p;
781}
782unsigned long long diff_words(const void* a, const void* b, size_t bytes) {
783    static unsigned long long* d = dalloc<unsigned long long>(1);
784    ck(cudaMemset(d, 0, sizeof(*d)), "memset");
785    count_diff<<<1024, 256>>>((const uint32_t*) a, (const uint32_t*) b, (int64_t) (bytes / 4), d);
786    unsigned long long h = 0;
787    ck(cudaMemcpy(&h, d, sizeof(h), cudaMemcpyDeviceToHost), "diff");
788    return h;
789}
790
791// The model's shapes with gaussian values; the defaults are the bit checks' inputs (the state as after an earlier
792// chunk, scale 0.05).  The others stress the tensor-core scan's f16 range handling: the state 100x smaller, 50x larger
793// or zero (a fresh conversation), v 50x larger, slow gates, coherent keys.
794struct Inputs {
795    int64_t T = 0;
796    float *h = nullptr, *gate = nullptr, *beta = nullptr, *z = nullptr, *gamma = nullptr, *state0 = nullptr;
797    explicit Inputs(int64_t t, uint64_t seed, float state_scale = 0.05f, float v_scale = 1.0f, bool slow_gates = false,
798                    bool coherent_keys = false)
799        : T(t) {
800        h = dalloc<float>((size_t) T * C);
801        gate = dalloc<float>((size_t) T * HV);
802        beta = dalloc<float>((size_t) T * HV);
803        z = dalloc<float>((size_t) T * HV * S);
804        gamma = dalloc<float>(S);
805        state0 = dalloc<float>((size_t) S * HV * S);
806        fill_gauss<<<4096, 256>>>(h, T * C, 1.0f, seed);
807        if (coherent_keys) coherent_k<<<dim3(HK, (unsigned) T), S>>>(h, seed + 5);
808        l2_rows<<<dim3(2 * HK, (unsigned) T), S>>>(h, 1e-6f);
809        if (v_scale != 1.0f) scale_v<<<4096, 256>>>(h, T, v_scale);
810        fill_gates<<<1024, 256>>>(gate, beta, T * HV, seed + 1, slow_gates);
811        fill_gauss<<<4096, 256>>>(z, T * HV * S, 1.0f, seed + 2);
812        fill_gauss<<<1, 128>>>(gamma, S, 0.1f, seed + 3, 1.0f);
813        fill_gauss<<<1024, 256>>>(state0, (int64_t) S * HV * S, state_scale, seed + 4);
814        ck(cudaDeviceSynchronize(), "inputs");
815    }
816    Inputs(const Inputs&) = delete;
817    Inputs& operator=(const Inputs&) = delete;
818    ~Inputs() { cudaFree(h); cudaFree(gate); cudaFree(beta); cudaFree(z); cudaFree(gamma); cudaFree(state0); }
819};
820
821enum Rec { kBefore, kKeyHead, kRecCount };
822void run_rec(Rec v, float* state, const Inputs& in, float* oc, cudaStream_t s = 0) {
823    if (v == kBefore)
824        gdn_rec_cols_pipe_kernel<<<HV * NCB, dim3(CB, RG), 0, s>>>(state, in.h, in.gate, in.beta, oc, in.T);
825    else
826        gdn_rec_kh_kernel<<<HK * NCB, dim3(CB, RG), 0, s>>>(state, in.h, in.gate, in.beta, oc, in.T);
827}
828
829int check_bits(int64_t T, uint64_t seed) {
830    Inputs in(T, seed);
831    const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S;
832    float* state[kRecCount];
833    float* oc[kRecCount];
834    for (int v = 0; v < kRecCount; ++v) {
835        state[v] = dalloc<float>(st);
836        oc[v] = dalloc<float>(oc_n);
837        ck(cudaMemcpy(state[v], in.state0, st * 4, cudaMemcpyDeviceToDevice), "state copy");
838        run_rec((Rec) v, state[v], in, oc[v]);
839    }
840    ck(cudaDeviceSynchronize(), "recurrence");
841    int fails = 0;
842    const unsigned long long d_oc = diff_words(oc[kBefore], oc[kKeyHead], oc_n * 4),
843                             d_st = diff_words(state[kBefore], state[kKeyHead], st * 4);
844    if (d_oc || d_st) {
845        std::printf("FAIL T=%lld recurrence: %llu of %zu outputs and %llu of %zu state values differ\n", (long long) T,
846                    d_oc, oc_n, d_st, st);
847        ++fails;
848    }
849    // the output norm: before (in place, with the FP32 store) against now (the FP16 store only), on the same output
850    uint16_t* y16a = dalloc<uint16_t>(oc_n);
851    uint16_t* y16b = dalloc<uint16_t>(oc_n);
852    float* yb = dalloc<float>(oc_n);
853    ck(cudaMemcpy(yb, oc[kBefore], oc_n * 4, cudaMemcpyDeviceToDevice), "y copy");
854    gdn_out_norm_kernel<<<dim3((unsigned) T, HV), S>>>(in.z, in.gamma, 1e-6f, yb, y16b);
855    gdn_out_norm_old_kernel<<<dim3((unsigned) T, HV), S>>>(in.z, in.gamma, 1e-6f, oc[kBefore], y16a);
856    ck(cudaDeviceSynchronize(), "norm");
857    const unsigned long long d16 = diff_words(y16a, y16b, oc_n * 2);
858    if (d16) {
859        std::printf("FAIL T=%lld output norm: %llu of %zu FP16 pairs differ\n", (long long) T, d16, oc_n / 2);
860        ++fails;
861    }
862    std::printf("T=%-6lld %s\n", (long long) T, fails ? "DIFFERENT" : "the same bits (output, state, FP16 output)");
863    for (int v = 0; v < kRecCount; ++v) { cudaFree(state[v]); cudaFree(oc[v]); }
864    cudaFree(y16a); cudaFree(y16b); cudaFree(yb);
865    return fails;
866}
867
868// The chunked recurrence against gdn_rec_kh_kernel (other bits: the largest |difference| over the largest |value|, the
869// output and the state after the chunk); a failure above 1e-4 (FP32 sums in another order stay near 1e-6).
870double max_rel(const float* a, const float* b, size_t n) {
871    std::vector<float> x(n), y(n);
872    ck(cudaMemcpy(x.data(), a, n * 4, cudaMemcpyDeviceToHost), "copy");
873    ck(cudaMemcpy(y.data(), b, n * 4, cudaMemcpyDeviceToHost), "copy");
874    double md = 0.0, mv = 0.0;
875    for (size_t i = 0; i < n; ++i) {
876        md = std::max(md, (double) std::fabs(x[i] - y[i]));
877        mv = std::max(mv, (double) std::fabs(x[i]));
878    }
879    return mv > 0.0 ? md / mv : md;
880}
881// The recurrence in FP64 (a thread per value head and column, the state in local memory): the reference both FP32
882// recurrences are measured against
883__global__ void gdn_rec_f64_kernel(double* __restrict__ state, const float* __restrict__ h, const float* __restrict__ gate,
884                                   const float* __restrict__ beta, double* __restrict__ out, int64_t T) {
885    const int head = blockIdx.x, col = threadIdx.x, qh = head % HK;
886    double s[S];
887    for (int r = 0; r < S; ++r) s[r] = state[((size_t) r * HV + head) * S + col];
888    for (int64_t t = 0; t < T; ++t) {
889        const float* ht = h + t * C;
890        const double g = exp((double) gate[t * HV + head]), b = beta[t * HV + head];
891        double kv = 0.0;
892        for (int r = 0; r < S; ++r) kv += s[r] * ht[HK * S + qh * S + r];
893        const double delta = (ht[2 * HK * S + head * S + col] - g * kv) * b;
894        double o = 0.0;
895        for (int r = 0; r < S; ++r) {
896            s[r] = g * s[r] + ht[HK * S + qh * S + r] * delta;
897            o += s[r] * ht[qh * S + r];
898        }
899        out[(t * HV + head) * S + col] = o / sqrt((double) S);
900    }
901    for (int r = 0; r < S; ++r) state[((size_t) r * HV + head) * S + col] = s[r];
902}
903__global__ void to_f64(const float* x, double* y, int64_t n) {
904    for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) y[i] = x[i];
905}
906double max_rel_f64(const float* a, const double* ref, size_t n) {   // max |a - ref| / max |ref|
907    std::vector<float> x(n);
908    std::vector<double> y(n);
909    ck(cudaMemcpy(x.data(), a, n * 4, cudaMemcpyDeviceToHost), "copy");
910    ck(cudaMemcpy(y.data(), ref, n * 8, cudaMemcpyDeviceToHost), "copy");
911    double md = 0.0, mv = 0.0;
912    for (size_t i = 0; i < n; ++i) {
913        md = std::max(md, std::fabs(x[i] - y[i]));
914        mv = std::max(mv, std::fabs(y[i]));
915    }
916    return mv > 0.0 ? md / mv : md;
917}
918// a recurrence of gdn_rec_chunked's shape (the FP32 chunked pair, the tensor-core scan) on the inputs given
919using RecLaunch = cudaError_t (*)(float*, const float*, const float*, const float*, float*, int64_t, cudaStream_t);
920int check_variant(const Inputs& in, const char* label, RecLaunch launch, const char* needs) {
921    const int64_t T = in.T;
922    const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S;
923    float* s0 = dalloc<float>(st);
924    float* s1 = dalloc<float>(st);
925    float* o0 = dalloc<float>(oc_n);
926    float* o1 = dalloc<float>(oc_n);
927    ck(cudaMemcpy(s0, in.state0, st * 4, cudaMemcpyDeviceToDevice), "state copy");
928    ck(cudaMemcpy(s1, in.state0, st * 4, cudaMemcpyDeviceToDevice), "state copy");
929    gdn_rec_kh_kernel<<<HK * NCB, dim3(CB, RG)>>>(s0, in.h, in.gate, in.beta, o0, in.T);
930    const cudaError_t e = launch(s1, in.h, in.gate, in.beta, o1, in.T, 0);
931    if (e == cudaErrorNotSupported) {
932        std::printf("     T=%-6lld %s: not on this card (%s)\n", (long long) T, label, needs);
933        cudaFree(s0); cudaFree(s1); cudaFree(o0); cudaFree(o1);
934        return 0;
935    }
936    ck(e, label);
937    ck(cudaDeviceSynchronize(), label);
938    const double eo = max_rel(o0, o1, oc_n), es = max_rel(s0, s1, st);
939    const bool bad = !(eo < 1e-4) || !(es < 1e-4);
940    std::printf("%s T=%-6lld %s: output %.2e, state %.2e (max |diff| / max |value|)\n", bad ? "FAIL" : "    ",
941                (long long) T, label, eo, es);
942    if (T <= 8192) {   // both against FP64 (its output: 8 bytes a value, so not at 32K)
943        double* sd = dalloc<double>(st);
944        double* od = dalloc<double>(oc_n);
945        to_f64<<<1024, 256>>>(in.state0, sd, (int64_t) st);
946        gdn_rec_f64_kernel<<<HV, S>>>(sd, in.h, in.gate, in.beta, od, in.T);
947        ck(cudaDeviceSynchronize(), "FP64 run");
948        std::printf("            against FP64: gdn_rec_kh_kernel output %.2e, state %.2e; this one output %.2e, state %.2e\n",
949                    max_rel_f64(o0, od, oc_n), max_rel_f64(s0, sd, st), max_rel_f64(o1, od, oc_n), max_rel_f64(s1, sd, st));
950        cudaFree(sd); cudaFree(od);
951    }
952    cudaFree(s0); cudaFree(s1); cudaFree(o0); cudaFree(o1);
953    return bad ? 1 : 0;
954}
955int check_chunked(int64_t T, uint64_t seed) {
956    Inputs in(T, seed);
957    return check_variant(in, "chunked (STRATA_GDN_CHUNKED)", gdn_rec_chunked, "sm_80+, 128 SMs, 93.7 KB a block");
958}
959constexpr const char* kTcNeeds = "sm_80+, 48 SMs, 122 KB a block";
960int check_tc(int64_t T, uint64_t seed) {
961    Inputs in(T, seed);
962    return check_variant(in, "tc (STRATA_GDN_TC=1)", gdn_rec_tc, kTcNeeds);
963}
964// the tensor-core scan on the stress inputs (Inputs): its f16 range handling has a case for each
965int check_tc_stress(int64_t T, uint64_t seed) {
966    struct Case { const char* label; float state_scale, v_scale; bool slow_gates, coherent_keys; };
967    const Case cases[] = {{"tc (STRATA_GDN_TC=1), state0 x 0.01", 5e-4f, 1.0f, false, false},
968                          {"tc (STRATA_GDN_TC=1), state0 x 50", 2.5f, 1.0f, false, false},
969                          {"tc (STRATA_GDN_TC=1), state0 = 0", 0.0f, 1.0f, false, false},
970                          {"tc (STRATA_GDN_TC=1), v x 50", 0.05f, 50.0f, false, false},
971                          {"tc (STRATA_GDN_TC=1), slow gates", 0.05f, 1.0f, true, false},
972                          {"tc (STRATA_GDN_TC=1), coherent keys", 0.05f, 1.0f, false, true}};
973    int fails = 0;
974    for (const Case& c : cases) {
975        Inputs in(T, seed++, c.state_scale, c.v_scale, c.slow_gates, c.coherent_keys);
976        fails += check_variant(in, c.label, gdn_rec_tc, kTcNeeds);
977    }
978    return fails;
979}
980
981// ------------------------------------------------------------------ the tensor-core scan's fragment self-test (--selftest-frag)
982// One warp each, random inputs, the reference in double on the host: (b) a 16x128 . 128x32 product through
983// gtc_prod_state (the f16 split with the state's 2^es and k's 2^8, ldmatrix), (c) a 16x32 . 32x128 update through
984// gtc_update_state (ldmatrix.trans, the 2^ed scale, the accumulator's pre / post scale), (d) a 16x32 . 32x32 product
985// through gtc_prod_dt on a full random T of wide range (the prep's 2^et on the B images), (e) the triangle-skipped
986// tile sets of gtc_prod_dt against the full ones on triangular T / P: the same bits, since the skipped tiles add
987// exact zeros.  Most bugs of a tensor-core kernel are fragment-layout bugs: these catch them before the kernel does.
988// ((a), the C -> A tf32 shuffle, went with the tf32 form of D^T.)
989__device__ void st_stage_k(uint16_t* kh, uint16_t* kl, const float* k) {   // k: 32 x 128 f32 -> the hi / lo images x 2^8
990    for (int p = threadIdx.x; p < GCH * S / 4; p += 32) {
991        const int t = p / (S / 4), r = (p % (S / 4)) * 4;
992        gtc_split_store4(kh + t * GTC_KP + r, kl + t * GTC_KP + r, *reinterpret_cast<const float4*>(k + t * S + r), 256.0f);
993    }
994    __syncwarp();
995}
996// a 16-row matrix (row stride ld) as 8-column tiles in the C layout: tile j, lane (gid, tig) holds (gid, 8j + 2tig),
997// (gid, 8j + 2tig + 1), (gid + 8, 8j + 2tig), (gid + 8, 8j + 2tig + 1)
998template <int NT> __device__ void st_load_c(float (&c)[NT][4], const float* m, int ld) {
999    const int lane = threadIdx.x & 31, gid = lane >> 2, tig = lane & 3;
1000#pragma unroll
1001    for (int j = 0; j < NT; ++j) {
1002        c[j][0] = m[gid * ld + 8 * j + 2 * tig];
1003        c[j][1] = m[gid * ld + 8 * j + 2 * tig + 1];
1004        c[j][2] = m[(gid + 8) * ld + 8 * j + 2 * tig];
1005        c[j][3] = m[(gid + 8) * ld + 8 * j + 2 * tig + 1];
1006    }
1007}
1008template <int NT> __device__ void st_store_c(const float (&c)[NT][4], float* m, int ld, float scale) {
1009    const int lane = threadIdx.x & 31, gid = lane >> 2, tig = lane & 3;
1010#pragma unroll
1011    for (int j = 0; j < NT; ++j) {
1012        m[gid * ld + 8 * j + 2 * tig] = c[j][0] * scale;
1013        m[gid * ld + 8 * j + 2 * tig + 1] = c[j][1] * scale;
1014        m[(gid + 8) * ld + 8 * j + 2 * tig] = c[j][2] * scale;
1015        m[(gid + 8) * ld + 8 * j + 2 * tig + 1] = c[j][3] * scale;
1016    }
1017}
1018template <int NT> __device__ float st_max_abs(const float (&c)[NT][4]) {
1019    float m = 0.0f;
1020#pragma unroll
1021    for (int j = 0; j < NT; ++j)
1022#pragma unroll
1023        for (int q = 0; q < 4; ++q) m = fmaxf(m, fabsf(c[j][q]));
1024    return gtc_warp_max(m);
1025}
1026__global__ void st_state_kernel(const float* a, const float* k, float* out) {   // out (16 x 32) = a (16 x 128) k^T
1027    __shared__ __align__(16) uint16_t kh[GCH * GTC_KP], kl[GCH * GTC_KP];
1028    st_stage_k(kh, kl, k);
1029    float s[16][4];
1030    st_load_c<16>(s, a, S);
1031    const int es = gtc_scale_exp(st_max_abs<16>(s));
1032    float xt[4][4] = {}, qs[4][4] = {};
1033    gtc_prod_state(s, gtc_pow2(es), kh, kl, kh, kl, xt, qs);
1034    st_store_c<4>(xt, out, GCH, gtc_pow2(-(8 + es)));
1035}
1036__global__ void st_update_kernel(const float* s0, const float* dd, const float* k, float eL, float* out) {   // out (16 x 128) = eL s0 + dd (16 x 32) k
1037    __shared__ __align__(16) uint16_t kh[GCH * GTC_KP], kl[GCH * GTC_KP];
1038    st_stage_k(kh, kl, k);
1039    float s[16][4], dt[4][4], ddt[4][4];
1040    st_load_c<16>(s, s0, S);
1041    st_load_c<4>(dt, dd, GCH);
1042    const int ed = gtc_scale_exp(st_max_abs<4>(dt));
1043    const float sD = gtc_pow2(ed), sPre = eL * gtc_pow2(ed + 8);
1044#pragma unroll
1045    for (int j = 0; j < 4; ++j)
1046#pragma unroll
1047        for (int q = 0; q < 4; ++q) ddt[j][q] = dt[j][q] * sD;
1048#pragma unroll
1049    for (int j = 0; j < 16; ++j)
1050#pragma unroll
1051        for (int q = 0; q < 4; ++q) s[j][q] *= sPre;
1052    gtc_update_state(s, ddt, kh, kl);
1053    st_store_c<16>(s, out, S, gtc_pow2(-(ed + 8)));
1054}
1055// out (16 x 32) = d p^T: p's images x 2^eb (the scan's P carry 2^8, its T the prep's 2^et), d x 2^ed from its maximum
1056template <bool SKIP> __global__ void st_dt_kernel(const float* d, const float* p, int eb, float* out) {
1057    __shared__ __align__(16) uint16_t ph[GCH * GTC_PP], pl[GCH * GTC_PP];
1058    for (int q = threadIdx.x; q < GCH * GCH / 4; q += 32) {
1059        const int t = q / (GCH / 4), i = (q % (GCH / 4)) * 4;
1060        gtc_split_store4(ph + t * GTC_PP + i, pl + t * GTC_PP + i, *reinterpret_cast<const float4*>(p + t * GCH + i), gtc_pow2(eb));
1061    }
1062    __syncwarp();
1063    float dt[4][4], ot[4][4] = {};
1064    st_load_c<4>(dt, d, GCH);
1065    const int ed = gtc_scale_exp(st_max_abs<4>(dt));
1066    gtc_prod_dt<SKIP>(dt, gtc_pow2(ed), ph, pl, ot);
1067    st_store_c<4>(ot, out, GCH, gtc_pow2(-(ed + eb)));
1068}
1069int st_scale_exp(const std::vector<float>& m) {   // the prep's gtc_scale_exp on the host: max |m| into [2^14, 2^15)
1070    float mx = 0.0f;
1071    for (float x : m) mx = std::max(mx, std::fabs(x));
1072    if (mx == 0.0f) return 0;
1073    int e = 0;
1074    std::frexp(mx, &e);   // mx = f 2^e, f in [0.5, 1): floor(log2 mx) = e - 1
1075    e = 14 - (e - 1);
1076    return e < -40 ? -40 : (e > 40 ? 40 : e);
1077}
1078struct StRng {   // xorshift64, host side
1079    uint64_t s;
1080    explicit StRng(uint64_t seed) : s(seed) {}
1081    float uni() { s ^= s << 13; s ^= s >> 7; s ^= s << 17; return ((float) (s >> 40) + 0.5f) / 16777216.0f; }
1082    float gauss() { return std::sqrt(-2.0f * std::log(uni())) * std::cos(6.2831853f * uni()); }
1083    float logmag(float lo, float hi) { return (uni() < 0.5f ? -1.0f : 1.0f) * std::pow(10.0f, lo + (hi - lo) * uni()); }
1084};
1085float* st_upload(const std::vector<float>& v) {
1086    float* d = dalloc<float>(v.size());
1087    ck(cudaMemcpy(d, v.data(), v.size() * 4, cudaMemcpyHostToDevice), "upload");
1088    return d;
1089}
1090std::vector<float> st_download(const float* d, size_t n) {
1091    std::vector<float> v(n);
1092    ck(cudaDeviceSynchronize(), "self-test kernel");
1093    ck(cudaMemcpy(v.data(), d, n * 4, cudaMemcpyDeviceToHost), "download");
1094    return v;
1095}
1096double st_max_rel(const std::vector<float>& got, const std::vector<double>& ref) {
1097    double md = 0.0, mv = 0.0;
1098    for (size_t i = 0; i < ref.size(); ++i) {
1099        md = std::max(md, std::fabs((double) got[i] - ref[i]));
1100        mv = std::max(mv, std::fabs(ref[i]));
1101    }
1102    return mv > 0.0 ? md / mv : md;
1103}
1104int selftest_frag() {
1105    std::printf("--selftest-frag: the tensor-core scan's fragment helpers, one warp each\n");
1106    int fails = 0;
1107    StRng rng(0x5e1f7e57ULL);
1108    auto unit_rows = [&](std::vector<float>& k, int rows, int cols) {   // gaussian rows, L2-normalized
1109        for (int t = 0; t < rows; ++t) {
1110            double ss = 0.0;
1111            for (int r = 0; r < cols; ++r) { k[t * cols + r] = rng.gauss(); ss += (double) k[t * cols + r] * k[t * cols + r]; }
1112            for (int r = 0; r < cols; ++r) k[t * cols + r] = (float) (k[t * cols + r] / std::sqrt(ss));
1113        }
1114    };
1115    {   // (b) X^T = S^T K^T: f16x3 with the state's 2^es and k's 2^8, B by ldmatrix
1116        std::vector<float> a(16 * S), k(GCH * S);
1117        for (float& x : a) x = rng.logmag(-3.0f, 2.0f);
1118        unit_rows(k, GCH, S);
1119        std::vector<double> ref(16 * GCH);
1120        for (int c = 0; c < 16; ++c)
1121            for (int i = 0; i < GCH; ++i) {
1122                double v = 0.0;
1123                for (int r = 0; r < S; ++r) v += (double) a[c * S + r] * k[i * S + r];
1124                ref[c * GCH + i] = v;
1125            }
1126        float* da = st_upload(a);
1127        float* dk = st_upload(k);
1128        float* dout = dalloc<float>(16 * GCH);
1129        st_state_kernel<<<1, 32>>>(da, dk, dout);
1130        const double rel = st_max_rel(st_download(dout, 16 * GCH), ref);
1131        const bool bad = !(rel <= 2e-6);
1132        std::printf("  (b) X^T = S^T K^T (16x128 . 128x32, f16x3, 2^es 2^8, ldmatrix): max |diff| / max |ref| %.2e  %s\n", rel, bad ? "FAIL" : "ok");
1133        fails += bad;
1134        cudaFree(da); cudaFree(dk); cudaFree(dout);
1135    }
1136    {   // (c) S^T = eL S^T + Dd^T K: ldmatrix.trans, 2^ed, the accumulator scaled before and after
1137        std::vector<float> s0(16 * S), dd(16 * GCH), k(GCH * S);
1138        for (float& x : s0) x = rng.logmag(-3.0f, 2.0f);
1139        for (float& x : dd) x = rng.logmag(-3.0f, 2.0f);
1140        unit_rows(k, GCH, S);
1141        const float eL = 0.25f + 0.75f * rng.uni();
1142        std::vector<double> ref(16 * S);
1143        for (int c = 0; c < 16; ++c)
1144            for (int r = 0; r < S; ++r) {
1145                double v = (double) eL * s0[c * S + r];
1146                for (int i = 0; i < GCH; ++i) v += (double) dd[c * GCH + i] * k[i * S + r];
1147                ref[c * S + r] = v;
1148            }
1149        float* ds = st_upload(s0);
1150        float* dd_ = st_upload(dd);
1151        float* dk = st_upload(k);
1152        float* dout = dalloc<float>(16 * S);
1153        st_update_kernel<<<1, 32>>>(ds, dd_, dk, eL, dout);
1154        const double rel = st_max_rel(st_download(dout, 16 * S), ref);
1155        const bool bad = !(rel <= 2e-6);
1156        std::printf("  (c) S^T = eL S^T + Dd^T K (16x32 . 32x128, f16x3, ldmatrix.trans, 2^ed pre / post scale): %.2e  %s\n", rel, bad ? "FAIL" : "ok");
1157        fails += bad;
1158        cudaFree(ds); cudaFree(dd_); cudaFree(dk); cudaFree(dout);
1159    }
1160    {   // (d) D^T = Y^T T^T on f16x3 through gtc_prod_dt, a full random T of wide range with the prep's 2^et
1161        std::vector<float> y(16 * GCH), t(GCH * GCH);
1162        for (float& x : y) x = rng.logmag(-3.0f, 2.0f);
1163        for (float& x : t) x = rng.logmag(-2.0f, 3.0f);
1164        std::vector<double> ref(16 * GCH);
1165        for (int c = 0; c < 16; ++c)
1166            for (int i = 0; i < GCH; ++i) {
1167                double v = 0.0;
1168                for (int ip = 0; ip < GCH; ++ip) v += (double) y[c * GCH + ip] * t[i * GCH + ip];
1169                ref[c * GCH + i] = v;
1170            }
1171        float* dy = st_upload(y);
1172        float* dt_ = st_upload(t);
1173        float* dout = dalloc<float>(16 * GCH);
1174        st_dt_kernel<false><<<1, 32>>>(dy, dt_, st_scale_exp(t), dout);
1175        const double rel = st_max_rel(st_download(dout, 16 * GCH), ref);
1176        const bool bad = !(rel <= 2e-6);
1177        std::printf("  (d) D^T = Y^T T^T (16x32 . 32x32, f16x3, Y x 2^ey, T x 2^et): %.2e  %s\n", rel, bad ? "FAIL" : "ok");
1178        fails += bad;
1179        cudaFree(dy); cudaFree(dt_); cudaFree(dout);
1180    }
1181    {   // (e) the triangle-skipped tile sets against the full ones: T unit lower triangular, P lower triangular
1182        std::vector<float> y(16 * GCH), t(GCH * GCH), d(16 * GCH), p(GCH * GCH);
1183        for (float& x : y) x = rng.logmag(-3.0f, 2.0f);
1184        for (float& x : d) x = rng.logmag(-3.0f, 2.0f);
1185        for (int i = 0; i < GCH; ++i)
1186            for (int j = 0; j < GCH; ++j) {
1187                t[i * GCH + j] = j < i ? rng.logmag(-2.0f, 3.0f) : (j == i ? 1.0f : 0.0f);
1188                p[i * GCH + j] = j <= i ? 2.0f * rng.uni() - 1.0f : 0.0f;
1189            }
1190        std::vector<double> ref_d(16 * GCH), ref_o(16 * GCH);
1191        for (int c = 0; c < 16; ++c)
1192            for (int i = 0; i < GCH; ++i) {
1193                double v = 0.0, w = 0.0;
1194                for (int ip = 0; ip < GCH; ++ip) { v += (double) y[c * GCH + ip] * t[i * GCH + ip]; w += (double) d[c * GCH + ip] * p[i * GCH + ip]; }
1195                ref_d[c * GCH + i] = v;
1196                ref_o[c * GCH + i] = w;
1197            }
1198        float* dy = st_upload(y);
1199        float* dt_ = st_upload(t);
1200        float* dd_ = st_upload(d);
1201        float* dp = st_upload(p);
1202        float* full = dalloc<float>(16 * GCH);
1203        float* skip = dalloc<float>(16 * GCH);
1204        st_dt_kernel<false><<<1, 32>>>(dy, dt_, st_scale_exp(t), full);
1205        st_dt_kernel<true><<<1, 32>>>(dy, dt_, st_scale_exp(t), skip);
1206        const std::vector<float> f1 = st_download(full, 16 * GCH), s1 = st_download(skip, 16 * GCH);
1207        const unsigned long long diff1 = std::memcmp(f1.data(), s1.data(), 16 * GCH * 4) != 0 ? diff_words(full, skip, 16 * GCH * 4) : 0;
1208        const double rel1 = st_max_rel(s1, ref_d);
1209        st_dt_kernel<false><<<1, 32>>>(dd_, dp, 8, full);
1210        st_dt_kernel<true><<<1, 32>>>(dd_, dp, 8, skip);
1211        const std::vector<float> f2 = st_download(full, 16 * GCH), s2 = st_download(skip, 16 * GCH);
1212        const unsigned long long diff2 = std::memcmp(f2.data(), s2.data(), 16 * GCH * 4) != 0 ? diff_words(full, skip, 16 * GCH * 4) : 0;
1213        const double rel2 = st_max_rel(s2, ref_o);
1214        const bool bad = diff1 != 0 || diff2 != 0 || !(rel1 <= 2e-6) || !(rel2 <= 2e-6);
1215        std::printf("  (e) triangle skipping: D^T 10 of 16 tiles %llu words differ (vs FP64 %.2e), o^T 6 of 8 tiles %llu words differ (vs FP64 %.2e)  %s\n",
1216                    diff1, rel1, diff2, rel2, bad ? "FAIL" : "ok");
1217        fails += bad;
1218        cudaFree(dy); cudaFree(dt_); cudaFree(dd_); cudaFree(dp); cudaFree(full); cudaFree(skip);
1219    }
1220    std::printf("--selftest-frag: %d failures\n", fails);
1221    return fails;
1222}
1223
1224float median(std::vector<float> v) {
1225    std::sort(v.begin(), v.end());
1226    return v.empty() ? 0.0f : v[v.size() / 2];
1227}
1228
1229// tc_only (--bench-tc): the tensor-core series alone, for A / B runs of two builds back to back
1230void bench(int64_t T, bool tc_only = false) {
1231    Inputs in(T, 0xB3);
1232    const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S;
1233    float* state = dalloc<float>(st);
1234    float* oc = dalloc<float>(oc_n);
1235    uint16_t* y16 = dalloc<uint16_t>(oc_n);
1236    cudaEvent_t e0, e1;
1237    ck(cudaEventCreate(&e0), "event");
1238    ck(cudaEventCreate(&e1), "event");
1239    auto timed = [&](auto&& launch) {
1240        ck(cudaMemcpy(state, in.state0, st * 4, cudaMemcpyDeviceToDevice), "state");
1241        cudaEventRecord(e0);
1242        launch();
1243        cudaEventRecord(e1);
1244        ck(cudaEventSynchronize(e1), "timed");
1245        float ms = 0.0f;
1246        cudaEventElapsedTime(&ms, e0, e1);
1247        return ms;
1248    };
1249    const int warm = 3, rounds = T >= 16384 ? 10 : 20;
1250    std::vector<float> t_rec[kRecCount], t_norm[2];
1251    for (int i = 0; !tc_only && i < warm + rounds; ++i) {
1252        for (int j = 0; j < kRecCount; ++j) {
1253            const Rec v = (Rec) ((i + j) % kRecCount);   // a different variant first in each round
1254            const float ms = timed([&] { run_rec(v, state, in, oc); });
1255            if (i >= warm) t_rec[v].push_back(ms);
1256        }
1257    }
1258    for (int i = 0; !tc_only && i < warm + rounds; ++i) {
1259        for (int j = 0; j < 2; ++j) {
1260            const int v = (i + j) % 2;
1261            const float ms = timed([&] {
1262                if (v == 0) gdn_out_norm_old_kernel<<<dim3((unsigned) T, HV), S>>>(in.z, in.gamma, 1e-6f, oc, y16);
1263                else gdn_out_norm_kernel<<<dim3((unsigned) T, HV), S>>>(in.z, in.gamma, 1e-6f, oc, y16);
1264            });
1265            if (i >= warm) t_norm[v].push_back(ms);
1266        }
1267    }
1268    std::vector<float> t_kc[2];   // gdn_rec_kh_kernel and the chunked recurrence, alternating
1269    const bool can_chunk = !tc_only && gdn_rec_chunked(state, in.h, in.gate, in.beta, oc, in.T, 0) == cudaSuccess &&
1270                           cudaDeviceSynchronize() == cudaSuccess;
1271    for (int i = 0; can_chunk && i < warm + rounds; ++i)
1272        for (int j = 0; j < 2; ++j) {
1273            const int v = (i + j) % 2;
1274            const float ms = timed([&] {
1275                if (v == 0) gdn_rec_kh_kernel<<<HK * NCB, dim3(CB, RG)>>>(state, in.h, in.gate, in.beta, oc, in.T);
1276                else ck(gdn_rec_chunked(state, in.h, in.gate, in.beta, oc, in.T, 0), "chunked");
1277            });
1278            if (i >= warm) t_kc[v].push_back(ms);
1279        }
1280    std::vector<float> t_tc[2];   // gdn_rec_kh_kernel and the tensor-core scan, alternating
1281    const bool can_tc = gdn_rec_tc(state, in.h, in.gate, in.beta, oc, in.T, 0) == cudaSuccess &&
1282                        cudaDeviceSynchronize() == cudaSuccess;
1283    for (int i = 0; can_tc && i < warm + rounds; ++i)
1284        for (int j = 0; j < 2; ++j) {
1285            const int v = (i + j) % 2;
1286            const float ms = timed([&] {
1287                if (v == 0) gdn_rec_kh_kernel<<<HK * NCB, dim3(CB, RG)>>>(state, in.h, in.gate, in.beta, oc, in.T);
1288                else ck(gdn_rec_tc(state, in.h, in.gate, in.beta, oc, in.T, 0), "tc");
1289            });
1290            if (i >= warm) t_tc[v].push_back(ms);
1291        }
1292    const float r0 = median(t_rec[kBefore]), r1 = median(t_rec[kKeyHead]), n0 = median(t_norm[0]), n1 = median(t_norm[1]);
1293    std::printf("  T = %lld tokens, one layer (48 value heads), medians of %d alternating runs:\n", (long long) T, rounds);
1294    if (tc_only) {
1295        const float kh = median(t_tc[0]), tc = median(t_tc[1]);
1296        std::printf("    recurrence, gdn_rec_kh_kernel                  %8.2f ms  (%.3f us per token)\n", kh, 1000.0f * kh / (float) T);
1297        std::printf("    recurrence, tensor-core chunked (STRATA_GDN_TC=1) %8.2f ms  (%.3f us per token)  %.2fx gdn_rec_kh_kernel\n",
1298                    tc, 1000.0f * tc / (float) T, kh / tc);
1299        cudaEventDestroy(e0);
1300        cudaEventDestroy(e1);
1301        cudaFree(state); cudaFree(oc); cudaFree(y16);
1302        return;
1303    }
1304    std::printf("    recurrence, before (gdn_rec_cols_pipe_kernel)  %8.2f ms  (%.3f us per token)\n", r0,
1305                1000.0f * r0 / (float) T);
1306    std::printf("    recurrence, gdn_rec_kh_kernel                  %8.2f ms  (%.3f us per token)  %.2fx\n", r1,
1307                1000.0f * r1 / (float) T, r0 / r1);
1308    if (can_chunk) {
1309        const float kh = median(t_kc[0]), kc = median(t_kc[1]);
1310        std::printf("    recurrence, chunked (STRATA_GDN_CHUNKED=1)     %8.2f ms  (%.3f us per token)  %.2fx gdn_rec_kh_kernel\n",
1311                    kc, 1000.0f * kc / (float) T, kh / kc);
1312    }
1313    if (can_tc) {
1314        const float kh = median(t_tc[0]), tc = median(t_tc[1]);
1315        std::printf("    recurrence, tensor-core chunked (STRATA_GDN_TC=1) %8.2f ms  (%.3f us per token)  %.2fx gdn_rec_kh_kernel\n",
1316                    tc, 1000.0f * tc / (float) T, kh / tc);
1317    }
1318    std::printf("    output norm, before (FP32 and FP16 store)      %8.2f ms\n", n0);
1319    std::printf("    output norm, FP16 store only                   %8.2f ms  %.2fx\n", n1, n0 / n1);
1320    std::printf("    36 DeltaNet layers per %lld-token block: recurrence + norm %.0f ms -> %.0f ms (-%.0f ms)\n",
1321                (long long) T, 36.0f * (r0 + n0), 36.0f * (r1 + n1), 36.0f * (r0 + n0 - r1 - n1));
1322    cudaEventDestroy(e0);
1323    cudaEventDestroy(e1);
1324    cudaFree(state); cudaFree(oc); cudaFree(y16);
1325}
1326
1327// gdn_rec_kh_kernel against the chunked recurrence on short chunks (the chunked one's launches, host side included:
1328// the GPU is idle at each start), where kernels.cu's kGdnChunkedMin comes from
1329void chunked_sweep() {
1330    std::printf("  short chunks, gdn_rec_kh_kernel -> chunked (medians of 21 alternating runs):\n");
1331    for (const int64_t T : {32, 64, 96, 128, 192, 256, 512, 1024}) {
1332        Inputs in(T, 0xC5);
1333        const size_t st = (size_t) S * HV * S;
1334        float* state = dalloc<float>(st);
1335        float* oc = dalloc<float>((size_t) T * HV * S);
1336        cudaEvent_t e0, e1;
1337        ck(cudaEventCreate(&e0), "event");
1338        ck(cudaEventCreate(&e1), "event");
1339        const bool can = gdn_rec_chunked(state, in.h, in.gate, in.beta, oc, in.T, 0) == cudaSuccess &&
1340                         cudaDeviceSynchronize() == cudaSuccess;
1341        std::vector<float> t[2];
1342        for (int i = 0; can && i < 5 + 21; ++i)
1343            for (int j = 0; j < 2; ++j) {
1344                const int v = (i + j) % 2;
1345                ck(cudaMemcpy(state, in.state0, st * 4, cudaMemcpyDeviceToDevice), "state");
1346                cudaEventRecord(e0);
1347                if (v == 0) gdn_rec_kh_kernel<<<HK * NCB, dim3(CB, RG)>>>(state, in.h, in.gate, in.beta, oc, in.T);
1348                else ck(gdn_rec_chunked(state, in.h, in.gate, in.beta, oc, in.T, 0), "chunked");
1349                cudaEventRecord(e1);
1350                ck(cudaEventSynchronize(e1), "timed");
1351                float ms = 0.0f;
1352                cudaEventElapsedTime(&ms, e0, e1);
1353                if (i >= 5) t[v].push_back(ms);
1354            }
1355        if (can) {
1356            const float kh = median(t[0]), kc = median(t[1]);
1357            std::printf("    T = %-5lld %8.1f us -> %8.1f us  %.2fx\n", (long long) T, 1000.0f * kh, 1000.0f * kc, kh / kc);
1358        } else {
1359            std::printf("    chunked: not on this card\n");
1360        }
1361        cudaEventDestroy(e0); cudaEventDestroy(e1);
1362        cudaFree(state); cudaFree(oc);
1363        if (!can) return;
1364    }
1365}
1366
1367// The two kernels at a given number of blocks per SM, as on cards with more or fewer SMs than this one: the kernel
1368// before puts ceil(192 / SMs) of its blocks on an SM, gdn_rec_kh_kernel ceil(64 / SMs), and the busiest SM sets the
1369// pace (every block walks the whole chunk).  b blocks per SM here: b rounds of one block per SM, each round one launch
1370// of SMs blocks (the first heads; split in launches of at most the engine's grid), every launch on its own stream with
1371// its own state and output, all started together, so the block scheduler puts one block of each round on every SM.
1372// The kernels are the ones above, unchanged.
1373void scale(int64_t T) {
1374    int dev = 0, sms = 0, per_sm[kRecCount] = {};
1375    ck(cudaGetDevice(&dev), "device");
1376    ck(cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev), "SMs");
1377    ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm[kBefore], gdn_rec_cols_pipe_kernel, CB * RG, 0), "occupancy");
1378    ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm[kKeyHead], gdn_rec_kh_kernel, CB * RG, 0), "occupancy");
1379    constexpr int kMaxB = 6, kMaxLaunches = 6;
1380    const int full[kRecCount] = {HV * NCB, HK * NCB};   // the grids as the engine launches them
1381    auto parts = [&](int v) { return (sms + full[v] - 1) / full[v]; };   // launches per round
1382    Inputs in(T, 0xC7);
1383    const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S;
1384    float* state[kMaxLaunches];
1385    float* oc[kMaxLaunches];
1386    cudaStream_t stream[kMaxLaunches];
1387    cudaEvent_t e0, e1, done[kMaxLaunches];
1388    ck(cudaEventCreate(&e0), "event");
1389    ck(cudaEventCreate(&e1), "event");
1390    for (int c = 0; c < kMaxLaunches; ++c) {
1391        state[c] = dalloc<float>(st);
1392        oc[c] = dalloc<float>(oc_n);
1393        ck(cudaStreamCreateWithFlags(&stream[c], cudaStreamNonBlocking), "stream");
1394        ck(cudaEventCreate(&done[c]), "event");
1395    }
1396    struct Case { int v, b; };
1397    std::vector<Case> cases;
1398    for (int v = 0; v < kRecCount; ++v)
1399        for (int b = 1; b <= std::min(kMaxB, per_sm[v]); ++b)
1400            if (b * parts(v) <= kMaxLaunches) cases.push_back({v, b});
1401    auto run = [&](const Case& cs) {
1402        for (int c = 0; c < kMaxLaunches; ++c) ck(cudaMemcpy(state[c], in.state0, st * 4, cudaMemcpyDeviceToDevice), "state");
1403        ck(cudaDeviceSynchronize(), "sync");
1404        const int np = parts(cs.v), n = cs.b * np;
1405        cudaEventRecord(e0, stream[0]);
1406        for (int c = 0; c < n; ++c) {
1407            const int k = c % np, grid = sms / np + (k < sms % np ? 1 : 0);   // round c / np, part k
1408            if (c > 0) cudaStreamWaitEvent(stream[c], e0, 0);
1409            if (cs.v == kBefore)
1410                gdn_rec_cols_pipe_kernel<<<grid, dim3(CB, RG), 0, stream[c]>>>(state[c], in.h, in.gate, in.beta, oc[c], T);
1411            else
1412                gdn_rec_kh_kernel<<<grid, dim3(CB, RG), 0, stream[c]>>>(state[c], in.h, in.gate, in.beta, oc[c], T);
1413            cudaEventRecord(done[c], stream[c]);
1414        }
1415        for (int c = 1; c < n; ++c) cudaStreamWaitEvent(stream[0], done[c], 0);
1416        cudaEventRecord(e1, stream[0]);
1417        ck(cudaEventSynchronize(e1), "scale");
1418        float ms = 0.0f;
1419        cudaEventElapsedTime(&ms, e0, e1);
1420        return ms;
1421    };
1422    const int warm = 2, rounds = 9;
1423    std::vector<std::vector<float>> t(cases.size());
1424    for (int i = 0; i < warm + rounds; ++i)
1425        for (size_t j = 0; j < cases.size(); ++j) {
1426            const size_t k = (i + j) % cases.size();   // a different case first in each round
1427            const float ms = run(cases[k]);
1428            if (i >= warm) t[k].push_back(ms);
1429        }
1430    auto us = [&](int v, int b) {   // per token, or < 0 if not measured
1431        for (size_t k = 0; k < cases.size(); ++k)
1432            if (cases[k].v == v && cases[k].b == b) return 1000.0f * median(t[k]) / (float) T;
1433        return -1.0f;
1434    };
1435    std::printf("  per token at a given number of blocks per SM (%lld tokens, medians of %d alternating runs; this card has "
1436                "%d SMs):\n", (long long) T, rounds, sms);
1437    std::printf("    blocks per SM   before      gdn_rec_kh_kernel\n");
1438    for (int b = 1; b <= kMaxB; ++b) {
1439        const float u0 = us(kBefore, b), u1 = us(kKeyHead, b);
1440        if (u0 < 0 && u1 < 0) continue;
1441        char a0[32] = "-", a1[32] = "-";
1442        if (u0 >= 0) std::snprintf(a0, sizeof a0, "%.3f us", u0);
1443        if (u1 >= 0) std::snprintf(a1, sizeof a1, "%.3f us", u1);
1444        std::printf("    %8d        %-11s %s\n", b, a0, a1);
1445    }
1446    std::printf("  so on a card with N SMs (the kernel before puts ceil(192 / N) blocks on an SM, gdn_rec_kh_kernel "
1447                "ceil(64 / N), at most %d):\n", per_sm[kKeyHead]);
1448    const int bands[][2] = {{192, 0}, {96, 191}, {64, 95}, {48, 63}, {39, 47}, {32, 38}};
1449    for (const auto& bd : bands) {
1450        const int nsm = bd[0], b0 = (192 + nsm - 1) / nsm, b1 = (64 + nsm - 1) / nsm;
1451        const float u0 = us(kBefore, b0), u1 = us(kKeyHead, b1);
1452        char range[32];
1453        if (bd[1]) std::snprintf(range, sizeof range, "%d-%d SMs", bd[0], bd[1]);
1454        else std::snprintf(range, sizeof range, "%d+ SMs", bd[0]);
1455        if (u0 < 0 || u1 < 0)
1456            std::printf("    %-12s before %d / new %d per SM: not measured on this card\n", range, b0, b1);
1457        else
1458            std::printf("    %-12s before %d / new %d per SM: %.3f -> %.3f us per token, %.2fx\n", range, b0, b1, u0, u1,
1459                        u0 / u1);
1460    }
1461    for (int c = 0; c < kMaxLaunches; ++c) {
1462        cudaFree(state[c]);
1463        cudaFree(oc[c]);
1464        cudaStreamDestroy(stream[c]);
1465        cudaEventDestroy(done[c]);
1466    }
1467    cudaEventDestroy(e0);
1468    cudaEventDestroy(e1);
1469}
1470
1471// The engine's grids on N of this card's SMs.  scale() puts as many blocks on every SM as the busiest SM of a card with
1472// N SMs gets; on that card only some SMs get that many (192 blocks on 80 SMs: 3 on 32 SMs, 2 on the other 48), the
1473// rest of the card has less to do, and the estimate came out 4-9 % above the real launch on two cards.  Here the
1474// recurrences run as the engine launches them, while hold_sm keeps all but N SMs: its blocks go out first, a small
1475// kernel on the timed launch's stream waits until they all sit, and one after the timed launch lets them go.  land()
1476// shows for every N where the two grids land: none on a held SM, and how many blocks share the busiest SM.  The
1477// recurrences are the ones above, unchanged; L2, memory and clock stay this card's.
1478void fewer_sms(int64_t T) {
1479    int dev = 0, sms = 0, optin = 0, smem_sm = 0, reserved = 0, hold_per_sm = 0, per_sm[kRecCount] = {};
1480    ck(cudaGetDevice(&dev), "device");
1481    ck(cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev), "SMs");
1482    ck(cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev), "shared memory");
1483    ck(cudaDeviceGetAttribute(&smem_sm, cudaDevAttrMaxSharedMemoryPerMultiprocessor, dev), "shared memory");
1484    ck(cudaDeviceGetAttribute(&reserved, cudaDevAttrReservedSharedMemoryPerBlock, dev), "shared memory");
1485    for (const void* f : {(const void*) hold_sm, (const void*) land}) {
1486        ck(cudaFuncSetAttribute(f, cudaFuncAttributeMaxDynamicSharedMemorySize, optin), "shared memory");
1487        ck(cudaFuncSetAttribute(f, cudaFuncAttributePreferredSharedMemoryCarveout, (int) cudaSharedmemCarveoutMaxShared),
1488           "carveout");
1489    }
1490    // Loaded now rather than at a first launch: with lazy loading (CUDA 12's default) a kernel's first launch may wait
1491    // until the device is idle, and so for hold_sm, which waits for release_sms.
1492    cudaFuncAttributes fa[kRecCount], fx;
1493    ck(cudaFuncGetAttributes(&fa[kBefore], gdn_rec_cols_pipe_kernel), "attributes");
1494    ck(cudaFuncGetAttributes(&fa[kKeyHead], gdn_rec_kh_kernel), "attributes");
1495    for (const void* f : {(const void*) hold_sm, (const void*) wait_sitting, (const void*) release_sms, (const void*) land})
1496        ck(cudaFuncGetAttributes(&fx, f), "attributes");
1497    ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&hold_per_sm, hold_sm, 1, optin), "occupancy");
1498    ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm[kBefore], gdn_rec_cols_pipe_kernel, CB * RG, 0), "occupancy");
1499    ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm[kKeyHead], gdn_rec_kh_kernel, CB * RG, 0), "occupancy");
1500    const int grid[kRecCount] = {HV * NCB, HK * NCB};   // as the engine launches them
1501    std::printf("  the engine's grids on N of this card's %d SMs (%lld tokens; the other SMs held by a sleeping kernel, see "
1502                "fewer_sms):\n", sms, (long long) T);
1503    const int left = smem_sm - optin - reserved;   // shared memory a holding block leaves on its SM
1504    if (hold_per_sm != 1 || (int) fa[kBefore].sharedSizeBytes + reserved <= left ||
1505        (int) fa[kKeyHead].sharedSizeBytes + reserved <= left) {
1506        std::printf("    not on this card: a block of a recurrence would fit beside a holding block (%d bytes left)\n",
1507                    left);
1508        return;
1509    }
1510    // land(): as much dynamic shared memory as still lets as many of its blocks share an SM as of the recurrence
1511    int land_smem[kRecCount];
1512    for (int v = 0; v < kRecCount; ++v) {
1513        int lo = 0, hi = optin;
1514        while (lo < hi) {
1515            const int mid = (lo + hi + 1) / 2;
1516            int nb = 0;
1517            ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&nb, land, CB * RG, mid), "occupancy");
1518            if (nb >= per_sm[v]) lo = mid;
1519            else hi = mid - 1;
1520        }
1521        land_smem[v] = lo;
1522    }
1523    // N: all SMs, and below that the SM counts of cards and the band edges, as long as both grids fit at once
1524    std::vector<int> ns = {sms};
1525    for (const int n : {170, 144, 132, 128, 112, 108, 96, 95, 84, 82, 80, 76, 72, 70, 66, 64, 63, 60, 56, 52, 48, 47, 46, 44,
1526                        40, 39, 38, 36, 34, 32})
1527        if (n < sms && (int64_t) n * per_sm[kBefore] >= grid[kBefore] && (int64_t) n * per_sm[kKeyHead] >= grid[kKeyHead])
1528            ns.push_back(n);
1529
1530    Inputs in(T, 0xD5);
1531    const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S;
1532    float* state = dalloc<float>(st);
1533    float* oc = dalloc<float>(oc_n);
1534    unsigned long long* sitting = dalloc<unsigned long long>(1);
1535    unsigned* flags = dalloc<unsigned>(4);
1536    unsigned *release = flags, *late = flags + 1, *landed = flags + 2, *apart = flags + 3;
1537    int* where = dalloc<int>((size_t) sms + grid[kBefore]);   // the holding blocks' SMs, then land()'s
1538    ck(cudaMemset(sitting, 0, sizeof(*sitting)), "memset");
1539    ck(cudaMemset(flags, 0, 4 * sizeof(unsigned)), "memset");
1540    cudaStream_t s_hold, s_run;
1541    ck(cudaStreamCreateWithFlags(&s_hold, cudaStreamNonBlocking), "stream");
1542    ck(cudaStreamCreateWithFlags(&s_run, cudaStreamNonBlocking), "stream");
1543    cudaEvent_t e0, e1;
1544    ck(cudaEventCreate(&e0), "event");
1545    ck(cudaEventCreate(&e1), "event");
1546    unsigned long long all = 0;   // holding blocks launched so far: sitting counts every one that sat down
1547    unsigned gen = 0;
1548    auto hold = [&](int n) {   // all but n SMs, before the next launch on s_run
1549        if (n >= sms) return;
1550        ++gen;
1551        all += (unsigned long long) (sms - n);
1552        hold_sm<<<sms - n, 1, optin, s_hold>>>(sitting, release, gen, where, late);
1553        ck(cudaGetLastError(), "hold_sm");
1554        const cudaError_t q = cudaStreamQuery(s_hold);   // hands the launch to the GPU now (Windows collects launches)
1555        if (q != cudaErrorNotReady) ck(q, "hold_sm");
1556        (void) cudaGetLastError();   // not ready is no error
1557        wait_sitting<<<1, 1, 0, s_run>>>(sitting, all, late);
1558    };
1559    auto let_go = [&](int n) {
1560        if (n < sms) release_sms<<<1, 1, 0, s_run>>>(release, gen);
1561    };
1562    auto settle = [&](const char* what) {
1563        ck(cudaStreamSynchronize(s_run), what);
1564        ck(cudaStreamSynchronize(s_hold), what);
1565    };
1566    auto count = [&](const unsigned* c) {   // after settle()
1567        unsigned h = 0;
1568        ck(cudaMemcpy(&h, c, sizeof(h), cudaMemcpyDeviceToHost), "count");
1569        return h;
1570    };
1571    auto done = [&] {
1572        cudaEventDestroy(e0);
1573        cudaEventDestroy(e1);
1574        cudaStreamDestroy(s_hold);
1575        cudaStreamDestroy(s_run);
1576        cudaFree(state); cudaFree(oc); cudaFree(sitting); cudaFree(flags); cudaFree(where);
1577    };
1578
1579    // where the grids land, once per N
1580    struct Landing { bool held = true; int busiest[kRecCount] = {}, on[kRecCount] = {}; };
1581    std::vector<Landing> lands(ns.size());
1582    for (size_t i = 0; i < ns.size(); ++i) {
1583        const int n = ns[i];
1584        for (int v = 0; v < kRecCount; ++v) {
1585            bool sat = false;
1586            unsigned apart0 = 0;
1587            for (int attempt = 0; attempt < 2 && !sat; ++attempt) {
1588                const unsigned late0 = count(late);
1589                apart0 = count(apart);
1590                ck(cudaMemsetAsync(landed, 0, sizeof(unsigned), s_run), "memset");
1591                hold(n);
1592                land<<<grid[v], dim3(CB, RG), land_smem[v], s_run>>>(where + sms, landed, apart);
1593                ck(cudaGetLastError(), "land");
1594                let_go(n);
1595                settle("land");
1596                sat = count(late) == late0;
1597            }
1598            if (!sat) {   // twice: the holding kernel and the launches beside it do not run at the same time here
1599                std::printf("    not on this card: the other SMs could not be held (the kernel holding them and the "
1600                            "launches beside it did not run at the same time)\n");
1601                done();
1602                return;
1603            }
1604            std::vector<int> w((size_t) sms + grid[v]);
1605            ck(cudaMemcpy(w.data(), where, w.size() * sizeof(int), cudaMemcpyDeviceToHost), "where");
1606            std::map<int, int> held, blocks;
1607            for (int b = 0; b < (n < sms ? sms - n : 0); ++b) ++held[w[b]];
1608            for (int b = 0; b < grid[v]; ++b) ++blocks[w[sms + b]];
1609            bool ok = count(apart) == apart0 && (int) held.size() == (n < sms ? sms - n : 0) && (int) blocks.size() <= n;
1610            int most = 0, on = 0;
1611            for (const auto& sb : blocks) {
1612                if (held.count(sb.first)) ok = false;
1613                if (sb.second > most) { most = sb.second; on = 0; }
1614                if (sb.second == most) ++on;
1615            }
1616            lands[i].held = lands[i].held && ok;
1617            lands[i].busiest[v] = most;
1618            lands[i].on[v] = on;
1619        }
1620    }
1621
1622    // the timings: every N and recurrence once per round, a different one first in each round
1623    struct Case { size_t i; Rec v; };
1624    std::vector<Case> cases;
1625    for (size_t i = 0; i < ns.size(); ++i)
1626        if (lands[i].held)
1627            for (int v = 0; v < kRecCount; ++v) cases.push_back({i, (Rec) v});
1628    auto run = [&](const Case& cs) {   // ms, or < 0 if the SMs were not held for the whole launch
1629        const int n = ns[cs.i];
1630        const unsigned late0 = count(late);
1631        ck(cudaMemcpyAsync(state, in.state0, st * 4, cudaMemcpyDeviceToDevice, s_run), "state");
1632        hold(n);
1633        ck(cudaEventRecord(e0, s_run), "event");
1634        run_rec(cs.v, state, in, oc, s_run);
1635        ck(cudaEventRecord(e1, s_run), "event");
1636        let_go(n);
1637        settle("fewer SMs");
1638        if (count(late) != late0) return -1.0f;
1639        float ms = 0.0f;
1640        ck(cudaEventElapsedTime(&ms, e0, e1), "event");
1641        return ms;
1642    };
1643    const int warm = 2, rounds = 15, max_dropped = 5;
1644    std::vector<std::vector<float>> t(cases.size());
1645    int dropped = 0;
1646    for (int r = 0; r < warm + rounds && dropped <= max_dropped; ++r)
1647        for (size_t j = 0; j < cases.size() && dropped <= max_dropped; ++j) {
1648            const size_t k = (r + j) % cases.size();
1649            const float ms = run(cases[k]);
1650            if (ms < 0.0f) ++dropped;
1651            else if (r >= warm) t[k].push_back(ms);
1652        }
1653    if (dropped > max_dropped) {   // each such run waits for a limit of a second or so
1654        std::printf("    stopped: in %d runs the other SMs were not held for the whole launch\n", dropped);
1655        done();
1656        return;
1657    }
1658    auto us = [&](size_t i, int v) {   // per token, or < 0 if not measured
1659        for (size_t k = 0; k < cases.size(); ++k)
1660            if (cases[k].i == i && cases[k].v == v && !t[k].empty()) return 1000.0f * median(t[k]) / (float) T;
1661        return -1.0f;
1662    };
1663    auto blocks_on = [](char* out, size_t size, int most, int on) {
1664        std::snprintf(out, size, "%d block%s on %d SM%s", most, most == 1 ? "" : "s", on, on == 1 ? "" : "s");
1665    };
1666    std::printf("  (medians of %d alternating runs; L2, memory and clock stay this card's)\n", rounds);
1667    std::printf("      N   before: busiest SM   new: busiest SM      us per token, before -> new\n");
1668    for (size_t i = 0; i < ns.size(); ++i) {
1669        if (!lands[i].held) {
1670            std::printf("    %3d   the other SMs were not held (a block landed on one, or a wait ran out)\n", ns[i]);
1671            continue;
1672        }
1673        char b0[40], b1[40];
1674        blocks_on(b0, sizeof b0, lands[i].busiest[kBefore], lands[i].on[kBefore]);
1675        blocks_on(b1, sizeof b1, lands[i].busiest[kKeyHead], lands[i].on[kKeyHead]);
1676        const float u0 = us(i, kBefore), u1 = us(i, kKeyHead);
1677        if (u0 < 0.0f || u1 < 0.0f) std::printf("    %3d   %-20s %-20s not measured\n", ns[i], b0, b1);
1678        else std::printf("    %3d   %-20s %-20s %.3f -> %.3f   %.2fx\n", ns[i], b0, b1, u0, u1, u0 / u1);
1679    }
1680    if (dropped) std::printf("    (%d runs dropped: the other SMs were not held for the whole launch)\n", dropped);
1681    std::printf("  so on a card with N SMs, as measured here (the kernel before puts ceil(192 / N) blocks on the busiest SM, "
1682                "gdn_rec_kh_kernel ceil(64 / N)):\n");
1683    const int bands[][2] = {{96, 191}, {64, 95}, {48, 63}, {39, 47}, {32, 38}};
1684    for (const auto& bd : bands) {
1685        const int b0 = (192 + bd[0] - 1) / bd[0], b1 = (64 + bd[0] - 1) / bd[0];
1686        float lo = 0.0f, hi = 0.0f;
1687        int cnt = 0, nmin = 0, nmax = 0;
1688        for (size_t i = 0; i < ns.size(); ++i) {
1689            const float u0 = us(i, kBefore), u1 = us(i, kKeyHead);
1690            if (ns[i] < bd[0] || ns[i] > bd[1] || u0 < 0.0f || u1 < 0.0f) continue;
1691            const float x = u0 / u1;
1692            if (cnt == 0 || x < lo) lo = x;
1693            if (cnt == 0 || x > hi) hi = x;
1694            if (cnt == 0 || ns[i] < nmin) nmin = ns[i];
1695            if (cnt == 0 || ns[i] > nmax) nmax = ns[i];
1696            ++cnt;
1697        }
1698        char range[32];
1699        std::snprintf(range, sizeof range, "%d-%d SMs", bd[0], bd[1]);
1700        if (cnt > 0)
1701            std::printf("    %-12s before %d / new %d per SM: %.2fx to %.2fx (%d to %d SMs)\n", range, b0, b1, lo, hi, nmin,
1702                        nmax);
1703        else if (bd[0] > sms)
1704            std::printf("    %-12s before %d / new %d per SM: more SMs than this card has (see the estimate above)\n", range,
1705                        b0, b1);
1706        else
1707            std::printf("    %-12s before %d / new %d per SM: not measured\n", range, b0, b1);
1708    }
1709    done();
1710}
1711
1712}  // namespace
1713
1714int main(int argc, char** argv) {
1715    bool do_bench = false, do_self = false, do_long = false, do_bench_tc = false;
1716    for (int i = 1; i < argc; ++i) {
1717        if (std::strcmp(argv[i], "--bench") == 0) do_bench = true;
1718        if (std::strcmp(argv[i], "--selftest-frag") == 0) do_self = true;
1719        if (std::strcmp(argv[i], "--long") == 0) do_long = true;
1720        if (std::strcmp(argv[i], "--bench-tc") == 0) do_bench_tc = true;
1721    }
1722    cudaDeviceProp p{};
1723    ck(cudaGetDeviceProperties(&p, 0), "device");
1724    std::printf("gdn_rec_parity on %s (sm_%d%d)\n", p.name, p.major, p.minor);
1725    int fails = 0;
1726    if (do_self) {   // the tensor-core helpers alone (one warp each, any sm_80+ card; the device code below sm_80 traps)
1727        if (p.major < 8) { std::printf("--selftest-frag: the tensor-core helpers need sm_80 or newer (skipped)\n"); return 77; }
1728        fails = selftest_frag();
1729        std::printf("gdn_rec_parity: %d failures\n", fails);
1730        return fails ? 1 : 0;
1731    }
1732    if (do_bench_tc) {   // the tensor-core timings alone
1733        for (const int64_t T : {(int64_t) 2048, (int64_t) 8192, (int64_t) 32768}) bench(T, true);
1734        return 0;
1735    }
1736    const int64_t Ts[] = {1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17, 31, 33, 257, 1000, 4099};
1737    uint64_t seed = 11;
1738    for (const int64_t T : Ts) fails += check_bits(T, seed++);
1739    for (const int64_t T : Ts) fails += check_chunked(T, seed++);
1740    for (const int64_t T : {(int64_t) 8192, (int64_t) 32768}) fails += check_chunked(T, seed++);
1741    for (const int64_t T : Ts) fails += check_tc(T, seed++);
1742    for (const int64_t T : {(int64_t) 8192, (int64_t) 32768}) fails += check_tc(T, seed++);
1743    for (const int64_t T : {(int64_t) 4099, (int64_t) 32768}) { fails += check_tc_stress(T, seed); seed += 8; }
1744    if (do_long) fails += check_tc(51820, seed++);   // the engine's longest prompt (about 7 GB of inputs and outputs)
1745    if (do_bench) {
1746        std::printf("--bench: the prompt path's DeltaNet recurrence\n");
1747        bench(2048);
1748        bench(8192);
1749        bench(32768);
1750        chunked_sweep();
1751        scale(8192);
1752        fewer_sms(8192);
1753    }
1754    std::printf("gdn_rec_parity: %d failures\n", fails);
1755    return fails ? 1 : 0;
1756}