okami.mom/strata

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

waveringanaedge0-strata: add the engine for Edge0 145B and Edge0 120Bfd19246dc

main
32.4 KiB638 linesraw
1// src/prefill/gdn_chunk.cu - see include/strata/prefill/gdn_chunk.hpp for the math and the contract.
2//
3// Three kernels, the same three stages as llama.cpp-v100's gdn-chunk-sm70 (cumsum / kkt / fwd), hand-written
4// plain CUDA - FP32 throughout, no FP16 staging and no tensor cores yet (the TileLang m8n8k4 output of the
5// reference is a later, speed-only step).  What the chunking buys is the shape of the serial chain: T tokens
6// become T/64 chunk steps, each step a batch of dense matmuls over 64 tokens instead of one token's rank-1
7// update behind two __syncthreads.
8//
9// Per CTA: one (v head, 32-column slice) of the state, all chunks in order (the state slice lives in
10// registers - the chunk-serial scan of the reference's fwd kernel).  The per-chunk 64x64 matrices A and P are
11// computed once per (chunk, head) by the kkt kernel and read by the four column slices.
12#include "strata/prefill/gdn_chunk.hpp"
13
14#include <cuda_runtime.h>
15#if !defined(__HIPCC__)
16#include <cuda_fp16.h>
17#include <mma.h>
18#endif
19
20#include <cstdint>
21#include <cstdio>
22#include <cstdlib>
23#include <mutex>
24
25#include "strata/core/geometry.hpp"
26
27namespace strata::prefill {
28namespace {
29
30constexpr int S = strata::core::kCompiledGeometry.ssm_state_size, HK = strata::core::kCompiledGeometry.ssm_k_heads, HV = strata::core::kCompiledGeometry.ssm_v_heads, C = strata::core::kCompiledGeometry.ssm_conv_channels;  // as src/prefill/kernels.cu
31constexpr int CH = 64;                               // tokens per chunk (the reference's chunk)
32constexpr int NS = 32;                               // value columns per fwd CTA
33constexpr int NSE = S / NS;                          // 4 slices per head
34constexpr int SEG = 32;                              // chunks per pipeline segment (sizes the workspace)
35// the wmma kernel's dynamic shared memory: Ks/Qs f16, W16 f16, Ug f32 (Gram scratch / U out), As/Ps f16,
36// dlt f32 and its f16 image - 84 KB, past the 48 KB default (opt-in), under the 96 KB Volta ceiling
37constexpr int WMMA_SMEM = (2 * CH * S + S * NS) * (int) sizeof(__half) + S * NS * (int) sizeof(float) +
38                          2 * CH * CH * (int) sizeof(__half) + CH * NS * (int) sizeof(float) +
39                          CH * NS * (int) sizeof(__half);
40
41void check(const char* what) {
42    const cudaError_t e = cudaGetLastError();
43    if (e != cudaSuccess) {
44        std::fprintf(stderr, "gdn_chunk %s: %s\n", what, cudaGetErrorString(e));
45        std::exit(1);
46    }
47}
48
49// g_cumsum[lt * HV + h] = inclusive cumsum of gate over the segment's tokens (lt = segment-local token).
50// One block of 64 per (chunk, head): a Kogge-Stone scan of 64 values, two tokens' worth of nothing.
51__global__ void __launch_bounds__(CH) gdn_chunk_cumsum_kernel(float* __restrict__ gcum,
52                                                              const float* __restrict__ gate, int ntok) {
53    const int h = blockIdx.y;
54    const int lt = blockIdx.x * CH + threadIdx.x;
55    __shared__ float sh[CH];
56    sh[threadIdx.x] = lt < ntok ? gate[(size_t) lt * HV + h] : 0.0f;
57    __syncthreads();
58#pragma unroll
59    for (int off = 1; off < CH; off <<= 1) {
60        const float add = threadIdx.x >= off ? sh[threadIdx.x - off] : 0.0f;
61        __syncthreads();
62        sh[threadIdx.x] += add;
63        __syncthreads();
64    }
65    if (lt < ntok) gcum[(size_t) lt * HV + h] = sh[threadIdx.x];
66}
67
68// Per (chunk, head): the decayed Gram matrices the fwd kernel's solve and output sum read,
69//   A[t][s] = beta_t exp(c_t - c_s) (k_t . k_s)  for s < t   (the (I + strict_lower) solve matrix)
70//   P[t][s] = exp(c_t - c_s) (q_t . k_s)          for s <= t  (the output sum)
71// in f32 (CH x CH per chunk-head; the upper triangle of A and P is never written and never read).  Every
72// decay factor is a decay from a LATER token back to an EARLIER one - <= 1 for a real GDN gate - so nothing
73// here can overflow, and delta stays O(beta v) in the fwd solve (gdn_chunk.hpp derives the form).
74__global__ void __launch_bounds__(128) gdn_chunk_kkt_kernel(float* __restrict__ A, float* __restrict__ P,
75                                                            const float* __restrict__ h,
76                                                            const float* __restrict__ beta,
77                                                            const float* __restrict__ gcum, int nchunks) {
78    // 2 * CH * SP f32: the k and q tiles (opt-in, > 48 KB).  SP pads the row so the dot loop's row-strided
79    // reads do not all land in one shared bank (S = 128 floats is a whole number of bank rows).
80    constexpr int SP = S + 1;
81    extern __shared__ float sh[];
82    float* ks = sh;
83    float* qs = sh + CH * SP;
84    const int hh = blockIdx.y, ch = blockIdx.x, qh = hh % HK;
85    const int64_t base = (size_t) ch * CH;
86    const float* kh = h + base * C + (size_t) HK * S + (size_t) qh * S;
87    const float* qh_ = h + base * C + (size_t) qh * S;
88    for (int i = threadIdx.x; i < CH * S; i += blockDim.x) {
89        const int t = i / S, j = i % S;
90        ks[t * SP + j] = kh[(size_t) t * C + j];
91        qs[t * SP + j] = qh_[(size_t) t * C + j];
92    }
93    __syncthreads();
94    float* Ap = A + ((size_t) ch * HV + hh) * CH * CH;
95    float* Pp = P + ((size_t) ch * HV + hh) * CH * CH;
96    for (int p = threadIdx.x; p < CH * CH; p += blockDim.x) {
97        const int t = p / CH, s = p % CH;
98        if (s > t) continue;
99        const float dec = expf(gcum[(base + t) * HV + hh] - gcum[(base + s) * HV + hh]);
100        float pq = 0.0f, pq1 = 0.0f;
101#pragma unroll 4
102        for (int i = 0; i < S; i += 2) {
103            pq = fmaf(qs[t * SP + i], ks[s * SP + i], pq);
104            pq1 = fmaf(qs[t * SP + i + 1], ks[s * SP + i + 1], pq1);
105        }
106        Pp[t * CH + s] = (pq + pq1) * dec;
107        if (s < t) {
108            float pk = 0.0f, pk1 = 0.0f;
109#pragma unroll 4
110            for (int i = 0; i < S; i += 2) {
111                pk = fmaf(ks[t * SP + i], ks[s * SP + i], pk);
112                pk1 = fmaf(ks[t * SP + i + 1], ks[s * SP + i + 1], pk1);
113            }
114            Ap[t * CH + s] = (pk + pk1) * dec * beta[(base + t) * HV + hh];
115        }
116    }
117}
118
119// The chunk-serial scan: one CTA per (v head, 32-column slice), state in registers, all chunks in order.
120// Per token: the two row-block reductions (k_t.W_in, q_t.W_in) give u_t and qW_t; the w==0 lane of each
121// column solves its delta and writes o.  The A/P tiles are staged to shared memory at the top of each chunk:
122// the solve and output sums are serial FMA chains, and a global load inside the chain (L2, ~200 cycles)
123// throttles the whole CTA to it.  One __syncthreads per token (the shared dlt row plus the partials), one
124// after the token loop (the last dlt row before the state update).
125__global__ void __launch_bounds__(128) gdn_chunk_fwd_kernel(float* __restrict__ state, float* __restrict__ oc,
126                                                            const float* __restrict__ h,
127                                                            const float* __restrict__ beta,
128                                                            const float* __restrict__ gcum,
129                                                            const float* __restrict__ A,
130                                                            const float* __restrict__ P, int nchunks) {
131    const int hh = blockIdx.y, sl = blockIdx.x, j0 = sl * NS, qh = hh % HK;
132    const int w = threadIdx.x >> 5, c = threadIdx.x & 31, col = j0 + c;
133    // red is double-buffered by token parity: the w==0 lane reads token t's partials while the other warps
134    // may already be staging token t+1's into the other slot (one barrier per token, no reader/writer race)
135    __shared__ float red[2][2][4][NS], dlt[CH][NS], As[CH][CH], Ps[CH][CH], ex[CH][2];
136    float W[NS];
137#pragma unroll
138    for (int r = 0; r < NS; ++r)
139        W[r] = state[((size_t) (w * NS + r) * HV + hh) * S + col];
140    const float rsqrt_S = rsqrtf((float) S);
141    for (int ch = 0; ch < nchunks; ++ch) {
142        const int64_t base = (size_t) ch * CH;
143        const float sg = gcum[(base + CH - 1) * HV + hh];  // sigma: the chunk's total log-decay
144        const float* Ap = A + ((size_t) ch * HV + hh) * CH * CH;
145        const float* Pp = P + ((size_t) ch * HV + hh) * CH * CH;
146        // stage the two 64x64 tiles and the per-token decay factors (exp(c_t), exp(sigma - c_t))
147        for (int i = threadIdx.x; i < CH * CH; i += blockDim.x) {
148            As[i / CH][i % CH] = Ap[i];
149            Ps[i / CH][i % CH] = Pp[i];
150        }
151        if (threadIdx.x < CH) {
152            const float gc = gcum[(base + threadIdx.x) * HV + hh];
153            ex[threadIdx.x][0] = expf(gc);
154            ex[threadIdx.x][1] = expf(sg - gc);
155        }
156        __syncthreads();
157        const float sg_exp = ex[CH - 1][0];  // exp(sigma)
158        for (int t = 0; t < CH; ++t) {
159            const float* kt = h + (base + t) * C + (size_t) HK * S + (size_t) qh * S + w * NS;
160            const float* qt = h + (base + t) * C + (size_t) qh * S + w * NS;
161            float up = 0.0f, up1 = 0.0f, qp = 0.0f, qp1 = 0.0f;
162#pragma unroll
163            for (int r = 0; r < NS; r += 2) {
164                const float w0 = W[r], w1 = W[r + 1];
165                up = fmaf(kt[r], w0, up);
166                up1 = fmaf(kt[r + 1], w1, up1);
167                qp = fmaf(qt[r], w0, qp);
168                qp1 = fmaf(qt[r + 1], w1, qp1);
169            }
170            red[t & 1][0][w][c] = up + up1;
171            red[t & 1][1][w][c] = qp + qp1;
172            __syncthreads();
173            if (w == 0) {
174                const float u_t = red[t & 1][0][0][c] + red[t & 1][0][1][c] + red[t & 1][0][2][c] + red[t & 1][0][3][c];
175                const float qW_t =
176                    red[t & 1][1][0][c] + red[t & 1][1][1][c] + red[t & 1][1][2][c] + red[t & 1][1][3][c];
177                const float b = beta[(base + t) * HV + hh];
178                const float v_t = h[(base + t) * C + (size_t) 2 * HK * S + (size_t) hh * S + col];
179                // delta_t = beta_t (v_t - exp(c_t) u_t) - sum_{s<t} A[t][s] delta_s
180                float d = b * (v_t - ex[t][0] * u_t), d1 = 0.0f;
181#pragma unroll 1
182                for (int s = 0; s < t; s += 2) {
183                    d = fmaf(-As[t][s], dlt[s][c], d);
184                    if (s + 1 < t) d1 = fmaf(-As[t][s + 1], dlt[s + 1][c], d1);
185                }
186                d += d1;
187                dlt[t][c] = d;
188                float o = ex[t][0] * qW_t + Ps[t][t] * d, o1 = 0.0f;
189#pragma unroll 1
190                for (int s = 0; s < t; s += 2) {
191                    o = fmaf(Ps[t][s], dlt[s][c], o);
192                    if (s + 1 < t) o1 = fmaf(Ps[t][s + 1], dlt[s + 1][c], o1);
193                }
194                oc[((base + t) * HV + hh) * S + col] = (o + o1) * rsqrt_S;
195            }
196        }
197        __syncthreads();  // the last dlt row is visible for the update
198        // W_out = exp(sigma) W_in + sum_s k_s exp(sigma - c_s) delta_s^T   (the decay folded into the delta)
199#pragma unroll
200        for (int r = 0; r < NS; ++r) W[r] *= sg_exp;
201        for (int s = 0; s < CH; ++s) {
202            const float* kt = h + (base + s) * C + (size_t) HK * S + (size_t) qh * S + w * NS;
203            const float ds = dlt[s][c] * ex[s][1];
204#pragma unroll
205            for (int r = 0; r < NS; ++r) W[r] = fmaf(kt[r], ds, W[r]);
206        }
207    }
208#pragma unroll
209    for (int r = 0; r < NS; ++r) state[((size_t) (w * NS + r) * HV + hh) * S + col] = W[r];
210}
211
212// ---------------------------------------------------------------- wmma (m16n16k16) variant
213//
214// The FMA scan above is correct but latency-bound: per token it streams k_t and q_t from global into
215// dependent FMA chains, and V100 FMA throughput cannot pay for that at this granularity (measured on the
216// V100: ~2x slower than the recurrence it was meant to beat).  This variant runs the same math the way
217// llama.cpp-v100's gdn-chunk-sm70 does it - q/k/v and the state staged through FP16, the matmuls on the
218// FP16 tensor cores with FP32 accumulate, the triangular solve still FMA - and folds the kkt stage's Gram
219// matrices into the same CTA (recomputed per column slice, which the tensor cores make cheap).
220//
221// Per chunk: stage k/q, -> f16; Gram K K^T and Q K^T -> A and P (decay + beta baked); the GEMM
222// U = [K; Q] W gives u_t and qW_t for every token at once; the solve and output sums are the FMA scan's;
223// W += K^T (delta * decay) on the tensor cores with W itself as the f32 accumulator fragments - the state
224// never leaves the registers across chunks.  W's f16 image exists only as the U GEMM's operand.
225//
226// Precision: the FP16 staging is the reference's f32 -> f16 staging (10-bit mantissa on the operands);
227// accumulations, the solve and the state are f32.  FP32-level, not bit-exact - see gdn_chunk_parity.
228#if !defined(__HIPCC__)
229
230__global__ void __launch_bounds__(128) gdn_chunk_wmma_kernel(float* __restrict__ state, float* __restrict__ oc,
231                                                             const float* __restrict__ h,
232                                                             const float* __restrict__ beta,
233                                                             const float* __restrict__ gcum, int nchunks) {
234#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700   // named in every device pass of a multi-arch build; only sm_70+ has wmma
235    namespace wmma = ::nvcuda::wmma;
236    // smem (84.5 KB, opt-in):  Ks/Qs the chunk's k and q rows f16; W16 the state slice f16 (U's operand);
237    //  Ug[128][32] f32 aliasing the 64x64 Gram scratch and then U = [K;Q] W;  As/Ps f16;  dlt f32 + f16.
238    extern __shared__ __align__(1024) unsigned char smem[];
239    __half* Ks = (__half*) smem;                                   // [CH][S]
240    __half* Qs = Ks + CH * S;                                      // [CH][S]
241    __half* W16 = Qs + CH * S;                                     // [S][NS]
242    float* Ug = (float*) (W16 + S * NS);                           // [S][NS] f32  (Gram scratch / U out)
243    __half* As = (__half*) (Ug + S * NS);                          // [CH][CH]
244    __half* Ps = As + CH * CH;                                     // [CH][CH]
245    float* dlt = (float*) (Ps + CH * CH);                          // [CH][NS]
246    __half* dlt16 = (__half*) (dlt + CH * NS);                     // [CH][NS]
247
248    const int hh = blockIdx.y, sl = blockIdx.x, j0 = sl * NS, qh = hh % HK;
249    const int w = threadIdx.x >> 5, c = threadIdx.x & 31, col = j0 + c;
250    // the state slice in through smem (load_matrix_sync of an accumulator tile is a shared-memory op on
251    // sm_70): Ug first as the f32 staging, then W's f32 image in the fragments and its f16 image in W16
252    for (int i = threadIdx.x; i < S * NS; i += blockDim.x) {
253        const int r = i / NS, j = i % NS;
254        Ug[i] = state[(size_t) r * HV * S + (size_t) hh * S + j0 + j];
255        W16[i] = __float2half_rn(Ug[i]);
256    }
257    __syncthreads();
258    // W as f32 accumulator fragments: warp w owns rows w*32..w*32+31 of the 128x32 slice, 2x2 tiles
259    wmma::fragment<wmma::accumulator, 16, 16, 16, float> wF[2][2];
260#pragma unroll
261    for (int mi = 0; mi < 2; ++mi)
262#pragma unroll
263        for (int nj = 0; nj < 2; ++nj)
264            wmma::load_matrix_sync(wF[mi][nj], Ug + (size_t) (w * 32 + 16 * mi) * NS + 16 * nj, NS,
265                                   wmma::mem_row_major);
266    const float rsqrt_S = rsqrtf((float) S);
267    for (int ch = 0; ch < nchunks; ++ch) {
268        const int64_t base = (size_t) ch * CH;
269        const float sg = gcum[(base + CH - 1) * HV + hh];  // sigma: the chunk's total log-decay
270        // stage the chunk's k and q rows through f16 - float4 loads, four in flight per thread: a scalar
271        // load loop here is a serial global-latency chain per thread (measured: it WAS the kernel's floor)
272        for (int i4 = threadIdx.x; i4 < CH * S / 4; i4 += blockDim.x) {
273            const int t = (i4 * 4) / S, j4 = (i4 * 4) % S;
274            const float4 k4 = *reinterpret_cast<const float4*>(h + (base + t) * C + (size_t) HK * S + (size_t) qh * S + j4);
275            const float4 q4 = *reinterpret_cast<const float4*>(h + (base + t) * C + (size_t) qh * S + j4);
276            Ks[t * S + j4 + 0] = __float2half_rn(k4.x);
277            Ks[t * S + j4 + 1] = __float2half_rn(k4.y);
278            Ks[t * S + j4 + 2] = __float2half_rn(k4.z);
279            Ks[t * S + j4 + 3] = __float2half_rn(k4.w);
280            Qs[t * S + j4 + 0] = __float2half_rn(q4.x);
281            Qs[t * S + j4 + 1] = __float2half_rn(q4.y);
282            Qs[t * S + j4 + 2] = __float2half_rn(q4.z);
283            Qs[t * S + j4 + 3] = __float2half_rn(q4.w);
284        }
285        // the state slice as f16: the fragments to Ug, then to W16
286#pragma unroll
287        for (int mi = 0; mi < 2; ++mi)
288#pragma unroll
289            for (int nj = 0; nj < 2; ++nj)
290                wmma::store_matrix_sync(Ug + (size_t) (w * 32 + 16 * mi) * NS + 16 * nj, wF[mi][nj], NS,
291                                        wmma::mem_row_major);
292        __syncthreads();
293        for (int i = threadIdx.x; i < S * NS; i += blockDim.x) W16[i] = __float2half_rn(Ug[i]);
294        __syncthreads();  // W16 done before Ug becomes the Gram scratch
295        // Gram:  Ug = K K^T, then As[t][s] = beta_t exp(c_t-c_s) Ug[t][s];  Ug = Q K^T, then Ps (no beta)
296        {
297            wmma::fragment<wmma::matrix_a, 16, 16, 16, __half, wmma::row_major> aF;
298            wmma::fragment<wmma::matrix_b, 16, 16, 16, __half, wmma::col_major> bF;
299            wmma::fragment<wmma::accumulator, 16, 16, 16, float> gF[4];
300            for (int pass = 0; pass < 2; ++pass) {
301#pragma unroll
302                for (int nj = 0; nj < 4; ++nj) wmma::fill_fragment(gF[nj], 0.0f);
303                for (int kk = 0; kk < S / 16; ++kk) {
304                    wmma::load_matrix_sync(aF, (pass ? Qs : Ks) + (size_t) (w * 16) * S + kk * 16, S);
305                    for (int nj = 0; nj < 4; ++nj) {
306                        wmma::load_matrix_sync(bF, Ks + kk * 16 + (size_t) (16 * nj) * S, S);
307                        wmma::mma_sync(gF[nj], aF, bF, gF[nj]);
308                    }
309                }
310                for (int nj = 0; nj < 4; ++nj)
311                    wmma::store_matrix_sync(Ug + (size_t) (w * 16) * CH + 16 * nj, gF[nj], CH, wmma::mem_row_major);
312                __syncthreads();
313                // fold decay (and beta) into the f16 tiles
314                for (int p = threadIdx.x; p < CH * CH; p += blockDim.x) {
315                    const int t = p / CH, s = p % CH;
316                    const float dec = expf(gcum[(base + t) * HV + hh] - gcum[(base + s) * HV + hh]);
317                    if (pass)  // Ps: s <= t live, the upper triangle zeroed - the o GEMM reads the whole tile
318                        Ps[t * CH + s] = s <= t ? __float2half_rn(Ug[t * CH + s] * dec) : __float2half_rn(0.0f);
319                    else if (s < t)  // As: strict lower only, the solve reads exactly that
320                        As[t * CH + s] = __float2half_rn(Ug[t * CH + s] * dec * beta[(base + t) * HV + hh]);
321                }
322                __syncthreads();
323            }
324        }
325        // U = [K; Q] W16 : rows 0..63 are u_t = k_t.W_in, rows 64..127 are qW_t = q_t.W_in.  The 128 output
326        // rows split as 32 per warp: warps 0-1 the K half, warps 2-3 the Q half.
327        {
328            wmma::fragment<wmma::matrix_a, 16, 16, 16, __half, wmma::row_major> aF;
329            wmma::fragment<wmma::matrix_b, 16, 16, 16, __half, wmma::row_major> bF[2];
330            wmma::fragment<wmma::accumulator, 16, 16, 16, float> uF[2][2];
331            const __half* src = w < 2 ? Ks : Qs;
332            const int row0 = (w & 1) * 32;
333#pragma unroll
334            for (int mi = 0; mi < 2; ++mi)
335#pragma unroll
336                for (int nj = 0; nj < 2; ++nj) wmma::fill_fragment(uF[mi][nj], 0.0f);
337            for (int kk = 0; kk < S / 16; ++kk) {
338                for (int nj = 0; nj < 2; ++nj)
339                    wmma::load_matrix_sync(bF[nj], W16 + kk * 16 * NS + 16 * nj, NS);
340#pragma unroll
341                for (int mi = 0; mi < 2; ++mi) {
342                    wmma::load_matrix_sync(aF, src + (size_t) (row0 + 16 * mi) * S + kk * 16, S);
343                    for (int nj = 0; nj < 2; ++nj) wmma::mma_sync(uF[mi][nj], aF, bF[nj], uF[mi][nj]);
344                }
345            }
346#pragma unroll
347            for (int mi = 0; mi < 2; ++mi)
348#pragma unroll
349                for (int nj = 0; nj < 2; ++nj)
350                    wmma::store_matrix_sync(Ug + (size_t) (w * 32 + 16 * mi) * NS + 16 * nj, uF[mi][nj], NS,
351                                            wmma::mem_row_major);
352            __syncthreads();
353        }
354        // the solve - 8 independent accumulator chains so the smem loads of one group hide behind the FMAs
355        // of the last (the 2-chain was smem-latency-bound and WAS half the kernel's runtime)
356        for (int t = 0; t < CH; ++t) {
357            if (w == 0) {
358                const float gc = gcum[(base + t) * HV + hh];
359                const float ex0 = expf(gc);
360                const float b = beta[(base + t) * HV + hh];
361                const float v_t = h[(base + t) * C + (size_t) 2 * HK * S + (size_t) hh * S + col];
362                float d[8];
363                d[0] = b * (v_t - ex0 * Ug[t * NS + c]);
364#pragma unroll
365                for (int q = 1; q < 8; ++q) d[q] = 0.0f;
366                int s0 = 0;
367#pragma unroll 1
368                for (; s0 + 8 <= t; s0 += 8) {
369#pragma unroll
370                    for (int q = 0; q < 8; ++q)
371                        d[q] = fmaf(-__half2float(As[t * CH + s0 + q]), dlt[(s0 + q) * NS + c], d[q]);
372                }
373#pragma unroll 1
374                for (; s0 < t; ++s0) d[0] = fmaf(-__half2float(As[t * CH + s0]), dlt[s0 * NS + c], d[0]);
375                dlt[t * NS + c] = (d[0] + d[1] + d[2] + d[3]) + (d[4] + d[5] + d[6] + d[7]);
376            }
377        }
378        __syncthreads();  // the deltas are complete
379        for (int i = threadIdx.x; i < CH * NS; i += blockDim.x) dlt16[i] = __float2half_rn(dlt[i]);
380        __syncthreads();
381        // o_intra = Ps delta on the tensor cores (the o FMA sum was the other latency chain), staged into the
382        // As tile (dead since the solve); 64 output rows split 16 per warp
383        {
384            wmma::fragment<wmma::matrix_a, 16, 16, 16, __half, wmma::row_major> aF;
385            wmma::fragment<wmma::matrix_b, 16, 16, 16, __half, wmma::row_major> bF[2];
386            wmma::fragment<wmma::accumulator, 16, 16, 16, float> oF[2];
387            for (int nj = 0; nj < 2; ++nj) wmma::fill_fragment(oF[nj], 0.0f);
388            for (int kk = 0; kk < CH / 16; ++kk) {
389                for (int nj = 0; nj < 2; ++nj)
390                    wmma::load_matrix_sync(bF[nj], dlt16 + (size_t) (kk * 16) * NS + 16 * nj, NS);
391                wmma::load_matrix_sync(aF, Ps + (size_t) (w * 16) * CH + kk * 16, CH);
392                for (int nj = 0; nj < 2; ++nj) wmma::mma_sync(oF[nj], aF, bF[nj], oF[nj]);
393            }
394            for (int nj = 0; nj < 2; ++nj)
395                wmma::store_matrix_sync(Ug + S * NS + (size_t) (w * 16) * NS + 16 * nj, oF[nj], NS,
396                                        wmma::mem_row_major);  // (the As tile's byte range)
397        }
398        __syncthreads();
399        for (int i = threadIdx.x; i < CH * NS; i += blockDim.x) {
400            const int t = i / NS;
401            oc[((base + t) * HV + hh) * S + j0 + (i % NS)] =
402                (Ug[S * NS + i] + expf(gcum[(base + t) * HV + hh]) * Ug[(64 + t) * NS + (i % NS)]) * rsqrt_S;
403        }
404        __syncthreads();
405        // dlt16 = f16(delta_s * exp(sigma - c_s)) - the decay folded in for the state update
406        for (int i = threadIdx.x; i < CH * NS; i += blockDim.x) {
407            const int s = i / NS;
408            dlt16[i] = __float2half_rn(__half2float(dlt16[i]) * expf(sg - gcum[(base + s) * HV + hh]));
409        }
410        const float sg_exp = expf(sg);
411        __syncthreads();
412#pragma unroll
413        for (int mi = 0; mi < 2; ++mi)
414#pragma unroll
415            for (int nj = 0; nj < 2; ++nj)
416#pragma unroll
417                for (int q = 0; q < 8; ++q) wF[mi][nj].x[q] *= sg_exp;
418        {
419            {
420            wmma::fragment<wmma::matrix_a, 16, 16, 16, __half, wmma::col_major> aF;
421            wmma::fragment<wmma::matrix_b, 16, 16, 16, __half, wmma::row_major> bF[2];
422            for (int kk = 0; kk < CH / 16; ++kk) {
423                for (int nj = 0; nj < 2; ++nj)
424                    wmma::load_matrix_sync(bF[nj], dlt16 + (size_t) (kk * 16) * NS + 16 * nj, NS);
425#pragma unroll
426                for (int mi = 0; mi < 2; ++mi) {
427                    wmma::load_matrix_sync(aF, Ks + (w * 32 + 16 * mi) + (size_t) (kk * 16) * S, S);
428                    for (int nj = 0; nj < 2; ++nj) wmma::mma_sync(wF[mi][nj], aF, bF[nj], wF[mi][nj]);
429                }
430            } }
431        }
432    }
433    // the state slice out through smem as well
434#pragma unroll
435    for (int mi = 0; mi < 2; ++mi)
436#pragma unroll
437        for (int nj = 0; nj < 2; ++nj)
438            wmma::store_matrix_sync(Ug + (size_t) (w * 32 + 16 * mi) * NS + 16 * nj, wF[mi][nj], NS,
439                                    wmma::mem_row_major);
440    __syncthreads();
441    for (int i = threadIdx.x; i < S * NS; i += blockDim.x) {
442        const int r = i / NS, j = i % NS;
443        state[(size_t) r * HV * S + (size_t) hh * S + j0 + j] = Ug[i];
444    }
445#endif
446}
447#endif  // !HIPCC
448
449// The grow-only workspace, one per (thread, device): a layer split runs the chunked recurrence on more than
450// one card, and each card's pointers are only valid on that card - a single per-thread buffer would hand a
451// second card the first card's pointers.
452struct Ws {
453    float* A = nullptr;      // [SEG][HV][CH][CH]
454    float* P = nullptr;      // [SEG][HV][CH][CH]
455    float* gcum = nullptr;   // [SEG*CH][HV]
456    size_t cap = 0;          // in chunks
457    void ensure(size_t chunks) {
458        if (chunks <= cap) return;
459        if (A) cudaFree(A);
460        if (P) cudaFree(P);
461        if (gcum) cudaFree(gcum);
462        cudaGetLastError();   // a free of another device's pointer must not surface in the mallocs below
463        cap = chunks;
464        const size_t mat = chunks * HV * CH * CH;
465        if (cudaMalloc((void**) &A, mat * sizeof(float)) != cudaSuccess ||
466            cudaMalloc((void**) &P, mat * sizeof(float)) != cudaSuccess ||
467            cudaMalloc((void**) &gcum, (size_t) chunks * CH * HV * sizeof(float)) != cudaSuccess) {
468            int dev = 0;
469            cudaGetDevice(&dev);
470            size_t fb = 0, tb = 0;
471            cudaMemGetInfo(&fb, &tb);
472            std::fprintf(stderr, "gdn_chunk: workspace alloc failed (%zu chunks, device %d, %.1f of %.1f MiB free): %s\n",
473                         chunks, dev, (double) fb / 1048576.0, (double) tb / 1048576.0,
474                         cudaGetErrorString(cudaGetLastError()));
475            std::exit(1);
476        }
477    }
478    ~Ws() {
479        // A prompt's stage threads are created per request (std::async in the layer split): without this, each
480        // request would leak its device's ~50 MB workspace until the card runs out.
481        if (A) cudaFree(A);
482        if (P) cudaFree(P);
483        if (gcum) cudaFree(gcum);
484    }
485};
486
487Ws& ws() {
488    static thread_local Ws w[8];   // [device]: the cards a layer split can run on in one process
489    int dev = 0;
490    if (cudaGetDevice(&dev) != cudaSuccess) {
491        cudaGetLastError();
492        dev = 0;
493    }
494    if (dev < 0 || dev >= 8) dev = 0;
495    return w[dev];
496}
497
498int gdn_chunk_cc_of(int dev) {
499    // Per DEVICE: a layer split runs on more than one card, and the capability is a card property - a
500    // process-global cache would dispatch a second card by the first card's capability.
501    static int cc[64] = {};
502    if (dev < 0 || dev >= 64) return 0;
503    if (cc[dev] == 0) {
504        cudaDeviceProp p{};
505        if (cudaGetDeviceProperties(&p, dev) != cudaSuccess) {
506            cudaGetLastError();
507            return 0;
508        }
509        cc[dev] = p.major * 10 + p.minor;
510    }
511    return cc[dev];
512}
513
514int gdn_chunk_cc() {
515    int dev = 0;
516    if (cudaGetDevice(&dev) != cudaSuccess) {
517        cudaGetLastError();
518        return 0;
519    }
520    return gdn_chunk_cc_of(dev);
521}
522
523}  // namespace
524
525bool gdn_chunk_available() {
526#if defined(__HIPCC__) || !defined(STRATA_EXPERIMENTAL_SM60)
527    return false;  // the chunked path is compiled and dispatched only in the Volta experimental build
528#else
529    return gdn_chunk_cc() == 70;
530#endif
531}
532
533void gdn_chunk_recurrence(float* state, const float* h, const float* gate, const float* beta, float* oc,
534                          int64_t T, void* stream) {
535#if defined(__HIPCC__)
536    (void) state; (void) h; (void) gate; (void) beta; (void) oc; (void) T; (void) stream;
537    std::fprintf(stderr, "gdn_chunk_recurrence: not built for HIP\n");
538    std::exit(1);
539#else
540    if (T <= 0) return;
541    const int64_t T64 = T - T % CH;
542    if (T64 <= 0) return;
543    cudaStream_t cs = (cudaStream_t) stream;
544    // the wmma path is the default; STRATA_GDN_CHUNK=2 selects the FP32-only FMA scan (the parity test's
545    // oracle - same math, no FP16 staging) and anything below sm_70 has no wmma to use.  Read per call (the
546    // tests flip it between launches).
547    const char* forced_v = std::getenv("STRATA_GDN_CHUNK");
548    const int forced = forced_v && *forced_v ? std::atoi(forced_v) : -1;
549    int dev = 0;
550    if (cudaGetDevice(&dev) != cudaSuccess) {
551        cudaGetLastError();
552        dev = 0;
553    }
554#if !defined(__HIPCC__)
555    const bool wmma_ok = gdn_chunk_cc_of(dev) == 70;
556#else
557    const bool wmma_ok = false;
558#endif
559    // The shared-memory opt-in is a property of the DEVICE's context, not the process: a layer split runs
560    // this call on more than one card, and each card needs its own cudaFuncSetAttribute before that card's
561    // past-48KB launches (a process-global std::call_once left the second card at the 48 KB default, and its
562    // first chunked launch failed with "invalid argument").  Per device, once; every attempt clears the
563    // runtime error so a refused opt-in cannot surface in a later check() as a spurious failure.
564    static std::mutex attr_mu;
565    static bool attr_done[64] = {};
566    static bool wmma_attr[64] = {};
567    {
568        std::lock_guard<std::mutex> lk(attr_mu);
569        if (dev >= 0 && dev < 64 && !attr_done[dev]) {
570            const cudaError_t ek = cudaFuncSetAttribute(gdn_chunk_kkt_kernel,
571                                                        cudaFuncAttributeMaxDynamicSharedMemorySize,
572                                                        2 * CH * (S + 1) * (int) sizeof(float));
573            const cudaError_t ew = cudaFuncSetAttribute(gdn_chunk_wmma_kernel,
574                                                        cudaFuncAttributeMaxDynamicSharedMemorySize, WMMA_SMEM);
575            cudaGetLastError();
576            (void) ek;   // a refused opt-in leaves the FMA path's own launch to report it
577            wmma_attr[dev] = ew == cudaSuccess;
578            attr_done[dev] = true;
579        }
580    }
581    const bool use_wmma = wmma_ok && forced != 2 && dev >= 0 && dev < 64 && wmma_attr[dev];
582    Ws& w = ws();
583    const size_t chunks_total = (size_t) (T64 / CH);
584    w.ensure(chunks_total < SEG ? (chunks_total ? chunks_total : 1) : SEG);
585    // STRATA_GDN_CHUNK_PROF=1: per-stage milliseconds over the whole call (a dev tool, not a hot path)
586    static const bool prof = std::getenv("STRATA_GDN_CHUNK_PROF") != nullptr;
587    cudaEvent_t pe0{}, pe1{};
588    float ms[3] = {0, 0, 0};
589    if (prof) cudaEventCreate(&pe0), cudaEventCreate(&pe1);
590    for (int64_t t0 = 0; t0 < T64; t0 += (int64_t) SEG * CH) {
591        const int64_t left = (T64 - t0) / CH;
592        const int nch = (int) (left < SEG ? left : SEG);
593        const int ntok = nch * CH;
594        if (prof) cudaEventRecord(pe0, cs);
595        gdn_chunk_cumsum_kernel<<<dim3((unsigned) nch, HV), CH, 0, cs>>>(w.gcum, gate + t0 * HV, ntok);
596        check("cumsum");
597        if (prof) {
598            cudaEventRecord(pe1, cs);
599            cudaEventSynchronize(pe1);
600            cudaEventElapsedTime(&ms[0], pe0, pe1);
601            cudaEventRecord(pe0, cs);
602        }
603        if (use_wmma) {
604            gdn_chunk_wmma_kernel<<<dim3(NSE, HV), 128, WMMA_SMEM, cs>>>(
605                state, oc + t0 * HV * S, h + t0 * C, beta + t0 * HV, w.gcum, nch);
606            check("wmma");
607        } else {
608            gdn_chunk_kkt_kernel<<<dim3((unsigned) nch, HV), 128, 2 * CH * (S + 1) * sizeof(float), cs>>>(
609                w.A, w.P, h + t0 * C, beta + t0 * HV, w.gcum, nch);
610            check("kkt");
611        }
612        if (prof) {
613            cudaEventRecord(pe1, cs);
614            cudaEventSynchronize(pe1);
615            cudaEventElapsedTime(&ms[1], pe0, pe1);
616            cudaEventRecord(pe0, cs);
617        }
618        if (!use_wmma) {
619            gdn_chunk_fwd_kernel<<<dim3(NSE, HV), 128, 0, cs>>>(state, oc + t0 * HV * S, h + t0 * C, beta + t0 * HV,
620                                                                w.gcum, w.A, w.P, nch);
621            check("fwd");
622        }
623        if (prof) {
624            cudaEventRecord(pe1, cs);
625            cudaEventSynchronize(pe1);
626            cudaEventElapsedTime(&ms[2], pe0, pe1);
627        }
628    }
629    if (prof) {
630        std::printf("gdn_chunk prof T=%lld: cumsum %.3fms stage2 %.3fms stage3 %.3fms\n", (long long) T, ms[0],
631                    ms[1], ms[2]);
632        cudaEventDestroy(pe0);
633        cudaEventDestroy(pe1);
634    }
635#endif
636}
637
638}  // namespace strata::prefill