okami.mom/strata

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

Niko1221Merge f-qwen36 into f-144-rel (geometry: #2179's read_geometry guard kept for qwen4exp, Qwen3.6's family guard on top)4cfeaa0f4

main
40.6 KiB832 linesraw
1// src/qwen35/q36ref.cu - NEW-MODELS-PLAN.md phase T1: the reference path for Qwen3.6-35B-A3B (GGUF architecture
2// qwen35moe), exactness first.  One GPU, the whole model resident in VRAM (UD-Q4_K_XL: 21.3 GiB on a 32 GB card),
3// one token at a time (the prompt too), fp32 activations, every weight read in its GGUF form.  Two kernel sets:
4// --kernels plain, this file's own plain kernels (the reference), and --kernels strata (default), Strata's native
5// MMVQ for the quantized matmuls (dense and routed experts) and its fused GDN step with the SiLU-gated norm - the
6// engine's kernels on the new family's shapes.  No expert cache, no MTP, no graphs: checked against llama.cpp
7// (per-layer hidden states, greedy tokens, teacher-forced KL: tools/qwen35/).
8//
9// The forward pass, as llama.cpp's src/models/qwen35moe.cpp builds it:
10//   x = token_embd[tok]
11//   per layer l < 40:  h = rms(x) * attn_norm
12//       GDN (l % 4 != 3): qkv = W_qkv h (8192), z = W_gate h (4096), b = sigmoid(W_beta h), a = W_alpha h (32 each)
13//            c = silu(causal conv4(qkv)); q, k = l2norm(c[0:2048]), l2norm(c[2048:4096]) (16 heads), v = c[4096:] (32)
14//            g = softplus(a + dt_bias) * ssm_a;  per V head h (K head h % 16):  S = S * exp(g_h);
15//            d = (v - S k) * b_h;  S += d k^T;  o = S q / sqrt(128);  o = rms(o) * ssm_norm * silu(z_h)
16//            y = W_ssm_out o
17//       attention (l % 4 == 3): attn_q -> per head [q 256 | gate 256]; q, k = rms(.) * q_norm/k_norm; NEOX RoPE over the
18//            first 64 dims (base 1e7; text positions: the M-RoPE sections all carry the same position); GQA 16 / 2;
19//            y = W_o (softmax(q k^T / 16) v * sigmoid(gate))
20//       x += y;  h2 = rms(x) * post_attention_norm
21//       MoE: p = softmax(W_router h2) over 256, top-8, renormalised; sum_e p_e W_down_e (silu(W_gate_e h2) * W_up_e h2)
22//            + sigmoid(w_shexp_gate . h2) * W_down_s (silu(W_gate_s h2) * W_up_s h2);  x += moe
23//   logits = W_output (rms(x) * output_norm)
24//
25// Usage: strata-q36ref --model Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf --tokens 248045,846,198,... [--n 64] [--ctx 4096]
26//                      [--dump-layers FILE] [--dump-logits FILE] [--act q8|f32] [--kernels strata|plain]
27//                      [--force IDS] [--dump-full-logits F]
28//   prints the greedy ids ("gen: id id ..."); --dump-layers writes every processed position's 40 layer outputs (f32,
29//   [pos][layer][2048]); --dump-logits writes each greedy step's top-2 (id, logit) pairs for the near-tie report;
30//   --force feeds the given continuation instead of the greedy ids and --dump-full-logits writes every step's
31//   logits (f32, [step][vocab]) for the teacher-forced KL check (tools/qwen35/kl.py).
32#include "strata/artifact/gguf_reader.hpp"
33#include "strata/core/family_layout.hpp"
34#include "strata/kernels/fused_gdn.hpp"
35#include "strata/kernels/native_mmvq.hpp"
36#include "strata/kernels/native_router.hpp"
37
38#include <cuda_runtime.h>
39
40#include <algorithm>
41#include <chrono>
42#include <cmath>
43#include <cstdint>
44#include <cstdio>
45#include <cstdlib>
46#include <cstring>
47#include <map>
48#include <string>
49#include <vector>
50
51namespace {
52
53#define CK(x)                                                                                                          \
54    do {                                                                                                               \
55        cudaError_t e_ = (x);                                                                                          \
56        if (e_ != cudaSuccess) {                                                                                       \
57            std::fprintf(stderr, "q36ref: %s failed: %s (%s:%d)\n", #x, cudaGetErrorString(e_), __FILE__, __LINE__); \
58            std::exit(1);                                                                                              \
59        }                                                                                                              \
60    } while (0)
61
62// ------------------------------------------------------------------------------------------------ dequantisation
63// ggml's block formats, 32 values at a time ("chunk" c of a row).  The formulas are ggml-quants.c's dequantize_row_*.
64enum : int { T_F32 = 0, T_F16 = 1, T_Q8_0 = 8, T_Q4_K = 12, T_Q5_K = 13, T_Q6_K = 14, T_BF16 = 30 };
65
66__device__ __forceinline__ float h2f(uint16_t h) {
67    const uint32_t s = (uint32_t) (h >> 15) << 31, e = (h >> 10) & 0x1f, m = h & 0x3ff;
68    if (e == 0) {
69        const float v = ldexpf((float) m, -24);
70        return s ? -v : v;
71    }
72    const uint32_t f = e == 31 ? (s | 0x7f800000u | (m << 13)) : (s | ((e + 112) << 23) | (m << 13));
73    return __uint_as_float(f);
74}
75__device__ __forceinline__ uint16_t ld16(const uint8_t* p) { return (uint16_t) (p[0] | (p[1] << 8)); }
76
77__device__ __forceinline__ void scale_min_k4(int j, const uint8_t* q, int& d, int& m) {
78    if (j < 4) {
79        d = q[j] & 63;
80        m = q[j + 4] & 63;
81    } else {
82        d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4);
83        m = (q[j + 4] >> 4) | ((q[j] >> 6) << 4);
84    }
85}
86
87/// The 32 values of chunk `c` of one row (`row` = the row's first byte).
88template <int T> __device__ void deq32(const uint8_t* row, int c, float* out) {
89    if constexpr (T == T_F32) {
90        const float* r = (const float*) row + 32 * c;
91        for (int l = 0; l < 32; ++l) out[l] = r[l];
92    } else if constexpr (T == T_F16) {
93        const uint8_t* r = row + 64 * c;
94        for (int l = 0; l < 32; ++l) out[l] = h2f(ld16(r + 2 * l));
95    } else if constexpr (T == T_BF16) {
96        const uint8_t* r = row + 64 * c;
97        for (int l = 0; l < 32; ++l) out[l] = __uint_as_float((uint32_t) ld16(r + 2 * l) << 16);
98    } else if constexpr (T == T_Q8_0) {
99        const uint8_t* b = row + 34 * c;
100        const float d = h2f(ld16(b));
101        const int8_t* q = (const int8_t*) (b + 2);
102        for (int l = 0; l < 32; ++l) out[l] = d * (float) q[l];
103    } else if constexpr (T == T_Q4_K) {
104        const uint8_t* b = row + 144 * (c >> 3);
105        const int j = c & 7;
106        const float d = h2f(ld16(b)), dmin = h2f(ld16(b + 2));
107        int sc, m;
108        scale_min_k4(j, b + 4, sc, m);
109        const float d1 = d * (float) sc, m1 = dmin * (float) m;
110        const uint8_t* qs = b + 16 + 32 * (j >> 1);
111        for (int l = 0; l < 32; ++l) out[l] = d1 * (float) ((j & 1) ? (qs[l] >> 4) : (qs[l] & 0xF)) - m1;
112    } else if constexpr (T == T_Q5_K) {
113        const uint8_t* b = row + 176 * (c >> 3);
114        const int j = c & 7;
115        const float d = h2f(ld16(b)), dmin = h2f(ld16(b + 2));
116        int sc, m;
117        scale_min_k4(j, b + 4, sc, m);
118        const float d1 = d * (float) sc, m1 = dmin * (float) m;
119        const uint8_t* qh = b + 16;
120        const uint8_t* qs = b + 48 + 32 * (j >> 1);
121        for (int l = 0; l < 32; ++l) {
122            const int q = ((j & 1) ? (qs[l] >> 4) : (qs[l] & 0xF)) + ((qh[l] >> j) & 1 ? 16 : 0);
123            out[l] = d1 * (float) q - m1;
124        }
125    } else if constexpr (T == T_Q6_K) {
126        const uint8_t* b = row + 210 * (c >> 3);
127        const int j = c & 7, n = j >> 2, r = j & 3;
128        const uint8_t* ql = b + 64 * n;
129        const uint8_t* qh = b + 128 + 32 * n;
130        const int8_t* sc = (const int8_t*) (b + 192) + 8 * n;
131        const float d = h2f(ld16(b + 208));
132        for (int l = 0; l < 32; ++l) {
133            const int is = l / 16;
134            int q;
135            if (r == 0) q = (ql[l] & 0xF) | (((qh[l] >> 0) & 3) << 4);
136            else if (r == 1) q = (ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4);
137            else if (r == 2) q = (ql[l] >> 4) | (((qh[l] >> 4) & 3) << 4);
138            else q = (ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4);
139            out[l] = d * (float) sc[is + 2 * r] * (float) (q - 32);
140        }
141    }
142}
143
144__device__ float block_sum(float v, float* sh) {
145    sh[threadIdx.x] = v;
146    __syncthreads();
147    for (int s = blockDim.x / 2; s > 0; s >>= 1) {
148        if ((int) threadIdx.x < s) sh[threadIdx.x] += sh[threadIdx.x + s];
149        __syncthreads();
150    }
151    const float r = sh[0];
152    __syncthreads();
153    return r;
154}
155
156constexpr int kThreads = 128;
157
158/// y[sel][o] = W_e[o] . x[sel] for row o (grid.x), selection `sel` (grid.y): expert ids[sel] (or 0 without ids),
159/// x of selection sel at x + sel * x_stride.  `beta` != 0 adds into y.
160template <int T>
161__global__ void k_gemv(const uint8_t* W, size_t row_bytes, size_t expert_bytes, const int* ids, int n_in, const float* x,
162                       size_t x_stride, float* y, int n_out) {
163    __shared__ float sh[kThreads];
164    const int o = blockIdx.x, sel = blockIdx.y;
165    const int e = ids ? ids[sel] : 0;
166    const uint8_t* row = W + (size_t) e * expert_bytes + (size_t) o * row_bytes;
167    const float* xs = x + (size_t) sel * x_stride;
168    float acc = 0.f, v[32];
169    for (int c = threadIdx.x; c < n_in / 32; c += blockDim.x) {
170        deq32<T>(row, c, v);
171        const float* xc = xs + 32 * c;
172        for (int l = 0; l < 32; ++l) acc += v[l] * xc[l];
173    }
174    acc = block_sum(acc, sh);
175    if (threadIdx.x == 0) y[(size_t) sel * n_out + o] = acc;
176}
177
178template <int T> __global__ void k_row(const uint8_t* W, size_t row_bytes, int row, int n, float* out) {
179    const uint8_t* r = W + (size_t) row * row_bytes;
180    for (int c = blockIdx.x * blockDim.x + threadIdx.x; c < n / 32; c += gridDim.x * blockDim.x) deq32<T>(r, c, out + 32 * c);
181}
182
183/// y = x / sqrt(mean(x^2) + eps) * w, per group of n (grid = groups); w (length n) may be null.
184__global__ void k_rms(const float* x, const float* w, float* y, int n, float eps) {
185    __shared__ float sh[kThreads];
186    const float* xg = x + (size_t) blockIdx.x * n;
187    float* yg = y + (size_t) blockIdx.x * n;
188    float s = 0.f;
189    for (int i = threadIdx.x; i < n; i += blockDim.x) s += xg[i] * xg[i];
190    s = block_sum(s, sh);
191    const float r = 1.0f / sqrtf(s / (float) n + eps);
192    for (int i = threadIdx.x; i < n; i += blockDim.x) yg[i] = xg[i] * r * (w ? w[i] : 1.0f);
193}
194
195__device__ __forceinline__ float silu(float v) { return v / (1.0f + expf(-v)); }
196__device__ __forceinline__ float sigm(float v) { return 1.0f / (1.0f + expf(-v)); }
197__device__ __forceinline__ float softplus(float v) { return v > 20.f ? v : log1pf(expf(v)); }
198
199/// The causal 4-tap conv over the 8192 qkv channels with its 3-input state, then SiLU; the state moves by one.
200__global__ void k_conv(const float* qkv, float* state, const float* w, float* out, int C, int K) {
201    const int c = blockIdx.x * blockDim.x + threadIdx.x;
202    if (c >= C) return;
203    float acc = 0.f;
204    for (int k = 0; k < K - 1; ++k) acc += state[(size_t) k * C + c] * w[(size_t) c * K + k];
205    acc += qkv[c] * w[(size_t) c * K + K - 1];
206    for (int k = 0; k < K - 2; ++k) state[(size_t) k * C + c] = state[(size_t) (k + 1) * C + c];
207    state[(size_t) (K - 2) * C + c] = qkv[c];
208    out[c] = silu(acc);
209}
210
211/// One gated delta-rule step per V head (grid = HV, block = D = 128): S[i][j] row i owned by thread i.
212__global__ void k_gdn(const float* conv, const float* alpha, const float* dt_bias, const float* ssm_a,
213                      const float* beta_raw, float* S, float* out, int HK, int /*HV: the grid*/, int D, float eps) {
214    extern __shared__ float sm[];
215    float* q = sm;
216    float* k = sm + D;
217    float* red = sm + 2 * D;
218    const int h = blockIdx.x, kh = h % HK, i = threadIdx.x;
219    const float qi = conv[kh * D + i], ki = conv[HK * D + kh * D + i], vi = conv[2 * HK * D + h * D + i];
220    const float qn = block_sum(qi * qi, red), kn = block_sum(ki * ki, red);
221    q[i] = qi / sqrtf(qn + eps) / sqrtf((float) D);
222    k[i] = ki / sqrtf(kn + eps);
223    __syncthreads();
224    const float g = expf(softplus(alpha[h] + dt_bias[h]) * ssm_a[h]);
225    const float b = sigm(beta_raw[h]);
226    float* Si = S + ((size_t) h * D + i) * D;
227    float sk = 0.f;
228    for (int j = 0; j < D; ++j) {
229        Si[j] *= g;
230        sk += Si[j] * k[j];
231    }
232    const float d = (vi - sk) * b;
233    float o = 0.f;
234    for (int j = 0; j < D; ++j) {
235        Si[j] += d * k[j];
236        o += Si[j] * q[j];
237    }
238    out[h * D + i] = o;
239}
240
241/// The fused path's gate and beta, in place: alpha -> softplus(alpha + dt) * ssm_a (exp'd by the step), beta -> sigmoid.
242__global__ void k_gdn_gb(float* alpha, const float* dt_bias, const float* ssm_a, float* beta, int HV) {
243    const int h = threadIdx.x;
244    if (h >= HV) return;
245    alpha[h] = softplus(alpha[h] + dt_bias[h]) * ssm_a[h];
246    beta[h] = sigm(beta[h]);
247}
248
249/// o = rms(o) * w * silu(z), per V head (grid = HV, block = D).
250__global__ void k_gated_norm(float* o, const float* w, const float* z, int D, float eps) {
251    __shared__ float sh[kThreads];
252    float* oh = o + (size_t) blockIdx.x * D;
253    const float v = oh[threadIdx.x];
254    const float s = block_sum(v * v, sh);
255    oh[threadIdx.x] = v / sqrtf(s / (float) D + eps) * w[threadIdx.x] * silu(z[blockIdx.x * D + threadIdx.x]);
256}
257
258/// The attention layer's per-token preparation: q (from the [q | gate] pairs) and k RMS-normed per head with their
259/// weights, NEOX RoPE over the first n_rot dims, k and v appended to the cache at `pos`, the gate kept.
260__global__ void k_attn_prep(const float* qg, const float* kx, const float* vx, const float* qw, const float* kw,
261                            float* q, float* gate, float* kc, float* vc, int H, int /*HKV: the grid*/, int D, int n_rot, int pos,
262                            int ctx, float base, float eps) {
263    __shared__ float sh[kThreads];
264    __shared__ float buf[512];
265    const int head = blockIdx.x;   // 0..H-1: query heads, H..H+HKV-1: key heads
266    const bool isq = head < H;
267    const float* src = isq ? qg + (size_t) head * 2 * D : kx + (size_t) (head - H) * D;
268    float s = 0.f;
269    for (int i = threadIdx.x; i < D; i += blockDim.x) s += src[i] * src[i];
270    s = block_sum(s, sh);
271    const float r = 1.0f / sqrtf(s / (float) D + eps);
272    for (int i = threadIdx.x; i < D; i += blockDim.x) buf[i] = src[i] * r * (isq ? qw[i] : kw[i]);
273    __syncthreads();
274    float* dst = isq ? q + (size_t) head * D : kc + ((size_t) (head - H) * ctx + pos) * D;
275    const int half = n_rot / 2;
276    for (int i = threadIdx.x; i < D; i += blockDim.x) {
277        float v = buf[i];
278        if (i < n_rot) {
279            const int p = i < half ? i : i - half;
280            const float theta = (float) pos * powf(base, -2.0f * (float) p / (float) n_rot);
281            const float cs = cosf(theta), sn = sinf(theta);
282            v = i < half ? buf[i] * cs - buf[i + half] * sn : buf[i - half] * sn + buf[i] * cs;
283        }
284        dst[i] = v;
285    }
286    if (isq)
287        for (int i = threadIdx.x; i < D; i += blockDim.x) gate[(size_t) head * D + i] = qg[(size_t) head * 2 * D + D + i];
288    else
289        for (int i = threadIdx.x; i < D; i += blockDim.x)
290            vc[((size_t) (head - H) * ctx + pos) * D + i] = vx[(size_t) (head - H) * D + i];
291}
292
293/// softmax(q k^T * scale) v for one query head per block (GQA: KV head = head / (H / HKV)), times sigmoid(gate).
294__global__ void k_attn(const float* q, const float* kc, const float* vc, const float* gate, float* out, int H, int HKV,
295                       int D, int n_pos, int ctx, float scale) {
296    extern __shared__ float sc[];
297    __shared__ float sh[kThreads];
298    const int h = blockIdx.x, kvh = h / (H / HKV);
299    const float* qh = q + (size_t) h * D;
300    for (int p = threadIdx.x; p < n_pos; p += blockDim.x) {
301        const float* kp = kc + ((size_t) kvh * ctx + p) * D;
302        float s = 0.f;
303        for (int i = 0; i < D; ++i) s += qh[i] * kp[i];
304        sc[p] = s * scale;
305    }
306    __syncthreads();
307    float mx = -INFINITY;
308    for (int p = threadIdx.x; p < n_pos; p += blockDim.x) mx = fmaxf(mx, sc[p]);
309    sh[threadIdx.x] = mx;
310    __syncthreads();
311    for (int s = blockDim.x / 2; s > 0; s >>= 1) {
312        if ((int) threadIdx.x < s) sh[threadIdx.x] = fmaxf(sh[threadIdx.x], sh[threadIdx.x + s]);
313        __syncthreads();
314    }
315    mx = sh[0];
316    __syncthreads();
317    float sum = 0.f;
318    for (int p = threadIdx.x; p < n_pos; p += blockDim.x) {
319        sc[p] = expf(sc[p] - mx);
320        sum += sc[p];
321    }
322    sum = block_sum(sum, sh);
323    for (int i = threadIdx.x; i < D; i += blockDim.x) {
324        float acc = 0.f;
325        for (int p = 0; p < n_pos; ++p) acc += sc[p] * vc[((size_t) kvh * ctx + p) * D + i];
326        out[(size_t) h * D + i] = acc / sum * sigm(gate[(size_t) h * D + i]);
327    }
328}
329
330__global__ void k_swiglu(const float* g, const float* u, float* h, int n) {
331    const int i = blockIdx.x * blockDim.x + threadIdx.x;
332    if (i < n) h[i] = silu(g[i]) * u[i];
333}
334__global__ void k_add(float* x, const float* y, int n) {
335    const int i = blockIdx.x * blockDim.x + threadIdx.x;
336    if (i < n) x[i] += y[i];
337}
338/// x += sum_s w[s] * y[s] (the routed experts), + sigmoid(gs) * ys (the shared expert)
339__global__ void k_moe_sum(float* x, const float* y, const float* w, int k, const float* ys, const float* gs, int n) {
340    const int i = blockIdx.x * blockDim.x + threadIdx.x;
341    if (i >= n) return;
342    float acc = 0.f;
343    for (int s = 0; s < k; ++s) acc += w[s] * y[(size_t) s * n + i];
344    x[i] += acc + sigm(gs[0]) * ys[i];
345}
346
347// ------------------------------------------------------------------------------------------------ the model
348struct Tensor {
349    const uint8_t* d = nullptr;   // device
350    int type = -1;
351    std::vector<int64_t> shape;
352    size_t row_bytes = 0;
353};
354
355size_t row_bytes_of(int type, int64_t n) {
356    int be = 0, bb = 0;
357    if (!strata::block_geometry((uint32_t) type, be, bb)) return 0;
358    return (size_t) (n / be) * (size_t) bb;
359}
360
361template <int T>
362void gemv_t(const Tensor& w, size_t expert_bytes, const int* ids, int n_sel, const float* x, size_t x_stride, float* y) {
363    const int n_in = (int) w.shape[0], n_out = (int) w.shape[1];
364    k_gemv<T><<<dim3(n_out, n_sel), kThreads>>>(w.d, w.row_bytes, expert_bytes, ids, n_in, x, x_stride, y, n_out);
365}
366
367/// llama.cpp's GPU matmuls on quantized weights (MMVQ for one token, MMQ for a batch) read the activations as q8_1:
368/// per 32 values d = amax / 127, q = round(x / d).  --act q8 (the default) gives this path the same rounding, so
369/// its numbers follow llama.cpp's instead of drifting from them by the activation rounding; --act f32 reads them as
370/// they are.  `x` (n_sel vectors of n, `stride` apart) -> `out` (packed, n apart).
371__global__ void k_act_q8(const float* x, size_t stride, int n, float* out) {
372    const int sel = blockIdx.y, blk = blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32, l = threadIdx.x % 32;
373    if (blk * 32 >= n) return;
374    const float v = x[(size_t) sel * stride + blk * 32 + l];
375    __shared__ float am[kThreads];
376    am[threadIdx.x] = fabsf(v);
377    __syncthreads();
378    const int base = threadIdx.x - l;
379    float amax = 0.f;
380    for (int i = 0; i < 32; ++i) amax = fmaxf(amax, am[base + i]);
381    const float d = amax / 127.0f;
382    const float q = amax == 0.0f ? 0.0f : roundf(v / d);
383    out[(size_t) sel * n + blk * 32 + l] = q * d;
384}
385
386bool g_act_q8 = true;
387float* g_act_buf = nullptr;
388constexpr size_t kActBuf = 1 << 16;
389
390// --kernels strata (the default): the quantized matmuls run on Strata's native MMVQ (llama.cpp's pinned MMVQ: q8_1
391// activations, one launch per routed expert) and the GDN step on Strata's fused kernels (conv + SiLU + L2, then the
392// step with the SiLU-gated norm); --kernels plain keeps every op on this file's own kernels (the reference).  The
393// Strata kernels run on a blocking stream, so they and the null-stream work here stay in order.
394bool g_strata = true;
395cudaStream_t g_st = nullptr;
396void* g_q8 = nullptr;
397std::vector<int> g_ids_host;   // the routed experts of the current layer (the native expert path launches per id)
398
399void gemv(const Tensor& w, const float* x, float* y, const int* ids = nullptr, int n_sel = 1, size_t x_stride = 0) {
400    const size_t eb = w.shape.size() == 3 ? w.row_bytes * (size_t) w.shape[1] : 0;
401    const bool quant = w.type == T_Q8_0 || w.type == T_Q4_K || w.type == T_Q5_K || w.type == T_Q6_K;
402    if (quant && g_strata) {
403        const int n_in = (int) w.shape[0], n_out = (int) w.shape[1], cols = x_stride ? n_sel : 1;
404        if (x_stride && x_stride != (size_t) n_in) {
405            std::fprintf(stderr, "q36ref: the native path wants contiguous input columns\n");
406            std::exit(1);
407        }
408        strata::kernels::native_quantize_q8_1(x, g_q8, n_in, cols, g_st);
409        const size_t qb = strata::kernels::native_q8_1_bytes(n_in, 1);
410        for (int sel = 0; sel < n_sel; ++sel) {
411            const uint8_t* we = w.d + (ids ? (size_t) g_ids_host[(size_t) sel] * eb : 0);
412            strata::kernels::native_mmvq(w.type, we, (const char*) g_q8 + (x_stride ? (size_t) sel * qb : 0),
413                                         y + (size_t) sel * n_out, n_in, n_out, 1, g_st);
414        }
415        CK(cudaGetLastError());
416        return;
417    }
418    if (quant && g_act_q8) {
419        const int n = (int) w.shape[0], sel = x_stride ? n_sel : 1;
420        if ((size_t) n * sel > kActBuf) {
421            std::fprintf(stderr, "q36ref: activation scratch too small\n");
422            std::exit(1);
423        }
424        k_act_q8<<<dim3((n / 32 + kThreads / 32 - 1) / (kThreads / 32), sel), kThreads>>>(x, x_stride, n, g_act_buf);
425        x = g_act_buf;
426        x_stride = x_stride ? (size_t) n : 0;
427    }
428    switch (w.type) {
429    case T_F32: gemv_t<T_F32>(w, eb, ids, n_sel, x, x_stride, y); break;
430    case T_F16: gemv_t<T_F16>(w, eb, ids, n_sel, x, x_stride, y); break;
431    case T_BF16: gemv_t<T_BF16>(w, eb, ids, n_sel, x, x_stride, y); break;
432    case T_Q8_0: gemv_t<T_Q8_0>(w, eb, ids, n_sel, x, x_stride, y); break;
433    case T_Q4_K: gemv_t<T_Q4_K>(w, eb, ids, n_sel, x, x_stride, y); break;
434    case T_Q5_K: gemv_t<T_Q5_K>(w, eb, ids, n_sel, x, x_stride, y); break;
435    case T_Q6_K: gemv_t<T_Q6_K>(w, eb, ids, n_sel, x, x_stride, y); break;
436    default:
437        std::fprintf(stderr, "q36ref: no kernel for ggml type %d (%s)\n", w.type, strata::ggml_type_name((uint32_t) w.type));
438        std::exit(1);
439    }
440    CK(cudaGetLastError());
441}
442
443/// A 1-D tensor as f32 on the device (F32 as is, BF16 widened at load).
444struct Model {
445    strata::core::ModelGeometry g;
446    int64_t top_k = 8;
447    float eps = 1e-6f, rope_base = 1e7f;
448    int n_rot = 64;
449    std::map<std::string, Tensor> t;
450    std::map<std::string, float*> f32;   // the small vectors, f32
451
452    const Tensor& W(const std::string& n) const {
453        auto it = t.find(n);
454        if (it == t.end()) {
455            std::fprintf(stderr, "q36ref: missing tensor %s\n", n.c_str());
456            std::exit(1);
457        }
458        return it->second;
459    }
460    const float* F(const std::string& n) const {
461        auto it = f32.find(n);
462        if (it == f32.end()) {
463            std::fprintf(stderr, "q36ref: missing vector %s\n", n.c_str());
464            std::exit(1);
465        }
466        return it->second;
467    }
468};
469
470float h2f_host(uint16_t h) {
471    const uint32_t s = (uint32_t) (h >> 15) << 31, e = (h >> 10) & 0x1f, m = h & 0x3ff;
472    if (e == 0) return (s ? -1.f : 1.f) * std::ldexp((float) m, -24);
473    const uint32_t f = e == 31 ? (s | 0x7f800000u | (m << 13)) : (s | ((e + 112) << 23) | (m << 13));
474    float r;
475    std::memcpy(&r, &f, 4);
476    return r;
477}
478
479bool load(const std::string& path, Model& m, std::string& err) {
480    const auto t0 = std::chrono::steady_clock::now();
481    const strata::GgufModel gm = strata::GgufModel::open(path);
482    if (!strata::core::geometry_from_gguf(gm.meta(), m.g, m.top_k, err)) return false;
483    if (m.g.family != strata::ModelFamily::Qwen35Moe) {
484        err = "this reference path is for Qwen3.6-35B-A3B (qwen35moe) only";
485        return false;
486    }
487    size_t checked = 0;
488    if (!strata::core::check_gguf_layout(gm, m.g, err, &checked)) return false;
489    const std::string p = "qwen35moe.";
490    if (const strata::MetaValue* v = gm.meta().get(p + "attention.layer_norm_rms_epsilon")) m.eps = (float) v->num();
491    if (const strata::MetaValue* v = gm.meta().get(p + "rope.freq_base")) m.rope_base = (float) v->num();
492    if (const strata::MetaValue* v = gm.meta().get(p + "rope.dimension_count")) m.n_rot = (int) v->u;
493    uint64_t bytes = 0;
494    for (size_t s = 0; s < gm.size(); ++s) {
495        const strata::GgufFile& f = gm.shard(s);
496        for (const strata::TensorInfo& ti : f.tensors()) {
497            const uint64_t nb = strata::tensor_payload_bytes(ti);
498            const uint8_t* src = f.tensor_data(ti);
499            // the MTP block (blk.40) is not run by this path: not loaded
500            if (ti.name.rfind("blk." + std::to_string(m.g.n_layers) + ".", 0) == 0) continue;
501            const bool conv = ti.name.size() > 17 && ti.name.compare(ti.name.size() - 17, 17, "ssm_conv1d.weight") == 0;
502            if (ti.shape.size() == 1 || conv) {
503                // the small vectors (and the conv taps): f32 on the device
504                std::vector<float> h(ti.elements());
505                if (ti.type == T_F32) std::memcpy(h.data(), src, h.size() * 4);
506                else if (ti.type == T_BF16)
507                    for (size_t i = 0; i < h.size(); ++i) {
508                        const uint32_t u = (uint32_t) (src[2 * i] | (src[2 * i + 1] << 8)) << 16;
509                        std::memcpy(&h[i], &u, 4);
510                    }
511                else if (ti.type == T_F16)
512                    for (size_t i = 0; i < h.size(); ++i) h[i] = h2f_host((uint16_t) (src[2 * i] | (src[2 * i + 1] << 8)));
513                else {
514                    err = ti.name + ": a 1-D tensor of type " + ti.type_name();
515                    return false;
516                }
517                float* d = nullptr;
518                CK(cudaMalloc(&d, h.size() * 4));
519                CK(cudaMemcpy(d, h.data(), h.size() * 4, cudaMemcpyHostToDevice));
520                m.f32[ti.name] = d;
521                bytes += h.size() * 4;
522                continue;
523            }
524            Tensor w;
525            w.type = (int) ti.type;
526            for (uint64_t d : ti.shape) w.shape.push_back((int64_t) d);
527            w.row_bytes = row_bytes_of(w.type, w.shape[0]);
528            uint8_t* d = nullptr;
529            CK(cudaMalloc(&d, nb));
530            CK(cudaMemcpy(d, src, nb, cudaMemcpyHostToDevice));
531            w.d = d;
532            m.t[ti.name] = w;
533            bytes += nb;
534        }
535    }
536    std::fprintf(stderr, "q36ref: %s: %zu tensors (layout checked), %.2f GiB on the GPU in %.1f s\n", path.c_str(),
537                 checked, (double) bytes / (1 << 30),
538                 std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count());
539    return true;
540}
541
542struct State {
543    int ctx = 4096, pos = 0;
544    // scratch
545    float *x, *h, *y, *qkv, *z, *alpha, *beta, *conv_out, *gdn_out, *qg, *k, *v, *q, *gate, *att, *router, *eg, *eu, *eh,
546        *ey, *sg, *su, *sh, *sy, *sgate, *wts, *logits;
547    int* ids;
548    std::vector<float*> conv_state, S, kc, vc;   // per layer (GDN: conv + S; attention: K/V cache)
549};
550
551float* dalloc(size_t n) {
552    float* p = nullptr;
553    CK(cudaMalloc(&p, n * 4));
554    CK(cudaMemset(p, 0, n * 4));
555    return p;
556}
557
558void init_state(const Model& m, State& s) {
559    const auto& g = m.g;
560    const int N = (int) g.n_embd, FF = (int) g.n_ff, K = (int) m.top_k;
561    s.x = dalloc(N); s.h = dalloc(N); s.y = dalloc(N);
562    s.qkv = dalloc(g.ssm_conv_channels); s.z = dalloc(g.ssm_value_dim); s.alpha = dalloc(g.ssm_v_heads);
563    s.beta = dalloc(g.ssm_v_heads); s.conv_out = dalloc(g.ssm_conv_channels); s.gdn_out = dalloc(g.ssm_value_dim);
564    s.qg = dalloc(2 * g.n_head * g.head_dim); s.k = dalloc(g.n_head_kv * g.head_dim); s.v = dalloc(g.n_head_kv * g.head_dim);
565    s.q = dalloc(g.n_head * g.head_dim); s.gate = dalloc(g.n_head * g.head_dim); s.att = dalloc(g.n_head * g.head_dim);
566    s.router = dalloc(g.n_expert);
567    s.eg = dalloc((size_t) K * FF); s.eu = dalloc((size_t) K * FF); s.eh = dalloc((size_t) K * FF); s.ey = dalloc((size_t) K * N);
568    s.sg = dalloc(g.n_ff_shexp); s.su = dalloc(g.n_ff_shexp); s.sh = dalloc(g.n_ff_shexp); s.sy = dalloc(N); s.sgate = dalloc(1);
569    s.wts = dalloc(K);
570    s.logits = dalloc(g.n_vocab);
571    CK(cudaMalloc(&s.ids, K * sizeof(int)));
572    g_act_buf = dalloc(kActBuf);
573    CK(cudaStreamCreate(&g_st));   // blocking: ordered with this file's null-stream launches and copies
574    CK(cudaMalloc(&g_q8, strata::kernels::native_q8_1_bytes((int) kActBuf, 1)));
575    for (int64_t l = 0; l < g.n_layers; ++l) {
576        if (strata::core::is_qsa_layer(g, l)) {
577            s.conv_state.push_back(nullptr);
578            s.S.push_back(nullptr);
579            s.kc.push_back(dalloc((size_t) g.n_head_kv * s.ctx * g.head_dim));
580            s.vc.push_back(dalloc((size_t) g.n_head_kv * s.ctx * g.head_dim));
581        } else {
582            s.conv_state.push_back(dalloc((size_t) (g.ssm_d_conv - 1) * g.ssm_conv_channels));
583            s.S.push_back(dalloc((size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size));
584            s.kc.push_back(nullptr);
585            s.vc.push_back(nullptr);
586        }
587    }
588}
589
590std::string L(int64_t l, const char* s) { return "blk." + std::to_string(l) + "." + s; }
591
592void embed(const Model& m, State& s, int tok) {
593    const Tensor& e = m.W("token_embd.weight");
594    const int N = (int) m.g.n_embd;
595    switch (e.type) {
596    case T_Q8_0: k_row<T_Q8_0><<<4, 128>>>(e.d, e.row_bytes, tok, N, s.x); break;
597    case T_Q4_K: k_row<T_Q4_K><<<4, 128>>>(e.d, e.row_bytes, tok, N, s.x); break;
598    case T_Q6_K: k_row<T_Q6_K><<<4, 128>>>(e.d, e.row_bytes, tok, N, s.x); break;
599    case T_BF16: k_row<T_BF16><<<4, 128>>>(e.d, e.row_bytes, tok, N, s.x); break;
600    case T_F16: k_row<T_F16><<<4, 128>>>(e.d, e.row_bytes, tok, N, s.x); break;
601    default:
602        std::fprintf(stderr, "q36ref: token_embd type %d has no row reader\n", e.type);
603        std::exit(1);
604    }
605    CK(cudaGetLastError());
606}
607
608/// One token through the model at position s.pos; the layer outputs into `layers` (host, n_layers x N) when given.
609void forward(const Model& m, State& s, int tok, float* layers) {
610    const auto& g = m.g;
611    const int N = (int) g.n_embd, K = (int) m.top_k, FF = (int) g.n_ff, FS = (int) g.n_ff_shexp;
612    const int B = 256;
613    embed(m, s, tok);
614    for (int64_t l = 0; l < g.n_layers; ++l) {
615        k_rms<<<1, kThreads>>>(s.x, m.F(L(l, "attn_norm.weight")), s.h, N, m.eps);
616        if (!strata::core::is_qsa_layer(g, l)) {
617            const int HK = (int) g.ssm_k_heads, HV = (int) g.ssm_v_heads, D = (int) g.ssm_state_size;
618            const int C = (int) g.ssm_conv_channels;
619            gemv(m.W(L(l, "attn_qkv.weight")), s.h, s.qkv);
620            gemv(m.W(L(l, "attn_gate.weight")), s.h, s.z);
621            gemv(m.W(L(l, "ssm_beta.weight")), s.h, s.beta);
622            gemv(m.W(L(l, "ssm_alpha.weight")), s.h, s.alpha);
623            if (g_strata && D == 128 && g.ssm_d_conv == 4) {
624                // Strata's fused GDN (its own state layouts: conv history [channel][3], S [row][head][col])
625                strata::kernels::fused_gdn_conv_l2(s.conv_state[l], s.qkv, m.F(L(l, "ssm_conv1d.weight")), s.conv_out,
626                                                   C, 2 * HK, m.eps, g_st);
627                k_gdn_gb<<<1, 64, 0, g_st>>>(s.alpha, m.F(L(l, "ssm_dt.bias")), m.F(L(l, "ssm_a")), s.beta, HV);
628                strata::kernels::fused_gdn_step_norm_silu(s.S[l], s.conv_out, s.conv_out + HK * D,
629                                                          s.conv_out + 2 * HK * D, s.alpha, s.beta, s.z,
630                                                          m.F(L(l, "ssm_norm.weight")), m.eps, s.gdn_out, HK, HV, g_st);
631            } else {
632                k_conv<<<(C + B - 1) / B, B>>>(s.qkv, s.conv_state[l], m.F(L(l, "ssm_conv1d.weight")), s.conv_out, C,
633                                               (int) g.ssm_d_conv);
634                k_gdn<<<HV, D, (2 * D + D) * sizeof(float)>>>(s.conv_out, s.alpha, m.F(L(l, "ssm_dt.bias")),
635                                                               m.F(L(l, "ssm_a")), s.beta, s.S[l], s.gdn_out, HK, HV, D,
636                                                               m.eps);
637                k_gated_norm<<<HV, D>>>(s.gdn_out, m.F(L(l, "ssm_norm.weight")), s.z, D, m.eps);
638            }
639            gemv(m.W(L(l, "ssm_out.weight")), s.gdn_out, s.y);
640        } else {
641            const int H = (int) g.n_head, HKV = (int) g.n_head_kv, D = (int) g.head_dim;
642            gemv(m.W(L(l, "attn_q.weight")), s.h, s.qg);
643            gemv(m.W(L(l, "attn_k.weight")), s.h, s.k);
644            gemv(m.W(L(l, "attn_v.weight")), s.h, s.v);
645            k_attn_prep<<<H + HKV, kThreads>>>(s.qg, s.k, s.v, m.F(L(l, "attn_q_norm.weight")),
646                                               m.F(L(l, "attn_k_norm.weight")), s.q, s.gate, s.kc[l], s.vc[l], H, HKV, D,
647                                               m.n_rot, s.pos, s.ctx, m.rope_base, m.eps);
648            k_attn<<<H, kThreads, (size_t) (s.pos + 1) * sizeof(float)>>>(s.q, s.kc[l], s.vc[l], s.gate, s.att, H, HKV, D,
649                                                                          s.pos + 1, s.ctx, 1.0f / sqrtf((float) D));
650            gemv(m.W(L(l, "attn_output.weight")), s.att, s.y);
651        }
652        CK(cudaGetLastError());
653        k_add<<<(N + B - 1) / B, B>>>(s.x, s.y, N);
654        k_rms<<<1, kThreads>>>(s.x, m.F(L(l, "post_attention_norm.weight")), s.h, N, m.eps);
655        // router: softmax over every expert, top-k, renormalised (host side: exact and simple)
656        gemv(m.W(L(l, "ffn_gate_inp.weight")), s.h, s.router);
657        if (g_strata && strata::kernels::native_router_topk_supported((int) g.n_expert, K)) {
658            // Strata's router (llama.cpp's topk-moe contract) for 256 / 8; the ids come back for the per-expert launches
659            strata::kernels::native_router_topk(s.router, s.ids, s.wts, (int) g.n_expert, K, 1, g_st);
660            g_ids_host.resize((size_t) K);
661            CK(cudaMemcpy(g_ids_host.data(), s.ids, K * sizeof(int), cudaMemcpyDeviceToHost));
662        } else {
663            std::vector<float> r((size_t) g.n_expert);
664            CK(cudaMemcpy(r.data(), s.router, r.size() * 4, cudaMemcpyDeviceToHost));
665            const float mx = *std::max_element(r.begin(), r.end());
666            double sum = 0;
667            for (float& v : r) sum += (v = std::exp(v - mx));
668            for (float& v : r) v = (float) (v / sum);
669            std::vector<int> idx((size_t) g.n_expert);
670            for (int i = 0; i < (int) idx.size(); ++i) idx[i] = i;
671            std::partial_sort(idx.begin(), idx.begin() + K, idx.end(),
672                              [&](int a, int b) { return r[a] > r[b] || (r[a] == r[b] && a < b); });
673            std::vector<float> w(K);
674            float ws = 0;
675            for (int i = 0; i < K; ++i) ws += (w[i] = r[idx[i]]);
676            for (float& v : w) v /= ws;
677            g_ids_host.assign(idx.begin(), idx.begin() + K);
678            CK(cudaMemcpy(s.ids, idx.data(), K * sizeof(int), cudaMemcpyHostToDevice));
679            CK(cudaMemcpy(s.wts, w.data(), K * 4, cudaMemcpyHostToDevice));
680        }
681        gemv(m.W(L(l, "ffn_gate_exps.weight")), s.h, s.eg, s.ids, K, 0);
682        gemv(m.W(L(l, "ffn_up_exps.weight")), s.h, s.eu, s.ids, K, 0);
683        k_swiglu<<<(K * FF + B - 1) / B, B>>>(s.eg, s.eu, s.eh, K * FF);
684        gemv(m.W(L(l, "ffn_down_exps.weight")), s.eh, s.ey, s.ids, K, FF);
685        // shared expert with its sigmoid scalar gate
686        gemv(m.W(L(l, "ffn_gate_shexp.weight")), s.h, s.sg);
687        gemv(m.W(L(l, "ffn_up_shexp.weight")), s.h, s.su);
688        k_swiglu<<<(FS + B - 1) / B, B>>>(s.sg, s.su, s.sh, FS);
689        gemv(m.W(L(l, "ffn_down_shexp.weight")), s.sh, s.sy);
690        {
691            Tensor gs;
692            gs.d = (const uint8_t*) m.F(L(l, "ffn_gate_inp_shexp.weight"));
693            gs.type = T_F32;
694            gs.shape = {N, 1};
695            gs.row_bytes = (size_t) N * 4;
696            gemv(gs, s.h, s.sgate);
697        }
698        k_moe_sum<<<(N + B - 1) / B, B>>>(s.x, s.ey, s.wts, K, s.sy, s.sgate, N);
699        CK(cudaGetLastError());
700        if (layers) CK(cudaMemcpy(layers + (size_t) l * N, s.x, (size_t) N * 4, cudaMemcpyDeviceToHost));
701    }
702    k_rms<<<1, kThreads>>>(s.x, m.F("output_norm.weight"), s.h, N, m.eps);
703    gemv(m.W("output.weight"), s.h, s.logits);
704    CK(cudaDeviceSynchronize());
705    ++s.pos;
706}
707
708std::vector<int> parse_ids(const std::string& s) {
709    std::vector<int> v;
710    size_t i = 0;
711    while (i < s.size()) {
712        while (i < s.size() && (s[i] == ',' || s[i] == ' ' || s[i] == '\n' || s[i] == '\r')) ++i;
713        if (i >= s.size()) break;
714        v.push_back(std::atoi(s.c_str() + i));
715        while (i < s.size() && s[i] != ',' && s[i] != ' ' && s[i] != '\n') ++i;
716    }
717    return v;
718}
719
720}  // namespace
721
722int main(int argc, char** argv) {
723    std::string model, tokens, dump_layers, dump_logits, force, dump_full;
724    int n_gen = 64, ctx = 4096;
725    for (int i = 1; i < argc; ++i) {
726        const std::string a = argv[i];
727        auto next = [&]() -> std::string {
728            if (i + 1 >= argc) {
729                std::fprintf(stderr, "q36ref: %s needs a value\n", a.c_str());
730                std::exit(2);
731            }
732            return argv[++i];
733        };
734        if (a == "--model") model = next();
735        else if (a == "--tokens") tokens = next();
736        else if (a == "--tokens-file") {
737            FILE* f = std::fopen(next().c_str(), "rb");
738            if (!f) { std::fprintf(stderr, "q36ref: cannot read the tokens file\n"); return 2; }
739            char buf[4096];
740            size_t n;
741            while ((n = std::fread(buf, 1, sizeof buf, f)) > 0) tokens.append(buf, n);
742            std::fclose(f);
743        } else if (a == "--n") n_gen = std::atoi(next().c_str());
744        else if (a == "--ctx") ctx = std::atoi(next().c_str());
745        else if (a == "--dump-layers") dump_layers = next();
746        else if (a == "--dump-logits") dump_logits = next();
747        else if (a == "--force") force = next();
748        else if (a == "--kernels") {
749            const std::string v = next();
750            if (v != "strata" && v != "plain") { std::fprintf(stderr, "q36ref: --kernels strata or plain\n"); return 2; }
751            g_strata = v == "strata";
752        }
753        else if (a == "--dump-full-logits") dump_full = next();
754        else if (a == "--act") {
755            const std::string v = next();
756            if (v != "q8" && v != "f32") { std::fprintf(stderr, "q36ref: --act q8 or f32\n"); return 2; }
757            g_act_q8 = v == "q8";
758        }
759        else {
760            std::fprintf(stderr, "usage: strata-q36ref --model GGUF --tokens ID,ID,... | --tokens-file F [--n 64] [--ctx 4096] "
761                                 "[--dump-layers FILE] [--dump-logits FILE] [--act q8|f32] [--kernels strata|plain] "
762                                 "[--force ID,ID,...] [--dump-full-logits FILE]\n");
763            return 2;
764        }
765    }
766    const std::vector<int> prompt = parse_ids(tokens);
767    // --force: the continuation is these tokens (teacher forcing: the KL check reads both engines on one sequence);
768    // the greedy ids are still printed
769    const std::vector<int> forced = parse_ids(force);
770    if (!forced.empty()) n_gen = (int) forced.size() + 1;
771    if (model.empty() || prompt.empty()) {
772        std::fprintf(stderr, "q36ref: --model and --tokens are required\n");
773        return 2;
774    }
775    Model m;
776    std::string err;
777    try {
778        if (!load(model, m, err)) {
779            std::fprintf(stderr, "q36ref: %s\n", err.c_str());
780            return 1;
781        }
782    } catch (const std::exception& e) {
783        std::fprintf(stderr, "q36ref: %s\n", e.what());
784        return 1;
785    }
786    State s;
787    s.ctx = ctx;
788    init_state(m, s);
789    const int N = (int) m.g.n_embd, NL = (int) m.g.n_layers, V = (int) m.g.n_vocab;
790    FILE* fl = dump_layers.empty() ? nullptr : std::fopen(dump_layers.c_str(), "wb");
791    FILE* fg = dump_logits.empty() ? nullptr : std::fopen(dump_logits.c_str(), "wb");
792    FILE* ff = dump_full.empty() ? nullptr : std::fopen(dump_full.c_str(), "wb");
793    std::vector<float> layers((size_t) NL * N), logits((size_t) V);
794    const auto t0 = std::chrono::steady_clock::now();
795    int next = -1;
796    std::vector<int> gen;
797    const int total = (int) prompt.size() + n_gen - 1;
798    if (total > ctx) {
799        std::fprintf(stderr, "q36ref: %d positions do not fit --ctx %d\n", total, ctx);
800        return 2;
801    }
802    for (int i = 0; i < total; ++i) {
803        const int tok = i < (int) prompt.size() ? prompt[i] : next;
804        forward(m, s, tok, fl ? layers.data() : nullptr);
805        if (fl) std::fwrite(layers.data(), 4, layers.size(), fl);
806        if (i + 1 >= (int) prompt.size()) {
807            CK(cudaMemcpy(logits.data(), s.logits, (size_t) V * 4, cudaMemcpyDeviceToHost));
808            int a = 0, b = -1;
809            for (int j = 1; j < V; ++j)
810                if (logits[j] > logits[a]) a = j;
811            for (int j = 0; j < V; ++j)
812                if (j != a && (b < 0 || logits[j] > logits[b])) b = j;
813            next = gen.size() < forced.size() ? forced[gen.size()] : a;
814            gen.push_back(a);
815            if (ff) std::fwrite(logits.data(), 4, logits.size(), ff);
816            if (fg) {
817                const float rec[4] = {(float) a, logits[a], (float) b, logits[b]};
818                std::fwrite(rec, 4, 4, fg);
819            }
820        }
821    }
822    const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
823    if (fl) std::fclose(fl);
824    if (fg) std::fclose(fg);
825    if (ff) std::fclose(ff);
826    std::printf("gen:");
827    for (int t : gen) std::printf(" %d", t);
828    std::printf("\n");
829    std::fprintf(stderr, "q36ref: %zu prompt + %zu generated positions in %.2f s (%.2f tok/s, one token at a time)\n",
830                 prompt.size(), gen.size(), sec, (double) total / sec);
831    return 0;
832}