okami.mom/strata

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

waveringanamtp: the request's hard bans (logit_bias -100) are masked out of the draft head, so a banned token is never drafted (STRATA_MTP_BAN_MASK=0: off)9a985cb12

main
93.1 KiB1875 linesraw
1// src/kernels/cuda/verify_kernels.cu - see include/strata/kernels/verify_kernels.hpp.
2//
3// The per-token arithmetic of every kernel here is transcribed from its single-token original (fused_gdn.cu,
4// elementwise.cu) with the same operation order, so a verify window reproduces plain decode bit for bit.
5#include "strata/kernels/verify_kernels.hpp"
6#include "strata/core/bw_dense_defaults.hpp"
7#include "strata/core/geometry.hpp"
8#include "strata/core/emulate.hpp"
9#include "strata/core/sm120_series.hpp"
10#define STRATA_Q81_FASTMATH_DIV 1   // #3948: the q8_1 stores divide as native_mmvq.cu (--use_fast_math) does, see q8_1_finite.hpp
11#include "strata/kernels/q8_1_finite.hpp"   // #606: q8_1_ds
12#include "strata/kernels/window_start.hpp"  // KVA: the draft layer's window floor
13#include "strata/kernels/dp4a.hpp"
14#include "strata/kernels/gfx_arch.hpp"   // #3264: the gfx12 test of the multi-block head ops
15#include "strata/kernels/pdl.hpp"
16
17#include <cuda_fp16.h>
18#include <cuda_runtime.h>
19
20#include <algorithm>
21#include <atomic>
22#include <cstdint>
23#include <cstdio>
24#include <cstdlib>
25#include <mutex>
26#include <utility>
27#include <vector>
28
29namespace strata::kernels {
30namespace {
31
32constexpr int S = 128;          // GDN state size
33static_assert(S == strata::core::kCompiledGeometry.ssm_state_size, "verify_kernels is compiled for core/geometry.hpp");
34constexpr int RG = 4;
35constexpr int RPG = S / RG;
36
37void check(const char* what) {
38    const cudaError_t e = cudaGetLastError();
39    if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(1); }
40}
41
42// `commit` (one token): the history then keeps it - [hist1, hist2, x_0], each thread its channel's, after reading them
43__device__ __forceinline__ void gdn_conv_l2_body(const int bx, const int by, float* hist, const float* __restrict__ qkv,
44                                                              const float* __restrict__ w, float* __restrict__ h,
45                                                              int C, int qk_heads, float eps, int t_begin, bool commit) {
46    __shared__ float part[S / 32];
47    const int t = t_begin + by;
48    const int c = bx * S + threadIdx.x;
49    // the window of token t: [hist0, hist1, hist2, x_0, ..., x_t], its last four entries
50    float win[3];
51#pragma unroll
52    for (int j = 0; j < 3; ++j) {
53        const int src = t + j;          // index into [hist(3) | x...]
54        win[j] = src < 3 ? hist[c * 3 + src] : qkv[(size_t) (src - 3) * C + c];
55    }
56    const float v0 = win[0], v1 = win[1], v2 = win[2], x = qkv[(size_t) t * C + c];
57    if (commit) {
58        hist[c * 3] = v1;
59        hist[c * 3 + 1] = v2;
60        hist[c * 3 + 2] = x;
61    }
62    float sum = v0 * w[c * 4] + v1 * w[c * 4 + 1] + v2 * w[c * 4 + 2] + x * w[c * 4 + 3];
63    float y = sum / (1.0f + __expf(-sum));
64    if ((int) bx < qk_heads) {
65        float sq = y * y;
66        for (int o = 16; o > 0; o >>= 1) sq += __shfl_xor_sync(0xffffffffu, sq, o);
67        if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sq;
68        __syncthreads();
69        const float ss = part[0] + part[1] + part[2] + part[3];
70        y *= rsqrtf(ss + eps);
71    }
72    h[(size_t) t * C + c] = y;
73}
74
75__global__ void __launch_bounds__(S) gdn_conv_l2_multi_kernel(float* hist, const float* __restrict__ qkv,
76                                                              const float* __restrict__ w, float* __restrict__ h,
77                                                              int C, int qk_heads, float eps, int t_begin, bool commit) {
78    gdn_conv_l2_body(blockIdx.x, blockIdx.y, hist, qkv, w, h, C, qk_heads, eps, t_begin, commit);
79}
80
81__global__ void gdn_conv_commit_kernel(float* __restrict__ hist, const float* __restrict__ qkv, int C,
82                                       const int32_t* __restrict__ n_keep) {
83    const int c = blockIdx.x * blockDim.x + threadIdx.x;
84    if (c >= C) return;
85    const int n = *n_keep;
86    if (n <= 0) return;
87    float seq[3];
88#pragma unroll
89    for (int j = 0; j < 3; ++j) {
90        const int src = n + j;          // the last three of [hist(3) | x_0..x_{n-1}]
91        seq[j] = src < 3 ? hist[c * 3 + src] : qkv[(size_t) (src - 3) * C + c];
92    }
93    hist[c * 3] = seq[0];
94    hist[c * 3 + 1] = seq[1];
95    hist[c * 3 + 2] = seq[2];
96}
97
98template <int MAX_T = kVerifyNarrowT, bool EXACT_T = false>
99__device__ __forceinline__ void gdn_ab_body(const int bx, const float* __restrict__ x, const uint16_t* __restrict__ wa,
100                                                          const uint16_t* __restrict__ wb,
101                                                          const float* __restrict__ dt,
102                                                          const float* __restrict__ ssm_a, float* __restrict__ gate,
103                                                          float* __restrict__ beta, int n, int h_v, int T, int fast = 0) {
104    const int row = bx * 2 + (threadIdx.x >> 5), lane = threadIdx.x & 31;
105    if (row >= 2 * h_v) return;
106    const bool is_beta = row >= h_v;
107    const int r = is_beta ? row - h_v : row;
108    const uint4* w4 = reinterpret_cast<const uint4*>((is_beta ? wb : wa) + (size_t) r * n);
109    float acc[MAX_T];
110#pragma unroll
111    for (int t = 0; t < MAX_T; ++t) acc[t] = 0.0f;
112    if (fast != 0 && n == 2560) {
113        // BW-DENSE (STRATA_SMALL_UNR bit 1): the same ten passes (j = lane + 32 jj, all < n / 8 = 320) with a constant trip count, so the
114        // compiler can issue the weight and activation loads of several passes before the first FMA chain; the same FMAs in the same
115        // order (pass ascending, token inside): bitwise the loop below.
116#pragma unroll
117        for (int jj = 0; jj < 10; ++jj) {
118            const int j = lane + 32 * jj;
119            const uint4 wv = __ldg(w4 + j);
120            const float w0 = __uint_as_float(wv.x << 16), w1 = __uint_as_float(wv.x & 0xffff0000u);
121            const float w2 = __uint_as_float(wv.y << 16), w3 = __uint_as_float(wv.y & 0xffff0000u);
122            const float w4f = __uint_as_float(wv.z << 16), w5 = __uint_as_float(wv.z & 0xffff0000u);
123            const float w6 = __uint_as_float(wv.w << 16), w7 = __uint_as_float(wv.w & 0xffff0000u);
124#pragma unroll
125            for (int t = 0; t < MAX_T; ++t) {
126                if (!EXACT_T && t >= T) break;
127                const float* xt = x + (size_t) t * n;
128                const float4 xa = __ldg(reinterpret_cast<const float4*>(xt + j * 8));
129                const float4 xb = __ldg(reinterpret_cast<const float4*>(xt + j * 8 + 4));
130                float a = acc[t];
131                a = fmaf(w0, xa.x, a); a = fmaf(w1, xa.y, a);
132                a = fmaf(w2, xa.z, a); a = fmaf(w3, xa.w, a);
133                a = fmaf(w4f, xb.x, a); a = fmaf(w5, xb.y, a);
134                a = fmaf(w6, xb.z, a); a = fmaf(w7, xb.w, a);
135                acc[t] = a;
136            }
137        }
138    } else
139    for (int j = lane; j < n / 8; j += 32) {
140        const uint4 wv = __ldg(w4 + j);
141        const float w0 = __uint_as_float(wv.x << 16), w1 = __uint_as_float(wv.x & 0xffff0000u);
142        const float w2 = __uint_as_float(wv.y << 16), w3 = __uint_as_float(wv.y & 0xffff0000u);
143        const float w4f = __uint_as_float(wv.z << 16), w5 = __uint_as_float(wv.z & 0xffff0000u);
144        const float w6 = __uint_as_float(wv.w << 16), w7 = __uint_as_float(wv.w & 0xffff0000u);
145#pragma unroll
146        for (int t = 0; t < MAX_T; ++t) {
147            if (!EXACT_T && t >= T) break;
148            const float* xt = x + (size_t) t * n;
149            const float4 xa = __ldg(reinterpret_cast<const float4*>(xt + j * 8));
150            const float4 xb = __ldg(reinterpret_cast<const float4*>(xt + j * 8 + 4));
151            float a = acc[t];
152            a = fmaf(w0, xa.x, a); a = fmaf(w1, xa.y, a);
153            a = fmaf(w2, xa.z, a); a = fmaf(w3, xa.w, a);
154            a = fmaf(w4f, xb.x, a); a = fmaf(w5, xb.y, a);
155            a = fmaf(w6, xb.z, a); a = fmaf(w7, xb.w, a);
156            acc[t] = a;
157        }
158    }
159#pragma unroll
160    for (int t = 0; t < MAX_T; ++t) {
161        if (!EXACT_T && t >= T) break;
162        float a = acc[t];
163#pragma unroll
164        for (int o = 16; o > 0; o >>= 1) a += __shfl_xor_sync(0xffffffffu, a, o);
165        if (lane != 0) continue;
166        if (is_beta) {
167            beta[(size_t) t * h_v + r] = 1.0f / (1.0f + __expf(-a));
168        } else {
169            const float v = a + dt[r];
170            const float sp = v > 20.0f ? v : log1pf(__expf(v));
171            gate[(size_t) t * h_v + r] = sp * ssm_a[r];
172        }
173    }
174}
175
176template <int MAX_T = kVerifyNarrowT, bool EXACT_T = false>
177__global__ void __launch_bounds__(64) gdn_ab_multi_kernel(const float* __restrict__ x, const uint16_t* __restrict__ wa,
178                                                          const uint16_t* __restrict__ wb,
179                                                          const float* __restrict__ dt,
180                                                          const float* __restrict__ ssm_a, float* __restrict__ gate,
181                                                          float* __restrict__ beta, int n, int h_v, int T, int fast) {
182    gdn_ab_body<MAX_T, EXACT_T>(blockIdx.x, x, wa, wb, dt, ssm_a, gate, beta, n, h_v, T, fast);
183}
184
185// 143-amdk (STRATA_FUSE_CONVAB): the conv + L2 norm and the a/b projections in ONE launch.  They read different inputs (the qkv
186// projection and the layer input) and write different outputs, so they only share a node: blocks [0, conv) run the conv body,
187// the following blocks (token row 0 only) the a/b body, each exactly as its own kernel.
188template <int MAX_T, bool EXACT_T>
189__global__ void __launch_bounds__(S) gdn_conv_ab_kernel(int conv_blocks, float* hist, const float* __restrict__ qkv,
190                                                        const float* __restrict__ w, float* __restrict__ h, int C, int qk_heads,
191                                                        float eps, int t_begin, bool commit, const float* __restrict__ x,
192                                                        const uint16_t* __restrict__ wa, const uint16_t* __restrict__ wb,
193                                                        const float* __restrict__ dt, const float* __restrict__ ssm_a,
194                                                        float* __restrict__ gate, float* __restrict__ beta, int n, int h_v, int T) {
195    const int ab_blocks = (2 * h_v + 1) / 2;   // the a/b blocks first: their dot chain is the longer one, so it starts with the first wave
196    if ((int) blockIdx.x >= ab_blocks) {
197        gdn_conv_l2_body((int) blockIdx.x - ab_blocks, (int) blockIdx.y, hist, qkv, w, h, C, qk_heads, eps, t_begin, commit);
198    } else if (blockIdx.y == 0 && threadIdx.x < 64) {
199        gdn_ab_body<MAX_T, EXACT_T>((int) blockIdx.x, x, wa, wb, dt, ssm_a, gate, beta, n, h_v, T);
200    }
201}
202
203// State-only commit kernel: each head's 128 independent state columns are split across 4 blocks of 32 columns
204// (48 * 4 = 192 blocks of 128 threads across all SMs, vs 48 blocks of 512 threads), with no sq/o/norm/z/y work.
205// DBG (STRATA_DBG_GDN=1, #937): a window count the launch never allowed (n_keep is read from device memory; n_max is the
206// rows the window holds) is reported and the commit skipped, where the fault would be a memory-aperture violation
207__device__ __forceinline__ void gdn_step_commit_body(float* __restrict__ state, const float* __restrict__ hbuf, int C,
208                                                     const float* __restrict__ gate, const float* __restrict__ beta,
209                                                     int h_k, int h_v, int n);
210
211template <bool DBG>
212__global__ void __launch_bounds__(32 * RG) gdn_step_commit_kernel(float* __restrict__ state,
213                                                                  const float* __restrict__ hbuf, int C,
214                                                                  const float* __restrict__ gate,
215                                                                  const float* __restrict__ beta,
216                                                                  int h_k, int h_v,
217                                                                  const int32_t* __restrict__ n_keep, int n_max) {
218    const int n = *n_keep;
219    if (n <= 0) return;
220    if (DBG && n > n_max) {
221        if (blockIdx.x == 0 && blockIdx.y == 0 && threadIdx.x == 0 && threadIdx.y == 0)
222            printf("strata DBG: gdn_step_commit: n_keep %d is past the window's %d rows: commit skipped (#937)\n", n, n_max);
223        return;
224    }
225    gdn_step_commit_body(state, hbuf, C, gate, beta, h_k, h_v, n);
226}
227
228// engine-latency: gdn_step_commit_kernel for every GDN layer of the commit in one launch (blockIdx.z = the layer); each
229// layer's blocks run gdn_step_commit_body on that layer's state and rows, exactly as its own launch did
230__global__ void __launch_bounds__(32 * RG) gdn_step_commit_layers_kernel(float* __restrict__ state, long long state_stride,
231                                                                         const float* __restrict__ hbuf, long long h_stride,
232                                                                         int C, const float* __restrict__ gate,
233                                                                         const float* __restrict__ beta, long long gb_stride,
234                                                                         int h_k, int h_v, const int32_t* __restrict__ n_keep) {
235    const int n = *n_keep;
236    if (n <= 0) return;
237    const long long z = blockIdx.z;
238    gdn_step_commit_body(state + z * state_stride, hbuf + z * h_stride, C, gate + z * gb_stride, beta + z * gb_stride, h_k,
239                         h_v, n);
240}
241
242// engine-latency: gdn_conv_commit_kernel for every GDN layer in one launch (blockIdx.y = the layer)
243__global__ void gdn_conv_commit_layers_kernel(float* __restrict__ hist0, long long hist_stride, const float* __restrict__ qkv0,
244                                              long long qkv_stride, int C, const int32_t* __restrict__ n_keep) {
245    const int c = blockIdx.x * blockDim.x + threadIdx.x;
246    if (c >= C) return;
247    const int n = *n_keep;
248    if (n <= 0) return;
249    float* hist = hist0 + (long long) blockIdx.y * hist_stride;
250    const float* qkv = qkv0 + (long long) blockIdx.y * qkv_stride;
251    float seq[3];
252#pragma unroll
253    for (int j = 0; j < 3; ++j) {
254        const int src = n + j;          // the last three of [hist(3) | x_0..x_{n-1}]
255        seq[j] = src < 3 ? hist[c * 3 + src] : qkv[(size_t) (src - 3) * C + c];
256    }
257    hist[c * 3] = seq[0];
258    hist[c * 3 + 1] = seq[1];
259    hist[c * 3 + 2] = seq[2];
260}
261
262__device__ __forceinline__ void gdn_step_commit_body(float* __restrict__ state, const float* __restrict__ hbuf, int C,
263                                                     const float* __restrict__ gate, const float* __restrict__ beta,
264                                                     int h_k, int h_v, int n) {
265    __shared__ float sk[S];
266    __shared__ float red[RG][32];
267    const int head = blockIdx.x;
268    const int col_local = threadIdx.x;
269    const int col = blockIdx.y * 32 + col_local;
270    const int rg = threadIdx.y;
271    const int tid = rg * 32 + col_local;    // 0 .. 127
272    const int qh = head % h_k;
273    const int qk = S * h_k;
274    float s[RPG];
275    float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;
276    const size_t row_stride = (size_t) h_v * S;
277#pragma unroll
278    for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride];
279    for (int t = 0; t < n; ++t) {
280        const float* ht = hbuf + (size_t) t * C;
281        __syncthreads();
282        sk[tid] = ht[qk + qh * S + tid];
283        __syncthreads();
284        const float g = __expf(gate[(size_t) t * h_v + head]);
285        float kv = 0.0f;
286#pragma unroll
287        for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv);
288        red[rg][col_local] = kv;
289        __syncthreads();
290        const float kv_col = red[0][col_local] + red[1][col_local] + red[2][col_local] + red[3][col_local];
291        const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head];
292#pragma unroll
293        for (int r = 0; r < RPG; ++r) s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta);
294    }
295#pragma unroll
296    for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r];
297}
298
299// S26 (STRATA_QFUSE=1): the q8_1 image of a 32-column block, written by the warp that holds those columns with
300// native_quantize_q8_1_kernel's quantizer (the same XOR-tree max and sum, d = amax / 127, roundf(x / d), ds = (d, sum)).
301struct GdnQ81 { half2 ds; int8_t qs[32]; };
302__device__ __forceinline__ void gdn_q8_1_store(GdnQ81* __restrict__ xq, size_t idx, float xi) {
303    // no contraction: xi is a product here, and fma(a, b, shfl) would round the first sum unlike the separate
304    // quantizer, which reads xi from memory (S26 harness: ds.sum differed by 1 ulp without this)
305#pragma clang fp contract(off)
306    float amax = fabsf(xi), sum = xi;
307#pragma unroll
308    for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
309#pragma unroll
310    for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
311    const float d = q8_1_finite(q81_div(amax, 127.0f));   // #606: as native_quantize_q8_1_kernel - finite blocks bit for bit (#3948: and its division)
312    const int8_t q = q8_1_quant(xi, d, amax);
313    xq[idx / 32].qs[idx % 32] = q;
314    if (idx % 32 == 0) xq[idx / 32].ds = q8_1_ds(d, sum);   // #606: clamped (the QFUSE path bypassed the finite helper)
315}
316
317template <bool ALL_OUT, bool Q>
318__global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __restrict__ state,
319                                                                     const float* __restrict__ hbuf, int C,
320                                                                     const float* __restrict__ gate,
321                                                                     const float* __restrict__ beta,
322                                                                     const float* __restrict__ z,
323                                                                     const float* __restrict__ gamma, float eps,
324                                                                     float* __restrict__ y, int h_k, int h_v, int T,
325                                                                     const int32_t* __restrict__ n_keep, int t_out_begin,
326                                                                     GdnQ81* __restrict__ xq, GdnGroups grp = {}) {
327    if (grp.n > 0) {   // group blockIdx.y - its slot's state and its rows of the window's buffers
328        const int gi = blockIdx.y, f = grp.first[gi];
329        state = grp.state[gi];
330        hbuf += (size_t) f * C;
331        gate += (size_t) f * h_v;
332        beta += (size_t) f * h_v;
333        z += (size_t) f * S * h_v;
334        y += (size_t) f * S * h_v;
335        T = grp.ntok[gi];
336        n_keep = grp.keep[gi];
337    }
338    __shared__ float sk[2][S], sq[2][S];
339    __shared__ float red_kv[RG][S];
340    __shared__ float red_o[RG][S];
341    __shared__ float wsum[S / 32];
342    const int head = blockIdx.x;
343    const int col = threadIdx.x;
344    const int rg = threadIdx.y;
345    const int qh = head % h_k;
346    const int qk = S * h_k;             // q at [0, qk), k at [qk, 2qk), v at [2qk, ...)
347    const int value_dim = S * h_v;
348    const int n = ALL_OUT ? T : (n_keep ? *n_keep : T);
349    if (n > 0) {
350        if (rg == 0) sk[0][col] = hbuf[qk + qh * S + col];
351        else if (rg == 1 && (ALL_OUT || 0 >= t_out_begin)) sq[0][col] = hbuf[qh * S + col];
352    }
353    const float gam = (rg == 0) ? gamma[col] : 0.0f;
354    float s[RPG];
355    float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;
356    const size_t row_stride = (size_t) h_v * S;
357#pragma unroll
358    for (int r = 0; r < RPG; ++r) s[r] = ALL_OUT ? __ldg(&base[r * row_stride]) : base[r * row_stride];
359    for (int t = 0; t < n; ++t) {
360        const int cur = t & 1, nxt = (t + 1) & 1;
361        const float* ht = hbuf + (size_t) t * C;
362        const bool need_out = ALL_OUT || (t >= t_out_begin);
363        __syncthreads();
364        if (t + 1 < n) {
365            const float* ht_next = ht + C;
366            const bool need_next = ALL_OUT || (t + 1 >= t_out_begin);
367            if (rg == 0) sk[nxt][col] = ht_next[qk + qh * S + col];
368            else if (rg == 1 && need_next) sq[nxt][col] = ht_next[qh * S + col];
369        }
370        const float g = __expf(gate[(size_t) t * h_v + head]);
371        float kv = 0.0f;
372#pragma unroll
373        for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[cur][rg * RPG + r], kv);
374        red_kv[rg][col] = kv;
375        __syncthreads();
376        const float kv_col = red_kv[0][col] + red_kv[1][col] + red_kv[2][col] + red_kv[3][col];
377        const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head];
378        if (!need_out) {
379#pragma unroll
380            for (int r = 0; r < RPG; ++r) s[r] = fmaf(g, s[r], sk[cur][rg * RPG + r] * delta);
381            continue;
382        }
383        float o = 0.0f;
384#pragma unroll
385        for (int r = 0; r < RPG; ++r) {
386            s[r] = fmaf(g, s[r], sk[cur][rg * RPG + r] * delta);
387            o = fmaf(s[r], sq[cur][rg * RPG + r], o);
388        }
389        red_o[rg][col] = o;
390        __syncthreads();
391        float oc = 0.0f, sq_part = 0.0f;
392        if (rg == 0) {
393            oc = (red_o[0][col] + red_o[1][col] + red_o[2][col] + red_o[3][col]) * rsqrtf((float) S);
394            sq_part = oc * oc;
395        }
396        // every thread takes the shuffles, as the single-token kernel does: inside the `rg == 0` branch hipcc on
397        // gfx1151 gave another rounding for 3% of the outputs (gdn_parity section 5 on Aurora)
398        for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part += __shfl_xor_sync(0xffffffffu, sq_part, o2);
399        if (rg == 0 && (col & 31) == 0) wsum[col >> 5] = sq_part;
400        __syncthreads();
401        if (rg == 0) {
402            const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
403            const float scale = rsqrtf(ss / (float) S + eps);
404            const float zz = z[(size_t) t * value_dim + head * S + col];
405            const float yv = oc * scale * gam * (1.0f / (1.0f + __expf(-zz)));
406            y[(size_t) t * value_dim + head * S + col] = yv;
407            if constexpr (Q) gdn_q8_1_store(xq, (size_t) (t - t_out_begin) * value_dim + head * S + col, yv);
408        }
409    }
410    if (!ALL_OUT && n_keep != nullptr && n > 0) {
411#pragma unroll
412        for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r];
413    }
414}
415
416// S25 (STRATA_GDN_SPLIT=1): the same recurrence with each head's 128 state columns over 4 blocks of 32 columns
417// (128 threads: the same (column, row group) threads, each with the same 32 state rows), so 4x the blocks of
418// gdn_step_norm_multi_kernel - which ran one 512-thread block per head (32 blocks) and read the 2 MB state of a layer
419// at ~60 GB/s. Every column's arithmetic is the original's; the output norm, which needs all 128 columns of a head,
420// moves to gdn_out_norm_kernel: this kernel leaves the unnormalized output `oc` in y and the second kernel sums the
421// squares by the same warps (columns 32w..32w+31, the same butterfly) in the same order.
422// S26: OUT = false (the commit, whose outputs nobody reads) drops the output reduction and its two barriers; the
423// norm kernel below has the old kernel's code shape (S x RG threads, rg 0 holding oc), which makes it bitwise equal -
424// the 128-thread version differed from the old kernel by 1 ulp in ~7% of the outputs.
425constexpr int GS_COLS = 32;
426template<bool OUT>
427__global__ void __launch_bounds__(GS_COLS * RG) gdn_step_split_kernel(float* __restrict__ state,
428                                                                      const float* __restrict__ hbuf, int C,
429                                                                      const float* __restrict__ gate,
430                                                                      const float* __restrict__ beta,
431                                                                      float* __restrict__ y, int h_k, int h_v, int T,
432                                                                      const int32_t* __restrict__ n_keep,
433                                                                      int t_out_begin) {
434    __shared__ float sk[S], sq[S];
435    __shared__ float red[RG][GS_COLS];
436    const int head = blockIdx.x;
437    const int c0 = blockIdx.y * GS_COLS;
438    const int lc = threadIdx.x;                 // local column
439    const int col = c0 + lc;
440    const int rg = threadIdx.y;
441    const int tid = rg * GS_COLS + lc;
442    const int qh = head % h_k;
443    const int qk = S * h_k;
444    const int value_dim = S * h_v;
445    const int n = n_keep ? *n_keep : T;
446    float s[RPG];
447    float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;
448    const size_t row_stride = (size_t) h_v * S;
449#pragma unroll
450    for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride];
451    for (int t = 0; t < n; ++t) {
452        const float* ht = hbuf + (size_t) t * C;
453        __syncthreads();
454        if (tid < S) { sk[tid] = ht[qk + qh * S + tid]; sq[tid] = ht[qh * S + tid]; }
455        __syncthreads();
456        const float g = __expf(gate[(size_t) t * h_v + head]);
457        float kv = 0.0f;
458#pragma unroll
459        for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv);
460        red[rg][lc] = kv;
461        __syncthreads();
462        const float kv_col = red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc];
463        const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head];
464        float o = 0.0f;
465#pragma unroll
466        for (int r = 0; r < RPG; ++r) {
467            s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta);
468            o = fmaf(s[r], sq[rg * RPG + r], o);
469        }
470        if (!OUT) continue;
471        __syncthreads();
472        red[rg][lc] = o;
473        __syncthreads();
474        if (rg == 0 && t >= t_out_begin)
475            y[(size_t) t * value_dim + head * S + col] =
476                (red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc]) * rsqrtf((float) S);
477    }
478    if (n_keep != nullptr && n > 0) {
479#pragma unroll
480        for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r];
481    }
482}
483
484
485// S26: the state-only replay (the commit) with its per-token inputs prefetched - gate, beta and the v column of every
486// row up front, the next row's k / q while the current one computes. The arithmetic and its order are
487// gdn_step_split_kernel<false>'s (gfx1151 harness: state bitwise equal; 44.5 -> 39.1 us at 1 row, 47.4 -> 40.5 at 2,
488// 53.8 -> 42.9 at 4, h_v 48). With outputs the prefetch lost (register pressure), so the window keeps the plain split.
489template<int MAXT>
490__global__ void __launch_bounds__(GS_COLS * RG) gdn_state_replay_kernel(float* __restrict__ state,
491                                                                        const float* __restrict__ hbuf, int C,
492                                                                        const float* __restrict__ gate,
493                                                                        const float* __restrict__ beta, int h_k,
494                                                                        int h_v, int T, const int32_t* __restrict__ n_keep) {
495    __shared__ float sk[S], sq[S];
496    __shared__ float red[RG][GS_COLS];
497    const int head = blockIdx.x;
498    const int c0 = blockIdx.y * GS_COLS;
499    const int lc = threadIdx.x;
500    const int col = c0 + lc;
501    const int rg = threadIdx.y;
502    const int tid = rg * GS_COLS + lc;
503    const int qh = head % h_k;
504    const int qk = S * h_k;
505    const int n = n_keep ? *n_keep : T;
506    float gv[MAXT], bv[MAXT], vv[MAXT];
507#pragma unroll
508    for (int t = 0; t < MAXT; ++t) {
509        if (t < n) {
510            gv[t] = gate[(size_t) t * h_v + head];
511            bv[t] = beta[(size_t) t * h_v + head];
512            vv[t] = hbuf[(size_t) t * C + 2 * qk + head * S + col];
513        }
514    }
515    float kn = 0.0f, qn = 0.0f;
516    if (n > 0) { kn = hbuf[qk + qh * S + tid]; qn = hbuf[qh * S + tid]; }
517    float s[RPG];
518    float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;
519    const size_t row_stride = (size_t) h_v * S;
520#pragma unroll
521    for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride];
522#pragma unroll
523    for (int t = 0; t < MAXT; ++t) {
524        if (t >= n) break;
525        __syncthreads();
526        sk[tid] = kn; sq[tid] = qn;
527        __syncthreads();
528        if (t + 1 < n) {
529            const float* hn = hbuf + (size_t) (t + 1) * C;
530            kn = hn[qk + qh * S + tid]; qn = hn[qh * S + tid];
531        }
532        const float g = __expf(gv[t]);
533        float kv = 0.0f;
534#pragma unroll
535        for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv);
536        red[rg][lc] = kv;
537        __syncthreads();
538        const float kv_col = red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc];
539        const float delta = (vv[t] - g * kv_col) * bv[t];
540        float o = 0.0f;   // unused: kept because the measured code had it (without it: 51 us instead of 39 at 1 row)
541#pragma unroll
542        for (int r = 0; r < RPG; ++r) {
543            s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta);
544            o = fmaf(s[r], sq[rg * RPG + r], o);
545        }
546        (void) o;
547    }
548    if (n_keep != nullptr && n > 0) {
549#pragma unroll
550        for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r];
551    }
552}
553// y = oc * rsqrt(mean(oc^2) + eps) * gamma * sigmoid(z) per head and token: gdn_step_norm_multi_kernel's tail with its
554// code shape (S x RG threads; rg 0 holds oc, the other row groups contribute 0 to wsum), reading oc from y
555template<bool Q>
556__global__ void __launch_bounds__(S * RG) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma,
557                                                             float eps, float* __restrict__ y, int h_v, int T,
558                                                             const int32_t* __restrict__ n_keep, int t_out_begin,
559                                                             GdnQ81* __restrict__ xq) {
560    __shared__ float wsum[S * RG / 32];
561    const int head = blockIdx.x, t = blockIdx.y + t_out_begin, col = threadIdx.x, rg = threadIdx.y;
562    const int tid = rg * S + col;
563    const int n = n_keep ? *n_keep : T;
564    if (t >= n) return;
565    const int value_dim = S * h_v;
566    float oc = 0.0f, sq_part = 0.0f;
567    if (rg == 0) {
568        oc = y[(size_t) t * value_dim + head * S + col];
569        sq_part = oc * oc;
570    }
571    for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part += __shfl_xor_sync(0xffffffffu, sq_part, o2);
572    if ((tid & 31) == 0) wsum[tid >> 5] = sq_part;
573    __syncthreads();
574    if (rg == 0) {
575        const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
576        const float scale = rsqrtf(ss / (float) S + eps);
577        const float zz = z[(size_t) t * value_dim + head * S + col];
578        if constexpr (Q) {
579            const float yv = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz)));
580            y[(size_t) t * value_dim + head * S + col] = yv;
581            gdn_q8_1_store(xq, (size_t) (t - t_out_begin) * value_dim + head * S + col, yv);
582        } else {
583            y[(size_t) t * value_dim + head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz)));
584        }
585    }
586}
587
588__global__ void embedding_gather_dev_kernel(const uint8_t* __restrict__ codes, const float* __restrict__ scales,
589                                            const float* __restrict__ offsets, const int32_t* __restrict__ tokens,
590                                            int64_t n, int code_bits, int code_bias, int group_elems,
591                                            unsigned long long row_codes, unsigned long long row_groups,
592                                            float* __restrict__ out) {
593    const int t = blockIdx.y;
594    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
595    if (i >= n) return;
596    const unsigned long long token = (unsigned long long) tokens[t];
597    const uint8_t* c = codes + token * row_codes;
598    const float* sc = scales + token * row_groups;
599    const float* of = offsets ? offsets + token * row_groups : nullptr;
600    const int per_byte = 8 / code_bits;
601    const unsigned mask = (1u << code_bits) - 1u;
602    const int code = (c[i / per_byte] >> ((i % per_byte) * code_bits)) & mask;
603    const int64_t group = i / group_elems;
604    const float product = __fmul_rn((float) (code + code_bias), sc[group]);
605    out[(size_t) t * n + i] = __fadd_rn(product, of ? of[group] : 0.0f);
606}
607
608__global__ void broadcast_streams_kernel(const float* __restrict__ x, float* __restrict__ R, int64_t n, int hc) {
609    const int t = blockIdx.y;
610    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
611    if (i >= n * hc) return;
612    R[(size_t) t * n * hc + i] = x[(size_t) t * n + i % n];
613}
614
615__global__ void hc_mean_streams_kernel(const float* __restrict__ R, float* __restrict__ out, int64_t n, int hc) {
616    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
617    if (i >= n) return;
618    float s = 0.0f;
619    for (int c = 0; c < hc; ++c) s += R[(size_t) c * n + i];
620    out[i] = s / (float) hc;
621}
622
623__global__ void route_marginal_stats_kernel(const int32_t* __restrict__ ids, int n, int k, unsigned long long* acc) {
624    const int r = threadIdx.x;
625    if (r >= n) return;
626    int fresh = 0;
627    for (int j = 0; j < k; ++j) {
628        const int32_t e = ids[r * k + j];
629        bool seen = false;
630        for (int j2 = 0; j2 < j && !seen; ++j2) seen = ids[r * k + j2] == e;
631        for (int r2 = 0; r2 < r && !seen; ++r2)
632            for (int j2 = 0; j2 < k && !seen; ++j2) seen = ids[r2 * k + j2] == e;
633        if (!seen) ++fresh;
634    }
635    atomicAdd(acc + r, (unsigned long long) fresh);
636}
637
638__global__ void copy_indexed_kernel(float* __restrict__ dst, const float* __restrict__ src, int64_t stride,
639                                    const int32_t* __restrict__ index, int64_t n) {
640    const int idx = *index;
641    if (idx < 0) return;
642    for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x)
643        dst[i] = src[(size_t) idx * stride + i];
644}
645
646__global__ void fetch_blobs_kernel(const unsigned long long* __restrict__ src, const int32_t* __restrict__ n,
647                                   uint4* __restrict__ dst, long long per, const unsigned long long* __restrict__ dst2) {
648    const long long total = (long long) *n * per;
649    long long kd = -1;
650    uint4* d = nullptr;
651    for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < total;
652         i += (long long) gridDim.x * blockDim.x) {
653        const long long k = i / per, off = i - k * per;
654        if (k != kd) {   // the blob's target, read once per blob a thread visits
655            kd = k;
656            d = dst2 != nullptr && dst2[k] != 0 ? (uint4*) dst2[k] : dst + k * per;
657        }
658        d[off] = ((const uint4*) src[k])[off];
659    }
660}
661
662__global__ void res_patch_kernel(int32_t* __restrict__ table, const volatile int32_t* pairs, int n) {
663    for (int k = blockIdx.x * blockDim.x + threadIdx.x; k < n; k += gridDim.x * blockDim.x) table[pairs[2 * k]] = pairs[2 * k + 1];
664}
665
666__global__ void rebase_ptrs_kernel(unsigned long long* ptr, const int32_t* n, unsigned long long base, long long bytes,
667                                   const unsigned long long* dst2) {
668    const int k = threadIdx.x;
669    if (k < *n) ptr[k] = dst2 != nullptr && dst2[k] != 0 ? dst2[k] : base + (unsigned long long) k * (unsigned long long) bytes;
670}
671
672__global__ void add_streams_broadcast_kernel(const float* __restrict__ h, const float* __restrict__ e,
673                                             float* __restrict__ R, int64_t n, int hc) {
674    const int t = blockIdx.y;
675    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
676    if (i >= n * hc) return;
677    R[(size_t) t * n * hc + i] = h[(size_t) t * n * hc + i] + e[(size_t) t * n + i % n];
678}
679
680__global__ void ident_hits_kernel(const int32_t* __restrict__ ids, int n, int32_t* __restrict__ slot,
681                                  int32_t* __restrict__ dst, int32_t* __restrict__ count) {
682    const int i = threadIdx.x;
683    if (i < n) { slot[i] = ids[i]; dst[i] = i; }
684    if (i == 0) *count = n;
685}
686
687// E = the widest element the row size divides into (16, 4 or 1 bytes): a Q6_K head row of 2560 values is 2100 bytes
688template<typename E>
689__global__ void gather_rows_kernel(const E* __restrict__ src, long long row_e, const int32_t* __restrict__ ids,
690                                   long long n, E* __restrict__ dst) {
691    const long long total = n * row_e;
692    for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < total; i += (long long) gridDim.x * blockDim.x) {
693        const long long r = i / row_e, o = i - r * row_e;
694        dst[i] = src[(long long) ids[r] * row_e + o];
695    }
696}
697
698__global__ void mask_cols_kernel(float* logits, int n_rows, int n, const int32_t* __restrict__ cols,
699                                 const int32_t* __restrict__ n_cols) {
700    const int k = *n_cols;
701    const long long total = (long long) k * n_rows;
702    for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < total; i += (long long) gridDim.x * blockDim.x) {
703        const long long r = i / k;
704        logits[r * n + cols[i - r * k]] = __int_as_float(0xff800000);
705    }
706}
707
708__global__ void map_ids_kernel(int32_t* ids, const int32_t* __restrict__ table, int n) {
709    const int i = threadIdx.x;
710    if (i < n) ids[i] = table[ids[i]];
711}
712
713__global__ void row_top_prob_kernel(const float* __restrict__ logits, int n_vocab, const int32_t* __restrict__ ids,
714                                    float* __restrict__ probs) {
715    __shared__ float part[32];
716    const int t = blockIdx.x;
717    const float* l = logits + (size_t) t * n_vocab;
718    const float m = l[ids[t]];
719    float s = 0.0f;
720#if defined(__HIPCC__)
721#pragma unroll 8
722#endif
723    for (int i = threadIdx.x; i < n_vocab; i += blockDim.x) s += __expf(l[i] - m);
724    for (int o = 16; o > 0; o >>= 1) s += __shfl_xor_sync(0xffffffffu, s, o);
725    if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = s;
726    __syncthreads();
727    if (threadIdx.x == 0) {
728        float tot = 0.0f;
729        for (int w = 0; w < (int) (blockDim.x >> 5); ++w) tot += part[w];
730        probs[t] = 1.0f / tot;
731    }
732}
733
734__global__ void mtp_select_kernel(const float* __restrict__ R_src, int64_t stride, const int32_t* __restrict__ ids,
735                                  const int32_t* __restrict__ row_dev, float* __restrict__ R_dst,
736                                  int32_t* __restrict__ tok_dst, int32_t* out, int j, const float* probs, float* out_p) {
737    const int row = *row_dev;
738    for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < stride; i += (int64_t) gridDim.x * blockDim.x)
739        R_dst[i] = R_src[(size_t) row * stride + i];
740    __syncthreads();
741    if (blockIdx.x == 0 && threadIdx.x == 0) {
742        const int32_t tok = ids[row];
743        *tok_dst = tok;
744        if (probs != nullptr && out_p != nullptr) ((volatile float*) out_p)[j] = probs[row];
745        __threadfence_system();
746        if (out != nullptr) ((volatile int32_t*) out)[j] = tok;
747    }
748}
749
750__global__ void dense_steps_kernel(const int32_t* __restrict__ cells, int n, int32_t* __restrict__ steps) {
751    const int i = threadIdx.x;
752    if (i >= n) return;
753    const int c = cells[i];
754    steps[i * 4 + 0] = c;
755    steps[i * 4 + 1] = c + 1;
756    steps[i * 4 + 2] = (c + 1) / 4;
757    steps[i * 4 + 3] = c + 1;
758}
759
760// --pipeline-windows: the drafter's chain, teacher forced (see force_token)
761__global__ void force_token_kernel(int32_t* tok, const int32_t* force, int j) {
762    const int32_t f = ((const volatile int32_t*) force)[j];
763    if (f >= 0) *tok = f;
764}
765
766}  // namespace
767
768void fetch_blobs(const unsigned long long* src, const int32_t* n, uint8_t* dst, int64_t blob_bytes, int cap, void* stream,
769                 const unsigned long long* dst2) {
770    if (cap <= 0) return;
771    if (blob_bytes % 16 != 0) { std::fprintf(stderr, "fetch_blobs: blob size must be a multiple of 16\n"); std::exit(1); }
772    fetch_blobs_kernel<<<48 * 8, 256, 0, (cudaStream_t) stream>>>(src, n, (uint4*) dst, (long long) (blob_bytes / 16), dst2);
773    check("fetch_blobs");
774}
775void fetch_blobs(const unsigned long long* src, const int32_t* n, uint8_t* dst, int64_t blob_bytes, int cap, void* stream) {
776    fetch_blobs(src, n, dst, blob_bytes, cap, stream, nullptr);
777}
778
779void res_patch(int32_t* table, const int32_t* pairs, int n, void* stream) {
780    if (n <= 0) return;
781    res_patch_kernel<<<(n + 255) / 256 < 64 ? (n + 255) / 256 : 64, 256, 0, (cudaStream_t) stream>>>(table, pairs, n);
782    check("res_patch");
783}
784
785void rebase_ptrs(unsigned long long* ptr, const int32_t* n, uint8_t* base, int64_t blob_bytes, void* stream,
786                 const unsigned long long* dst2) {
787    rebase_ptrs_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(ptr, n, (unsigned long long) base, (long long) blob_bytes,
788                                                             dst2);
789    check("rebase_ptrs");
790}
791void rebase_ptrs(unsigned long long* ptr, const int32_t* n, uint8_t* base, int64_t blob_bytes, void* stream) {
792    rebase_ptrs(ptr, n, base, blob_bytes, stream, nullptr);
793}
794
795void add_streams_broadcast(const float* h, const float* e, float* R, int64_t n_embd, int hc, int n_tok, void* stream) {
796    add_streams_broadcast_kernel<<<dim3((unsigned) ((n_embd * hc + 255) / 256), (unsigned) n_tok), 256, 0,
797                                   (cudaStream_t) stream>>>(h, e, R, n_embd, hc);
798    check("add_streams_broadcast");
799}
800
801void ident_hits(const int32_t* ids, int n, int32_t* slot, int32_t* dst, int32_t* count, void* stream) {
802    if (n < 1 || n > 1024) { std::fprintf(stderr, "ident_hits: n out of range\n"); std::exit(1); }
803    ident_hits_kernel<<<1, 1024, 0, (cudaStream_t) stream>>>(ids, n, slot, dst, count);
804    check("ident_hits");
805}
806
807namespace {
808__global__ void copy_row_to_first_kernel(const int32_t* __restrict__ row_dev, float* a, int64_t a_n, float* b,
809                                         int64_t b_n, float* c, int64_t c_n) {
810    const int64_t row = *row_dev;
811    if (row == 0) return;
812    const int64_t i0 = (int64_t) blockIdx.x * blockDim.x + threadIdx.x, st = (int64_t) gridDim.x * blockDim.x;
813    for (int64_t i = i0; i < a_n; i += st) a[i] = a[row * a_n + i];
814    for (int64_t i = i0; i < b_n; i += st) b[i] = b[row * b_n + i];
815    for (int64_t i = i0; i < c_n; i += st) c[i] = c[row * c_n + i];
816}
817}  // namespace
818
819void copy_row_to_first(const int32_t* row_dev, float* a, int64_t a_n, float* b, int64_t b_n, float* c, int64_t c_n,
820                       void* stream) {
821    copy_row_to_first_kernel<<<16, 256, 0, (cudaStream_t) stream>>>(row_dev, a, a_n, b, b_n, c, c_n);
822    check("copy_row_to_first");
823}
824
825void mtp_select(const float* R_src, int64_t R_stride, const int32_t* ids, const int32_t* row_dev, float* R_dst,
826                int32_t* tok_dst, int32_t* out, int j, void* stream, const float* probs, float* out_p) {
827    mtp_select_kernel<<<1, 256, 0, (cudaStream_t) stream>>>(R_src, R_stride, ids, row_dev, R_dst, tok_dst, out, j,
828                                                            probs, out_p);
829    check("mtp_select");
830}
831
832void force_token(int32_t* tok, const int32_t* force, int j, void* stream) {
833    force_token_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(tok, force, j);
834    check("force_token");
835}
836
837void gather_rows(const uint8_t* src, int64_t row_bytes, const int32_t* ids, int64_t n, uint8_t* dst, void* stream) {
838    cudaStream_t s = (cudaStream_t) stream;
839    if (row_bytes % 16 == 0)
840        gather_rows_kernel<<<48 * 8, 256, 0, s>>>((const uint4*) src, row_bytes / 16, ids, n, (uint4*) dst);
841    else if (row_bytes % 4 == 0)
842        gather_rows_kernel<<<48 * 8, 256, 0, s>>>((const uint32_t*) src, row_bytes / 4, ids, n, (uint32_t*) dst);
843    else
844        gather_rows_kernel<<<48 * 8, 256, 0, s>>>(src, row_bytes, ids, n, dst);
845    check("gather_rows");
846}
847
848void mask_cols(float* logits, int n_rows, int n, const int32_t* cols, const int32_t* n_cols, void* stream) {
849    mask_cols_kernel<<<4, 256, 0, (cudaStream_t) stream>>>(logits, n_rows, n, cols, n_cols);
850    check("mask_cols");
851}
852
853void map_ids(int32_t* ids, const int32_t* table, int n, void* stream) {
854    map_ids_kernel<<<1, 64, 0, (cudaStream_t) stream>>>(ids, table, n);
855    check("map_ids");
856}
857
858void row_top_prob(const float* logits, int n_rows, int n_vocab, const int32_t* ids, float* probs, void* stream) {
859    row_top_prob_kernel<<<n_rows, 1024, 0, (cudaStream_t) stream>>>(logits, n_vocab, ids, probs);
860    check("row_top_prob");
861}
862
863#if !defined(STRATA_HIP_GFX906)   // wave32 kernels (CUDA and RDNA HIP; wave64 gfx906 keeps the one-block kernels)
864namespace {
865
866#if defined(__HIPCC__)
867constexpr int kArgMaxBlocks = 128, kArgThreads = 256, kTopBlocks = 32;   // RDNA HIP (#3264): single-warp blocks, no block barrier
868#else
869constexpr int kArgMaxBlocks = 128, kArgThreads = 256, kTopBlocks = 8;
870#endif
871
872// the larger value, on equality the lower index: sampler_greedy_kernel's order
873__device__ __forceinline__ void arg_take(float ov, int oi, float& bv, int& bi) {
874    if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
875}
876
877// a block's (value, index) pick, in thread 0; `none` is the index of no candidate
878__device__ __forceinline__ void arg_block(float& bv, int& bi, int none) {
879    __shared__ float sv[32];
880    __shared__ int si[32];
881    for (int off = 16; off > 0; off >>= 1) {
882        const float ov = __shfl_down_sync(0xffffffffu, bv, off);
883        const int oi = __shfl_down_sync(0xffffffffu, bi, off);
884        arg_take(ov, oi, bv, bi);
885    }
886    const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31);
887    if (lane == 0) { sv[warp] = bv; si[warp] = bi; }
888    __syncthreads();
889    if (warp == 0) {
890        const int nw = (int) (blockDim.x >> 5);
891        bv = lane < nw ? sv[lane] : __int_as_float(0xff800000);
892        bi = lane < nw ? si[lane] : none;
893        for (int off = 16; off > 0; off >>= 1) {
894            const float ov = __shfl_down_sync(0xffffffffu, bv, off);
895            const int oi = __shfl_down_sync(0xffffffffu, bi, off);
896            arg_take(ov, oi, bv, bi);
897        }
898    }
899}
900
901// A row's scratch, whatever the launch's row count (one scratch serves windows of every size): its counter, then
902// the blocks' values and indices.
903struct ArgRow {
904    unsigned counter;
905    unsigned pad[3];
906    float v[kArgMaxBlocks];
907    int i[kArgMaxBlocks];
908};
909
910// grid (blocks, rows): block b scans [b * per_block, +per_block) of its row
911__global__ void argmax_rows_kernel(const float* __restrict__ logits, int n, int per_block, ArgRow* __restrict__ rows,
912                                   int32_t* out) {
913    const int row = (int) blockIdx.y, b = (int) blockIdx.x, nb = (int) gridDim.x;
914    unsigned* counter = &rows[row].counter;
915    float* pv = rows[row].v;
916    int* pi = rows[row].i;
917    const float* l = logits + (size_t) row * n;
918    const int lo = b * per_block, hi = min(n, lo + per_block);
919    float bv = __int_as_float(0xff800000);   // -inf
920    int bi = n;
921    for (int v = lo + (int) threadIdx.x; v < hi; v += (int) blockDim.x) {
922        const float s = l[v];
923        if (s > bv) { bv = s; bi = v; }
924    }
925    arg_block(bv, bi, n);
926    __shared__ bool last;
927    if (threadIdx.x == 0) {
928        pv[b] = bv;
929        pi[b] = bi;
930        __threadfence();
931        last = atomicAdd(counter, 1u) == (unsigned) (nb - 1);
932    }
933    __syncthreads();
934    if (!last) return;
935    __threadfence();
936    bv = __int_as_float(0xff800000);
937    bi = n;
938    if ((int) threadIdx.x < nb) {
939        bv = ((volatile const float*) pv)[threadIdx.x];
940        bi = ((volatile const int*) pi)[threadIdx.x];
941    }
942    arg_block(bv, bi, n);
943    if (threadIdx.x == 0) {
944        out[row] = bi < n ? bi : 0;   // no value above -inf: 0, as the one-block kernel
945        *counter = 0;
946    }
947}
948
949// a row's top-probability scratch: its counter, then its 32 warps' sums
950struct TopRow {
951    unsigned counter;
952    unsigned pad[3];
953    float parts[32];
954};
955
956// grid (kTopBlocks, rows), 1024 / kTopBlocks threads: thread j of block b is row_top_prob's thread b * blockDim + j
957__global__ void row_top_prob_split_kernel(const float* __restrict__ logits, int n_vocab, const int32_t* __restrict__ ids,
958                                          float* __restrict__ probs, TopRow* __restrict__ rows) {
959    const int row = (int) blockIdx.y;
960    float* parts = rows[row].parts;
961    const float* l = logits + (size_t) row * n_vocab;
962    const float m = l[ids[row]];
963    const int vt = (int) (blockIdx.x * blockDim.x + threadIdx.x);
964    float s = 0.0f;
965#if defined(__HIPCC__)
966#pragma unroll 8
967#endif
968    for (int i = vt; i < n_vocab; i += 1024) s += __expf(l[i] - m);
969    for (int o = 16; o > 0; o >>= 1) s += __shfl_xor_sync(0xffffffffu, s, o);
970    if ((threadIdx.x & 31) == 0) parts[vt >> 5] = s;
971    __threadfence();
972    if (blockDim.x > 32) __syncthreads();
973    if (threadIdx.x != 0) return;
974    if (atomicAdd(&rows[row].counter, 1u) != (unsigned) (gridDim.x - 1)) return;
975    __threadfence();
976    float tot = 0.0f;
977    for (int w = 0; w < 32; ++w) tot += ((volatile const float*) parts)[w];
978    probs[row] = 1.0f / tot;
979    rows[row].counter = 0;
980}
981
982}  // namespace
983
984uint64_t argmax_rows_scratch_bytes(int n_rows) { return (uint64_t) n_rows * sizeof(ArgRow); }
985
986void argmax_rows(const float* logits, int n_rows, int n, void* scratch, int32_t* out, void* stream) {
987    if (n_rows <= 0) return;
988    const int nb = std::min(kArgMaxBlocks, std::max(1, (n + 4095) / 4096));
989    const int per_block = (n + nb - 1) / nb;
990    argmax_rows_kernel<<<dim3((unsigned) nb, (unsigned) n_rows), kArgThreads, 0, (cudaStream_t) stream>>>(
991        logits, n, per_block, (ArgRow*) scratch, out);
992    check("argmax_rows");
993}
994
995uint64_t row_top_prob_scratch_bytes(int n_rows) { return (uint64_t) n_rows * sizeof(TopRow); }
996
997void row_top_prob_split(const float* logits, int n_rows, int n_vocab, const int32_t* ids, float* probs, void* scratch,
998                        void* stream) {
999    if (n_rows <= 0) return;
1000    row_top_prob_split_kernel<<<dim3(kTopBlocks, (unsigned) n_rows), 1024 / kTopBlocks, 0, (cudaStream_t) stream>>>(
1001        logits, n_vocab, ids, probs, (TopRow*) scratch);
1002    check("row_top_prob_split");
1003}
1004#else
1005uint64_t argmax_rows_scratch_bytes(int) { return 0; }
1006void argmax_rows(const float*, int, int, void*, int32_t*, void*) {
1007    std::fprintf(stderr, "argmax_rows: not built for this backend\n");
1008    std::exit(1);
1009}
1010uint64_t row_top_prob_scratch_bytes(int) { return 0; }
1011void row_top_prob_split(const float* logits, int n_rows, int n_vocab, const int32_t* ids, float* probs, void*,
1012                        void* stream) {
1013    row_top_prob(logits, n_rows, n_vocab, ids, probs, stream);
1014}
1015#endif
1016
1017namespace {
1018// grid (kNonfiniteBlocks, rows): block b of row t scans [b * per_block, +per_block) and writes its own word.  The
1019// test is on the bits (exponent all ones), so --use_fast_math cannot fold it away.
1020__global__ void logits_nonfinite_kernel(const float* __restrict__ logits, int n, int per_block, uint32_t* flags) {
1021    const int row = (int) blockIdx.y, b = (int) blockIdx.x;
1022    const float* l = logits + (size_t) row * n;
1023    const int lo = b * per_block, hi = min(n, lo + per_block);
1024    int bad = 0;
1025    for (int v = lo + (int) threadIdx.x; v < hi; v += (int) blockDim.x)
1026        bad |= (__float_as_uint(l[v]) & 0x7f800000u) == 0x7f800000u;
1027    bad = __syncthreads_or(bad);
1028    if (threadIdx.x == 0) flags[row * kNonfiniteBlocks + b] = bad ? 1u : 0u;
1029}
1030}  // namespace
1031
1032void logits_nonfinite_rows(const float* logits, int n_rows, int n, uint32_t* flags, void* stream) {
1033    if (n_rows <= 0 || n <= 0) return;
1034    const int per_block = (n + kNonfiniteBlocks - 1) / kNonfiniteBlocks;
1035    logits_nonfinite_kernel<<<dim3((unsigned) kNonfiniteBlocks, (unsigned) n_rows), 256, 0, (cudaStream_t) stream>>>(
1036        logits, n, per_block, flags);
1037    check("logits_nonfinite_rows");
1038}
1039
1040bool multi_block_head_ops() {
1041#if defined(STRATA_HIP_GFX906)
1042    return false;
1043#else
1044    static const int env = [] {
1045        const char* v = std::getenv("STRATA_MULTI_BLOCK_ARGMAX");
1046        return v != nullptr ? (std::atoi(v) != 0 ? 1 : 0) : -1;
1047    }();
1048    if (env == 0) return false;
1049#if defined(__HIPCC__)
1050    static int arch[64] = {};   // 0 unknown, 1 gfx12 (RDNA4: the only HIP target #3264 was run on), 2 other
1051    int dev = 0;
1052    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false;
1053    if (arch[dev] == 0) {
1054        cudaDeviceProp p{};
1055        arch[dev] = (cudaGetDeviceProperties(&p, dev) == cudaSuccess && strata::kernels::gfx_arch_is_gfx12(p.gcnArchName)) ? 1 : 2;
1056    }
1057    return arch[dev] == 1;
1058#else
1059    return true;
1060#endif
1061#endif
1062}
1063
1064bool argmax_rows_wanted() {
1065#if defined(STRATA_HIP_GFX906)
1066    return false;
1067#else
1068    static const int env = [] {
1069        const char* v = std::getenv("STRATA_ARGMAX_ROWS");
1070        return v != nullptr ? (std::atoi(v) != 0 ? 1 : 0) : -1;
1071    }();
1072    if (env >= 0) return env != 0 && multi_block_head_ops();
1073#if defined(__HIPCC__)
1074    static int arch[64] = {};   // 0 unknown, 1 gfx12 (RDNA4), 2 other
1075    int dev = 0;
1076    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false;
1077    if (arch[dev] == 0) {
1078        cudaDeviceProp p{};
1079        arch[dev] = (cudaGetDeviceProperties(&p, dev) == cudaSuccess && strata::kernels::gfx_arch_is_gfx12(p.gcnArchName)) ? 1 : 2;
1080    }
1081    return arch[dev] == 1 && multi_block_head_ops();
1082#else
1083    // sm_80 to sm_89, and sm_7x with STRATA_ARGMAX_ROWS_SM70=1: sample_tokens' greedy pick there is the one-block kernel (sm_90+ has the cluster kernel)
1084    static const bool want = [] {
1085        int dev = 0, major = 0;
1086        if (cudaGetDevice(&dev) != cudaSuccess || cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess)
1087            return false;
1088        if (major == 7) {   // STRATA_ARGMAX_ROWS_SM70=1: opt-in on Volta (measured on sm_70 only)
1089            const char* e = std::getenv("STRATA_ARGMAX_ROWS_SM70");
1090            return e != nullptr && std::atoi(e) != 0;
1091        }
1092        return major == 8;
1093    }();
1094    return want && multi_block_head_ops();
1095#endif
1096#endif
1097}
1098
1099namespace {
1100__global__ void window_ids_kernel(int32_t* steps, int window, int32_t* ids, long long stride) {
1101    const int q = blockIdx.y;
1102    int32_t* st = steps + q * 4;
1103    const int n_kv = st[1];
1104    const int start = n_kv > window ? n_kv - window : 0;
1105    const int width = n_kv - start;
1106    for (int j = blockIdx.x * blockDim.x + threadIdx.x; j < width; j += gridDim.x * blockDim.x)
1107        ids[q * stride + j] = start + j;
1108    __syncthreads();
1109    if (blockIdx.x == 0 && threadIdx.x == 0) st[3] = width;
1110}
1111}  // namespace
1112
1113void window_ids(int32_t* steps, int n, int window, int32_t* ids, int64_t ids_stride, void* stream) {
1114    window_ids_kernel<<<dim3(8, (unsigned) n), 256, 0, (cudaStream_t) stream>>>(steps, window, ids, (long long) ids_stride);
1115    check("window_ids");
1116}
1117
1118namespace {
1119// window_ids with a floor read from (mapped) memory when the kernel RUNS: the captured graph keeps the pointer, the
1120// value changes between sessions.  A floor of 0 gives window_ids' selection exactly (strata::kernels::window_start).
1121__global__ void window_ids_floor_kernel(int32_t* steps, int window, int32_t* ids, long long stride,
1122                                        const volatile int32_t* floor_cell) {
1123    const int q = blockIdx.y;
1124    int32_t* st = steps + q * 4;
1125    const int n_kv = st[1];
1126    const int start = strata::kernels::window_start(n_kv, window, *floor_cell);
1127    const int width = n_kv - start;
1128    for (int j = blockIdx.x * blockDim.x + threadIdx.x; j < width; j += gridDim.x * blockDim.x)
1129        ids[q * stride + j] = start + j;
1130    __syncthreads();
1131    if (blockIdx.x == 0 && threadIdx.x == 0) st[3] = width;
1132}
1133}  // namespace
1134
1135void window_ids_floor(int32_t* steps, int n, int window, int32_t* ids, int64_t ids_stride, const int32_t* floor_cell,
1136                      void* stream) {
1137    window_ids_floor_kernel<<<dim3(8, (unsigned) n), 256, 0, (cudaStream_t) stream>>>(steps, window, ids, (long long) ids_stride,
1138                                                                                    floor_cell);
1139    check("window_ids_floor");
1140}
1141
1142void dense_steps(const int32_t* cells, int n, int32_t* steps, void* stream) {
1143    dense_steps_kernel<<<1, 64, 0, (cudaStream_t) stream>>>(cells, n, steps);
1144    check("dense_steps");
1145}
1146
1147void gdn_conv_l2_multi(const float* history, const float* qkv, const float* conv_w, float* h, int channels,
1148                       int qk_heads, float eps, int n_tok, void* stream, int t_begin, bool commit) {
1149    if (!history || !qkv || !conv_w || !h || channels % S != 0 || n_tok < 1 || n_tok > kVerifyMaxT ||
1150        (commit && (n_tok != 1 || t_begin != 0))) {
1151        std::fprintf(stderr, "gdn_conv_l2_multi: invalid arguments\n");
1152        std::exit(1);
1153    }
1154    gdn_conv_l2_multi_kernel<<<dim3((unsigned) (channels / S), (unsigned) n_tok), S, 0, (cudaStream_t) stream>>>(
1155        const_cast<float*>(history), qkv, conv_w, h, channels, qk_heads, eps, t_begin, commit);
1156    check("gdn_conv_l2_multi");
1157}
1158
1159void gdn_conv_ab_multi(const float* history, const float* qkv, const float* conv_w, float* h, int channels, int qk_heads,
1160                       float eps, int n_tok, int t_begin, bool commit, const float* x, const uint16_t* w_alpha,
1161                       const uint16_t* w_beta, const float* dt, const float* ssm_a, float* gate, float* beta, int n_embd,
1162                       int h_v, void* stream) {
1163    if (!history || !qkv || !conv_w || !h || channels % S != 0 || n_tok < 1 || n_tok > kVerifyMaxT || n_embd % 8 != 0 ||
1164        (commit && (n_tok != 1 || t_begin != 0))) {
1165        std::fprintf(stderr, "gdn_conv_ab_multi: invalid arguments\n");
1166        std::exit(1);
1167    }
1168    const int conv_blocks = channels / S, ab_blocks = (2 * h_v + 1) / 2;
1169    const dim3 grid((unsigned) (conv_blocks + ab_blocks), (unsigned) n_tok);
1170    cudaStream_t st = (cudaStream_t) stream;
1171    float* hist = const_cast<float*>(history);
1172    switch (n_tok) {
1173        case 1: gdn_conv_ab_kernel<1, true><<<grid, S, 0, st>>>(conv_blocks, hist, qkv, conv_w, h, channels, qk_heads, eps, t_begin, commit, x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok); break;
1174        case 2: gdn_conv_ab_kernel<2, true><<<grid, S, 0, st>>>(conv_blocks, hist, qkv, conv_w, h, channels, qk_heads, eps, t_begin, commit, x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok); break;
1175        case 3: gdn_conv_ab_kernel<3, true><<<grid, S, 0, st>>>(conv_blocks, hist, qkv, conv_w, h, channels, qk_heads, eps, t_begin, commit, x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok); break;
1176        case 4: gdn_conv_ab_kernel<4, true><<<grid, S, 0, st>>>(conv_blocks, hist, qkv, conv_w, h, channels, qk_heads, eps, t_begin, commit, x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok); break;
1177        case 5: gdn_conv_ab_kernel<5, true><<<grid, S, 0, st>>>(conv_blocks, hist, qkv, conv_w, h, channels, qk_heads, eps, t_begin, commit, x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok); break;
1178        case 6: gdn_conv_ab_kernel<6, true><<<grid, S, 0, st>>>(conv_blocks, hist, qkv, conv_w, h, channels, qk_heads, eps, t_begin, commit, x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok); break;
1179        case 7: case 8: gdn_conv_ab_kernel<kVerifyNarrowT, false><<<grid, S, 0, st>>>(conv_blocks, hist, qkv, conv_w, h, channels, qk_heads, eps, t_begin, commit, x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok); break;
1180        default: gdn_conv_ab_kernel<kVerifyMaxT, false><<<grid, S, 0, st>>>(conv_blocks, hist, qkv, conv_w, h, channels, qk_heads, eps, t_begin, commit, x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok); break;
1181    }
1182    check("gdn_conv_ab_multi");
1183}
1184
1185void gdn_conv_commit(float* history, const float* qkv, int channels, const int32_t* n_keep, void* stream) {
1186    gdn_conv_commit_kernel<<<(unsigned) ((channels + 255) / 256), 256, 0, (cudaStream_t) stream>>>(history, qkv,
1187                                                                                                 channels, n_keep);
1188    check("gdn_conv_commit");
1189}
1190
1191bool gdn_commit_layers(float* state, int64_t state_stride, int64_t conv_off, const float* qkv, int64_t qkv_stride,
1192                       const float* h, int64_t h_stride, const float* gate, const float* beta, int64_t gb_stride,
1193                       int conv_channels, int h_k, int h_v, int n_max, int n_layers, const int32_t* n_keep, void* stream) {
1194    // the per-layer commit's kernel choice (gdn_step_norm_multi below): only its state-only kernel is batched here
1195    static const bool per_layer = [] {
1196        const char* sp = std::getenv("STRATA_GDN_SPLIT");
1197        const char* cs = std::getenv("STRATA_GDN_COMMIT_SPLIT");
1198        const char* dbg = std::getenv("STRATA_DBG_GDN");
1199        return (sp && sp[0] == '1') || (cs && cs[0] == '0') || (dbg && dbg[0] == '1');
1200    }();
1201    // n_max: the window's rows (kVerifyLongT with --lookup-max-t; both kernels loop over the kept rows, no per-row arrays)
1202    if (per_layer || n_layers <= 0 || n_layers > 65535 || n_max < 1 || n_max > kVerifyLongT || n_keep == nullptr ||
1203        h_v <= 0 || h_k <= 0 || h_v % h_k != 0)
1204        return false;
1205    cudaStream_t st = (cudaStream_t) stream;
1206    gdn_conv_commit_layers_kernel<<<dim3((unsigned) ((conv_channels + 255) / 256), (unsigned) n_layers), 256, 0, st>>>(
1207        state + conv_off, (long long) state_stride, qkv, (long long) qkv_stride, conv_channels, n_keep);
1208    gdn_step_commit_layers_kernel<<<dim3((unsigned) h_v, 4u, (unsigned) n_layers), dim3(32, RG), 0, st>>>(
1209        state, (long long) state_stride, h, (long long) h_stride, conv_channels, gate, beta, (long long) gb_stride, h_k, h_v,
1210        n_keep);
1211    check("gdn_commit_layers");
1212    return true;
1213}
1214
1215// BW-DENSE STRATA_SMALL_UNR bit 1: see gdn_ab_body (bw_dense_defaults.hpp: on for a 12.0 card, else off; the variable wins)
1216static int gdn_ab_fast() {
1217    static int per_dev[64];   // 0 unknown, else bit + 1
1218    const char* e = std::getenv("STRATA_SMALL_UNR");
1219    if (e != nullptr) return (std::atoi(e) >> 1) & 1;
1220#if defined(__HIPCC__)
1221    return 0;
1222#else
1223    int dev = 0;
1224    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return 0; }
1225    if (!per_dev[dev]) {
1226        int ma = 0, mi = 0;
1227        const bool ok = cudaDeviceGetAttribute(&ma, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
1228                        cudaDeviceGetAttribute(&mi, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess;
1229        if (!ok) cudaGetLastError();
1230        per_dev[dev] = 1 + (ok ? ((strata::small_unr_default(ma, mi) >> 1) & 1) : 0);
1231    }
1232    return per_dev[dev] - 1;
1233#endif
1234}
1235void gdn_ab_multi(const float* x, const uint16_t* w_alpha, const uint16_t* w_beta, const float* dt, const float* ssm_a,
1236                  float* gate, float* beta, int n_embd, int h_v, int n_tok, void* stream) {
1237    if (n_embd % 8 != 0 || n_tok < 1 || n_tok > kVerifyMaxT) {
1238        std::fprintf(stderr, "gdn_ab_multi: invalid arguments\n");
1239        std::exit(1);
1240    }
1241    const unsigned blocks = (unsigned) ((2 * h_v + 1) / 2);
1242    cudaStream_t st = (cudaStream_t) stream;
1243    switch (n_tok) {
1244        case 1: gdn_ab_multi_kernel<1, true><<<blocks, 64, 0, st>>>(x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok, gdn_ab_fast()); break;
1245        case 2: gdn_ab_multi_kernel<2, true><<<blocks, 64, 0, st>>>(x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok, gdn_ab_fast()); break;
1246        case 3: gdn_ab_multi_kernel<3, true><<<blocks, 64, 0, st>>>(x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok, gdn_ab_fast()); break;
1247        case 4: gdn_ab_multi_kernel<4, true><<<blocks, 64, 0, st>>>(x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok, gdn_ab_fast()); break;
1248        case 5: gdn_ab_multi_kernel<5, true><<<blocks, 64, 0, st>>>(x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok, gdn_ab_fast()); break;
1249        case 6: gdn_ab_multi_kernel<6, true><<<blocks, 64, 0, st>>>(x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok, gdn_ab_fast()); break;
1250        case 7: case 8: gdn_ab_multi_kernel<kVerifyNarrowT, false><<<blocks, 64, 0, st>>>(x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok, gdn_ab_fast()); break;
1251        default: gdn_ab_multi_kernel<kVerifyMaxT, false><<<blocks, 64, 0, st>>>(x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok, gdn_ab_fast()); break;
1252    }
1253    check("gdn_ab_multi");
1254}
1255
1256void gdn_step_norm_groups(const GdnGroups& groups, const float* h, int conv_channels, const float* gate, const float* beta,
1257                          const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, bool commit,
1258                          void* stream) {
1259    if (groups.n < 1 || groups.n > 8 || !h || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v % h_k) {
1260        std::fprintf(stderr, "gdn_step_norm_groups: invalid arguments\n");
1261        std::exit(1);
1262    }
1263    for (int i = 0; i < groups.n; ++i)
1264        if (!groups.state[i] || groups.ntok[i] < 1 || groups.ntok[i] > kVerifyMaxT || (commit && !groups.keep[i])) {
1265            std::fprintf(stderr, "gdn_step_norm_groups: invalid group %d\n", i);
1266            std::exit(1);
1267        }
1268    const dim3 g1((unsigned) h_v, (unsigned) groups.n), b1(S, RG);
1269    // the kernel gdn_step_norm_multi picks for these calls: a window's rows (all outputs, no keep) or a commit of
1270    // one-row groups (keep, t_out_begin 0)
1271    if (commit)
1272        gdn_step_norm_multi_kernel<false, false><<<g1, b1, 0, (cudaStream_t) stream>>>(
1273            nullptr, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, 0, nullptr, 0, nullptr, groups);
1274    else
1275        gdn_step_norm_multi_kernel<true, false><<<g1, b1, 0, (cudaStream_t) stream>>>(
1276            nullptr, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, 0, nullptr, 0, nullptr, groups);
1277    check("gdn_step_norm_groups");
1278}
1279
1280void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta,
1281                         const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok,
1282                         const int32_t* n_keep, void* stream, int t_out_begin, void* xq_out) {
1283    GdnQ81* const xq = static_cast<GdnQ81*>(xq_out);   // S26: non-null = also the outputs' q8_1 (STRATA_QFUSE)
1284    // n_tok: up to kVerifyLongT (a long window's second token group replays the state from its first token); the
1285    // default kernels loop over the tokens, the STRATA_GDN_SPLIT ones hold kVerifyMaxT per thread
1286    static const bool split = [] { const char* v = std::getenv("STRATA_GDN_SPLIT"); return v && v[0] == '1'; }();
1287    if (!state || !h || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v % h_k || n_tok < 1 ||
1288        n_tok > (split ? kVerifyMaxT : kVerifyLongT)) {
1289        std::fprintf(stderr, "gdn_step_norm_multi: invalid arguments\n");
1290        std::exit(1);
1291    }
1292    // S26: the split runs where it is faster (gfx1151 harness, h_v 48: the commit 8-19% per call; a window of 2+ rows
1293    // 3-13%; one row: no gain, the old kernel stays) - bitwise equal in every case
1294    if (split && (t_out_begin >= n_tok || n_tok - t_out_begin >= 2)) {
1295        const dim3 grid((unsigned) h_v, S / GS_COLS), block(GS_COLS, RG);
1296        if (t_out_begin >= n_tok) {   // no outputs (the commit): the state only
1297            if (n_tok > kVerifyNarrowT)
1298                gdn_state_replay_kernel<kVerifyMaxT><<<grid, block, 0, (cudaStream_t) stream>>>(
1299                    state, h, conv_channels, gate, beta, h_k, h_v, n_tok, n_keep);
1300            else
1301                gdn_state_replay_kernel<kVerifyNarrowT><<<grid, block, 0, (cudaStream_t) stream>>>(
1302                    state, h, conv_channels, gate, beta, h_k, h_v, n_tok, n_keep);
1303        } else {
1304            gdn_step_split_kernel<true><<<grid, block, 0, (cudaStream_t) stream>>>(
1305                state, h, conv_channels, gate, beta, y, h_k, h_v, n_tok, n_keep, t_out_begin);
1306            const dim3 ng((unsigned) h_v, (unsigned) (n_tok - t_out_begin));
1307            if (xq) gdn_out_norm_kernel<true><<<ng, dim3(S, RG), 0, (cudaStream_t) stream>>>(z, gamma, eps, y, h_v, n_tok, n_keep, t_out_begin, xq);
1308            else gdn_out_norm_kernel<false><<<ng, dim3(S, RG), 0, (cudaStream_t) stream>>>(z, gamma, eps, y, h_v, n_tok, n_keep, t_out_begin, nullptr);
1309        }
1310        check("gdn_step_norm_multi (split)");
1311        return;
1312    }
1313    static const bool commit_split = [] {
1314        const char* e = std::getenv("STRATA_GDN_COMMIT_SPLIT");
1315        return !e || e[0] != '0';
1316    }();
1317    if (commit_split && n_keep != nullptr && t_out_begin >= n_tok) {
1318        static const bool dbg = [] { const char* e = std::getenv("STRATA_DBG_GDN"); return e && e[0] == '1'; }();
1319        if (dbg) gdn_step_commit_kernel<true><<<dim3((unsigned) h_v, 4u), dim3(32, RG), 0, (cudaStream_t) stream>>>(
1320            state, h, conv_channels, gate, beta, h_k, h_v, n_keep, n_tok);
1321        else gdn_step_commit_kernel<false><<<dim3((unsigned) h_v, 4u), dim3(32, RG), 0, (cudaStream_t) stream>>>(
1322            state, h, conv_channels, gate, beta, h_k, h_v, n_keep, n_tok);
1323        check("gdn_step_commit");
1324        return;
1325    }
1326    const dim3 g1((unsigned) h_v), b1(S, RG);
1327    const bool all_out = n_keep == nullptr && t_out_begin <= 0;
1328    if (xq && t_out_begin < n_tok) {
1329        if (all_out) gdn_step_norm_multi_kernel<true, true><<<g1, b1, 0, (cudaStream_t) stream>>>(
1330            state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, nullptr, 0, xq);
1331        else gdn_step_norm_multi_kernel<false, true><<<g1, b1, 0, (cudaStream_t) stream>>>(
1332            state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, n_keep, t_out_begin, xq);
1333    } else if (all_out) {
1334        gdn_step_norm_multi_kernel<true, false><<<g1, b1, 0, (cudaStream_t) stream>>>(
1335            state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, nullptr, 0, nullptr);
1336    } else {
1337        gdn_step_norm_multi_kernel<false, false><<<g1, b1, 0, (cudaStream_t) stream>>>(
1338            state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, n_keep, t_out_begin, nullptr);
1339    }
1340    check("gdn_step_norm_multi");
1341}
1342
1343namespace {
1344__global__ void wait_flag_ge_kernel(const volatile uint32_t* flag, uint32_t value) {
1345    while (*flag < value) strata_spin_pause();
1346    __threadfence_system();
1347}
1348
1349// the GPU's clock in ns (the same sources as gpu_stamp_kernel)
1350__device__ __forceinline__ unsigned long long strata_now_ns() {
1351    unsigned long long t;
1352#if defined(STRATA_HIP_GFX906)
1353    t = wall_clock64() * 40ull;
1354#elif defined(__HIPCC__)
1355    t = wall_clock64() * 10ull;
1356#else
1357    asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t));
1358#endif
1359    return t;
1360}
1361
1362// the overlapped split's hand-off wait, bounded: spin until *flag >= value, or give up after timeout_ns (0: never),
1363// marking *err = 1 (mapped) so the host fails the window instead of using a stale hand-off.  The window's later
1364// kernels still run (on whatever the hand-off buffer holds) so the graph completes and no stream is left hanging.
1365__global__ void wait_handoff_kernel(const volatile uint32_t* flag, uint32_t value, uint32_t* err,
1366                                    unsigned long long timeout_ns) {
1367    const unsigned long long t0 = timeout_ns ? strata_now_ns() : 0ull;
1368    while (*flag < value) {
1369        strata_spin_pause();
1370        if (timeout_ns && strata_now_ns() - t0 > timeout_ns) {
1371            *(volatile uint32_t*) err = 1u;
1372            __threadfence_system();
1373            return;
1374        }
1375    }
1376    __threadfence_system();
1377}
1378
1379__global__ void handoff_publish_kernel(float* dst, const float* __restrict__ a, int64_t na, const float* __restrict__ b,
1380                                       int64_t nb, const float* __restrict__ c, int64_t nc, uint32_t* counter,
1381                                       uint32_t* flag, const volatile uint32_t* drop) {
1382    const int64_t n = na + nb + nc;
1383    volatile float* const out = dst;
1384    for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x)
1385        out[i] = i < na ? a[i] : i < na + nb ? b[i - na] : c[i - na - nb];
1386    __threadfence_system();   // this thread's stores reach host memory before the block counts itself done
1387    __syncthreads();
1388    if (threadIdx.x == 0) {
1389        const uint32_t prev = atomicAdd(counter, 1u);
1390        if (prev == gridDim.x - 1) {   // every block's payload is out: raise the next stage's flag
1391            *(volatile uint32_t*) counter = 0u;
1392            __threadfence_system();
1393            if (drop == nullptr || *drop == 0u) {   // test hook (STRATA_TEST_HANDOFF_DROP): a lost publish
1394                *(volatile uint32_t*) flag = 1u;
1395                __threadfence_system();
1396            }
1397        }
1398    }
1399}
1400
1401// wait_flag_ge, with the GPU's clock as it arrives (t_in) and as it leaves (t_out), either may be null
1402__global__ void wait_flag_ge_stamped_kernel(const volatile uint32_t* flag, uint32_t value, volatile unsigned long long* t_in,
1403                                            volatile unsigned long long* t_out) {
1404    if (t_in != nullptr) *t_in = strata_now_ns();
1405    while (*flag < value) strata_spin_pause();
1406    __threadfence_system();
1407    if (t_out != nullptr) *t_out = strata_now_ns();
1408}
1409}  // namespace
1410
1411void wait_handoff(const uint32_t* flag, uint32_t value, uint32_t* err, unsigned long long timeout_ns, void* stream) {
1412    wait_handoff_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(flag, value, err, timeout_ns);
1413    check("wait_handoff");
1414}
1415
1416void handoff_publish(float* dst, const float* a, int64_t na, const float* b, int64_t nb, const float* c, int64_t nc,
1417                     uint32_t* counter, uint32_t* flag, void* stream, const uint32_t* drop) {
1418    const int64_t n = na + nb + nc;
1419    if (n <= 0 || dst == nullptr || counter == nullptr || flag == nullptr) {
1420        std::fprintf(stderr, "handoff_publish: invalid arguments\n");
1421        std::exit(1);
1422    }
1423    const int64_t nb256 = (n + 255) / 256;
1424    const int blocks = (int) (nb256 < 64 ? nb256 : 64);
1425    handoff_publish_kernel<<<blocks, 256, 0, (cudaStream_t) stream>>>(dst, a, na, b, nb, c, nc, counter, flag, drop);
1426    check("handoff_publish");
1427}
1428
1429namespace {
1430// one thread per window entry: up to kVerifyNarrowT tokens x 10 routed experts (80), so 128 (#646 had 64: a window of
1431// 7+ tokens lost its last entries).  A window of 9..16 rows (up to 160 entries) runs the same kernel on 256 threads;
1432// one block size per window class, so a narrow window launches exactly the 128-thread kernel it always did.
1433constexpr int kResidentPlanNarrow = 128;
1434constexpr int kResidentPlanMax = kVerifyMaxT > kVerifyNarrowT ? 256 : kResidentPlanNarrow;
1435static_assert(kVerifyNarrowT * 10 <= kResidentPlanNarrow, "resident_plan: one thread per entry");
1436static_assert(kVerifyMaxT * 10 <= kResidentPlanMax, "resident_plan: one thread per entry");
1437// the parallel scan keeps one partial sum per warp in s_wsum[NT / 32] and packs (entries << 16 | groups) in an int
1438static_assert(kResidentPlanMax <= 256 && kResidentPlanMax % 32 == 0, "resident_plan: at most 8 warps");
1439static_assert(kResidentPlanMax < 32768, "resident_plan: the packed entry count must stay below 2^15");
1440template <int NT>
1441__global__ void __launch_bounds__(NT) resident_plan_kernel(const int32_t* __restrict__ ids, int n, int k, const int32_t* __restrict__ res,
1442                                     int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off,
1443                                     long long blob, int32_t* __restrict__ pl, long long capx, uint32_t* skip,
1444                                     uint32_t ring, volatile uint32_t* plan_err) {
1445    constexpr int NW = NT / 32;
1446    __shared__ int32_t s_ids[NT];
1447    __shared__ int32_t s_excl[NT];
1448    __shared__ int32_t s_wsum[NW];
1449    __shared__ int s_bad;
1450    const int tid = threadIdx.x;
1451    if (tid == 0) s_bad = 0;
1452    __syncthreads();
1453
1454    int32_t eid = -1;
1455    int32_t slot = -1;
1456    if (tid < n) {
1457        eid = ids[tid];
1458        s_ids[tid] = eid;
1459        slot = (eid >= 0 && eid < n_expert) ? res[eid] : -1;
1460        if (slot < 0) atomicOr(&s_bad, 1);
1461    }
1462    __syncthreads();
1463    if (s_bad) {
1464        if (tid == 0 && skip != nullptr) *skip = 0;
1465        if (tid == 0 && skip == nullptr) {   // #871: the all-resident graph has no host plan to fall back on
1466            pl[0] = 0; pl[1] = 0; pl[2] = 0;   // an empty plan: no expert runs on a stale pointer
1467            if (plan_err != nullptr) { *plan_err = 1; __threadfence_system(); }
1468        }
1469        return;
1470    }
1471
1472    int first_j = tid;
1473    int rank_in_group = 0;
1474    int count_same = 0;
1475    if (tid < n) {
1476        for (int j = 0; j < n; ++j) {
1477            if (s_ids[j] == eid) {
1478                if (j < first_j) first_j = j;
1479                if (j < tid) ++rank_in_group;
1480                ++count_same;
1481            }
1482        }
1483    }
1484    const bool is_first = (tid < n && first_j == tid && slot >= 0);
1485    const int my_cnt = is_first ? count_same : 0;
1486    const int my_pack = (my_cnt << 16) | (is_first ? 1 : 0);
1487    const int lane = tid & 31;
1488    const int warp = tid >> 5;
1489    int pref = my_pack;
1490#pragma unroll
1491    for (int d = 1; d < 32; d <<= 1) {
1492        const int up = __shfl_up_sync(0xffffffffu, pref, d);
1493        if (lane >= d) pref += up;
1494    }
1495    s_excl[tid] = pref - my_pack;
1496    if (lane == 31) {
1497        s_wsum[warp] = pref;
1498    }
1499    __syncthreads();
1500
1501    int32_t* counts = pl;
1502    int32_t* start = pl + 4;
1503    int32_t* dst = start + capx + 1;
1504    int32_t* tok = dst + capx;
1505    const long long ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll;
1506    unsigned long long* ptr = (unsigned long long*) (pl + ptr_off);
1507    int32_t* start2 = pl + ptr_off + 4 * capx;
1508
1509    if (is_first) {
1510        int tot = s_excl[tid];
1511#pragma unroll
1512        for (int w = 0; w < NW; ++w) {
1513            if (w < warp) tot += s_wsum[w];
1514        }
1515        const int grp_idx = tot & 0xffff;
1516        const int ent_start = tot >> 16;
1517        ptr[grp_idx] = (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob));
1518        start[grp_idx] = ent_start;
1519    }
1520    if (tid < n) {
1521        const int fj_warp = first_j >> 5;
1522        int fj_tot = s_excl[first_j];
1523#pragma unroll
1524        for (int w = 0; w < NW; ++w) {
1525            if (w < fj_warp) fj_tot += s_wsum[w];
1526        }
1527        const int out_idx = (fj_tot >> 16) + rank_in_group;
1528        dst[out_idx] = tid;
1529        tok[out_idx] = tid / k;
1530    }
1531    if (tid == 0) {
1532        int groups;
1533        if constexpr (NW == 4) groups = (s_wsum[0] + s_wsum[1] + s_wsum[2] + s_wsum[3]) & 0xffff;   // (the 128-thread kernel as it was)
1534        else {
1535            groups = 0;
1536#pragma unroll
1537            for (int w = 0; w < NW; ++w) groups += s_wsum[w];
1538            groups &= 0xffff;
1539        }
1540        start[groups] = n;
1541        start2[0] = n;
1542        counts[0] = groups;
1543        counts[1] = n;
1544        counts[2] = 0;
1545        if (skip != nullptr) {
1546            __threadfence();
1547            *skip = ring;
1548        }
1549    }
1550}
1551// The same plan in one block of 128 threads (n <= 128): thread i owns entry i. Groups are the distinct experts in
1552// order of first occurrence; group g's entries are its occurrences in increasing i - exactly the loop above
1553// (S26: the one-thread loop took ~44 us per call on gfx1151, 48 per window).
1554__global__ void resident_plan_par_kernel(const int32_t* __restrict__ ids, int n, int k, const int32_t* __restrict__ res,
1555                                         int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off,
1556                                         long long blob, int32_t* __restrict__ pl, long long capx, uint32_t* skip,
1557                                         uint32_t ring) {
1558    __shared__ int32_t s_id[128];
1559    __shared__ int s_first[128], s_size[128];
1560    __shared__ int s_bad;
1561    const int i = threadIdx.x;
1562    if (i == 0) s_bad = 0;
1563    __syncthreads();
1564    int32_t e = -1;
1565    if (i < n) {
1566        e = ids[i];
1567        s_id[i] = e;
1568        if (e < 0 || e >= n_expert || res[e] < 0) s_bad = 1;
1569    }
1570    __syncthreads();
1571    if (s_bad) { if (i == 0) *skip = 0; return; }
1572    int first = i, rank = 0, size = 0;
1573    if (i < n) {
1574        for (int j = 0; j < n; ++j) {
1575            const bool same = s_id[j] == e;
1576            if (same && j < first) first = j;
1577            if (same && j < i) ++rank;
1578            size += same;
1579        }
1580    }
1581    if (i < n) { s_first[i] = first; s_size[i] = size; }
1582    __syncthreads();
1583    int32_t* counts = pl;
1584    int32_t* start = pl + 4;
1585    int32_t* dst = start + capx + 1;
1586    int32_t* tok = dst + capx;
1587    const long long ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll;
1588    unsigned long long* ptr = (unsigned long long*) (pl + ptr_off);
1589    int32_t* start2 = pl + ptr_off + 4 * capx;
1590    if (i < n) {
1591        // group of entry i = the number of first occurrences before `first`; its start = their sizes' sum
1592        int group = 0, gstart = 0;
1593        for (int j = 0; j < first; ++j)
1594            if (s_first[j] == j) { ++group; gstart += s_size[j]; }
1595        if (i == first) {
1596            const int32_t slot = res[e];
1597            ptr[group] = (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob));
1598            start[group] = gstart;
1599        }
1600        dst[gstart + rank] = i;
1601        tok[gstart + rank] = i / k;
1602        if (i == 0) {
1603            int groups = 0;
1604            for (int j = 0; j < n; ++j) groups += s_first[j] == j;
1605            start[groups] = n;
1606            start2[0] = n;
1607            counts[0] = groups;
1608            counts[1] = n;
1609            counts[2] = 0;
1610        }
1611    }
1612    __threadfence();
1613    __syncthreads();
1614    if (i == 0) *skip = ring;
1615}
1616__global__ void wait_flag_ge_or_kernel(const volatile uint32_t* flag, uint32_t value, const volatile uint32_t* skip) {
1617    if (*skip == value) return;
1618    while (*flag < value) strata_spin_pause();
1619    __threadfence_system();
1620}
1621__global__ void copy_i32_unless_kernel(int32_t* __restrict__ dst, const volatile int32_t* src, int n,
1622                                       const uint32_t* skip, uint32_t value) {
1623    if (*skip == value) return;
1624    for (int i = threadIdx.x; i < n; i += blockDim.x) dst[i] = src[i];
1625}
1626__global__ void copy_or_zero_kernel(float4* __restrict__ dst, const volatile float4* src, long long n4,
1627                                    const uint32_t* skip, uint32_t value) {
1628    const bool zero = *skip == value;
1629    for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < n4; i += (long long) gridDim.x * blockDim.x)
1630        dst[i] = zero ? make_float4(0.f, 0.f, 0.f, 0.f) : const_cast<const float4*>(src)[i];
1631}
1632}  // namespace
1633
1634void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_layer, int n_expert,
1635                   const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan,
1636                   long long capx, uint32_t* skip, uint32_t ring, void* stream, uint32_t* plan_err) {
1637    if (n_entries > kResidentPlanNarrow) {   // a 9..16-row window (kResidentPlanMax == 256 only in a wide build)
1638        if (kResidentPlanMax > kResidentPlanNarrow && n_entries <= kResidentPlanMax)
1639            resident_plan_kernel<kResidentPlanMax><<<1, kResidentPlanMax, 0, (cudaStream_t) stream>>>(ids, n_entries, k, res_layer, n_expert, cache_base, slot_off,
1640                                                              blob, plan, capx, skip, ring, plan_err);
1641        else {
1642            std::fprintf(stderr, "resident_plan: %d entries, at most %d\n", n_entries, kResidentPlanMax);
1643            std::exit(1);
1644        }
1645    } else {
1646        resident_plan_kernel<kResidentPlanNarrow><<<1, kResidentPlanNarrow, 0, (cudaStream_t) stream>>>(ids, n_entries, k, res_layer, n_expert, cache_base, slot_off,
1647                                                              blob, plan, capx, skip, ring, plan_err);
1648    }
1649    check("resident_plan");
1650}
1651void wait_flag_ge_or(const uint32_t* flag, uint32_t value, const uint32_t* skip, void* stream) {
1652    wait_flag_ge_or_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(flag, value, skip);
1653    check("wait_flag_ge_or");
1654}
1655void copy_i32_from_mapped_unless(int32_t* dst, const int32_t* src, long long n, const uint32_t* skip, uint32_t value,
1656                                 void* stream) {
1657    if (n <= 0) return;
1658    copy_i32_unless_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(dst, (const volatile int32_t*) src, (int) n, skip, value);
1659    check("copy_i32_from_mapped_unless");
1660}
1661void copy_or_zero_from_mapped(float* dst, const float* src, long long n, const uint32_t* skip, uint32_t value,
1662                              void* stream) {
1663    if (n <= 0) return;
1664    const long long n4 = n / 4;
1665    const int blocks = (int) ((n4 + 255) / 256 < 64 ? (n4 + 255) / 256 : 64);
1666    copy_or_zero_kernel<<<blocks, 256, 0, (cudaStream_t) stream>>>((float4*) dst, (const volatile float4*) src, n4, skip,
1667                                                                    value);
1668    check("copy_or_zero_from_mapped");
1669}
1670
1671namespace {
1672__global__ void wait_copy_i32_kernel(const volatile uint32_t* flag, uint32_t value, int32_t* __restrict__ dst,
1673                                     const volatile int32_t* src, int n) {
1674    if (threadIdx.x == 0) {
1675        while (*flag < value) strata_spin_pause();
1676        __threadfence_system();
1677    }
1678    __syncthreads();
1679    for (int i = threadIdx.x; i < n; i += blockDim.x) dst[i] = src[i];
1680}
1681}  // namespace
1682void wait_copy_i32_from_mapped(const uint32_t* flag, uint32_t value, int32_t* dst, const int32_t* src, int64_t n,
1683                               void* stream) {
1684    wait_copy_i32_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(flag, value, dst, src, (int) n);
1685    check("wait_copy_i32_from_mapped");
1686}
1687
1688void wait_flag_ge(const uint32_t* flag, uint32_t value, void* stream) {
1689    wait_flag_ge_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(flag, value);
1690    check("wait_flag_ge");
1691}
1692
1693void wait_flag_ge_stamped(const uint32_t* flag, uint32_t value, unsigned long long* t_in, unsigned long long* t_out,
1694                          void* stream) {
1695    wait_flag_ge_stamped_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(flag, value, t_in, t_out);
1696    check("wait_flag_ge_stamped");
1697}
1698
1699void embedding_gather_dev(const uint8_t* codes, const float* scales, const float* offsets, const int32_t* tokens,
1700                          int n_tok, int64_t n, int code_bits, int code_bias, int group_elems, uint64_t row_codes,
1701                          uint64_t row_groups, float* out, void* stream) {
1702    embedding_gather_dev_kernel<<<dim3((unsigned) ((n + 255) / 256), (unsigned) n_tok), 256, 0,
1703                                  (cudaStream_t) stream>>>(codes, scales, offsets, tokens, n, code_bits, code_bias,
1704                                                           group_elems, row_codes, row_groups, out);
1705    check("embedding_gather_dev");
1706}
1707
1708void broadcast_streams(const float* x, float* R, int64_t n_embd, int hc, int n_tok, void* stream) {
1709    broadcast_streams_kernel<<<dim3((unsigned) ((n_embd * hc + 255) / 256), (unsigned) n_tok), 256, 0,
1710                               (cudaStream_t) stream>>>(x, R, n_embd, hc);
1711    check("broadcast_streams");
1712}
1713
1714void hc_mean_streams(const float* R, float* out, int64_t n_embd, int hc, void* stream) {
1715    hc_mean_streams_kernel<<<(unsigned) ((n_embd + 255) / 256), 256, 0, (cudaStream_t) stream>>>(R, out, n_embd, hc);
1716    check("hc_mean_streams");
1717}
1718
1719void route_marginal_stats(const int32_t* ids, int n, int k, unsigned long long* acc, void* stream) {
1720    route_marginal_stats_kernel<<<1, 32, 0, (cudaStream_t) stream>>>(ids, n, k, acc);
1721    check("route_marginal_stats");
1722}
1723
1724void copy_indexed(float* dst, const float* src, int64_t stride, const int32_t* index, int64_t n, void* stream) {
1725    const unsigned blocks = (unsigned) ((n + 255) / 256 < 64 ? (n + 255) / 256 : 64);
1726    copy_indexed_kernel<<<blocks, 256, 0, (cudaStream_t) stream>>>(dst, src, stride, index, n);
1727    check("copy_indexed");
1728}
1729
1730// a GPU timestamp (ns, %globaltimer) into buf[i] - the verify window's stage profiler.  Pdl: launched inside a PDL
1731// stretch, the stamp lets the next kernel launch at once and takes its time when the one before it has finished.
1732namespace {
1733template <bool Pdl>
1734__global__ void gpu_stamp_kernel(unsigned long long* buf, int i) {
1735    if constexpr (Pdl) {
1736        pdl_trigger();
1737        pdl_wait();
1738    }
1739    unsigned long long t;
1740#if defined(STRATA_HIP_GFX906)
1741    t = wall_clock64() * 40ull;   // gfx906: the wall clock runs at 25 MHz (hipDeviceAttributeWallClockRate) -> ns
1742#elif defined(__HIPCC__)
1743    t = wall_clock64() * 10ull;   // gfx10.3 / gfx11 / gfx12: a constant 100 MHz counter, in ns
1744#else
1745    asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t));
1746#endif
1747    buf[i] = t;
1748}
1749}  // namespace
1750namespace {
1751__global__ void noop_kernel() {}
1752}  // namespace
1753void gpu_noop(void* stream) { noop_kernel<<<1, 32, 0, (cudaStream_t) stream>>>(); }
1754void gpu_stamp(unsigned long long* buf, int i, void* stream) {
1755    if (pdl_scope()) launch_pdl(gpu_stamp_kernel<true>, dim3(1), dim3(1), 0, (cudaStream_t) stream, buf, i);
1756    else gpu_stamp_kernel<false><<<1, 1, 0, (cudaStream_t) stream>>>(buf, i);
1757}
1758
1759namespace {
1760__global__ void copy_rows_strided_kernel(float4* __restrict__ dst, const float4* __restrict__ src, long long rows,
1761                                         int w4, int src_w4) {
1762    const long long total = rows * w4;
1763    for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < total;
1764         i += (long long) gridDim.x * blockDim.x) {
1765        const long long r = i / w4, c = i - r * w4;
1766        dst[i] = src[r * src_w4 + c];
1767    }
1768}
1769}  // namespace
1770void copy_rows_strided(float* dst, const float* src, int64_t rows, int64_t w, int64_t src_w, void* stream) {
1771    if (rows <= 0 || w <= 0) return;
1772    if ((w & 3) || (src_w & 3) || src_w < w || ((uintptr_t) dst & 15) || ((uintptr_t) src & 15)) {
1773        std::fprintf(stderr, "copy_rows_strided: widths must be multiples of 4 floats (src_w >= w), pointers 16-byte "
1774                             "aligned\n");
1775        std::exit(1);
1776    }
1777    const long long total = (long long) rows * (w / 4);
1778    const unsigned blocks = (unsigned) ((total + 255) / 256 < 256 ? (total + 255) / 256 : 256);
1779    copy_rows_strided_kernel<<<blocks, 256, 0, (cudaStream_t) stream>>>((float4*) dst, (const float4*) src, rows,
1780                                                                         (int) (w / 4), (int) (src_w / 4));
1781    check("copy_rows_strided");
1782}
1783
1784// ---- programmatic dependent launch (pdl.hpp)
1785bool& pdl_scope() {
1786    static thread_local bool on = false;
1787    return on;
1788}
1789
1790bool pdl_supported() {
1791#if defined(__HIPCC__) || !defined(CUDART_VERSION) || CUDART_VERSION < 12030
1792    return false;   // HIP; or a CUDA runtime without the capture-dependency query pdl_launch_ok needs
1793#else
1794    // per device (a layer split runs on several): 1 = runs, 2 = does not.  sm_90+ (the card's, or STRATA_EMULATE_CC's),
1795    // and code built for it: on a build with only older code the driver JIT-compiles PTX without griddepcontrol.
1796    static std::atomic<int> state[64];
1797    int dev = 0;
1798    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
1799    int s = state[dev].load(std::memory_order_relaxed);
1800    if (s == 0) {
1801        // STRATA_DF_PDL: 1 / 2 = on for every window graph, 0 = off; unset = on for a compute capability 12.0 card (STRATA_SM120_PERF=0 turns
1802        // that off), where the verifier asks for it for the all-resident graph only (BW-MEASURE, E21: +0.3..+0.5% decode there, bit-identical;
1803        // -1.6% .. -4.5% in the doorbell graph of a partly resident cache)
1804        static const int env_mode = [] { const char* v = std::getenv("STRATA_DF_PDL"); return v == nullptr ? -1 : (std::atoi(v) != 0 ? 1 : 0); }();
1805        int major = 0, minor = 0;
1806        cudaFuncAttributes fa{};
1807        const bool on_attr = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
1808                             cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess;
1809        const bool env_on = env_mode == 1 || (env_mode < 0 && on_attr && strata::sm120_default(major, minor));
1810        const bool on = env_on && on_attr &&
1811                        strata::cc_major_of(major) >= 9 &&
1812                        cudaFuncGetAttributes(&fa, gpu_stamp_kernel<true>) == cudaSuccess && fa.ptxVersion >= 90 &&
1813                        fa.binaryVersion >= 90;
1814        cudaGetLastError();
1815        s = on ? 1 : 2;
1816        state[dev].store(s, std::memory_order_relaxed);
1817    }
1818    return s == 1;
1819#endif
1820}
1821
1822#if !defined(__HIPCC__)
1823bool pdl_launch_ok(const void* kernel, cudaStream_t stream) {
1824#if !defined(CUDART_VERSION) || CUDART_VERSION < 12030
1825    (void) kernel; (void) stream;
1826    return false;
1827#else
1828    // the kernel's own code is sm_90+ (each kernel checked once per device: its PTX, or a JIT from older PTX, decides)
1829    {
1830        static std::mutex mu;
1831        static std::vector<std::pair<std::pair<const void*, int>, bool>> seen;
1832        int dev = 0;
1833        if (cudaGetDevice(&dev) != cudaSuccess) { cudaGetLastError(); return false; }
1834        std::lock_guard<std::mutex> lock(mu);
1835        bool found = false, ok = false;
1836        for (const auto& e : seen)
1837            if (e.first.first == kernel && e.first.second == dev) { found = true; ok = e.second; break; }
1838        if (!found) {
1839            cudaFuncAttributes fa{};
1840            ok = cudaFuncGetAttributes(&fa, kernel) == cudaSuccess && fa.ptxVersion >= 90 && fa.binaryVersion >= 90;
1841            cudaGetLastError();
1842            seen.push_back({{kernel, dev}, ok});
1843        }
1844        if (!ok) return false;
1845    }
1846    // every node the next captured node will depend on is a kernel (CUDA allows a programmatic edge only between two
1847    // kernel nodes): never after a memcpy, memset, host or event node.  A join of branches gives several kernels, a
1848    // programmatic edge from each; STRATA_DF_PDL=2 allows a single predecessor only.
1849    static const int mode = [] { const char* v = std::getenv("STRATA_DF_PDL"); return v ? std::atoi(v) : 1; }();
1850    cudaStreamCaptureStatus status = cudaStreamCaptureStatusNone;
1851    const cudaGraphNode_t* deps = nullptr;
1852    const cudaGraphEdgeData* edges = nullptr;
1853    size_t n = 0;
1854#if CUDART_VERSION >= 13000
1855    const cudaError_t e = cudaStreamGetCaptureInfo(stream, &status, nullptr, nullptr, &deps, &edges, &n);
1856#else
1857    const cudaError_t e = cudaStreamGetCaptureInfo_v3(stream, &status, nullptr, nullptr, &deps, &edges, &n);
1858#endif
1859    if (e != cudaSuccess) { cudaGetLastError(); return false; }
1860    if (status != cudaStreamCaptureStatusActive || n == 0 || deps == nullptr) return false;
1861    if (mode == 2 && n != 1) return false;
1862    for (size_t i = 0; i < n; ++i) {
1863        if (edges != nullptr && (edges[i].type != cudaGraphDependencyTypeDefault || edges[i].from_port != 0 ||
1864                                 edges[i].to_port != 0))
1865            return false;
1866        cudaGraphNodeType type;
1867        if (cudaGraphNodeGetType(deps[i], &type) != cudaSuccess) { cudaGetLastError(); return false; }
1868        if (type != cudaGraphNodeTypeKernel) return false;
1869    }
1870    return true;
1871#endif
1872}
1873#endif
1874
1875}  // namespace strata::kernels