Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
metal: QSA decode (prep, block scores, top-k, split-K attention, gated merge) and the greedy sampler
Niko12216d94e2e40972
diff --git a/metal/kernels/qsa.metal b/metal/kernels/qsa.metalnew file mode 100644index 000000000..11b5f90d1--- /dev/null+++ b/metal/kernels/qsa.metal@@ -0,0 +1,376 @@+// metal/kernels/qsa.metal - QSA (sparse full attention) decode for a window of tokens, between the projections.+// Contract of include/strata/kernels/qsa.hpp / qsa_select.hpp / qsa_decode_attn.hpp / kv_q8.hpp (the engine's+// native path), in a Metal layout (no paging: unified memory):+//+// qsa_prep per token t (cell pos0 + t): q heads rms_norm * q_norm, NEOX RoPE on 64 dims -> qcur;+// k rms_norm * k_norm, RoPE -> int8 KV append (fp16 scale per 64 = fp16(amax/127), rint, clamp);+// v -> int8 append; indexer q rms_norm * iq_norm, RoPE -> qidx. The indexer KEYS (last+// threadgroup, all window tokens in order): raw tail [cell % 4]; on a block completion+// pooled[b] = rope(rms_norm(mean of the block's 4 raw keys) * ik_norm, pos of the block's first cell);+// cell 0 also sets dead = rms_norm(raw) * ik_norm (the tail block's key).+// qsa_score per token, block b <= n_bid: sum over the 4 indexer heads of relu(qidx . key_b); key_b = pooled[b],+// the tail block n_bid scores `dead` and gets +1e9 when it has cells.+// qsa_topk per token: width = min(n_kv, 2051) cells; n_kv <= 2051: all; else the width cells of largest+// score (a cell inherits its block's), ties to the lowest cell, emitted ascending (radix select).+// qsa_attn split-K: (chunk of CH cells, kv head, token): 12 query heads; s = q.k / 16, chunk max m, sum l,+// acc = p . v -> partials+// qsa_merge per (head, token): log-sum-exp merge, * sigmoid(gate), written as prepared activations (xprep+// planes) for attn_output.+//+// RoPE: cos/sin from a host table [pos][32] (double precision, as build_rope_table).++#define QH 24+#define QKV 2+#define QD 256+#define QROT 64+#define IH 4+#define ID 128+#define QBUDGET 2051+#define QCH 64++constant int QSA_NTOK [[function_constant(3)]];++struct QsaArgs {+ uint pos0; // the window's first cell (relative to the sequence)+ uint pos_base; // absolute position of cell 0 (RoPE)+ uint max_cells;+ uint n_tok;+ float eps;+};++// cache layout per layer+// kq/vq [cell][kv head][256] int8, ks/vs [cell][kv head][4] half+// tail [4][128] f32 (slot = cell % 4), dead [128], pooled [max_cells / 4 + 1][128]++static inline float tg_sum256(float v, threadgroup float* part, ushort sg, ushort lane, ushort nsg) {+ v = simd_sum(v);+ if (lane == 0) part[sg] = v;+ threadgroup_barrier(mem_flags::mem_threadgroup);+ float t = 0.0f;+ for (int i = 0; i < nsg; ++i) t += part[i];+ threadgroup_barrier(mem_flags::mem_threadgroup);+ return t;+}++// one row (width w <= 256 = threads) : out = rope((rs * x) * g) (RoPE on the first 64 dims, NEOX pairs i, i+32)+static inline float norm_rope(float x, float xhi_unused, device const float* g, threadgroup float* row,+ threadgroup float* part, ushort tid, ushort sg, ushort lane, int w, float eps,+ device const float2* cs, uint absp, bool rope) {+ const float ss = tg_sum256(tid < w ? x * x : 0.0f, part, sg, lane, 8);+ const float rs = rsqrt(ss / float(w) + eps);+ const float y = tid < w ? (rs * x) * g[tid] : 0.0f;+ row[tid] = y;+ threadgroup_barrier(mem_flags::mem_threadgroup);+ float o = y;+ if (rope && tid < QROT) {+ const int p = tid & 31;+ const float2 c = cs[absp * 32 + p];+ const float a = row[p], b = row[p + 32];+ o = tid < 32 ? a * c.x - b * c.y : a * c.y + b * c.x;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ (void)xhi_unused;+ return o;+}++// grid (32 rows + 1, n_tok): rows 0..23 q heads, 24..25 k heads, 26..27 v heads, 28..31 indexer q heads;+// threadgroup 32 (x = 32, y = 0) is the indexer-key threadgroup. 256 threads.+kernel void qsa_prep(device const float* qfull [[buffer(0)]], device const float* kcur [[buffer(1)]],+ device const float* vcur [[buffer(2)]], device const float* iqraw [[buffer(3)]],+ device const float* ikraw [[buffer(4)]], device const float* qn [[buffer(5)]],+ device const float* kn [[buffer(6)]], device const float* iqn [[buffer(7)]],+ device const float* ikn [[buffer(8)]], device const float2* cs [[buffer(9)]],+ device float* qcur [[buffer(10)]], device float* qidx [[buffer(11)]],+ device char* kq [[buffer(12)]], device char* vq [[buffer(13)]], device half* ksc [[buffer(14)]],+ device half* vsc [[buffer(15)]], device float* tail [[buffer(16)]], device float* dead [[buffer(17)]],+ device float* pooled [[buffer(18)]], constant QsaArgs& a [[buffer(19)]],+ uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],+ ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {+ threadgroup float part[8];+ threadgroup float row[256];+ threadgroup float amax[8];+ const int r = int(tg.x);+ if (r == 32) {+ // the indexer keys, every window token in order (only threadgroup (32, 0) works)+ if (tg.y != 0) return;+ for (int t = 0; t < int(a.n_tok); ++t) {+ const uint cell = a.pos0 + uint(t);+ const float x = tid < ID ? ikraw[t * ID + tid] : 0.0f;+ if (tid < ID) tail[(cell & 3) * ID + tid] = x;+ threadgroup_barrier(mem_flags::mem_device);+ if (cell == 0) {+ const float o = norm_rope(x, 0.0f, ikn, row, part, tid, sg, lane, ID, a.eps, cs, 0, false);+ if (tid < ID) dead[tid] = o;+ }+ if ((cell & 3) == 3) {+ float m = 0.0f;+ if (tid < ID) m = (((tail[tid] + tail[ID + tid]) + tail[2 * ID + tid]) + tail[3 * ID + tid]) * 0.25f;+ const uint b = cell >> 2;+ const float o = norm_rope(m, 0.0f, ikn, row, part, tid, sg, lane, ID, a.eps, cs, a.pos_base + 4 * b, true);+ if (tid < ID) pooled[b * ID + tid] = o;+ }+ threadgroup_barrier(mem_flags::mem_device);+ }+ return;+ }+ const int t = int(tg.y);+ const uint cell = a.pos0 + uint(t), absp = a.pos_base + cell;+ if (r < QH) {+ const float x = qfull[(t * QH + r) * 2 * QD + tid];+ const float o = norm_rope(x, 0.0f, qn, row, part, tid, sg, lane, QD, a.eps, cs, absp, true);+ qcur[(t * QH + r) * QD + tid] = o;+ } else if (r < QH + 2 * QKV) {+ const bool isv = r >= QH + QKV;+ const int h = r - QH - (isv ? QKV : 0);+ float x = (isv ? vcur : kcur)[(t * QKV + h) * QD + tid];+ if (!isv) x = norm_rope(x, 0.0f, kn, row, part, tid, sg, lane, QD, a.eps, cs, absp, true);+ // int8 with an fp16 scale per 64 values: groups = simdgroup pairs (64 threads)+ float m = simd_max(fabs(x));+ if (lane == 0) amax[sg] = m;+ threadgroup_barrier(mem_flags::mem_threadgroup);+ const int g = tid >> 6;+ m = max(amax[2 * g], amax[2 * g + 1]);+ const half sh = half(m / 127.0f);+ const float sf = float(sh);+ int q = 0;+ if (sf > 0.0f) q = clamp(int(rint(x / sf)), -127, 127);+ const uint rowi = cell * QKV + uint(h);+ (isv ? vq : kq)[rowi * QD + tid] = char(q);+ if ((tid & 63) == 0) (isv ? vsc : ksc)[rowi * 4 + g] = sh;+ } else {+ const int h = r - QH - 2 * QKV;+ const float x = tid < ID ? iqraw[(t * IH + h) * ID + tid] : 0.0f;+ const float o = norm_rope(x, 0.0f, iqn, row, part, tid, sg, lane, ID, a.eps, cs, absp, true);+ if (tid < ID) qidx[(t * IH + h) * ID + tid] = o;+ }+}++// scores [n_tok][max_blocks]; grid (ceil(max_blocks / 8), n_tok), 256 threads: a simdgroup per block.+kernel void qsa_score(device const float* qidx [[buffer(0)]], device const float* pooled [[buffer(1)]],+ device const float* dead [[buffer(2)]], device float* scores [[buffer(3)]],+ constant QsaArgs& a [[buffer(4)]],+ uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],+ ushort lane [[thread_index_in_simdgroup]]) {+ const int t = int(tg.y);+ const uint n_kv = a.pos0 + uint(t) + 1, n_bid = n_kv >> 2;+ const uint b = tg.x * 8 + sg;+ if (b > n_bid) return;+ device const float* key = b == n_bid ? dead : pooled + b * ID;+ float k[4];+ for (int i = 0; i < 4; ++i) k[i] = key[lane + 32 * i];+ float s = 0.0f;+ for (int h = 0; h < IH; ++h) {+ float d = 0.0f;+ for (int i = 0; i < 4; ++i) d = fma(qidx[(t * IH + h) * ID + lane + 32 * i], k[i], d);+ d = simd_sum(d);+ s += max(d, 0.0f);+ }+ if (b == n_bid && (n_kv & 3) != 0) s += 1e9f;+ if (lane == 0) scores[uint(t) * (a.max_cells / 4 + 2) + b] = s;+}++// ids [n_tok][QBUDGET], ascending. One threadgroup of 1024 threads per token. Order key of a float: larger score =+// larger key; a radix select (4 passes of 8 bits) over the blocks with weights = their cell counts finds the+// threshold key T and how many cells with key == T to take (the lowest cells first).+static inline uint okey(float f) {+ const uint u = as_type<uint>(f);+ return (u & 0x80000000u) ? ~u : (u | 0x80000000u);+}+kernel void qsa_topk(device const float* scores [[buffer(0)]], device int* ids [[buffer(1)]],+ constant QsaArgs& a [[buffer(2)]],+ uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],+ ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {+ threadgroup atomic_uint hist[256];+ threadgroup uint sel[4];+ threadgroup uint pref[32];+ const int t = int(tg.x);+ const uint n_kv = a.pos0 + uint(t) + 1, n_bid = n_kv >> 2, nb = n_bid + 1;+ device int* out = ids + t * QBUDGET;+ device const float* sc = scores + uint(t) * (a.max_cells / 4 + 2);+ if (n_kv <= QBUDGET) {+ for (uint c = tid; c < n_kv; c += 1024) out[c] = int(c);+ return;+ }+ // radix select of the `need`-th largest cell key+ uint prefix = 0, pmask = 0, need = QBUDGET;+ for (int pass = 0; pass < 4; ++pass) {+ const int shift = 24 - 8 * pass;+ if (tid < 256) atomic_store_explicit(&hist[tid], 0u, memory_order_relaxed);+ threadgroup_barrier(mem_flags::mem_threadgroup);+ for (uint b = tid; b < nb; b += 1024) {+ const uint k = okey(sc[b]);+ if ((k & pmask) == prefix) {+ const uint w = b < n_bid ? 4u : (n_kv & 3u);+ if (w) atomic_fetch_add_explicit(&hist[(k >> shift) & 255u], w, memory_order_relaxed);+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if (tid == 0) {+ uint acc = 0, d = 0;+ for (int v = 255; v >= 0; --v) {+ const uint h = atomic_load_explicit(&hist[v], memory_order_relaxed);+ if (acc + h >= need) { d = uint(v); break; }+ acc += h;+ }+ sel[0] = d;+ sel[1] = need - acc;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ prefix |= sel[0] << shift;+ pmask |= 255u << shift;+ need = sel[1];+ threadgroup_barrier(mem_flags::mem_threadgroup);+ }+ // T = prefix; take every cell with key > T and the first `need` cells (lowest index) with key == T, ascending.+ // Pass over blocks in order of index with a prefix scan of each block's selected cell count.+ const uint T = prefix;+ uint base = 0, eq_taken = 0;+ for (uint b0 = 0; b0 < nb; b0 += 1024) {+ const uint b = b0 + tid;+ uint w = 0, weq = 0;+ if (b < nb) {+ const uint k = okey(sc[b]);+ const uint cells = b < n_bid ? 4u : (n_kv & 3u);+ if (k > T) w = cells;+ else if (k == T) weq = cells;+ }+ // equal-key cells: the lowest first, `need` of them in total+ const uint eq_before = simd_prefix_exclusive_sum(weq);+ if (lane == 31) pref[sg] = eq_before + weq;+ threadgroup_barrier(mem_flags::mem_threadgroup);+ uint eq_sg = 0;+ for (int i = 0; i < int(sg); ++i) eq_sg += pref[i];+ uint eq_tot = 0;+ for (int i = 0; i < 32; ++i) eq_tot += pref[i];+ threadgroup_barrier(mem_flags::mem_threadgroup);+ const uint eq0 = eq_taken + eq_sg + eq_before;+ uint take_eq = 0;+ if (weq && eq0 < need) take_eq = min(weq, need - eq0);+ const uint mine = w + take_eq;+ const uint before = simd_prefix_exclusive_sum(mine);+ if (lane == 31) pref[sg] = before + mine;+ threadgroup_barrier(mem_flags::mem_threadgroup);+ uint off = base;+ for (int i = 0; i < int(sg); ++i) off += pref[i];+ uint tot = 0;+ for (int i = 0; i < 32; ++i) tot += pref[i];+ threadgroup_barrier(mem_flags::mem_threadgroup);+ off += before;+ for (uint c = 0; c < mine; ++c) out[off + c] = int(4 * b + c);+ base += tot;+ eq_taken += eq_tot;+ }+}++// partials: [n_tok][chunks][QH][QD + 2] (acc, then m, l). grid (chunks, QKV, n_tok), 256 threads.+kernel void qsa_attn(device const float* qcur [[buffer(0)]], device const char* kq [[buffer(1)]],+ device const char* vq [[buffer(2)]], device const half* ksc [[buffer(3)]],+ device const half* vsc [[buffer(4)]], device const int* ids [[buffer(5)]],+ device float* part [[buffer(6)]], constant QsaArgs& a [[buffer(7)]],+ uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],+ ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {+ constexpr int HPG = QH / QKV; // 12 query heads per kv head+ threadgroup float qs[HPG][QD];+ threadgroup float s[HPG][QCH];+ threadgroup int cid[QCH];+ const int chunk = int(tg.x), g = int(tg.y), t = int(tg.z);+ const uint n_kv = a.pos0 + uint(t) + 1, width = min(n_kv, uint(QBUDGET));+ const int c0 = chunk * QCH;+ const int nchunks = (QBUDGET + QCH - 1) / QCH;+ device float* pp = part + ((uint(t) * nchunks + chunk) * QH) * (QD + 2);+ if (uint(c0) >= width) {+ // an empty chunk: m = -inf, l = 0 (the merge skips it)+ for (int h = 0; h < HPG; ++h)+ if (tid == 0) { pp[(g * HPG + h) * (QD + 2) + QD] = -INFINITY; pp[(g * HPG + h) * (QD + 2) + QD + 1] = 0.0f; }+ return;+ }+ const int nc = min(QCH, int(width) - c0);+ for (int h = 0; h < HPG; ++h) qs[h][tid] = qcur[(t * QH + g * HPG + h) * QD + tid];+ if (tid < QCH) cid[tid] = tid < nc ? ids[t * QBUDGET + c0 + tid] : 0;+ threadgroup_barrier(mem_flags::mem_threadgroup);+ // scores: 12 x 64 dots of 256; simdgroup sg takes cells sg, sg + 8, ...; lanes split the 256 dims (8 each)+ for (int c = sg; c < nc; c += 8) {+ const uint rowi = uint(cid[c]) * QKV + uint(g);+ device const char* kr = kq + rowi * QD;+ float kv[8];+ const float scl = float(ksc[rowi * 4 + (lane >> 3)]);+ for (int i = 0; i < 8; ++i) kv[i] = float(kr[lane * 8 + i]) * scl;+ for (int h = 0; h < HPG; ++h) {+ float d = 0.0f;+ for (int i = 0; i < 8; ++i) d = fma(qs[h][lane * 8 + i], kv[i], d);+ d = simd_sum(d);+ if (lane == 0) s[h][c] = d * 0.0625f;+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ // per head: max, exp, sum (simdgroup h % 8 handles heads h, h + 8)+ threadgroup float mh[HPG], lh[HPG];+ for (int h = sg; h < HPG; h += 8) {+ float m = -INFINITY;+ for (int c = lane; c < nc; c += 32) m = max(m, s[h][c]);+ m = simd_max(m);+ float l = 0.0f;+ for (int c = lane; c < nc; c += 32) {+ const float p = exp(s[h][c] - m);+ s[h][c] = p;+ l += p;+ }+ l = simd_sum(l);+ if (lane == 0) { mh[h] = m; lh[h] = l; }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ // acc[h][j] = sum_c p[h][c] v[c][j]: thread = dim j+ float acc[HPG];+ for (int h = 0; h < HPG; ++h) acc[h] = 0.0f;+ for (int c = 0; c < nc; ++c) {+ const uint rowi = uint(cid[c]) * QKV + uint(g);+ const float v = float(vq[rowi * QD + tid]) * float(vsc[rowi * 4 + (tid >> 6)]);+ for (int h = 0; h < HPG; ++h) acc[h] = fma(s[h][c], v, acc[h]);+ }+ for (int h = 0; h < HPG; ++h) {+ device float* o = pp + (g * HPG + h) * (QD + 2);+ o[tid] = acc[h];+ if (tid == 0) { o[QD] = mh[h]; o[QD + 1] = lh[h]; }+ }+}++// grid (QH, n_tok), 256 threads: out = merge * sigmoid(gate), as prepared activations of n = QH * QD per token+kernel void qsa_merge(device const float* part [[buffer(0)]], device const float* qfull [[buffer(1)]],+ device float* xp [[buffer(2)]], constant QsaArgs& a [[buffer(3)]],+ uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {+ threadgroup float msum[256];+ const int h = int(tg.x), t = int(tg.y);+ const int nchunks = (QBUDGET + QCH - 1) / QCH;+ const uint n_kv = a.pos0 + uint(t) + 1, width = min(n_kv, uint(QBUDGET));+ const int nc = int((width + QCH - 1) / QCH);+ device const float* pp = part + (uint(t) * nchunks * QH + uint(h)) * (QD + 2);+ float M = -INFINITY;+ for (int k = 0; k < nc; ++k) M = max(M, pp[k * QH * (QD + 2) + QD]);+ float L = 0.0f, o = 0.0f;+ for (int k = 0; k < nc; ++k) {+ device const float* q = pp + k * QH * (QD + 2);+ const float e = exp(q[QD] - M);+ L = fma(q[QD + 1], e, L);+ o = fma(q[tid], e, o);+ }+ o = o / L;+ const float gate = qfull[(t * QH + h) * 2 * QD + QD + tid];+ const float y = o * (1.0f / (1.0f + exp(-gate)));+ // prepared planes (xprep layout) of the n = QH * QD vector+ const uint n = QH * QD, plane = a.n_tok * n, d = uint(h) * QD + tid;+ const int j = tid & 15;+ const float q2s[8] = {1.0f, 0.25f, 0.0625f, 0.015625f, 0.00390625f, 0.0009765625f, 0.000244140625f, 0.00006103515625f};+ const float p4s[4] = {1.0f, 0.00390625f, 1.52587890625e-05f, 5.9604644775390625e-08f};+ device float* raw = xp + uint(t) * n + d;+ raw[0] = y;+ raw[plane] = y * q2s[j & 7];+ raw[2 * plane] = y * p4s[j & 3];+ raw[3 * plane] = (j & 1) ? y * 0.00390625f : y;+ msum[tid] = y;+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if (j == 0) {+ float s0 = 0.0f, s1 = 0.0f;+ for (int k = 0; k < 16; k += 2) { s0 += msum[tid + k]; s1 += msum[tid + k + 1]; }+ xp[4 * plane + uint(t) * (n / 16) + d / 16] = s0 + s1;+ }+}diff --git a/metal/kernels/sample.metal b/metal/kernels/sample.metalnew file mode 100644index 000000000..8443d3608--- /dev/null+++ b/metal/kernels/sample.metal@@ -0,0 +1,59 @@+// metal/kernels/sample.metal - greedy sampling over the LM head's logits: the largest logit, ties to the lowest+// token id (NaN never wins). Two stages: argmax_part (grid (parts, n_tok), 256 threads) writes one (value, id)+// pair per threadgroup; argmax_final (grid (n_tok), 256 threads) reduces them in order.++struct ArgArgs {+ uint n_vocab;+ uint parts;+};++static inline void better(thread float& bv, thread int& bi, float v, int i) {+ if (v > bv || (v == bv && i < bi)) { bv = v; bi = i; }+}++static inline void tg_argmax(thread float& bv, thread int& bi, threadgroup float* sv, threadgroup int* si, ushort sg,+ ushort lane) {+ for (ushort m = 16; m > 0; m >>= 1) {+ const float ov = simd_shuffle_xor(bv, m);+ const int oi = simd_shuffle_xor(bi, m);+ better(bv, bi, ov, oi);+ }+ if (lane == 0) { sv[sg] = bv; si[sg] = bi; }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ bv = -INFINITY;+ bi = 0x7fffffff;+ for (int k = 0; k < 8; ++k) better(bv, bi, sv[k], si[k]);+}++kernel void argmax_part(device const float* logits [[buffer(0)]], device float* pv [[buffer(1)]],+ device int* pi [[buffer(2)]], constant ArgArgs& a [[buffer(3)]],+ uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],+ ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {+ threadgroup float sv[8];+ threadgroup int si[8];+ const uint t = tg.y, per = (a.n_vocab + a.parts - 1) / a.parts;+ const uint b0 = tg.x * per, b1 = min(b0 + per, a.n_vocab);+ device const float* l = logits + t * a.n_vocab;+ float bv = -INFINITY;+ int bi = 0x7fffffff;+ for (uint i = b0 + tid; i < b1; i += 256) {+ const float v = l[i];+ if (!isnan(v)) better(bv, bi, v, int(i));+ }+ tg_argmax(bv, bi, sv, si, sg, lane);+ if (tid == 0) { pv[t * a.parts + tg.x] = bv; pi[t * a.parts + tg.x] = bi; }+}++kernel void argmax_final(device const float* pv [[buffer(0)]], device const int* pi [[buffer(1)]],+ device int* out [[buffer(2)]], constant ArgArgs& a [[buffer(3)]],+ uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],+ ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {+ threadgroup float sv[8];+ threadgroup int si[8];+ const uint t = tg.x;+ float bv = -INFINITY;+ int bi = 0x7fffffff;+ for (uint k = tid; k < a.parts; k += 256) better(bv, bi, pv[t * a.parts + k], pi[t * a.parts + k]);+ tg_argmax(bv, bi, sv, si, sg, lane);+ if (tid == 0) out[t] = bi;+}diff --git a/metal/tests/qsa_parity.cpp b/metal/tests/qsa_parity.cppnew file mode 100644index 000000000..89faa9981--- /dev/null+++ b/metal/tests/qsa_parity.cpp@@ -0,0 +1,292 @@+// metal/tests/qsa_parity.cpp - QSA decode (qsa.metal) stage by stage against a CPU reference, and its speed.+//+// qsa_parity [P] a context of P cells built by qsa_prep (default 3000: the selection is active above+// 2051), then a window of 3 tokens: prep, score, top-k, attention, merge. Each stage is+// checked against the CPU fed with the GPU's inputs to that stage; the ids exactly.+// qsa_parity --bench [P] GPU time of the window's kernels at context P, 1 and 3 tokens+#include "mtl_rt.h"+#include "ref_quant.h"++#include <algorithm>+#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <string>+#include <vector>++namespace {+constexpr int QH = 24, QKV = 2, QD = 256, IH = 4, ID = 128, BUDGET = 2051, CH = 64, NCH = (BUDGET + CH - 1) / CH;+struct QsaArgs { uint32_t pos0, pos_base, max_cells, n_tok; float eps; };+double median(std::vector<double> v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; }+struct Err {+ double se = 0, sr = 0;+ void add(double g, double r) { se += (g - r) * (g - r); sr += r * r; }+ double l2() const { return sr > 0 ? std::sqrt(se / sr) : std::sqrt(se); }+};+float h2f(uint16_t h) { return ref::f16_to_f32(h); }+} // namespace++int main(int argc, char** argv) {+ bool bench = false;+ int P = 3000;+ for (int i = 1; i < argc; ++i) {+ std::string a = argv[i];+ if (a == "--bench") bench = true;+ else P = std::atoi(argv[i]);+ }+ const int MAXT = 8, MAXC = std::max(4096, (P + 64) / 4 * 4 + 64);+ mtl::Context cx;+ const int lib = cx.compile({"qsa.metal"}, "#define NO_GGML_COMMON 1\n");+ mtl::Pipeline pprep = cx.pipeline(lib, "qsa_prep"), pscore = cx.pipeline(lib, "qsa_score"),+ ptopk = cx.pipeline(lib, "qsa_topk"), pattn = cx.pipeline(lib, "qsa_attn"),+ pmerge = cx.pipeline(lib, "qsa_merge");+ const int MB = MAXC / 4 + 2;+ // per-cell inputs for every cell (context + window)+ const int NC = P + MAXT;+ mtl::Buffer qfull = cx.alloc(4 * (size_t)NC * QH * 2 * QD), kc = cx.alloc(4 * (size_t)NC * QKV * QD),+ vc = cx.alloc(4 * (size_t)NC * QKV * QD), iq = cx.alloc(4 * (size_t)NC * IH * ID),+ ik = cx.alloc(4 * (size_t)NC * ID), qn = cx.alloc(4 * QD), kn = cx.alloc(4 * QD), iqn = cx.alloc(4 * ID),+ ikn = cx.alloc(4 * ID), cs = cx.alloc(8 * (size_t)(MAXC + 16) * 32), qcur = cx.alloc(4 * MAXT * QH * QD),+ qidx = cx.alloc(4 * MAXT * IH * ID), kq = cx.alloc((size_t)MAXC * QKV * QD), vq = cx.alloc((size_t)MAXC * QKV * QD),+ ksc = cx.alloc(2 * (size_t)MAXC * QKV * 4), vsc = cx.alloc(2 * (size_t)MAXC * QKV * 4), tail = cx.alloc(4 * 4 * ID),+ dead = cx.alloc(4 * ID), pooled = cx.alloc(4 * (size_t)MB * ID), scores = cx.alloc(4 * (size_t)MAXT * MB),+ ids = cx.alloc(4 * MAXT * BUDGET), part = cx.alloc(4 * (size_t)MAXT * NCH * QH * (QD + 2)),+ xp = cx.alloc(4 * (4 * MAXT * QH * QD + MAXT * QH * QD / 16));+ ref::Rng r(23);+ for (size_t i = 0; i < qfull.bytes / 4; ++i) qfull.as<float>()[i] = r.sym() * 2.0f;+ for (size_t i = 0; i < kc.bytes / 4; ++i) kc.as<float>()[i] = r.sym() * 2.0f;+ for (size_t i = 0; i < vc.bytes / 4; ++i) vc.as<float>()[i] = r.sym();+ for (size_t i = 0; i < iq.bytes / 4; ++i) iq.as<float>()[i] = r.sym();+ for (size_t i = 0; i < ik.bytes / 4; ++i) ik.as<float>()[i] = r.sym();+ for (int i = 0; i < QD; ++i) { qn.as<float>()[i] = 1.0f + 0.2f * r.sym(); kn.as<float>()[i] = 1.0f + 0.2f * r.sym(); }+ for (int i = 0; i < ID; ++i) { iqn.as<float>()[i] = 1.0f + 0.2f * r.sym(); ikn.as<float>()[i] = 1.0f + 0.2f * r.sym(); }+ const uint32_t pos_base = 0;+ for (int p = 0; p < MAXC + 16; ++p)+ for (int i = 0; i < 32; ++i) {+ const double inv = std::pow(1e7, -2.0 * i / 64.0), th = (double)p * inv;+ cs.as<float>()[(p * 32 + i) * 2] = (float)std::cos(th);+ cs.as<float>()[(p * 32 + i) * 2 + 1] = (float)std::sin(th);+ }+ auto prep = [&](uint32_t pos0, int nt) {+ QsaArgs a{pos0, pos_base, (uint32_t)MAXC, (uint32_t)nt, 1e-6f};+ mtl::Dispatch d;+ d.p = &pprep;+ d.args = {mtl::Arg::B(qfull, 4 * (size_t)pos0 * QH * 2 * QD), mtl::Arg::B(kc, 4 * (size_t)pos0 * QKV * QD),+ mtl::Arg::B(vc, 4 * (size_t)pos0 * QKV * QD), mtl::Arg::B(iq, 4 * (size_t)pos0 * IH * ID),+ mtl::Arg::B(ik, 4 * (size_t)pos0 * ID), mtl::Arg::B(qn), mtl::Arg::B(kn), mtl::Arg::B(iqn),+ mtl::Arg::B(ikn), mtl::Arg::B(cs), mtl::Arg::B(qcur), mtl::Arg::B(qidx), mtl::Arg::B(kq),+ mtl::Arg::B(vq), mtl::Arg::B(ksc), mtl::Arg::B(vsc), mtl::Arg::B(tail), mtl::Arg::B(dead),+ mtl::Arg::B(pooled), mtl::Arg::V(a)};+ d.grid[0] = 33;+ d.grid[1] = nt;+ d.tg[0] = 256;+ return d;+ };+ auto window = [&](uint32_t pos0, int nt, std::vector<mtl::Dispatch>& ds) {+ QsaArgs a{pos0, pos_base, (uint32_t)MAXC, (uint32_t)nt, 1e-6f};+ ds.push_back(prep(pos0, nt));+ mtl::Dispatch s;+ s.p = &pscore;+ s.args = {mtl::Arg::B(qidx), mtl::Arg::B(pooled), mtl::Arg::B(dead), mtl::Arg::B(scores), mtl::Arg::V(a)};+ s.grid[0] = ((pos0 + nt) / 4 + 1 + 7) / 8;+ s.grid[1] = nt;+ s.tg[0] = 256;+ ds.push_back(s);+ mtl::Dispatch k;+ k.p = &ptopk;+ k.args = {mtl::Arg::B(scores), mtl::Arg::B(ids), mtl::Arg::V(a)};+ k.grid[0] = nt;+ k.tg[0] = 1024;+ ds.push_back(k);+ mtl::Dispatch at;+ at.p = &pattn;+ at.args = {mtl::Arg::B(qcur), mtl::Arg::B(kq), mtl::Arg::B(vq), mtl::Arg::B(ksc), mtl::Arg::B(vsc),+ mtl::Arg::B(ids), mtl::Arg::B(part), mtl::Arg::V(a)};+ at.grid[0] = NCH;+ at.grid[1] = QKV;+ at.grid[2] = nt;+ at.tg[0] = 256;+ ds.push_back(at);+ mtl::Dispatch m;+ m.p = &pmerge;+ m.args = {mtl::Arg::B(part), mtl::Arg::B(qfull, 4 * (size_t)pos0 * QH * 2 * QD), mtl::Arg::B(xp), mtl::Arg::V(a)};+ m.grid[0] = QH;+ m.grid[1] = nt;+ m.tg[0] = 256;+ ds.push_back(m);+ };+ // the context, one cell at a time+ {+ std::vector<mtl::Dispatch> ds;+ for (int p = 0; p < P; ++p) ds.push_back(prep(p, 1));+ cx.run(ds);+ }+ if (bench) {+ std::printf("device %s, context %d cells\n", cx.device_name().c_str(), P);+ for (int nt : {1, 3}) {+ std::vector<mtl::Dispatch> ds;+ window(P, nt, ds);+ const char* names[] = {"prep", "score", "topk", "attn", "merge"};+ double total = 0;+ for (int i = 0; i < 5; ++i) {+ std::vector<mtl::Dispatch> one(32, ds[i]);+ cx.warm(one, 0.05);+ std::vector<double> t;+ for (int k = 0; k < 7; ++k) t.push_back(cx.run(one) / 32);+ std::printf(" ntok %d %-6s %7.2f us\n", nt, names[i], median(t) * 1e6);+ total += median(t);+ }+ std::vector<double> t;+ for (int k = 0; k < 7; ++k) t.push_back(cx.run(ds));+ std::printf(" ntok %d window (5 dependent dispatches): %.2f us (sum of parts %.2f)\n", nt, median(t) * 1e6,+ total * 1e6);+ }+ return 0;+ }+ const int NT = 3;+ std::vector<mtl::Dispatch> ds;+ window(P, NT, ds);+ // stage by stage, re-reading GPU state in between+ cx.run({ds[0]});+ int fails = 0;+ // ---- prep: qcur, qidx, the window cells' KV codes and the pooled keys vs CPU+ {+ Err eq, ei, ekv, ep;+ auto normrope = [&](const float* x, const float* g, int w, int absp, bool rope, std::vector<double>& out) {+ double ss = 0;+ for (int i = 0; i < w; ++i) ss += (double)x[i] * x[i];+ const double rs = 1.0 / std::sqrt(ss / w + 1e-6);+ out.assign(w, 0.0);+ for (int i = 0; i < w; ++i) out[i] = rs * x[i] * g[i];+ if (rope)+ for (int i = 0; i < 32; ++i) {+ const double c = cs.as<float>()[(absp * 32 + i) * 2], s = cs.as<float>()[(absp * 32 + i) * 2 + 1];+ const double a = out[i], b = out[i + 32];+ out[i] = a * c - b * s;+ out[i + 32] = a * s + b * c;+ }+ };+ std::vector<double> o;+ for (int t = 0; t < NT; ++t) {+ const int cell = P + t;+ for (int h = 0; h < QH; ++h) {+ normrope(qfull.as<float>() + ((size_t)cell * QH + h) * 2 * QD, qn.as<float>(), QD, cell, true, o);+ for (int i = 0; i < QD; ++i) eq.add(qcur.as<float>()[(t * QH + h) * QD + i], o[i]);+ }+ for (int h = 0; h < IH; ++h) {+ normrope(iq.as<float>() + ((size_t)cell * IH + h) * ID, iqn.as<float>(), ID, cell, true, o);+ for (int i = 0; i < ID; ++i) ei.add(qidx.as<float>()[(t * IH + h) * ID + i], o[i]);+ }+ for (int h = 0; h < QKV; ++h) {+ normrope(kc.as<float>() + ((size_t)cell * QKV + h) * QD, kn.as<float>(), QD, cell, true, o);+ for (int i = 0; i < QD; ++i) {+ const size_t row = (size_t)cell * QKV + h;+ const double deq = (double)(int8_t)kq.as<int8_t>()[row * QD + i] * h2f(ksc.as<uint16_t>()[row * 4 + i / 64]);+ ekv.add(deq, o[i]);+ }+ }+ }+ // pooled keys of the last few completed blocks+ const int nb = (P + NT) / 4;+ for (int b = std::max(0, nb - 8); b < nb; ++b) {+ std::vector<float> m(ID);+ for (int i = 0; i < ID; ++i)+ m[i] = (((ik.as<float>()[(4 * b) * ID + i] + ik.as<float>()[(4 * b + 1) * ID + i]) ++ ik.as<float>()[(4 * b + 2) * ID + i]) + ik.as<float>()[(4 * b + 3) * ID + i]) * 0.25f;+ normrope(m.data(), ikn.as<float>(), ID, 4 * b, true, o);+ for (int i = 0; i < ID; ++i) ep.add(pooled.as<float>()[b * ID + i], o[i]);+ }+ // int8 quantization error is ~1/254 of max|x| per group: the KV check is a quantization tolerance+ const bool ok = eq.l2() < 1e-5 && ei.l2() < 1e-5 && ep.l2() < 1e-5 && ekv.l2() < 6e-3;+ fails += !ok;+ std::printf("prep: q rel L2 %.2e, indexer q %.2e, pooled keys %.2e, K int8 (vs float) %.2e %s\n", eq.l2(),+ ei.l2(), ep.l2(), ekv.l2(), ok ? "PASS" : "FAIL");+ }+ // ---- score+ cx.run({ds[1]});+ {+ Err es;+ for (int t = 0; t < NT; ++t) {+ const int n_kv = P + t + 1, n_bid = n_kv / 4;+ for (int b = 0; b <= n_bid; ++b) {+ const float* key = b == n_bid ? dead.as<float>() : pooled.as<float>() + b * ID;+ double s = 0;+ for (int h = 0; h < IH; ++h) {+ double d = 0;+ for (int i = 0; i < ID; ++i) d += (double)qidx.as<float>()[(t * IH + h) * ID + i] * key[i];+ s += std::max(d, 0.0);+ }+ if (b == n_bid && (n_kv & 3)) {+ // float(s + 1e9) keeps no bits of s: only check that the bias is there+ if (!(scores.as<float>()[t * MB + b] >= 1e9f)) es.add(1.0, 0.0);+ } else {+ es.add(scores.as<float>()[t * MB + b], s);+ }+ }+ }+ const bool ok = es.l2() < 1e-5;+ fails += !ok;+ std::printf("score: rel L2 %.2e (tail +1e9 checked separately) %s\n", es.l2(), ok ? "PASS" : "FAIL");+ }+ // ---- top-k (exact, from the GPU's scores)+ cx.run({ds[2]});+ {+ int bad = 0;+ for (int t = 0; t < NT; ++t) {+ const int n_kv = P + t + 1, n_bid = n_kv / 4, width = std::min(n_kv, BUDGET);+ std::vector<int> cells(n_kv);+ for (int c = 0; c < n_kv; ++c) cells[c] = c;+ if (n_kv > BUDGET) {+ const float* sc = scores.as<float>() + t * MB;+ std::stable_sort(cells.begin(), cells.end(), [&](int x, int y) { return sc[x / 4] > sc[y / 4]; });+ cells.resize(width);+ std::sort(cells.begin(), cells.end());+ }+ (void)n_bid;+ for (int i = 0; i < width; ++i) bad += ids.as<int>()[t * BUDGET + i] != cells[i];+ }+ fails += bad != 0;+ std::printf("top-k: %d of %d ids differ (context %d: selection %s) %s\n", bad, NT * std::min(P + 1, BUDGET), P,+ P + 1 > BUDGET ? "active" : "identity", bad ? "FAIL" : "PASS");+ }+ // ---- attention + merge (from the GPU's qcur, ids and KV codes)+ cx.run({ds[3], ds[4]});+ {+ Err eo;+ for (int t = 0; t < NT; ++t) {+ const int n_kv = P + t + 1, width = std::min(n_kv, BUDGET);+ for (int h = 0; h < QH; ++h) {+ const int g = h / (QH / QKV);+ std::vector<double> s(width);+ double mx = -1e300;+ for (int c = 0; c < width; ++c) {+ const size_t row = (size_t)ids.as<int>()[t * BUDGET + c] * QKV + g;+ double d = 0;+ for (int i = 0; i < QD; ++i)+ d += (double)qcur.as<float>()[(t * QH + h) * QD + i] * (int8_t)kq.as<int8_t>()[row * QD + i] *+ h2f(ksc.as<uint16_t>()[row * 4 + i / 64]);+ s[c] = d / 16.0;+ mx = std::max(mx, s[c]);+ }+ double l = 0;+ for (int c = 0; c < width; ++c) l += (s[c] = std::exp(s[c] - mx));+ for (int i = 0; i < QD; ++i) {+ double o = 0;+ for (int c = 0; c < width; ++c) {+ const size_t row = (size_t)ids.as<int>()[t * BUDGET + c] * QKV + g;+ o += s[c] * (int8_t)vq.as<int8_t>()[row * QD + i] * h2f(vsc.as<uint16_t>()[row * 4 + i / 64]);+ }+ o /= l;+ const double gate = qfull.as<float>()[((size_t)(P + t) * QH + h) * 2 * QD + QD + i];+ eo.add(xp.as<float>()[t * QH * QD + h * QD + i], o / (1.0 + std::exp(-gate)));+ }+ }+ }+ const bool ok = eo.l2() < 1e-5;+ fails += !ok;+ std::printf("attention + gate: rel L2 %.2e %s\n", eo.l2(), ok ? "PASS" : "FAIL");+ }+ std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS");+ return fails ? 1 : 0;+}diff --git a/metal/tests/sample_parity.cpp b/metal/tests/sample_parity.cppnew file mode 100644index 000000000..049439af6--- /dev/null+++ b/metal/tests/sample_parity.cpp@@ -0,0 +1,61 @@+// metal/tests/sample_parity.cpp - greedy argmax (sample.metal) vs the CPU over 248,320 logits with planted ties,+// and its time.+#include "mtl_rt.h"+#include "ref_quant.h"++#include <algorithm>+#include <cmath>+#include <cstdio>+#include <vector>++int main() {+ constexpr uint32_t V = 248320, PARTS = 120;+ mtl::Context cx;+ const int lib = cx.compile({"sample.metal"}, "#define NO_GGML_COMMON 1\n");+ mtl::Pipeline pp = cx.pipeline(lib, "argmax_part"), pf = cx.pipeline(lib, "argmax_final");+ const int MAXT = 8;+ mtl::Buffer lg = cx.alloc(4 * (size_t)V * MAXT), pv = cx.alloc(4 * PARTS * MAXT), pi = cx.alloc(4 * PARTS * MAXT),+ out = cx.alloc(4 * MAXT);+ ref::Rng r(5);+ int fails = 0;+ struct A { uint32_t n_vocab, parts; } a{V, PARTS};+ for (int trial = 0; trial < 20; ++trial) {+ const int nt = 1 + trial % MAXT;+ for (size_t i = 0; i < (size_t)V * nt; ++i) lg.as<float>()[i] = std::round(r.sym() * 1000.0f) / 100.0f;+ for (int t = 0; t < nt; ++t) {+ // plant a tie at the maximum+ const size_t i1 = r.next() % V, i2 = r.next() % V;+ lg.as<float>()[t * V + i1] = 20.0f;+ lg.as<float>()[t * V + i2] = 20.0f;+ }+ mtl::Dispatch d1, d2;+ d1.p = &pp;+ d1.args = {mtl::Arg::B(lg), mtl::Arg::B(pv), mtl::Arg::B(pi), mtl::Arg::V(a)};+ d1.grid[0] = PARTS;+ d1.grid[1] = nt;+ d1.tg[0] = 256;+ d2.p = &pf;+ d2.args = {mtl::Arg::B(pv), mtl::Arg::B(pi), mtl::Arg::B(out), mtl::Arg::V(a)};+ d2.grid[0] = nt;+ d2.tg[0] = 256;+ cx.run({d1, d2});+ for (int t = 0; t < nt; ++t) {+ const float* l = lg.as<float>() + (size_t)t * V;+ int best = 0;+ for (uint32_t i = 1; i < V; ++i)+ if (l[i] > l[best]) best = (int)i;+ fails += out.as<int>()[t] != best;+ }+ if (trial == 19) {+ std::vector<mtl::Dispatch> ds;+ for (int k = 0; k < 64; ++k) { ds.push_back(d1); ds.push_back(d2); }+ cx.warm(ds, 0.05);+ std::vector<double> ts;+ for (int k = 0; k < 7; ++k) ts.push_back(cx.run(ds) / 64);+ std::sort(ts.begin(), ts.end());+ std::printf("argmax %d token(s) over %u logits: %.2f us (2 dispatches)\n", nt, V, ts[3] * 1e6);+ }+ }+ std::printf("argmax parity, 20 windows with planted ties: %d wrong %s\n", fails, fails ? "FAIL" : "PASS");+ return fails ? 1 : 0;+}