bitgpu 0.13.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3,6 +3,9 @@ const SHADERS = {
3
3
  "add": "// Elementwise residual add: y[i] = a[i] + b[i].\nstruct Params { n: u32, _p0: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> a: array<f32>;\n@group(0) @binding(2) var<storage, read> b: array<f32>;\n@group(0) @binding(3) var<storage, read_write> y: array<f32>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.n) { return; }\n y[i] = a[i] + b[i];\n}\n",
4
4
  "argmax": "// GPU argmax over the logits, writing one token id into a GPU buffer so the token never leaves the\n// GPU (enables the deferred-sync decode loop). Single workgroup, WG threads strided-scan the N\n// logits tracking (maxVal, maxIdx), then a shared-mem tree reduction. Tie-break = LOWEST index, to\n// match the CPU argmax (strict > keeps the first max). No subgroup ops -> all devices.\noverride WG: u32 = 256u;\nstruct Params { N: u32, outIdx: u32, _0: u32, _1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> logits: array<f32>;\n@group(0) @binding(2) var<storage, read_write> outTok: array<u32>; // outTok[p.outIdx] = argmax\n\nvar<workgroup> sval: array<f32, 256>;\nvar<workgroup> sidx: array<u32, 256>;\n\n@compute @workgroup_size(WG)\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\n let tid = lid.x;\n var bv = -3.4e38;\n var bi = 0u;\n for (var i = tid; i < p.N; i = i + WG) {\n let v = logits[i];\n if (v > bv) { bv = v; bi = i; } // strict > keeps the lowest index within this thread's stride\n }\n sval[tid] = bv; sidx[tid] = bi;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s) {\n let ov = sval[tid + s]; let oi = sidx[tid + s];\n if (ov > sval[tid] || (ov == sval[tid] && oi < sidx[tid])) { sval[tid] = ov; sidx[tid] = oi; }\n }\n workgroupBarrier();\n }\n if (tid == 0u) { outTok[p.outIdx] = sidx[0]; }\n}\n",
5
5
  "argmax_masked": "// Masked argmax: like argmax.wgsl but skips any id already chosen in a prior round, and writes BOTH\n// the winning id and its logit value. Calling it K times (roundCount = 0..K-1, all in one compute\n// pass so each round sees the prior rounds' writes) yields the exact top-K (id, logit) pairs in\n// descending order = ONNX TopK over the (penalty-filtered) logits, which is what the transformers.js\n// sampler consumes. Then only K pairs are read back (not the full vocab), and the CPU does\n// temperature + softmax + multinomial. Single workgroup, no subgroup ops -> all devices. Tie-break =\n// lowest index (strict >), matching argmax.wgsl / ORT TopK in practice.\noverride WG: u32 = 256u;\nstruct Params { N: u32, roundCount: u32, _0: u32, _1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> logits: array<f32>;\n@group(0) @binding(2) var<storage, read_write> candIds: array<u32>; // [K]; reads 0..roundCount-1, writes [roundCount]\n@group(0) @binding(3) var<storage, read_write> candVals: array<f32>; // [K]; writes [roundCount]\n\nvar<workgroup> sval: array<f32, 256>;\nvar<workgroup> sidx: array<u32, 256>;\n\n@compute @workgroup_size(WG)\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\n let tid = lid.x;\n var bv = -3.4e38;\n var bi = 0u;\n for (var i = tid; i < p.N; i = i + WG) {\n let v = logits[i];\n if (v > bv) {\n var skip = false;\n for (var r = 0u; r < p.roundCount; r = r + 1u) { if (candIds[r] == i) { skip = true; break; } }\n if (!skip) { bv = v; bi = i; } // strict > keeps the lowest index within this thread's stride\n }\n }\n sval[tid] = bv; sidx[tid] = bi;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s) {\n let ov = sval[tid + s]; let oi = sidx[tid + s];\n if (ov > sval[tid] || (ov == sval[tid] && oi < sidx[tid])) { sval[tid] = ov; sidx[tid] = oi; }\n }\n workgroupBarrier();\n }\n if (tid == 0u) { candIds[p.roundCount] = sidx[0]; candVals[p.roundCount] = sval[0]; }\n}\n",
6
+ "attention_online": "// Causal GQA attention with online (flash) softmax, head-dim up to the workgroup size (256) - the\n// Qwen3.5 full-attention layers use head_dim 256, past the <=128 the register-array kernels assume.\n// One workgroup per query (s,h); thread d owns output dim d. Streams keys j<=s keeping running\n// max/sum/acc, so no O(S) score storage. Output gate + RoPE + QK-norm are applied separately.\noverride WGD: u32 = 256u; // threads == head_dim D\nstruct Params { S: u32, H: u32, KV: u32, D: u32, scale: f32, _p0: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> k: array<f32>; // [S, KV, D]\n@group(0) @binding(3) var<storage, read> v: array<f32>; // [S, KV, D]\n@group(0) @binding(4) var<storage, read_write> outp: array<f32>; // [S, H, D]\nvar<workgroup> qsh: array<f32, 256>;\nvar<workgroup> red: array<f32, 256>;\n\n@compute @workgroup_size(WGD)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let qi = wg.x; // query flat index = s*H + h\n let s = qi / p.H;\n let h = qi % p.H;\n let hkv = h / (p.H / p.KV); // GQA: which kv head\n let d = lid.x;\n let D = p.D;\n if (d < D) { qsh[d] = q[qi * D + d]; }\n workgroupBarrier();\n\n var m = -1e30;\n var l = 0.0;\n var acc = 0.0;\n for (var j = 0u; j <= s; j = j + 1u) {\n red[d] = select(0.0, qsh[d] * k[(j * p.KV + hkv) * D + d], d < D);\n workgroupBarrier();\n for (var st = WGD / 2u; st > 0u; st = st >> 1u) {\n if (d < st) { red[d] = red[d] + red[d + st]; }\n workgroupBarrier();\n }\n let score = red[0] * p.scale;\n let mn = max(m, score);\n let corr = exp(m - mn);\n let pj = exp(score - mn);\n l = l * corr + pj;\n if (d < D) { acc = acc * corr + pj * v[(j * p.KV + hkv) * D + d]; }\n m = mn;\n workgroupBarrier(); // before next j overwrites red\n }\n if (d < D) { outp[qi * D + d] = acc / l; }\n}\n",
7
+ "attention_online_cache": "// Causal GQA attention (online/flash softmax, head_dim up to 256) reading K/V from the persistent\n// f32 cache (Kc/Vc, layout [pos*KV + kv_head, D]) - the Qwen3.5 full-attention path for both prefill\n// and decode. One workgroup per query (s,h); thread d owns output dim d. The query at absolute\n// position posBase+s attends to cache positions 0 .. posBase+s (causal). Keys are cached already\n// RoPE'd, so no read-time rotation.\noverride WGD: u32 = 256u; // threads == head_dim D\nstruct Params { S: u32, H: u32, KV: u32, D: u32, scale: f32, posBase: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> kc: array<f32>; // cache [cap*KV, D]\n@group(0) @binding(3) var<storage, read> vc: array<f32>; // cache [cap*KV, D]\n@group(0) @binding(4) var<storage, read_write> outp: array<f32>; // [S, H, D]\nvar<workgroup> qsh: array<f32, 256>;\nvar<workgroup> red: array<f32, 256>;\n\n@compute @workgroup_size(WGD)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let qi = wg.x; // query flat index = s*H + h\n let s = qi / p.H;\n let h = qi % p.H;\n let hkv = h / (p.H / p.KV);\n let d = lid.x;\n let D = p.D;\n if (d < D) { qsh[d] = q[qi * D + d]; }\n workgroupBarrier();\n\n var m = -1e30;\n var l = 0.0;\n var acc = 0.0;\n let last = p.posBase + s; // inclusive: attend cache positions 0..last\n for (var j = 0u; j <= last; j = j + 1u) {\n red[d] = select(0.0, qsh[d] * kc[(j * p.KV + hkv) * D + d], d < D);\n workgroupBarrier();\n for (var st = WGD / 2u; st > 0u; st = st >> 1u) {\n if (d < st) { red[d] = red[d] + red[d + st]; }\n workgroupBarrier();\n }\n let score = red[0] * p.scale;\n let mn = max(m, score);\n let corr = exp(m - mn);\n let pj = exp(score - mn);\n l = l * corr + pj;\n if (d < D) { acc = acc * corr + pj * vc[(j * p.KV + hkv) * D + d]; }\n m = mn;\n workgroupBarrier();\n }\n if (d < D) { outp[qi * D + d] = acc / l; }\n}\n",
8
+ "attention_online_cache_kv8": "// q8 variant of attention_online_cache: the Qwen3.5 full-attention path reading K/V from the packed\n// snorm8 cache (kcQ/vcQ = 4 x snorm8 per u32 word, kcS/vcS = one f32 scale per 32-element block,\n// llama.cpp q8_0-style, written by copy_kv8). Each element is dequantized with one unpack4x8snorm +\n// block-scale multiply at read time; all online-softmax arithmetic stays f32, so this matches the f32\n// attention_online_cache exactly except for the single snorm8 rounding of K/V at write (nothing\n// compounds). Same structure: one workgroup per query (s,h), thread d owns output dim d. head_dim <=256.\noverride WGD: u32 = 256u; // threads == head_dim D\nstruct Params { S: u32, H: u32, KV: u32, D: u32, scale: f32, posBase: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> kcQ: array<u32>; // cache [cap*KV, D/4] packed snorm8\n@group(0) @binding(3) var<storage, read> kcS: array<f32>; // cache [cap*KV, D/32] block scales\n@group(0) @binding(4) var<storage, read> vcQ: array<u32>; // cache [cap*KV, D/4]\n@group(0) @binding(5) var<storage, read> vcS: array<f32>; // cache [cap*KV, D/32]\n@group(0) @binding(6) var<storage, read_write> outp: array<f32>; // [S, H, D]\nvar<workgroup> qsh: array<f32, 256>;\nvar<workgroup> red: array<f32, 256>;\n\n@compute @workgroup_size(WGD)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let qi = wg.x; // query flat index = s*H + h\n let s = qi / p.H;\n let h = qi % p.H;\n let hkv = h / (p.H / p.KV);\n let d = lid.x;\n let D = p.D;\n let W4 = D / 4u;\n let NB = D / 32u;\n if (d < D) { qsh[d] = q[qi * D + d]; }\n workgroupBarrier();\n\n var m = -1e30;\n var l = 0.0;\n var acc = 0.0;\n let last = p.posBase + s; // inclusive: attend cache positions 0..last\n for (var j = 0u; j <= last; j = j + 1u) {\n let row = j * p.KV + hkv;\n var kval = 0.0;\n if (d < D) { kval = unpack4x8snorm(kcQ[row * W4 + (d >> 2u)])[d & 3u] * kcS[row * NB + (d >> 5u)]; }\n red[d] = select(0.0, qsh[d] * kval, d < D);\n workgroupBarrier();\n for (var st = WGD / 2u; st > 0u; st = st >> 1u) {\n if (d < st) { red[d] = red[d] + red[d + st]; }\n workgroupBarrier();\n }\n let score = red[0] * p.scale;\n let mn = max(m, score);\n let corr = exp(m - mn);\n let pj = exp(score - mn);\n l = l * corr + pj;\n if (d < D) {\n let vval = unpack4x8snorm(vcQ[row * W4 + (d >> 2u)])[d & 3u] * vcS[row * NB + (d >> 5u)];\n acc = acc * corr + pj * vval;\n }\n m = mn;\n workgroupBarrier();\n }\n if (d < D) { outp[qi * D + d] = acc / l; }\n}\n",
6
9
  "attention_sg": "// Causal GQA attention, subgroup-parallel: one subgroup (= one workgroup) per (query, head).\n// Lanes split head_dim; flash-style online softmax over the cached positions; the per-position\n// score (q.k) is reduced with subgroupAdd. Fixes the decode bottleneck where attention ran only\n// H threads. SG = device subgroup size (16/32/64, so head_dim/SG <= 8). Reads K/V from the cache.\nenable subgroups;\noverride SG: u32 = 32u;\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> Kc: array<f32>; // [Ltot, KV, D]\n@group(0) @binding(3) var<storage, read> Vc: array<f32>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read_write> out: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let idx = wg.x;\n if (idx >= p.S * p.H) { return; }\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n let dper = p.D / SG; // <= 8 for SG>=16, D=128\n\n var acc: array<f32, 8>;\n for (var t = 0u; t < dper; t = t + 1u) { acc[t] = 0.0; }\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n var part = 0.0;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; part = part + q[qb + d] * Kc[kb + d]; }\n let score = subgroupAdd(part) * inv; // full q.k dot, broadcast to all lanes\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let w = exp(score - mnew);\n l = l * corr + w;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; acc[t] = acc[t] * corr + w * Vc[kb + d]; }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; out[ob + d] = acc[t] / l; }\n}\n",
7
10
  "attention_sg_kv16": "// attention_sg with an f16-STORAGE KV cache (kvCache: 'f16'). Keep in lockstep with\n// attention_sg.wgsl: the ONLY difference is Kc/Vc are array<f16> and each cached value is\n// widened to f32 at the read. All arithmetic (dot, softmax, accumulation) stays f32, so the\n// precision loss is exactly one rounding of K/V at cache-write time, nothing compounding.\nenable subgroups;\nenable f16;\noverride SG: u32 = 32u;\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> Kc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(3) var<storage, read> Vc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read_write> out: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let idx = wg.x;\n if (idx >= p.S * p.H) { return; }\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n let dper = p.D / SG;\n\n var acc: array<f32, 8>;\n for (var t = 0u; t < dper; t = t + 1u) { acc[t] = 0.0; }\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n var part = 0.0;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; part = part + q[qb + d] * f32(Kc[kb + d]); }\n let score = subgroupAdd(part) * inv;\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let w = exp(score - mnew);\n l = l * corr + w;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; acc[t] = acc[t] * corr + w * f32(Vc[kb + d]); }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; out[ob + d] = acc[t] / l; }\n}\n",
8
11
  "attention_sg_kv16_roll": "// attention_sg_kv16 for the rolling-window / attention-sinks mode (see attention_sg_roll.wgsl\n// for the rope-at-read scheme). Keep in lockstep with attention_sg_kv16.wgsl: the ONLY\n// difference is the K rotation in the score loop; each cached f16 value is widened to f32 at\n// the read and rotated with the same `k*cos + rot*sin` operand order as rmsnorm_rope_sg.\n// The engine only selects this kernel when SG <= D/2 (partner dim stays in-lane).\nenable subgroups;\nenable f16;\noverride SG: u32 = 32u;\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\n@group(0) @binding(2) var<storage, read> Kc: array<f16>; // [Ltot, KV, D] UNROPED\n@group(0) @binding(3) var<storage, read> Vc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read> cosT: array<f32>; // [positions, D/2]\n@group(0) @binding(5) var<storage, read> sinT: array<f32>; // [positions, D/2]\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let idx = wg.x;\n if (idx >= p.S * p.H) { return; }\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n let dper = p.D / SG;\n let half = p.D / 2u;\n let hs = half / SG; // strides from a dim to its rotate partner\n\n var acc: array<f32, 8>;\n for (var t = 0u; t < dper; t = t + 1u) { acc[t] = 0.0; }\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n var kd: array<f32, 8>;\n for (var t = 0u; t < dper; t = t + 1u) { kd[t] = f32(Kc[kb + lane + t * SG]); }\n var part = 0.0;\n for (var t = 0u; t < dper; t = t + 1u) {\n let d = lane + t * SG;\n var rot: f32;\n if (d < half) { rot = -kd[t + hs]; } else { rot = kd[t - hs]; }\n let rb = j * half + (d % half);\n part = part + q[qb + d] * (kd[t] * cosT[rb] + rot * sinT[rb]);\n }\n let score = subgroupAdd(part) * inv;\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let w = exp(score - mnew);\n l = l * corr + w;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; acc[t] = acc[t] * corr + w * f32(Vc[kb + d]); }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; out[ob + d] = acc[t] / l; }\n}\n",
@@ -15,11 +18,16 @@ const SHADERS = {
15
18
  "attention_wg_kv8": "// attention_wg with a q8 KV cache (kvCache: 'q8'): the no-subgroup fallback reader for the\n// packed-snorm8 cache (see copy_kv8.wgsl for the write side). Keep in lockstep with\n// attention_wg.wgsl: same online softmax, all arithmetic f32; each thread owns one packed word\n// (D <= 128 -> at most 32 words, so threads 32..63 only carry zeros through the reduction).\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> Kq: array<u32>; // [Ltot, KV, D/4] packed snorm8\n@group(0) @binding(3) var<storage, read> Vq: array<u32>; // [Ltot, KV, D/4] packed snorm8\n@group(0) @binding(4) var<storage, read> Ks: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(5) var<storage, read> Vs: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\nvar<workgroup> red: array<f32, 64>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (idx >= p.S * p.H) { return; }\n let t = lid.x;\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n let W4 = p.D / 4u;\n\n var qv = vec4<f32>(0.0);\n if (t < W4) {\n qv = vec4<f32>(q[qb + t * 4u], q[qb + t * 4u + 1u], q[qb + t * 4u + 2u], q[qb + t * 4u + 3u]);\n }\n var acc = vec4<f32>(0.0);\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let rowQ = (j * p.KV + kvh) * W4;\n let rowS = (j * p.KV + kvh) * (p.D / 32u);\n var part = 0.0;\n if (t < W4) {\n let kw = unpack4x8snorm(Kq[rowQ + t]) * Ks[rowS + (t >> 3u)];\n part = dot(qv, kw);\n }\n red[t] = part;\n workgroupBarrier();\n for (var s = 32u; s > 0u; s = s >> 1u) {\n if (t < s) { red[t] = red[t] + red[t + s]; }\n workgroupBarrier();\n }\n let score = red[0] * inv;\n workgroupBarrier();\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let wgt = exp(score - mnew);\n l = l * corr + wgt;\n if (t < W4) {\n let vw = unpack4x8snorm(Vq[rowQ + t]) * Vs[rowS + (t >> 3u)];\n acc = acc * corr + wgt * vw;\n }\n m = mnew;\n }\n if (t < W4) {\n let ob = (qi * p.H + h) * p.D;\n let o = acc / l;\n out[ob + t * 4u] = o.x;\n out[ob + t * 4u + 1u] = o.y;\n out[ob + t * 4u + 2u] = o.z;\n out[ob + t * 4u + 3u] = o.w;\n }\n}\n",
16
19
  "attention_wg_kv8_roll": "// attention_wg_kv8 for the rolling-window / attention-sinks mode: the no-subgroup fallback of\n// attention_sg_kv8_roll (see there and attention_sg_roll.wgsl for the rope-at-read scheme).\n// Keep in lockstep with attention_wg_kv8.wgsl: the ONLY difference is the K rotation in the\n// score loop; each thread's word rotates against its partner word D/8 away, dequantized from\n// global with its own scale.\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\n@group(0) @binding(2) var<storage, read> Kq: array<u32>; // [Ltot, KV, D/4] packed snorm8, UNROPED\n@group(0) @binding(3) var<storage, read> Vq: array<u32>; // [Ltot, KV, D/4] packed snorm8\n@group(0) @binding(4) var<storage, read> Ks: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(5) var<storage, read> Vs: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(6) var<storage, read> cosT: array<f32>; // [positions, D/2]\n@group(0) @binding(7) var<storage, read> sinT: array<f32>; // [positions, D/2]\n@group(0) @binding(8) var<storage, read_write> out: array<f32>; // [S, H, D]\nvar<workgroup> red: array<f32, 64>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (idx >= p.S * p.H) { return; }\n let t = lid.x;\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n let W4 = p.D / 4u;\n let half = p.D / 2u;\n let hw = half / 4u; // words from a word to its rotate partner\n\n var qv = vec4<f32>(0.0);\n if (t < W4) {\n qv = vec4<f32>(q[qb + t * 4u], q[qb + t * 4u + 1u], q[qb + t * 4u + 2u], q[qb + t * 4u + 3u]);\n }\n var acc = vec4<f32>(0.0);\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let rowQ = (j * p.KV + kvh) * W4;\n let rowS = (j * p.KV + kvh) * (p.D / 32u);\n var part = 0.0;\n if (t < W4) {\n let kw = unpack4x8snorm(Kq[rowQ + t]) * Ks[rowS + (t >> 3u)];\n let wp = select(t - hw, t + hw, t < hw);\n let kp = unpack4x8snorm(Kq[rowQ + wp]) * Ks[rowS + (wp >> 3u)];\n let rot = select(kp, -kp, t < hw);\n let cb = j * half + select(t - hw, t, t < hw) * 4u;\n let cs = vec4<f32>(cosT[cb], cosT[cb + 1u], cosT[cb + 2u], cosT[cb + 3u]);\n let sn = vec4<f32>(sinT[cb], sinT[cb + 1u], sinT[cb + 2u], sinT[cb + 3u]);\n part = dot(qv, kw * cs + rot * sn);\n }\n red[t] = part;\n workgroupBarrier();\n for (var s = 32u; s > 0u; s = s >> 1u) {\n if (t < s) { red[t] = red[t] + red[t + s]; }\n workgroupBarrier();\n }\n let score = red[0] * inv;\n workgroupBarrier();\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let wgt = exp(score - mnew);\n l = l * corr + wgt;\n if (t < W4) {\n let vw = unpack4x8snorm(Vq[rowQ + t]) * Vs[rowS + (t >> 3u)];\n acc = acc * corr + wgt * vw;\n }\n m = mnew;\n }\n if (t < W4) {\n let ob = (qi * p.H + h) * p.D;\n let o = acc / l;\n out[ob + t * 4u] = o.x;\n out[ob + t * 4u + 1u] = o.y;\n out[ob + t * 4u + 2u] = o.z;\n out[ob + t * 4u + 3u] = o.w;\n }\n}\n",
17
20
  "attention_wg_roll": "// attention_wg for the rolling-window / attention-sinks mode: no-subgroup fallback of\n// attention_sg_roll (see there for the rope-at-read scheme). Keep in lockstep with\n// attention_wg.wgsl: the ONLY differences are the shared-memory K stage (kk) - the rotate\n// partner d±D/2 may live in another thread's stride - and the rotation in the score loop,\n// written as `k*cos + rot*sin` with the same operand order as rmsnorm_rope_sg.\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\n@group(0) @binding(2) var<storage, read> Kc: array<f32>; // [Ltot, KV, D] UNROPED\n@group(0) @binding(3) var<storage, read> Vc: array<f32>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read> cosT: array<f32>; // [positions, D/2]\n@group(0) @binding(5) var<storage, read> sinT: array<f32>; // [positions, D/2]\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\nvar<workgroup> red: array<f32, 64>;\nvar<workgroup> kk: array<f32, 128>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (idx >= p.S * p.H) { return; }\n let tid = lid.x;\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n let half = p.D / 2u;\n\n var acc: array<f32, 2>;\n acc[0] = 0.0;\n acc[1] = 0.0;\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { kk[d] = Kc[kb + d]; }\n }\n workgroupBarrier();\n var part = 0.0;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) {\n var rot: f32;\n if (d < half) { rot = -kk[d + half]; } else { rot = kk[d - half]; }\n let rb = j * half + (d % half);\n part = part + q[qb + d] * (kk[d] * cosT[rb] + rot * sinT[rb]);\n }\n }\n red[tid] = part;\n workgroupBarrier();\n for (var s = 32u; s > 0u; s = s >> 1u) {\n if (tid < s) { red[tid] = red[tid] + red[tid + s]; }\n workgroupBarrier();\n }\n let score = red[0] * inv; // full q.k dot, visible to all threads\n workgroupBarrier(); // red[0] + kk consumed before the next position overwrites them\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let w = exp(score - mnew);\n l = l * corr + w;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { acc[t] = acc[t] * corr + w * Vc[kb + d]; }\n }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { out[ob + d] = acc[t] / l; }\n }\n}\n",
21
+ "conv1d_causal": "// Depthwise causal Conv1d (kernel width K) + SiLU, for the gated-DeltaNet q/k/v stream. x is\n// [S, C] (C = conv_dim channels), weight is [C, K] (per-channel taps, the GGUF ssm_conv1d layout).\n// Carries a persistent left-context so segmented prefill and token-by-token decode continue across\n// calls: state_in / state_out hold the last K-1 inputs ([K-1, C]); loadState!=0 uses them (else the\n// causal left pad is zero). Extended input ext = [state_in (K-1), x (S)]:\n// y[t,c] = silu( sum_{j<K} w[c,j] * ext[t+j, c] ), state_out[i,c] = ext[S+i, c] (i < K-1)\nstruct Params { S: u32, C: u32, K: u32, loadState: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [S, C]\n@group(0) @binding(2) var<storage, read> w: array<f32>; // [C, K]\n@group(0) @binding(3) var<storage, read> state_in: array<f32>; // [K-1, C]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [S, C]\n@group(0) @binding(5) var<storage, read_write> state_out: array<f32>; // [K-1, C]\n\nfn ext(m: u32, c: u32) -> f32 {\n if (m + 1u < p.K) { return select(0.0, state_in[m * p.C + c], p.loadState != 0u); }\n return x[(m - (p.K - 1u)) * p.C + c];\n}\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n let outN = p.S * p.C;\n if (i < outN) {\n let c = i % p.C;\n let t = i / p.C;\n var acc = 0.0;\n for (var j = 0u; j < p.K; j = j + 1u) { acc = acc + w[c * p.K + j] * ext(t + j, c); }\n y[i] = acc / (1.0 + exp(-acc)); // SiLU\n } else if (i < outN + (p.K - 1u) * p.C) {\n let si = i - outN;\n let sc = si % p.C;\n let sk = si / p.C; // 0 .. K-2\n state_out[sk * p.C + sc] = ext(p.S + sk, sc);\n }\n}\n",
18
22
  "copy": "// Copy src[0..n) into dst[dstOff..dstOff+n). Used to append K/V into the persistent cache.\nstruct Params { n: u32, dstOff: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>;\n@group(0) @binding(2) var<storage, read_write> dst: array<f32>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.n) { return; }\n dst[p.dstOff + i] = src[i];\n}\n",
19
23
  "copy_kv16": "// copy with an f16-STORAGE destination (kvCache: 'f16'): appends f32 K/V rows into the f16\n// cache (one f32 -> f16 rounding per value). Keep in lockstep with copy.wgsl.\nenable f16;\nstruct Params { n: u32, dstOff: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>;\n@group(0) @binding(2) var<storage, read_write> dst: array<f16>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.n) { return; }\n dst[p.dstOff + i] = f16(src[i]);\n}\n",
20
- "copy_kv8": "// q8 cache append (kvCache: 'q8'): quantize f32 K/V rows into the packed-snorm8 cache, one f32\n// scale per 32-element block (llama.cpp q8_0-style). One 64-thread workgroup per row of D\n// elements: thread t owns packed word t (4 consecutive values), the workgroup reduces per-block\n// absolute maxima through shared memory, then packs with pack4x8snorm. Replaces copy/copy_kv16\n// at every cache-append site under q8. All attention arithmetic stays f32; the precision loss is\n// exactly one snorm8 rounding of K/V at write time, nothing compounding.\nstruct Params { rows: u32, D: u32, dstRow0: u32, _p: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>; // [rows, D]\n@group(0) @binding(2) var<storage, read_write> dstQ: array<u32>; // packed 4 x snorm8 per word\n@group(0) @binding(3) var<storage, read_write> dstS: array<f32>; // [.., D/32] block scales\n\nvar<workgroup> wabs: array<f32, 32>; // per-word abs max (D <= 128 -> at most 32 words)\nvar<workgroup> wblk: array<f32, 4>; // per-block scale (D/32 <= 4 blocks)\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let row = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (row >= p.rows) { return; }\n let t = lid.x;\n let W4 = p.D / 4u;\n let base = row * p.D;\n var v = vec4<f32>(0.0);\n if (t < W4) {\n v = vec4<f32>(src[base + t * 4u], src[base + t * 4u + 1u], src[base + t * 4u + 2u], src[base + t * 4u + 3u]);\n wabs[t] = max(max(abs(v.x), abs(v.y)), max(abs(v.z), abs(v.w)));\n }\n workgroupBarrier();\n if (t < p.D / 32u) {\n var m = 0.0;\n for (var i = 0u; i < 8u; i = i + 1u) { m = max(m, wabs[t * 8u + i]); }\n let s = max(m, 1e-30); // an all-zero block packs zeros, never NaN\n wblk[t] = s;\n dstS[(p.dstRow0 + row) * (p.D / 32u) + t] = s;\n }\n workgroupBarrier();\n if (t < W4) {\n dstQ[(p.dstRow0 + row) * W4 + t] = pack4x8snorm(v / wblk[t >> 3u]);\n }\n}\n",
24
+ "copy_kv8": "// q8 cache append (kvCache: 'q8'): quantize f32 K/V rows into the packed-snorm8 cache, one f32\n// scale per 32-element block (llama.cpp q8_0-style). One 64-thread workgroup per row of D\n// elements: thread t owns packed word t (4 consecutive values), the workgroup reduces per-block\n// absolute maxima through shared memory, then packs with pack4x8snorm. Replaces copy/copy_kv16\n// at every cache-append site under q8. All attention arithmetic stays f32; the precision loss is\n// exactly one snorm8 rounding of K/V at write time, nothing compounding.\nstruct Params { rows: u32, D: u32, dstRow0: u32, _p: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>; // [rows, D]\n@group(0) @binding(2) var<storage, read_write> dstQ: array<u32>; // packed 4 x snorm8 per word\n@group(0) @binding(3) var<storage, read_write> dstS: array<f32>; // [.., D/32] block scales\n\nvar<workgroup> wabs: array<f32, 64>; // per-word abs max (D <= 256 -> at most 64 words)\nvar<workgroup> wblk: array<f32, 8>; // per-block scale (D/32 <= 8 blocks)\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let row = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (row >= p.rows) { return; }\n let t = lid.x;\n let W4 = p.D / 4u;\n let base = row * p.D;\n var v = vec4<f32>(0.0);\n if (t < W4) {\n v = vec4<f32>(src[base + t * 4u], src[base + t * 4u + 1u], src[base + t * 4u + 2u], src[base + t * 4u + 3u]);\n wabs[t] = max(max(abs(v.x), abs(v.y)), max(abs(v.z), abs(v.w)));\n }\n workgroupBarrier();\n if (t < p.D / 32u) {\n var m = 0.0;\n for (var i = 0u; i < 8u; i = i + 1u) { m = max(m, wabs[t * 8u + i]); }\n let s = max(m, 1e-30); // an all-zero block packs zeros, never NaN\n wblk[t] = s;\n dstS[(p.dstRow0 + row) * (p.D / 32u) + t] = s;\n }\n workgroupBarrier();\n if (t < W4) {\n dstQ[(p.dstRow0 + row) * W4 + t] = pack4x8snorm(v / wblk[t >> 3u]);\n }\n}\n",
25
+ "deltanet_gbeta": "// DeltaNet gate/decay compute: from the a (decay input) and b (beta input) projections,\n// g[s,h] = a_neg[h] * softplus(a[s,h] + dt_bias[h]) (<= 0, log-space decay)\n// beta[s,h] = sigmoid(b[s,h])\n// per value head h. a_neg is -exp(A_log): the PrismML GGUF stores this pre-computed in the ssm_a\n// tensor (verified against the transformers A_log), so no exp() here. One invocation per (s,h);\n// output is [g (S*H) ; beta (S*H)] concatenated (engine binds two sub-ranges). Matches qwen35_numpy.\nstruct Params { S: u32, H: u32, _p0: u32, _p1: u32 }; // H = num_value_heads\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> a: array<f32>; // [S, H]\n@group(0) @binding(2) var<storage, read> b: array<f32>; // [S, H]\n@group(0) @binding(3) var<storage, read> a_neg: array<f32>; // [H] = -exp(A_log)\n@group(0) @binding(4) var<storage, read> dt_bias: array<f32>; // [H]\n@group(0) @binding(5) var<storage, read_write> out: array<f32>;// [2*S*H]: g then beta\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n let n = p.S * p.H;\n if (i >= n) { return; }\n let h = i % p.H;\n let x = a[i] + dt_bias[h];\n let sp = max(x, 0.0) + log(1.0 + exp(-abs(x))); // softplus (stable)\n out[i] = a_neg[h] * sp; // g (a_neg already = -exp(A_log))\n out[n + i] = 1.0 / (1.0 + exp(-b[i])); // beta\n}\n",
26
+ "deltanet_norm_gate": "// Gated RMSNorm for the DeltaNet output: y = gamma * rmsnorm(core) * silu(z), normalized over the\n// value head dim (one workgroup per head-vector row). Unlike the model's plain RMSNorm this uses\n// the weight directly (not 1+weight), matching tools/qwen35_numpy (Qwen3NextRMSNormGated).\noverride WG: u32 = 128u;\nstruct Params { rows: u32, DV: u32, eps: f32, _pad: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> core: array<f32>; // [rows, DV]\n@group(0) @binding(2) var<storage, read> z: array<f32>; // [rows, DV] gate\n@group(0) @binding(3) var<storage, read> gamma: array<f32>; // [DV]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>;// [rows, DV]\nvar<workgroup> sdata: array<f32, 256>;\n\n@compute @workgroup_size(WG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let row = wg.x;\n if (row >= p.rows) { return; }\n let tid = lid.x;\n let base = row * p.DV;\n var s = 0.0;\n for (var i = tid; i < p.DV; i = i + WG) { let c = core[base + i]; s = s + c * c; }\n sdata[tid] = s;\n workgroupBarrier();\n for (var st = WG / 2u; st > 0u; st = st >> 1u) {\n if (tid < st) { sdata[tid] = sdata[tid] + sdata[tid + st]; }\n workgroupBarrier();\n }\n let inv = inverseSqrt(sdata[0] / f32(p.DV) + p.eps);\n for (var i = tid; i < p.DV; i = i + WG) {\n let zz = z[base + i];\n y[base + i] = gamma[i] * (core[base + i] * inv) * (zz / (1.0 + exp(-zz))); // * silu(z)\n }\n}\n",
27
+ "deltanet_recur": "// Gated DeltaNet recurrent scan (the sequential O(1)/token gated delta rule; bitgpu's decode path\n// and a correctness reference for prefill). One workgroup per value head; thread `dv` owns value\n// column dv of the per-head state S[dk,dv], held in registers across the token loop. Per token:\n// S *= exp(g); kv = Kn·S; delta = (v - kv)·beta; S += Kn⊗delta; out = Qn·S\n// with Kn = l2norm(k), Qn = l2norm(q)/sqrt(dk) (matches tools/qwen35_numpy._delta_recurrent).\n// GQA: value head h reads q/k from key head h%HK. GGUF/bitgpu store value heads grouped\n// [rep, n_key_heads] (transposed from HF's [n_key_heads, rep]), so the shared key/query head is\n// h%HK (a \"tile\"), NOT h/(H/HK) (a \"repeat-interleave\"). loadState!=0 continues from state_in\n// (persistent decode/cross-segment state); state_out always carries the final state out.\noverride WGV: u32 = 128u; // threads per workgroup == head_v_dim (dv)\nstruct Params { S: u32, H: u32, DK: u32, DV: u32, HK: u32, betaOff: u32, loadState: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, HK, DK]\n@group(0) @binding(2) var<storage, read> k: array<f32>; // [S, HK, DK]\n@group(0) @binding(3) var<storage, read> v: array<f32>; // [S, H, DV]\n@group(0) @binding(4) var<storage, read> g: array<f32>; // [S, H]\n@group(0) @binding(5) var<storage, read> beta: array<f32>; // [S, H]\n@group(0) @binding(6) var<storage, read> state_in: array<f32>; // [H, DK, DV]\n@group(0) @binding(7) var<storage, read_write> core: array<f32>; // [S, H, DV]\n@group(0) @binding(8) var<storage, read_write> state_out: array<f32>; // [H, DK, DV]\nvar<workgroup> ksh: array<f32, 128>; // current token's raw k (>= DK)\nvar<workgroup> qsh: array<f32, 128>; // current token's raw q\n\n@compute @workgroup_size(WGV)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let h = wg.x; // value head\n let hk = h % p.HK; // GQA: shared key/query head (GGUF [rep,n_key] tile order)\n let dv = lid.x;\n let DK = p.DK;\n let sbase = h * DK * p.DV + dv; // state column S[:, dv] of head h, stride DV\n let scale = inverseSqrt(f32(DK));\n var s: array<f32, 128>; // state column S[:, dv], length DK\n for (var dk = 0u; dk < DK; dk = dk + 1u) { s[dk] = select(0.0, state_in[sbase + dk * p.DV], p.loadState != 0u); }\n\n for (var t = 0u; t < p.S; t = t + 1u) {\n let base = t * p.H + h; // value-head row (v, g, beta, out)\n let basek = t * p.HK + hk; // key-head row (q, k)\n for (var i = lid.x; i < DK; i = i + WGV) { ksh[i] = k[basek * DK + i]; qsh[i] = q[basek * DK + i]; }\n workgroupBarrier();\n var sk = 0.0;\n var sq = 0.0;\n for (var dk = 0u; dk < DK; dk = dk + 1u) { sk = sk + ksh[dk] * ksh[dk]; sq = sq + qsh[dk] * qsh[dk]; }\n let ik = inverseSqrt(sk + 1e-6); // l2norm(k)\n let iq = inverseSqrt(sq + 1e-6) * scale; // l2norm(q) / sqrt(dk)\n if (dv < p.DV) {\n let gt = exp(g[base]);\n let bt = beta[p.betaOff + base]; // beta may share g's buffer (engine: gbeta = [g; beta])\n for (var dk = 0u; dk < DK; dk = dk + 1u) { s[dk] = s[dk] * gt; } // decay\n var kv = 0.0;\n for (var dk = 0u; dk < DK; dk = dk + 1u) { kv = kv + s[dk] * ksh[dk] * ik; }\n let delta = (v[base * p.DV + dv] - kv) * bt;\n var o = 0.0;\n for (var dk = 0u; dk < DK; dk = dk + 1u) {\n s[dk] = s[dk] + ksh[dk] * ik * delta; // S += Kn ⊗ delta\n o = o + s[dk] * qsh[dk] * iq; // out = Qn · S (updated)\n }\n core[base * p.DV + dv] = o;\n }\n workgroupBarrier();\n }\n if (dv < p.DV) { for (var dk = 0u; dk < DK; dk = dk + 1u) { state_out[sbase + dk * p.DV] = s[dk]; } }\n}\n",
21
28
  "embed_gather": "// GPU embedding gather + 4-bit dequant: reads a token id from a GPU buffer and writes that token's\n// embedding (H f32) directly into a GPU buffer, so the decode loop never round-trips the token id to\n// the CPU. Faithful port of the CPU embedDequant (4-bit codes via the tgt4 LUT, per-128 zero-point,\n// per-block scale). uint8 source arrays are read as u32 and byte-extracted (little-endian).\noverride WG: u32 = 256u;\nstruct Params { H: u32, srcIdx: u32, _0: u32, _1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> tokenId: array<u32>; // tokenId[p.srcIdx] = the token to embed\n@group(0) @binding(2) var<storage, read> embWq: array<u32>; // uint8 [vocab * H/8] packed\n@group(0) @binding(3) var<storage, read> tgt4: array<u32>; // uint8 [256*4] packed (1 src byte -> 4)\n@group(0) @binding(4) var<storage, read> embScales: array<f32>;// [vocab * H/128]\n@group(0) @binding(5) var<storage, read> embZp: array<u32>; // uint8 [vocab * ceil(H/256)] packed\n@group(0) @binding(6) var<storage, read_write> out: array<f32>;// [H]\n\n@compute @workgroup_size(WG)\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\n let id = tokenId[p.srcIdx];\n // Per-row strides derived from H: rowBytes source bytes, scaleRow f32 scales,\n // zpRow packed zero-point bytes (H=2048 -> 256/16/8, H=2560 -> 320/20/10).\n let rowBytes = p.H >> 3u;\n let scaleRow = p.H >> 7u;\n let zpRow = (scaleRow + 1u) >> 1u;\n for (var k = lid.x; k < p.H; k = k + WG) {\n let i = k >> 3u;\n let qd = (k >> 1u) & 3u;\n let c = k & 1u;\n let wqIdx = id * rowBytes + i;\n let e = (embWq[wqIdx >> 2u] >> (8u * (wqIdx & 3u))) & 0xffu; // source byte 0..255\n let tIdx = 4u * e + qd;\n let t = (tgt4[tIdx >> 2u] >> (8u * (tIdx & 3u))) & 0xffu; // expanded byte (2 codes)\n let code = (t >> (4u * c)) & 0xfu;\n let blk = k >> 7u;\n let zpIdx = id * zpRow + (blk >> 1u);\n let zpByte = (embZp[zpIdx >> 2u] >> (8u * (zpIdx & 3u))) & 0xffu;\n let zp = (zpByte >> (4u * (blk & 1u))) & 0xfu;\n out[k] = (f32(code) - f32(zp)) * embScales[id * scaleRow + blk];\n }\n}\n",
22
29
  "embed_gather_batch": "// Batched GPU embedding gather + 4-bit dequant for PROMPT tokens: one invocation per output\n// element writes out[s*H + k] for tokenIds[s]. A prefill segment uploads S u32 token ids\n// instead of S*H dequantized floats, so the CPU-side embedding tables are not needed at all\n// (~50-100 MB RAM per model). Same per-row stride math and dequant as embed_gather.wgsl\n// (H=2048 -> 256/16/8 strides); uint8 sources read as u32 and byte-extracted (little-endian).\nstruct Params { S: u32, H: u32, _0: u32, _1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> tokenIds: array<u32>; // [S]\n@group(0) @binding(2) var<storage, read> embWq: array<u32>; // uint8 [vocab * H/8] packed\n@group(0) @binding(3) var<storage, read> tgt4: array<u32>; // uint8 [256*4] packed (1 src byte -> 4)\n@group(0) @binding(4) var<storage, read> embScales: array<f32>; // [vocab * H/128]\n@group(0) @binding(5) var<storage, read> embZp: array<u32>; // uint8 [vocab * ceil(H/256)] packed\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S * H]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let gi = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (gi >= p.S * p.H) { return; }\n let k = gi % p.H;\n let id = tokenIds[gi / p.H];\n let rowBytes = p.H >> 3u;\n let scaleRow = p.H >> 7u;\n let zpRow = (scaleRow + 1u) >> 1u;\n let i = k >> 3u;\n let qd = (k >> 1u) & 3u;\n let c = k & 1u;\n let wqIdx = id * rowBytes + i;\n let e = (embWq[wqIdx >> 2u] >> (8u * (wqIdx & 3u))) & 0xffu; // source byte 0..255\n let tIdx = 4u * e + qd;\n let t = (tgt4[tIdx >> 2u] >> (8u * (tIdx & 3u))) & 0xffu; // expanded byte (2 codes)\n let code = (t >> (4u * c)) & 0xfu;\n let blk = k >> 7u;\n let zpIdx = id * zpRow + (blk >> 1u);\n let zpByte = (embZp[zpIdx >> 2u] >> (8u * (zpIdx & 3u))) & 0xffu;\n let zp = (zpByte >> (4u * (blk & 1u))) & 0xfu;\n out[gi] = (f32(code) - f32(zp)) * embScales[id * scaleRow + blk];\n}\n",
30
+ "gate_sigmoid": "// Output gate for Qwen3.5 gated attention: y = x * sigmoid(gate), elementwise. Applied to the\n// attention output before o_proj (the gate is the second half of the doubled q_proj).\nstruct Params { n: u32, _p0: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>;\n@group(0) @binding(2) var<storage, read> gate: array<f32>;\n@group(0) @binding(3) var<storage, read_write> y: array<f32>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.n) { return; }\n y[i] = x[i] / (1.0 + exp(-gate[i]));\n}\n",
23
31
  "logsumexp": "// log-sum-exp over the (penalty-filtered) logits, the softmax normalizer that turns a raw logit\n// into a true logprob on the CPU: logprob(id) = logit[id] - lse. Runs AFTER sampler_penalty and\n// BEFORE the argmax_masked rounds (those mask their winners in place, which would corrupt the\n// sum). Two-phase single-workgroup reduction: strided max, then strided sum of exp(x - max);\n// entries at the -inf sentinel (banned ids) contribute nothing. Only one f32 is read back.\noverride WG: u32 = 256u;\nstruct Params { N: u32, _0: u32, _1: u32, _2: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> logits: array<f32>;\n@group(0) @binding(2) var<storage, read_write> outLse: array<f32>; // outLse[0] = max + log(sum)\n\nconst NEG_SENTINEL: f32 = -3.0e38; // below any real logit; banned entries sit at f32 -inf\n\nvar<workgroup> sval: array<f32, 256>;\n\n@compute @workgroup_size(WG)\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\n let tid = lid.x;\n var m = -3.4e38;\n for (var i = tid; i < p.N; i = i + WG) {\n let v = logits[i];\n if (v > NEG_SENTINEL && v > m) { m = v; }\n }\n sval[tid] = m;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s && sval[tid + s] > sval[tid]) { sval[tid] = sval[tid + s]; }\n workgroupBarrier();\n }\n let gmax = sval[0];\n workgroupBarrier();\n var acc = 0.0;\n for (var i = tid; i < p.N; i = i + WG) {\n let v = logits[i];\n if (v > NEG_SENTINEL) { acc = acc + exp(v - gmax); }\n }\n sval[tid] = acc;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s) { sval[tid] = sval[tid] + sval[tid + s]; }\n workgroupBarrier();\n }\n if (tid == 0u) { outLse[0] = gmax + log(sval[0]); }\n}\n",
24
32
  "matmul_binary_vec4": "// Binary matmul, vectorized: y[M,N] = x[M,K] @ W[N,K]^T, W = (+/-1) * per-block scale.\n// One thread per output; the K loop processes a 32-bit sign word at a time and the\n// activations as vec4 via dot() (4 weights per FMA instead of 1 scalar op). M-agnostic\n// (works for prefill M=S and decode M=1). x is bound as vec4 (K must be a multiple of 4).\nstruct Params { M: u32, N: u32, K: u32, nb: u32, block: u32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4]\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [M, N]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (idx >= p.M * p.N) { return; }\n let m = idx / p.N;\n let n = idx % p.N;\n let xRow = m * (p.K / 4u);\n let wRow = n * (p.K / 32u);\n let sbase = n * p.nb;\n let wordsPerBlock = p.block / 32u; // 4 for block=128\n\n var acc = 0.0;\n for (var b = 0u; b < p.nb; b = b + 1u) {\n var bsum = 0.0;\n for (var w = 0u; w < wordsPerBlock; w = w + 1u) {\n let word = signbits[wRow + b * wordsPerBlock + w];\n let xb = xRow + b * (p.block / 4u) + w * 8u; // vec4 base for this word (32 weights = 8 vec4)\n for (var g = 0u; g < 8u; g = g + 1u) {\n let bits4 = (word >> (g * 4u)) & 0xfu;\n let sv = vec4<f32>(\n select(-1.0, 1.0, (bits4 & 1u) != 0u),\n select(-1.0, 1.0, (bits4 & 2u) != 0u),\n select(-1.0, 1.0, (bits4 & 4u) != 0u),\n select(-1.0, 1.0, (bits4 & 8u) != 0u),\n );\n bsum = bsum + dot(x[xb + g], sv);\n }\n }\n acc = acc + bsum * scales[sbase + b];\n }\n y[idx] = acc;\n}\n",
25
33
  "matmul_q2": "// 2-bit dequant matmul (lm_head): y[M,N] = x[M,K] @ W[N,K]^T, W[n,k] = (code - zp) * scale[n, k/block].\n// codes are 2-bit, 4 per byte, packed into u32 words. Correctness-first (one thread per output, fp32).\nstruct Params { M: u32, N: u32, K: u32, nb: u32, block: u32, zp: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [M, K]\n@group(0) @binding(2) var<storage, read> codes: array<u32>; // [N, K/4] bytes packed as u32\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [M, N]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (idx >= p.M * p.N) { return; }\n let m = idx / p.N;\n let n = idx % p.N;\n let xbase = m * p.K;\n let cbyteBase = n * (p.K / 4u); // byte offset of row n in the codes stream\n let sbase = n * p.nb;\n let zpf = f32(p.zp);\n\n var acc = 0.0;\n for (var b = 0u; b < p.nb; b = b + 1u) {\n var bsum = 0.0;\n let k0 = b * p.block;\n for (var j = 0u; j < p.block; j = j + 1u) {\n let k = k0 + j;\n let byteIdx = cbyteBase + (k >> 2u);\n let word = codes[byteIdx >> 2u];\n let byte = (word >> (8u * (byteIdx & 3u))) & 0xffu;\n let code = (byte >> (2u * (k & 3u))) & 3u;\n bsum = bsum + (f32(code) - zpf) * x[xbase + k];\n }\n acc = acc + bsum * scales[sbase + b];\n }\n y[idx] = acc;\n}\n",
@@ -28,22 +36,29 @@ const SHADERS = {
28
36
  "matmul_q2_wg": "// No-subgroup fallback: 2-bit lm_head GEMV for decode (M=1), workgroup-shared-memory reduction.\n// One workgroup per output column; WG threads split K and tree-reduce. value = (code - zp) * scale.\n// 2D dispatch since N (vocab) > 65535. This is the v1 path's biggest cost (scalar was ~48ms/token).\noverride WG: u32 = 64u;\nstruct Params { N: u32, K: u32, nb: u32, zp: u32, gridX: u32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\n@group(0) @binding(2) var<storage, read> codes: array<u32>; // [N, K/4] bytes packed as u32\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [N]\nvar<workgroup> sdata: array<f32, 256>;\n\n@compute @workgroup_size(WG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let n = wg.y * p.gridX + wg.x;\n if (n >= p.N) { return; }\n let tid = lid.x;\n let cbase = n * (p.K / 4u);\n let sbase = n * p.nb;\n let zpf = f32(p.zp);\n let Kvec = p.K / 4u;\n var acc = 0.0;\n for (var gi = tid; gi < Kvec; gi = gi + WG) {\n let byteIdx = cbase + gi;\n let word = codes[byteIdx >> 2u];\n let byte = (word >> (8u * (byteIdx & 3u))) & 0xffu;\n let cv = vec4<f32>(f32(byte & 3u) - zpf, f32((byte >> 2u) & 3u) - zpf,\n f32((byte >> 4u) & 3u) - zpf, f32((byte >> 6u) & 3u) - zpf);\n acc = acc + dot(x[gi], cv) * scales[sbase + (gi >> 5u)];\n }\n sdata[tid] = acc;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s) { sdata[tid] = sdata[tid] + sdata[tid + s]; }\n workgroupBarrier();\n }\n if (tid == 0u) { y[n] = sdata[0]; }\n}\n",
29
37
  "matmul_resid": "// Binary matmul with a fused residual add: y[M,N] = x[M,K] @ W[N,K]^T + resid[M,N].\n// Folds the residual add into o_proj / down_proj so it's not a separate dispatch.\nstruct Params { M: u32, N: u32, K: u32, nb: u32, block: u32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4]\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\n@group(0) @binding(4) var<storage, read> resid: array<f32>; // [M, N]\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [M, N]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (idx >= p.M * p.N) { return; }\n let n = idx % p.N;\n let xRow = (idx / p.N) * (p.K / 4u);\n let wRow = n * (p.K / 32u);\n let sbase = n * p.nb;\n\n var acc = 0.0;\n for (var b = 0u; b < p.nb; b = b + 1u) {\n var bsum = 0.0;\n for (var w = 0u; w < 4u; w = w + 1u) {\n let word = signbits[wRow + b * 4u + w];\n let xb = xRow + b * 32u + w * 8u;\n for (var g = 0u; g < 8u; g = g + 1u) {\n let bits4 = (word >> (g * 4u)) & 0xfu;\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\n bsum = bsum + dot(x[xb + g], sv);\n }\n }\n acc = acc + bsum * scales[sbase + b];\n }\n y[idx] = acc + resid[idx];\n}\n",
30
38
  "matmul_resid_mr_sg": "// Multi-row subgroup GEMV for decode (M=1) with fused residual. Same as matmul_resid_sg but each\n// workgroup computes ROWS output columns at once: per K-step it issues ROWS independent weight\n// loads before the dots, giving the memory system more in-flight requests (memory-level\n// parallelism) to hide latency on the bandwidth-bound decode GEMV. One subgroup per workgroup;\n// lanes split K; ROWS accumulators reduced with subgroupAdd. value = sign * per-block scale.\nenable subgroups;\noverride SG: u32 = 32u;\noverride ROWS: u32 = 4u;\nstruct Params { N: u32, K: u32, nb: u32, gridX: u32, _p0: u32, _p1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\n@group(0) @binding(4) var<storage, read> resid: array<f32>; // [N]\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [N]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let rowBase = (wg.y * p.gridX + wg.x) * ROWS;\n let Kvec = p.K / 4u;\n let wStride = p.K / 32u;\n\n var acc: array<f32, 8>; // ROWS <= 8\n for (var r = 0u; r < ROWS; r = r + 1u) { acc[r] = 0.0; }\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\n let k = gi * 4u;\n let xv = x[gi];\n let widx = k >> 5u;\n let sh = k & 31u;\n let sc = k / 128u;\n for (var r = 0u; r < ROWS; r = r + 1u) {\n let n = rowBase + r;\n if (n < p.N) {\n let w = (signbits[n * wStride + widx] >> sh) & 0xfu;\n let sv = vec4<f32>(select(-1.0, 1.0, (w & 1u) != 0u), select(-1.0, 1.0, (w & 2u) != 0u),\n select(-1.0, 1.0, (w & 4u) != 0u), select(-1.0, 1.0, (w & 8u) != 0u));\n acc[r] = acc[r] + dot(xv, sv) * scales[n * p.nb + sc];\n }\n }\n }\n for (var r = 0u; r < ROWS; r = r + 1u) {\n let n = rowBase + r;\n let total = subgroupAdd(acc[r]); // collective: called for every r by all lanes\n if (lane == 0u && n < p.N) { y[n] = total + resid[n]; }\n }\n}\n",
39
+ "matmul_resid_mr_sg_af16": "// f16-activation variant of matmul_resid_mr_sg (multi-row decode GEMV + fused residual, M=1),\n// used for down_proj (its input is the f16 SwiGLU intermediate). Reads f16 x, dots in f16,\n// accumulates in f32; the residual add and the output stay f32. Weights unchanged.\nenable subgroups;\nenable f16;\noverride SG: u32 = 32u;\noverride ROWS: u32 = 4u;\nstruct Params { N: u32, K: u32, nb: u32, gridX: u32, _p0: u32, _p1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f16>>; // [K/4] f16 activations\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\n@group(0) @binding(4) var<storage, read> resid: array<f32>; // [N]\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [N]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let rowBase = (wg.y * p.gridX + wg.x) * ROWS;\n let Kvec = p.K / 4u;\n let wStride = p.K / 32u;\n\n var acc: array<f32, 8>; // ROWS <= 8\n for (var r = 0u; r < ROWS; r = r + 1u) { acc[r] = 0.0; }\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\n let k = gi * 4u;\n let xv = x[gi];\n let widx = k >> 5u;\n let sh = k & 31u;\n let sc = k / 128u;\n for (var r = 0u; r < ROWS; r = r + 1u) {\n let n = rowBase + r;\n if (n < p.N) {\n let w = (signbits[n * wStride + widx] >> sh) & 0xfu;\n let sv = vec4<f16>(select(-1.0h, 1.0h, (w & 1u) != 0u), select(-1.0h, 1.0h, (w & 2u) != 0u),\n select(-1.0h, 1.0h, (w & 4u) != 0u), select(-1.0h, 1.0h, (w & 8u) != 0u));\n acc[r] = acc[r] + f32(dot(xv, sv)) * scales[n * p.nb + sc];\n }\n }\n }\n for (var r = 0u; r < ROWS; r = r + 1u) {\n let n = rowBase + r;\n let total = subgroupAdd(acc[r]);\n if (lane == 0u && n < p.N) { y[n] = total + resid[n]; }\n }\n}\n",
31
40
  "matmul_resid_sm": "// Small-batch (M = 2..9) subgroup split-K GEMV with fused residual add (o_proj / down_proj in\n// the speculative-decode verify pass). One workgroup per output column; each weight word is\n// loaded once and dotted with all M activation rows. Per row the loop stride and accumulation\n// expression match the validated M=1 kernels, so results are row-wise bit-identical to them.\nenable subgroups;\noverride SG: u32 = 32u;\nstruct Params { N: u32, K: u32, nb: u32, gridX: u32, M: u32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4] row-major\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\n@group(0) @binding(4) var<storage, read> resid: array<f32>; // [M, N]\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [M, N]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let n = wg.y * p.gridX + wg.x;\n if (n >= p.N) { return; }\n let wRow = n * (p.K / 32u);\n let sbase = n * p.nb;\n let Kvec = p.K / 4u;\n\n var acc: array<f32, 9>; // M <= 9\n for (var m = 0u; m < p.M; m = m + 1u) { acc[m] = 0.0; }\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\n let k = gi * 4u;\n let word = signbits[wRow + (k >> 5u)];\n let bits4 = (word >> (k & 31u)) & 0xfu;\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\n let s = scales[sbase + (k / 128u)];\n for (var m = 0u; m < p.M; m = m + 1u) {\n acc[m] = acc[m] + dot(x[m * Kvec + gi], sv) * s;\n }\n }\n for (var m = 0u; m < p.M; m = m + 1u) {\n let total = subgroupAdd(acc[m]);\n if (lane == 0u) { y[m * p.N + n] = total + resid[m * p.N + n]; }\n }\n}\n",
32
41
  "matmul_resid_tiled": "// Tiled register-blocked binary GEMM with fused residual, for PREFILL (M>1), vec4 K-accumulation:\n// y[M,N] = x[M,K] @ W[N,K]^T + resid[M,N], W binary {-1,+1} sign-packed, per-128-block fp32 scale.\n// 64x64 output tile per workgroup, 16x16 threads each computing a 4x4 register tile, BK=16 K-step.\n// Activation + decoded/scaled weight tiles are staged in shared memory as vec4 (4 K per element);\n// each inner step is a dot() of vec4s, and one weight load decodes a whole nibble (4 signs) at once.\n// No subgroup ops -> all devices. Near-bit-exact (f32 accum; tiled K-order differs in last ULPs).\nconst BM: u32 = 64u;\nconst BN: u32 = 64u;\nconst BKV: u32 = 4u; // BK / 4 (BK = 16)\nstruct Params { M: u32, N: u32, K: u32, nb: u32, _0: u32, _1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4]\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\n@group(0) @binding(4) var<storage, read> resid: array<f32>; // [M, N]\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [M, N]\n\nvar<workgroup> xs: array<vec4<f32>, 256>; // BM*BKV\nvar<workgroup> ws: array<vec4<f32>, 256>; // BN*BKV\n\n@compute @workgroup_size(256)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let tid = lid.x;\n let tileM = wg.y * BM;\n let tileN = wg.x * BN;\n let tr = (tid / 16u) * 4u;\n let tc = (tid % 16u) * 4u;\n let Kv = p.K / 4u;\n var acc: array<f32, 16>;\n for (var i = 0u; i < 16u; i = i + 1u) { acc[i] = 0.0; }\n\n let Ksteps = Kv / BKV;\n for (var ks = 0u; ks < Ksteps; ks = ks + 1u) {\n let k0v = ks * BKV;\n for (var e = tid; e < BM * BKV; e = e + 256u) { // stage activation tile (vec4)\n let m = e / BKV; let kv = e % BKV; let gm = tileM + m;\n xs[e] = select(vec4<f32>(0.0), x[gm * Kv + (k0v + kv)], gm < p.M);\n }\n for (var e = tid; e < BN * BKV; e = e + 256u) { // stage decoded+scaled weight tile (vec4)\n let n = e / BKV; let kv = e % BKV; let gn = tileN + n; let k = (k0v + kv) * 4u;\n var wv = vec4<f32>(0.0);\n if (gn < p.N) {\n let bits4 = (signbits[gn * (p.K / 32u) + (k >> 5u)] >> (k & 31u)) & 0xfu;\n let s = scales[gn * p.nb + (k / 128u)];\n wv = vec4<f32>(select(-s, s, (bits4 & 1u) != 0u), select(-s, s, (bits4 & 2u) != 0u),\n select(-s, s, (bits4 & 4u) != 0u), select(-s, s, (bits4 & 8u) != 0u));\n }\n ws[e] = wv;\n }\n workgroupBarrier();\n for (var kv = 0u; kv < BKV; kv = kv + 1u) {\n var xr: array<vec4<f32>, 4>;\n for (var tm = 0u; tm < 4u; tm = tm + 1u) { xr[tm] = xs[(tr + tm) * BKV + kv]; }\n for (var tn = 0u; tn < 4u; tn = tn + 1u) {\n let w = ws[(tc + tn) * BKV + kv];\n for (var tm = 0u; tm < 4u; tm = tm + 1u) { acc[tm * 4u + tn] = acc[tm * 4u + tn] + dot(xr[tm], w); }\n }\n }\n workgroupBarrier();\n }\n\n for (var tm = 0u; tm < 4u; tm = tm + 1u) {\n let gm = tileM + tr + tm;\n if (gm < p.M) {\n for (var tn = 0u; tn < 4u; tn = tn + 1u) {\n let gn = tileN + tc + tn;\n if (gn < p.N) { let idx = gm * p.N + gn; y[idx] = acc[tm * 4u + tn] + resid[idx]; }\n }\n }\n }\n}\n",
33
42
  "matmul_resid_wg": "// No-subgroup fallback: split-K GEMV for decode (M=1) with fused residual, workgroup-shared-memory\n// reduction. One workgroup per output column; WG threads split K and tree-reduce. Used for o_proj/down.\noverride WG: u32 = 64u;\nstruct Params { N: u32, K: u32, nb: u32, gridX: u32, _p0: u32, _p1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\n@group(0) @binding(4) var<storage, read> resid: array<f32>; // [N]\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [N]\nvar<workgroup> sdata: array<f32, 256>;\n\n@compute @workgroup_size(WG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let n = wg.y * p.gridX + wg.x;\n if (n >= p.N) { return; }\n let tid = lid.x;\n let wRow = n * (p.K / 32u);\n let sbase = n * p.nb;\n let Kvec = p.K / 4u;\n var acc = 0.0;\n for (var gi = tid; gi < Kvec; gi = gi + WG) {\n let k = gi * 4u;\n let word = signbits[wRow + (k >> 5u)];\n let bits4 = (word >> (k & 31u)) & 0xfu;\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\n acc = acc + dot(x[gi], sv) * scales[sbase + (k / 128u)];\n }\n sdata[tid] = acc;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s) { sdata[tid] = sdata[tid] + sdata[tid + s]; }\n workgroupBarrier();\n }\n if (tid == 0u) { y[n] = sdata[0] + resid[n]; }\n}\n",
34
43
  "matmul_split": "// Fused binary matmul writing to up to 3 output buffers (qkv or gate/up in one dispatch).\n// Weights for the outputs are concatenated along N (rows N0 | N1 | N2). One thread per\n// output column n routes its result to out0/out1/out2 by range. Vectorized like matmul_binary_vec4.\nstruct Params { M: u32, K: u32, nb: u32, N0: u32, N1: u32, N2: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4]\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let Ntot = p.N0 + p.N1 + p.N2;\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (idx >= p.M * Ntot) { return; }\n let row = idx / Ntot;\n let n = idx % Ntot;\n let xRow = row * (p.K / 4u);\n let wRow = n * (p.K / 32u);\n let sbase = n * p.nb;\n\n var acc = 0.0;\n for (var b = 0u; b < p.nb; b = b + 1u) {\n var bsum = 0.0;\n for (var w = 0u; w < 4u; w = w + 1u) {\n let word = signbits[wRow + b * 4u + w];\n let xb = xRow + b * 32u + w * 8u;\n for (var g = 0u; g < 8u; g = g + 1u) {\n let bits4 = (word >> (g * 4u)) & 0xfu;\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\n bsum = bsum + dot(x[xb + g], sv);\n }\n }\n acc = acc + bsum * scales[sbase + b];\n }\n\n if (n < p.N0) { out0[row * p.N0 + n] = acc; }\n else if (n < p.N0 + p.N1) { out1[row * p.N1 + (n - p.N0)] = acc; }\n else { out2[row * p.N2 + (n - p.N0 - p.N1)] = acc; }\n}\n",
35
44
  "matmul_split_sg": "// Subgroup split-K GEMV for decode (M=1), fused: one subgroup (= one workgroup) per output\n// column; lanes split the K dimension and reduce with subgroupAdd (register-only, no barriers).\n// Cuts each matmul's latency ~SG-fold vs one-thread-per-output (the real decode bottleneck:\n// kernels run at full latency in the dependent chain). Routes to out0/out1/out2 by range (qkv / gate-up).\nenable subgroups;\noverride SG: u32 = 32u;\nstruct Params { K: u32, nb: u32, N0: u32, N1: u32, N2: u32, gridX: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let Ntot = p.N0 + p.N1 + p.N2;\n let n = wg.y * p.gridX + wg.x;\n if (n >= Ntot) { return; }\n let wRow = n * (p.K / 32u);\n let sbase = n * p.nb;\n let Kvec = p.K / 4u;\n\n var acc = 0.0;\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\n let k = gi * 4u;\n let word = signbits[wRow + (k >> 5u)];\n let bits4 = (word >> (k & 31u)) & 0xfu;\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\n acc = acc + dot(x[gi], sv) * scales[sbase + (k / 128u)];\n }\n let total = subgroupAdd(acc);\n if (lane == 0u) {\n if (n < p.N0) { out0[n] = total; }\n else if (n < p.N0 + p.N1) { out1[n - p.N0] = total; }\n else { out2[n - p.N0 - p.N1] = total; }\n }\n}\n",
45
+ "matmul_split_sg_af16": "// f16-activation variant of matmul_split_sg (fused QKV decode GEMV, M=1). The activation x is\n// read as f16 and the per-group dot runs in f16 (2x ALU rate on Apple/AMD/recent NVIDIA); the\n// per-block accumulation stays f32 (dot promoted before x scale, acc in f32) so accuracy tracks\n// f32 to ~f16 rounding. Weights (sign bits + f32 block scales) are unchanged. Outputs f32.\nenable subgroups;\nenable f16;\noverride SG: u32 = 32u;\nstruct Params { K: u32, nb: u32, N0: u32, N1: u32, N2: u32, gridX: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f16>>; // [K/4] f16 activations\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let Ntot = p.N0 + p.N1 + p.N2;\n let n = wg.y * p.gridX + wg.x;\n if (n >= Ntot) { return; }\n let wRow = n * (p.K / 32u);\n let sbase = n * p.nb;\n let Kvec = p.K / 4u;\n\n var acc = 0.0;\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\n let k = gi * 4u;\n let word = signbits[wRow + (k >> 5u)];\n let bits4 = (word >> (k & 31u)) & 0xfu;\n let sv = vec4<f16>(select(-1.0h, 1.0h, (bits4 & 1u) != 0u), select(-1.0h, 1.0h, (bits4 & 2u) != 0u),\n select(-1.0h, 1.0h, (bits4 & 4u) != 0u), select(-1.0h, 1.0h, (bits4 & 8u) != 0u));\n acc = acc + f32(dot(x[gi], sv)) * scales[sbase + (k / 128u)];\n }\n let total = subgroupAdd(acc);\n if (lane == 0u) {\n if (n < p.N0) { out0[n] = total; }\n else if (n < p.N0 + p.N1) { out1[n - p.N0] = total; }\n else { out2[n - p.N0 - p.N1] = total; }\n }\n}\n",
36
46
  "matmul_split_sm": "// Small-batch (M = 2..9) subgroup split-K GEMV, fused qkv / gate-up. The speculative-decode\n// verify pass computes M drafted rows in one forward; the scalar prefill kernels re-read the\n// weights per output thread, so a k-row pass cost ~k GEMVs. Here each weight word is loaded\n// ONCE per (column, k-chunk) and dotted with all M activation rows (activations are ~8 KB/row,\n// cache-resident). Per row the loop stride and accumulation expression are IDENTICAL to\n// matmul_split_sg, so each row's partials - and therefore the subgroupAdd result - match the\n// M=1 decode path bit-for-bit.\nenable subgroups;\noverride SG: u32 = 32u;\nstruct Params { K: u32, nb: u32, N0: u32, N1: u32, N2: u32, gridX: u32, M: u32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4] row-major\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>; // [M, N0]\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>; // [M, N1]\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>; // [M, N2]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let Ntot = p.N0 + p.N1 + p.N2;\n let n = wg.y * p.gridX + wg.x;\n if (n >= Ntot) { return; } // uniform per workgroup: the whole subgroup exits together\n let wRow = n * (p.K / 32u);\n let sbase = n * p.nb;\n let Kvec = p.K / 4u;\n\n var acc: array<f32, 9>; // M <= 9\n for (var m = 0u; m < p.M; m = m + 1u) { acc[m] = 0.0; }\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\n let k = gi * 4u;\n let word = signbits[wRow + (k >> 5u)];\n let bits4 = (word >> (k & 31u)) & 0xfu;\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\n let s = scales[sbase + (k / 128u)];\n for (var m = 0u; m < p.M; m = m + 1u) {\n acc[m] = acc[m] + dot(x[m * Kvec + gi], sv) * s;\n }\n }\n for (var m = 0u; m < p.M; m = m + 1u) { // p.M is uniform: collective calls stay uniform\n let total = subgroupAdd(acc[m]);\n if (lane == 0u) {\n if (n < p.N0) { out0[m * p.N0 + n] = total; }\n else if (n < p.N0 + p.N1) { out1[m * p.N1 + (n - p.N0)] = total; }\n else { out2[m * p.N2 + (n - p.N0 - p.N1)] = total; }\n }\n }\n}\n",
37
47
  "matmul_split_tiled": "// Tiled register-blocked binary GEMM to 3 outputs (qkv or gate/up), PREFILL (M>1), vec4 K-accum.\n// Weights concatenated along N (N0|N1|N2); each output element routes individually to\n// out0/out1/out2 by its global column, so N0/N1/N2 need no alignment. Same vec4 design as\n// matmul_resid_tiled.\nconst BM: u32 = 64u;\nconst BN: u32 = 64u;\nconst BKV: u32 = 4u; // BK / 4 (BK = 16)\nstruct Params { M: u32, K: u32, nb: u32, N0: u32, N1: u32, N2: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4]\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\n\nvar<workgroup> xs: array<vec4<f32>, 256>;\nvar<workgroup> ws: array<vec4<f32>, 256>;\n\n@compute @workgroup_size(256)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let Ntot = p.N0 + p.N1 + p.N2;\n let tid = lid.x;\n let tileM = wg.y * BM;\n let tileN = wg.x * BN;\n let tr = (tid / 16u) * 4u;\n let tc = (tid % 16u) * 4u;\n let Kv = p.K / 4u;\n var acc: array<f32, 16>;\n for (var i = 0u; i < 16u; i = i + 1u) { acc[i] = 0.0; }\n\n let Ksteps = Kv / BKV;\n for (var ks = 0u; ks < Ksteps; ks = ks + 1u) {\n let k0v = ks * BKV;\n for (var e = tid; e < BM * BKV; e = e + 256u) {\n let m = e / BKV; let kv = e % BKV; let gm = tileM + m;\n xs[e] = select(vec4<f32>(0.0), x[gm * Kv + (k0v + kv)], gm < p.M);\n }\n for (var e = tid; e < BN * BKV; e = e + 256u) {\n let n = e / BKV; let kv = e % BKV; let gn = tileN + n; let k = (k0v + kv) * 4u;\n var wv = vec4<f32>(0.0);\n if (gn < Ntot) {\n let bits4 = (signbits[gn * (p.K / 32u) + (k >> 5u)] >> (k & 31u)) & 0xfu;\n let s = scales[gn * p.nb + (k / 128u)];\n wv = vec4<f32>(select(-s, s, (bits4 & 1u) != 0u), select(-s, s, (bits4 & 2u) != 0u),\n select(-s, s, (bits4 & 4u) != 0u), select(-s, s, (bits4 & 8u) != 0u));\n }\n ws[e] = wv;\n }\n workgroupBarrier();\n for (var kv = 0u; kv < BKV; kv = kv + 1u) {\n var xr: array<vec4<f32>, 4>;\n for (var tm = 0u; tm < 4u; tm = tm + 1u) { xr[tm] = xs[(tr + tm) * BKV + kv]; }\n for (var tn = 0u; tn < 4u; tn = tn + 1u) {\n let w = ws[(tc + tn) * BKV + kv];\n for (var tm = 0u; tm < 4u; tm = tm + 1u) { acc[tm * 4u + tn] = acc[tm * 4u + tn] + dot(xr[tm], w); }\n }\n }\n workgroupBarrier();\n }\n\n for (var tm = 0u; tm < 4u; tm = tm + 1u) {\n let gm = tileM + tr + tm;\n if (gm >= p.M) { continue; }\n for (var tn = 0u; tn < 4u; tn = tn + 1u) {\n let gn = tileN + tc + tn;\n if (gn >= Ntot) { continue; }\n let v = acc[tm * 4u + tn];\n if (gn < p.N0) { out0[gm * p.N0 + gn] = v; }\n else if (gn < p.N0 + p.N1) { out1[gm * p.N1 + (gn - p.N0)] = v; }\n else { out2[gm * p.N2 + (gn - p.N0 - p.N1)] = v; }\n }\n }\n}\n",
38
48
  "matmul_split_wg": "// No-subgroup fallback: split-K GEMV for decode (M=1), workgroup-shared-memory reduction instead\n// of subgroupAdd. One workgroup per output column; WG threads split K and tree-reduce via shared\n// memory + barriers. ~WG-fold faster than one-thread-per-output (the v1 path). Routes qkv / gate-up.\noverride WG: u32 = 64u;\nstruct Params { K: u32, nb: u32, N0: u32, N1: u32, N2: u32, gridX: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\nvar<workgroup> sdata: array<f32, 256>; // >= max WG\n\n@compute @workgroup_size(WG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let Ntot = p.N0 + p.N1 + p.N2;\n let n = wg.y * p.gridX + wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (n >= Ntot) { return; }\n let tid = lid.x;\n let wRow = n * (p.K / 32u);\n let sbase = n * p.nb;\n let Kvec = p.K / 4u;\n var acc = 0.0;\n for (var gi = tid; gi < Kvec; gi = gi + WG) {\n let k = gi * 4u;\n let word = signbits[wRow + (k >> 5u)];\n let bits4 = (word >> (k & 31u)) & 0xfu;\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\n acc = acc + dot(x[gi], sv) * scales[sbase + (k / 128u)];\n }\n sdata[tid] = acc;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s) { sdata[tid] = sdata[tid] + sdata[tid + s]; }\n workgroupBarrier();\n }\n if (tid == 0u) {\n let total = sdata[0];\n if (n < p.N0) { out0[n] = total; }\n else if (n < p.N0 + p.N1) { out1[n - p.N0] = total; }\n else { out2[n - p.N0 - p.N1] = total; }\n }\n}\n",
39
49
  "matmul_swiglu_mr_sg": "// Multi-row fused gate/up GEMV + SwiGLU for decode (M=1). Each workgroup computes ROWS\n// intermediate indices; per K-step it issues 2*ROWS independent weight loads (gate row n and up\n// row F+n for each of the ROWS) before the dots, giving the bandwidth-bound decode GEMV more\n// in-flight memory requests. One subgroup per workgroup; lanes split K; reduced with subgroupAdd.\nenable subgroups;\noverride SG: u32 = 32u;\noverride ROWS: u32 = 4u;\nstruct Params { K: u32, nb: u32, F: u32, gridX: u32, _p0: u32, _p1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [2F, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [2F, nb]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [F]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let nBase = (wg.y * p.gridX + wg.x) * ROWS;\n let Kvec = p.K / 4u;\n let wStride = p.K / 32u;\n\n var g: array<f32, 8>; // ROWS <= 8\n var u: array<f32, 8>;\n for (var r = 0u; r < ROWS; r = r + 1u) { g[r] = 0.0; u[r] = 0.0; }\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\n let k = gi * 4u;\n let xv = x[gi];\n let widx = k >> 5u;\n let sh = k & 31u;\n let sc = k / 128u;\n for (var r = 0u; r < ROWS; r = r + 1u) {\n let n = nBase + r;\n if (n < p.F) {\n let gw = (signbits[n * wStride + widx] >> sh) & 0xfu;\n let gv = vec4<f32>(select(-1.0, 1.0, (gw & 1u) != 0u), select(-1.0, 1.0, (gw & 2u) != 0u),\n select(-1.0, 1.0, (gw & 4u) != 0u), select(-1.0, 1.0, (gw & 8u) != 0u));\n g[r] = g[r] + dot(xv, gv) * scales[n * p.nb + sc];\n let uw = (signbits[(p.F + n) * wStride + widx] >> sh) & 0xfu;\n let uv = vec4<f32>(select(-1.0, 1.0, (uw & 1u) != 0u), select(-1.0, 1.0, (uw & 2u) != 0u),\n select(-1.0, 1.0, (uw & 4u) != 0u), select(-1.0, 1.0, (uw & 8u) != 0u));\n u[r] = u[r] + dot(xv, uv) * scales[(p.F + n) * p.nb + sc];\n }\n }\n }\n for (var r = 0u; r < ROWS; r = r + 1u) {\n let n = nBase + r;\n let gt = subgroupAdd(g[r]);\n let ut = subgroupAdd(u[r]);\n if (lane == 0u && n < p.F) { y[n] = (gt / (1.0 + exp(-gt))) * ut; }\n }\n}\n",
50
+ "matmul_swiglu_mr_sg_af16": "// f16-activation variant of matmul_swiglu_mr_sg (fused gate/up GEMV + SwiGLU, M=1). Reads the\n// f16 activation x, dots in f16, accumulates each of gate/up in f32, applies SwiGLU in f32, and\n// writes the intermediate as f16 (the input side of the f16 down_proj). Weights unchanged.\nenable subgroups;\nenable f16;\noverride SG: u32 = 32u;\noverride ROWS: u32 = 4u;\nstruct Params { K: u32, nb: u32, F: u32, gridX: u32, _p0: u32, _p1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f16>>; // [K/4] f16 activations\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [2F, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [2F, nb]\n@group(0) @binding(4) var<storage, read_write> y: array<f16>; // [F] f16 intermediate\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let nBase = (wg.y * p.gridX + wg.x) * ROWS;\n let Kvec = p.K / 4u;\n let wStride = p.K / 32u;\n\n var g: array<f32, 8>; // ROWS <= 8\n var u: array<f32, 8>;\n for (var r = 0u; r < ROWS; r = r + 1u) { g[r] = 0.0; u[r] = 0.0; }\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\n let k = gi * 4u;\n let xv = x[gi];\n let widx = k >> 5u;\n let sh = k & 31u;\n let sc = k / 128u;\n for (var r = 0u; r < ROWS; r = r + 1u) {\n let n = nBase + r;\n if (n < p.F) {\n let gw = (signbits[n * wStride + widx] >> sh) & 0xfu;\n let gv = vec4<f16>(select(-1.0h, 1.0h, (gw & 1u) != 0u), select(-1.0h, 1.0h, (gw & 2u) != 0u),\n select(-1.0h, 1.0h, (gw & 4u) != 0u), select(-1.0h, 1.0h, (gw & 8u) != 0u));\n g[r] = g[r] + f32(dot(xv, gv)) * scales[n * p.nb + sc];\n let uw = (signbits[(p.F + n) * wStride + widx] >> sh) & 0xfu;\n let uv = vec4<f16>(select(-1.0h, 1.0h, (uw & 1u) != 0u), select(-1.0h, 1.0h, (uw & 2u) != 0u),\n select(-1.0h, 1.0h, (uw & 4u) != 0u), select(-1.0h, 1.0h, (uw & 8u) != 0u));\n u[r] = u[r] + f32(dot(xv, uv)) * scales[(p.F + n) * p.nb + sc];\n }\n }\n }\n for (var r = 0u; r < ROWS; r = r + 1u) {\n let n = nBase + r;\n let gt = subgroupAdd(g[r]);\n let ut = subgroupAdd(u[r]);\n if (lane == 0u && n < p.F) { y[n] = f16((gt / (1.0 + exp(-gt))) * ut); }\n }\n}\n",
40
51
  "rmsnorm_rope_sg": "// Fused per-head RMSNorm + RoPE for decode (S=1). One subgroup (= one workgroup) per head row;\n// lanes split head_dim, reduce sum-of-squares with subgroupAdd, then apply rope. rotate_half\n// pairs (d, d+-D/2): with SG>=32 and D=128 a lane owns d in {lane, lane+32, lane+64, lane+96},\n// so every (d, d+-64) pair is held by the same lane (no cross-lane reads for the rotate).\n// outOff/outStride let the K result write straight into the KV cache at its position.\nenable subgroups;\noverride SG: u32 = 32u;\nstruct Params { R: u32, D: u32, eps: f32, outOff: u32, outStride: u32, _p: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [R, D]\n@group(0) @binding(2) var<storage, read> gamma: array<f32>; // [D]\n@group(0) @binding(3) var<storage, read> cos: array<f32>; // [D]\n@group(0) @binding(4) var<storage, read> sin: array<f32>; // [D]\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [outOff + R*outStride]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let row = wg.x;\n if (row >= p.R) { return; }\n let base = row * p.D;\n var s = 0.0;\n for (var i = lane; i < p.D; i = i + SG) { let v = x[base + i]; s = s + v * v; }\n let inv = inverseSqrt(subgroupAdd(s) / f32(p.D) + p.eps);\n let half = p.D / 2u;\n let ob = p.outOff + row * p.outStride;\n for (var i = lane; i < p.D; i = i + SG) {\n let nd = x[base + i] * inv * gamma[i];\n var pd: u32; var sgn: f32;\n if (i < half) { pd = i + half; sgn = -1.0; } else { pd = i - half; sgn = 1.0; }\n let rot = sgn * (x[base + pd] * inv * gamma[pd]);\n y[ob + i] = nd * cos[i] + rot * sin[i];\n }\n}\n",
41
52
  "rmsnorm_rope_sg_kv16": "// rmsnorm_rope_sg writing into an f16-STORAGE KV cache (kvCache: 'f16'): used ONLY for the K\n// projection on the fused decode path, where the normed+roped K is written straight into the\n// cache. Keep in lockstep with rmsnorm_rope_sg.wgsl: the ONLY difference is y is array<f16>\n// (one f32 -> f16 rounding at the write). The q call keeps the f32 kernel.\nenable subgroups;\nenable f16;\noverride SG: u32 = 32u;\nstruct Params { R: u32, D: u32, eps: f32, outOff: u32, outStride: u32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [R, D]\n@group(0) @binding(2) var<storage, read> gamma: array<f32>; // [D]\n@group(0) @binding(3) var<storage, read> cos: array<f32>; // [D]\n@group(0) @binding(4) var<storage, read> sin: array<f32>; // [D]\n@group(0) @binding(5) var<storage, read_write> y: array<f16>; // [outOff + R*outStride]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let row = wg.x;\n if (row >= p.R) { return; }\n let base = row * p.D;\n var s = 0.0;\n for (var i = lane; i < p.D; i = i + SG) { let v = x[base + i]; s = s + v * v; }\n let inv = inverseSqrt(subgroupAdd(s) / f32(p.D) + p.eps);\n let half = p.D / 2u;\n let ob = p.outOff + row * p.outStride;\n for (var i = lane; i < p.D; i = i + SG) {\n let nd = x[base + i] * inv * gamma[i];\n var pd: u32; var sgn: f32;\n if (i < half) { pd = i + half; sgn = -1.0; } else { pd = i - half; sgn = 1.0; }\n let rot = sgn * (x[base + pd] * inv * gamma[pd]);\n y[ob + i] = f16(nd * cos[i] + rot * sin[i]);\n }\n}\n",
42
53
  "rmsnorm_rope_sg_kv8": "// rmsnorm_rope_sg writing into the q8 cache (kvCache: 'q8'): used ONLY for the K projection on\n// the fused decode path, where the normed+roped K quantizes straight into the cache. Keep the\n// math in lockstep with rmsnorm_rope_sg.wgsl; the write side mirrors copy_kv8.wgsl (packed\n// snorm8 words + one f32 scale per 32-element block). The q call keeps the f32 kernel.\nenable subgroups;\noverride SG: u32 = 32u;\nstruct Params { R: u32, D: u32, eps: f32, outRow0: u32, _p0: u32, _p1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [R, D]\n@group(0) @binding(2) var<storage, read> gamma: array<f32>; // [D]\n@group(0) @binding(3) var<storage, read> cos: array<f32>; // [D]\n@group(0) @binding(4) var<storage, read> sin: array<f32>; // [D]\n@group(0) @binding(5) var<storage, read_write> dstQ: array<u32>; // packed 4 x snorm8 per word\n@group(0) @binding(6) var<storage, read_write> dstS: array<f32>; // [.., D/32] block scales\n\nvar<workgroup> wabs: array<f32, 32>; // per-word abs max (D <= 128 -> at most 32 words)\nvar<workgroup> wblk: array<f32, 4>; // per-block scale (D/32 <= 4 blocks)\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let row = wg.x; // uniform: the barrier pattern below stays safe\n if (row >= p.R) { return; }\n let base = row * p.D;\n var s = 0.0;\n for (var i = lane; i < p.D; i = i + SG) { let v = x[base + i]; s = s + v * v; }\n let inv = inverseSqrt(subgroupAdd(s) / f32(p.D) + p.eps);\n let half = p.D / 2u;\n let W4 = p.D / 4u;\n\n var vals: array<vec4<f32>, 8>; // words per lane: W4/SG <= 8 for SG >= 4\n var wi = 0u;\n for (var w = lane; w < W4; w = w + SG) {\n var vv = vec4<f32>(0.0);\n for (var e = 0u; e < 4u; e = e + 1u) {\n let i = w * 4u + e;\n let nd = x[base + i] * inv * gamma[i];\n var pd: u32; var sgn: f32;\n if (i < half) { pd = i + half; sgn = -1.0; } else { pd = i - half; sgn = 1.0; }\n let rot = sgn * (x[base + pd] * inv * gamma[pd]);\n vv[e] = nd * cos[i] + rot * sin[i];\n }\n vals[wi] = vv;\n wi = wi + 1u;\n wabs[w] = max(max(abs(vv.x), abs(vv.y)), max(abs(vv.z), abs(vv.w)));\n }\n workgroupBarrier();\n if (lane < p.D / 32u) {\n var m = 0.0;\n for (var i = 0u; i < 8u; i = i + 1u) { m = max(m, wabs[lane * 8u + i]); }\n let sc = max(m, 1e-30);\n wblk[lane] = sc;\n dstS[(p.outRow0 + row) * (p.D / 32u) + lane] = sc;\n }\n workgroupBarrier();\n wi = 0u;\n for (var w = lane; w < W4; w = w + SG) {\n dstQ[(p.outRow0 + row) * W4 + w] = pack4x8snorm(vals[wi] / wblk[w >> 3u]);\n wi = wi + 1u;\n }\n}\n",
43
54
  "rmsnorm_sg": "// RMSNorm, subgroup-parallel: one subgroup (= one workgroup) per row; lanes split D and\n// reduce the sum-of-squares with subgroupAdd (register-only, no barriers/shared memory).\n// Fixes the decode bottleneck where R=1 ran on a single thread. SG is set from the device's\n// subgroup size at pipeline creation; requires workgroup_size == subgroup size.\nenable subgroups;\noverride SG: u32 = 32u;\nstruct Params { R: u32, D: u32, eps: f32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>;\n@group(0) @binding(2) var<storage, read> gamma: array<f32>;\n@group(0) @binding(3) var<storage, read_write> y: array<f32>;\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let row = wg.x;\n if (row >= p.R) { return; }\n let base = row * p.D;\n var s = 0.0;\n for (var i = lane; i < p.D; i = i + SG) { let v = x[base + i]; s = s + v * v; }\n let total = subgroupAdd(s); // sum across the subgroup, broadcast to all lanes\n let inv = inverseSqrt(total / f32(p.D) + p.eps);\n for (var i = lane; i < p.D; i = i + SG) { y[base + i] = x[base + i] * inv * gamma[i]; }\n}\n",
55
+ "rmsnorm_sg_af16": "// RMSNorm (subgroup) that writes the normalized activation as f16 - the input side of the\n// f16-activation decode matmuls (activation: 'f16'). Reads the f32 residual stream; the\n// sum-of-squares reduction stays f32 (accuracy); only the stored output is rounded to f16.\n// Identical reduction to rmsnorm_sg, so it is bit-comparable up to the final f16 rounding.\nenable subgroups;\nenable f16;\noverride SG: u32 = 32u;\nstruct Params { R: u32, D: u32, eps: f32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>;\n@group(0) @binding(2) var<storage, read> gamma: array<f32>;\n@group(0) @binding(3) var<storage, read_write> y: array<f16>;\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let row = wg.x;\n if (row >= p.R) { return; }\n let base = row * p.D;\n var s = 0.0;\n for (var i = lane; i < p.D; i = i + SG) { let v = x[base + i]; s = s + v * v; }\n let total = subgroupAdd(s);\n let inv = inverseSqrt(total / f32(p.D) + p.eps);\n for (var i = lane; i < p.D; i = i + SG) { y[base + i] = f16(x[base + i] * inv * gamma[i]); }\n}\n",
44
56
  "rmsnorm_wg": "// RMSNorm, no-subgroup fallback: one workgroup per row; threads split D and tree-reduce the\n// sum of squares via shared memory. Replaces the one-thread-per-row kernel on this path: at\n// decode (R=1) that kernel walked 2xD elements serially on a single thread, latency-bound,\n// and it ran twice per layer - the dominant cost of the whole fallback decode step.\n// Mirrors rmsnorm_sg exactly, with subgroupAdd swapped for the shared-memory reduction.\noverride WG: u32 = 64u;\nstruct Params { R: u32, D: u32, eps: f32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [R, D]\n@group(0) @binding(2) var<storage, read> gamma: array<f32>; // [D]\n@group(0) @binding(3) var<storage, read_write> y: array<f32>; // [R, D]\nvar<workgroup> sdata: array<f32, 256>; // >= max WG\n\n@compute @workgroup_size(WG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let row = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (row >= p.R) { return; }\n let tid = lid.x;\n let base = row * p.D;\n var s = 0.0;\n for (var i = tid; i < p.D; i = i + WG) { let v = x[base + i]; s = s + v * v; }\n sdata[tid] = s;\n workgroupBarrier();\n for (var st = WG / 2u; st > 0u; st = st >> 1u) {\n if (tid < st) { sdata[tid] = sdata[tid] + sdata[tid + st]; }\n workgroupBarrier();\n }\n let inv = inverseSqrt(sdata[0] / f32(p.D) + p.eps);\n for (var i = tid; i < p.D; i = i + WG) { y[base + i] = x[base + i] * inv * gamma[i]; }\n}\n",
45
57
  "rope": "// RoPE (rotate_half) with precomputed full cos/sin [S, D]. x is [S, H, D]. One invocation per element.\nstruct Params { S: u32, H: u32, D: u32, _pad: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> cos: array<f32>; // [S, D]\n@group(0) @binding(3) var<storage, read> sin: array<f32>; // [S, D]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (idx >= p.S * p.H * p.D) { return; }\n let d = idx % p.D;\n let sh = idx / p.D;\n let s = sh / p.H;\n let half = p.D / 2u;\n let row = sh * p.D; // s*H*D + h*D\n var rot: f32;\n if (d < half) {\n rot = -x[row + d + half];\n } else {\n rot = x[row + d - half];\n }\n y[idx] = x[idx] * cos[s * p.D + d] + rot * sin[s * p.D + d];\n}\n",
58
+ "rope_partial": "// Partial RoPE: rotate only the first ROT dims of each head (rotate_half within [0,ROT)); the\n// remaining head_dim-ROT dims pass through unrotated. cos/sin are [S, ROT]. x/y are [S, H, D].\n// Matches tools/qwen35_numpy._rope_partial (Qwen3.5 full-attention layers, partial_rotary_factor).\nstruct Params { S: u32, H: u32, D: u32, ROT: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> cosb: array<f32>; // [S, ROT]\n@group(0) @binding(3) var<storage, read> sinb: array<f32>; // [S, ROT]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (idx >= p.S * p.H * p.D) { return; }\n let d = idx % p.D;\n if (d >= p.ROT) { y[idx] = x[idx]; return; } // passthrough tail\n let sh = idx / p.D;\n let s = sh / p.H;\n let half = p.ROT / 2u;\n var rot: f32;\n if (d < half) { rot = -x[idx + half]; } else { rot = x[idx - half]; }\n y[idx] = x[idx] * cosb[s * p.ROT + d] + rot * sinb[s * p.ROT + d];\n}\n",
46
59
  "sampler_penalty": "// GPU logits pre-filter for sampling: applies repetition_penalty then no_repeat_ngram bans in place\n// on the full vocab logit buffer, so only a tiny top-K candidate set has to be read back (not all\n// ~151k logits). Matches transformers.js exactly: rep_penalty over the DEDUPED prompt+generated id\n// set (logit<0 ? *penalty : /penalty), then ngram-banned next-tokens set to -Infinity. Both id lists\n// are computed on the CPU each step (exact, since at syncN=1 the full history is known) and uploaded.\n// Temperature is NOT applied here: top-k is invariant under the monotonic divide, so temperature is\n// applied on the CPU to just the K candidate values before softmax (bit-identical, one less pass).\n// Single workgroup, no subgroup ops -> all devices. The storageBarrier guarantees every penalty\n// write lands before any ban write, so a token that is both repeated and ngram-banned ends at -inf\n// (ban wins, matching the reference order rep_penalty -> ngram).\noverride WG: u32 = 256u;\n// negInf carries the -Infinity bit pattern (0xff800000) from the host: bitcasting it at RUNTIME yields\n// -inf, whereas bitcast<f32>(0xff800000u) is a const-expression evaluating to inf, which is a WGSL\n// shader-creation error. (Runtime inf is fine; only const/override inf/nan is rejected.)\nstruct Params { affectedLen: u32, banLen: u32, penalty: f32, negInf: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> affectedIds: array<u32>; // deduped prompt+generated ids\n@group(0) @binding(2) var<storage, read> banIds: array<u32>; // ngram-banned next-token ids\n@group(0) @binding(3) var<storage, read_write> logits: array<f32>; // [vocab], modified in place\n\n@compute @workgroup_size(WG)\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\n let tid = lid.x;\n for (var i = tid; i < p.affectedLen; i = i + WG) {\n let t = affectedIds[i];\n let v = logits[t];\n if (v < 0.0) { logits[t] = v * p.penalty; } else { logits[t] = v / p.penalty; }\n }\n storageBarrier(); // all penalty writes before any ban write\n for (var i = tid; i < p.banLen; i = i + WG) {\n logits[banIds[i]] = bitcast<f32>(p.negInf); // -Infinity (runtime bitcast)\n }\n}\n",
60
+ "slice_cols": "// Extract a contiguous column range [off, off+w) from each row of a [rows, stride] buffer into a\n// packed [rows, w] buffer. Splits the DeltaNet conv output (q|k|v concatenated per token) into the\n// separate q/k/v activation buffers the scan reads.\nstruct Params { rows: u32, w: u32, stride: u32, off: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>; // [rows, stride]\n@group(0) @binding(2) var<storage, read_write> dst: array<f32>;// [rows, w]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.rows * p.w) { return; }\n let r = i / p.w;\n let c = i % p.w;\n dst[i] = src[r * p.stride + p.off + c];\n}\n",
61
+ "split_head": "// De-interleave a per-head doubled projection [S, H, 2*Dh] into [S, H, Dh], taking the half at\n// `off` (0 = query, Dh = gate). The Qwen3.5 gated-attention q_proj packs query and output-gate\n// interleaved per head; this pulls one out into a packed buffer.\nstruct Params { S: u32, H: u32, Dh: u32, off: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>; // [S, H, 2*Dh]\n@group(0) @binding(2) var<storage, read_write> dst: array<f32>;// [S, H, Dh]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.S * p.H * p.Dh) { return; }\n let d = i % p.Dh;\n let sh = i / p.Dh; // s*H + h\n dst[i] = src[sh * (2u * p.Dh) + p.off + d];\n}\n",
47
62
  "swiglu": "// SwiGLU gate: y[i] = silu(gate[i]) * up[i], silu(g) = g * sigmoid(g). One invocation per element.\nstruct Params { n: u32, _p0: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> gate: array<f32>;\n@group(0) @binding(2) var<storage, read> up: array<f32>;\n@group(0) @binding(3) var<storage, read_write> y: array<f32>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.n) { return; }\n let g = gate[i];\n y[i] = (g / (1.0 + exp(-g))) * up[i];\n}\n"
48
63
  };
49
64
  //#endregion
@@ -238,17 +253,17 @@ const eqBytes = (a, b) => {
238
253
  * baked caches (v2/GGUF). Plain rope or YaRN (transformers formula: beta_fast 32, beta_slow 1,
239
254
  * mscale = 0.1*ln(factor)+1). Angles accumulate in f64 and round once to f32 per entry -
240
255
  * tools/reference.py implements the identical recipe for fixture generation. */
241
- function synthRope(A, positions) {
242
- const half = A.head_dim / 2;
256
+ function synthRope(A, positions, rotaryDim = A.head_dim) {
257
+ const half = rotaryDim / 2;
243
258
  const rope = A.rope;
244
259
  const base = rope.rope_theta;
245
260
  const factor = rope.rope_type === "yarn" ? rope.factor ?? 1 : 1;
246
261
  const inv = new Float64Array(half);
247
262
  const orig = rope.original_max_position_embeddings ?? 0;
248
- const lo = factor === 1 ? 0 : Math.max(0, Math.floor(A.head_dim * Math.log(orig / (64 * Math.PI)) / (2 * Math.log(base))));
249
- const hi = factor === 1 ? 0 : Math.min(half - 1, Math.ceil(A.head_dim * Math.log(orig / (2 * Math.PI)) / (2 * Math.log(base))));
263
+ const lo = factor === 1 ? 0 : Math.max(0, Math.floor(rotaryDim * Math.log(orig / (64 * Math.PI)) / (2 * Math.log(base))));
264
+ const hi = factor === 1 ? 0 : Math.min(half - 1, Math.ceil(rotaryDim * Math.log(orig / (2 * Math.PI)) / (2 * Math.log(base))));
250
265
  for (let j = 0; j < half; j++) {
251
- const pf = base ** (2 * j / A.head_dim);
266
+ const pf = base ** (2 * j / rotaryDim);
252
267
  if (factor === 1) {
253
268
  inv[j] = 1 / pf;
254
269
  continue;
@@ -327,7 +342,8 @@ async function createEngineInner(options, holder) {
327
342
  const T = manifest.tensors;
328
343
  const FINAL_NORM = `layers.${A.layers}.final_norm_layernorm`;
329
344
  if (A.act !== "silu") throw new Error(`bitgpu: unsupported activation '${A.act}' (kernels implement silu/SwiGLU)`);
330
- if (A.head_dim > 128) throw new Error(`bitgpu: unsupported head_dim ${A.head_dim} (kernels assume <= 128)`);
345
+ if (A.head_dim > (A.hybrid ? 256 : 128)) throw new Error(`bitgpu: unsupported head_dim ${A.head_dim}`);
346
+ const ROPE_D = A.hybrid?.rotary_dim ?? A.head_dim;
331
347
  if (A.heads % A.kv_heads !== 0) throw new Error(`bitgpu: heads ${A.heads} not divisible by kv_heads ${A.kv_heads} (GQA kernels assume an integer group size)`);
332
348
  if (!T[FINAL_NORM]) throw new Error(`bitgpu: manifest is missing the final norm tensor '${FINAL_NORM}'`);
333
349
  if (manifest.version !== void 0 && manifest.version !== 1 && manifest.version !== 2) throw new Error(`bitgpu: unsupported manifest version ${manifest.version} (this engine reads versions 1 and 2)`);
@@ -381,15 +397,19 @@ async function createEngineInner(options, holder) {
381
397
  const SYNC_N = Math.max(1, opts.syncSteps ?? 4);
382
398
  const maxSeqLen = Math.max(1, opts.maxSeqLen ?? DEFAULT_MAX_SEQ);
383
399
  const useSG = hasSG && sgMin === sgMax && (sgMax === 16 || sgMax === 32 || sgMax === 64) && A.head_dim % sgMax === 0 && !forceNoSG;
384
- const kv16 = opts.kvCache === "f16" && adapter.features.has("shader-f16");
400
+ const kv16 = opts.kvCache === "f16" && !A.hybrid && adapter.features.has("shader-f16");
385
401
  const kv8 = opts.kvCache === "q8";
386
402
  const roll = opts.overflow === "sinks";
387
403
  const SINKS = roll ? Math.max(1, Math.floor(opts.sinkTokens ?? 4)) : 0;
404
+ if (roll && A.hybrid) throw new Error("bitgpu: overflow 'sinks' is not yet supported for the qwen3_5 hybrid backbone (the full-attention read path has no sink/roll K-rotation, and windowing only the full layers while the linear layers keep full-history state is unvalidated)");
388
405
  if (roll && maxSeqLen < SINKS + 64) throw new Error(`bitgpu: overflow 'sinks' needs maxSeqLen >= sinkTokens + 64 (got ${maxSeqLen} with ${SINKS} sinks)`);
389
406
  const KVB = kv16 ? 2 : kv8 ? 1 : 4;
407
+ const actF16 = opts.activation === "f16" && useSG && adapter.features.has("shader-f16");
390
408
  const features = [];
391
409
  if (useSG) features.push("subgroups");
392
- if (kv16) features.push("shader-f16");
410
+ if (kv16 || actF16) features.push("shader-f16");
411
+ const hasTS = adapter.features.has("timestamp-query");
412
+ if (hasTS) features.push("timestamp-query");
393
413
  const DEFAULT_BINDING = 134217728;
394
414
  const DEFAULT_BUFFER = 268435456;
395
415
  let needBind = 0;
@@ -405,7 +425,25 @@ async function createEngineInner(options, holder) {
405
425
  } else if (t.kind === "f32" && t.weight) track(t.weight.len);
406
426
  const fusedLen = (names, f) => names.reduce((n, nm) => n + T[nm][f].len, 0);
407
427
  for (let li = 0; li < A.layers; li++) {
408
- const groups = [
428
+ let groups;
429
+ if (A.hybrid) groups = [
430
+ ...A.hybrid.layer_types[li] === "full" ? [
431
+ "attn.q_proj",
432
+ "attn.k_proj",
433
+ "attn.v_proj",
434
+ "attn.o_proj"
435
+ ] : [
436
+ "linear.in_qkv",
437
+ "linear.z",
438
+ "linear.a",
439
+ "linear.b",
440
+ "linear.out_proj"
441
+ ],
442
+ "mlp.gate_proj",
443
+ "mlp.up_proj",
444
+ "mlp.down_proj"
445
+ ].map((s) => [`layers.${li}.${s}`]);
446
+ else groups = [
409
447
  [
410
448
  `layers.${li}.attn.q_proj`,
411
449
  `layers.${li}.attn.k_proj`,
@@ -523,6 +561,13 @@ async function createEngineInner(options, holder) {
523
561
  if (useSG) for (const n of ["attention_sg_kv8", "rmsnorm_rope_sg_kv8"]) specs.push([n, { SG: sgMax }]);
524
562
  else specs.push(["attention_wg_kv8"]);
525
563
  }
564
+ if (actF16) {
565
+ for (const n of ["rmsnorm_sg_af16", "matmul_split_sg_af16"]) specs.push([n, { SG: sgMax }]);
566
+ for (const n of ["matmul_swiglu_mr_sg_af16", "matmul_resid_mr_sg_af16"]) specs.push([n, {
567
+ SG: sgMax,
568
+ ROWS: ROWS_MR
569
+ }]);
570
+ }
526
571
  const rollSG = useSG && sgMax <= A.head_dim / 2;
527
572
  if (roll) {
528
573
  const rollAtt = kv16 ? "attention_sg_kv16_roll" : kv8 ? "attention_sg_kv8_roll" : "attention_sg_roll";
@@ -533,6 +578,20 @@ async function createEngineInner(options, holder) {
533
578
  const ATT = roll ? kv16 ? rollSG ? "attention_sg_kv16_roll" : "attention_wg_kv16_roll" : kv8 ? rollSG ? "attention_sg_kv8_roll" : "attention_wg_kv8_roll" : rollSG ? "attention_sg_roll" : "attention_wg_roll" : kv16 ? useSG ? "attention_sg_kv16" : "attention_wg_kv16" : kv8 ? useSG ? "attention_sg_kv8" : "attention_wg_kv8" : useSG ? "attention_sg" : "attention_wg";
534
579
  const ROPE_K = kv16 ? "rmsnorm_rope_sg_kv16" : "rmsnorm_rope_sg";
535
580
  const COPY_KV = kv16 ? "copy_kv16" : "copy";
581
+ if (A.hybrid) {
582
+ for (const n of [
583
+ "conv1d_causal",
584
+ "deltanet_gbeta",
585
+ "rope_partial",
586
+ "slice_cols",
587
+ "split_head",
588
+ "gate_sigmoid"
589
+ ]) specs.push([n]);
590
+ specs.push(["deltanet_recur", { WGV: A.hybrid.linear_head_dim }]);
591
+ specs.push(["deltanet_norm_gate", { WG: 64 }]);
592
+ specs.push(["attention_online", { WGD: A.head_dim }]);
593
+ specs.push([kv8 ? "attention_online_cache_kv8" : "attention_online_cache", { WGD: A.head_dim }]);
594
+ }
536
595
  await Promise.all(specs.map(([n, c]) => mkPipe(n, c)));
537
596
  const S_ = GPUBufferUsage.STORAGE, CD = GPUBufferUsage.COPY_DST, CS = GPUBufferUsage.COPY_SRC, U = GPUBufferUsage.UNIFORM;
538
597
  let transients = null;
@@ -593,10 +652,35 @@ async function createEngineInner(options, holder) {
593
652
  bufIdx++;
594
653
  return b;
595
654
  };
655
+ const actBuf16 = (n) => {
656
+ const bytes = n * 2;
657
+ if (!pool) {
658
+ const b = device.createBuffer({
659
+ size: bytes,
660
+ usage: S_ | CS | CD
661
+ });
662
+ transients?.push(b);
663
+ return b;
664
+ }
665
+ let b = pool.buf[bufIdx];
666
+ if (!b || b.size !== bytes) {
667
+ b = device.createBuffer({
668
+ size: bytes,
669
+ usage: S_ | CS | CD
670
+ });
671
+ pool.buf[bufIdx] = b;
672
+ }
673
+ bufIdx++;
674
+ return b;
675
+ };
596
676
  const dummy = device.createBuffer({
597
677
  size: 16,
598
678
  usage: S_
599
679
  });
680
+ const dummy2 = device.createBuffer({
681
+ size: 16,
682
+ usage: S_
683
+ });
600
684
  let fullHistory = [];
601
685
  let cacheLen = 0;
602
686
  const resetCache = () => {
@@ -787,7 +871,40 @@ async function createEngineInner(options, holder) {
787
871
  scales
788
872
  };
789
873
  };
790
- for (let li = 0; li < A.layers; li++) {
874
+ if (manifest.arch.hybrid) {
875
+ const bin = (nm) => {
876
+ const r = T[nm];
877
+ W[nm] = {
878
+ N: r.N,
879
+ K: r.K,
880
+ nb: r.K / 128,
881
+ N0: r.N,
882
+ N1: 0,
883
+ N2: 0,
884
+ ...fuse([r])
885
+ };
886
+ };
887
+ for (let li = 0; li < A.layers; li++) {
888
+ for (const s of [
889
+ "mlp.gate_proj",
890
+ "mlp.up_proj",
891
+ "mlp.down_proj"
892
+ ]) bin(`layers.${li}.${s}`);
893
+ if (manifest.arch.hybrid.layer_types[li] === "full") for (const s of [
894
+ "attn.q_proj",
895
+ "attn.k_proj",
896
+ "attn.v_proj",
897
+ "attn.o_proj"
898
+ ]) bin(`layers.${li}.${s}`);
899
+ else for (const s of [
900
+ "linear.in_qkv",
901
+ "linear.z",
902
+ "linear.a",
903
+ "linear.b",
904
+ "linear.out_proj"
905
+ ]) bin(`layers.${li}.${s}`);
906
+ }
907
+ } else for (let li = 0; li < A.layers; li++) {
791
908
  const q = T[`layers.${li}.attn.q_proj`], k = T[`layers.${li}.attn.k_proj`], v = T[`layers.${li}.attn.v_proj`];
792
909
  W[`layers.${li}.attn.qkv`] = {
793
910
  K: q.K,
@@ -849,12 +966,12 @@ async function createEngineInner(options, holder) {
849
966
  const sinBytes = wireCpu(T.sin_cache);
850
967
  cosCache = new Float32Array(cosBytes.buffer);
851
968
  sinCache = new Float32Array(sinBytes.buffer);
852
- const ropePositions = cosCache.length / (A.head_dim / 2);
969
+ const ropePositions = cosCache.length / (ROPE_D / 2);
853
970
  if (maxSeqLen > ropePositions) throw new Error(`bitgpu: maxSeqLen ${maxSeqLen} exceeds the model's baked RoPE cache (${ropePositions} positions); lower maxSeqLen or re-export with a longer cache`);
854
971
  } else {
855
972
  const cap = A.max_positions ?? 40960;
856
973
  if (maxSeqLen > cap) throw new Error(`bitgpu: maxSeqLen ${maxSeqLen} exceeds the model's max_positions (${cap})`);
857
- [cosCache, sinCache] = synthRope(A, maxSeqLen);
974
+ [cosCache, sinCache] = synthRope(A, maxSeqLen, ROPE_D);
858
975
  }
859
976
  routes.sort((a, b) => a.off - b.off || a.len - b.len);
860
977
  const merged = [];
@@ -937,7 +1054,7 @@ async function createEngineInner(options, holder) {
937
1054
  return out;
938
1055
  }
939
1056
  function ropeBufs(posBase, S) {
940
- const D = A.head_dim, R = D / 2, cos = new Float32Array(S * D), sin = new Float32Array(S * D);
1057
+ const D = ROPE_D, R = D / 2, cos = new Float32Array(S * D), sin = new Float32Array(S * D);
941
1058
  for (let s = 0; s < S; s++) for (let d = 0; d < D; d++) {
942
1059
  cos[s * D + d] = cosCache[(posBase + s) * R + d % R];
943
1060
  sin[s * D + d] = sinCache[(posBase + s) * R + d % R];
@@ -951,30 +1068,55 @@ async function createEngineInner(options, holder) {
951
1068
  };
952
1069
  }
953
1070
  const KV = A.kv_heads, Dh = A.head_dim, Hd = A.hidden, H = A.heads, F = A.intermediate;
1071
+ const NK = A.hybrid?.linear_key_heads ?? 0, NV = A.hybrid?.linear_value_heads ?? 0, DKV = A.hybrid?.linear_head_dim ?? 0, CONVK = A.hybrid?.conv_kernel ?? 0, KEYDIM = NK * DKV, VALDIM = NV * DKV, CONVDIM = KEYDIM * 2 + VALDIM;
954
1072
  let kvCapacity = Math.min(maxSeqLen, 512);
955
1073
  const Kc = [], Vc = [];
956
1074
  const Ksc = [], Vsc = [];
957
1075
  const kvScaleBytes = (cap) => cap * KV * (Dh / 32) * 4;
958
- for (let li = 0; li < A.layers; li++) {
959
- Kc.push(device.createBuffer({
1076
+ const kvLayers = [];
1077
+ for (let li = 0; li < A.layers; li++) if (!A.hybrid || A.hybrid.layer_types[li] === "full") kvLayers.push(li);
1078
+ const linearLayers = [];
1079
+ for (let li = 0; li < A.layers; li++) if (A.hybrid && A.hybrid.layer_types[li] === "linear") linearLayers.push(li);
1080
+ const rsSz = A.hybrid ? NV * DKV * DKV * 4 : 0;
1081
+ const csSz = A.hybrid ? (CONVK - 1) * CONVDIM * 4 : 0;
1082
+ for (const li of kvLayers) {
1083
+ Kc[li] = device.createBuffer({
960
1084
  size: kvCapacity * KV * Dh * KVB,
961
1085
  usage: S_ | CS | CD
962
- }));
963
- Vc.push(device.createBuffer({
1086
+ });
1087
+ Vc[li] = device.createBuffer({
964
1088
  size: kvCapacity * KV * Dh * KVB,
965
1089
  usage: S_ | CS | CD
966
- }));
1090
+ });
967
1091
  if (kv8) {
968
- Ksc.push(device.createBuffer({
1092
+ Ksc[li] = device.createBuffer({
969
1093
  size: kvScaleBytes(kvCapacity),
970
1094
  usage: S_ | CS | CD
971
- }));
972
- Vsc.push(device.createBuffer({
1095
+ });
1096
+ Vsc[li] = device.createBuffer({
973
1097
  size: kvScaleBytes(kvCapacity),
974
1098
  usage: S_ | CS | CD
975
- }));
1099
+ });
976
1100
  }
977
1101
  }
1102
+ const hyRS = [], hyCS = [];
1103
+ let hyPar = 0;
1104
+ if (A.hybrid) for (const li of linearLayers) {
1105
+ hyRS[li] = [device.createBuffer({
1106
+ size: rsSz,
1107
+ usage: S_ | CS | CD
1108
+ }), device.createBuffer({
1109
+ size: rsSz,
1110
+ usage: S_ | CS | CD
1111
+ })];
1112
+ hyCS[li] = [device.createBuffer({
1113
+ size: csSz,
1114
+ usage: S_ | CS | CD
1115
+ }), device.createBuffer({
1116
+ size: csSz,
1117
+ usage: S_ | CS | CD
1118
+ })];
1119
+ }
978
1120
  let rollCosT = null, rollSinT = null, rollOnes = null, rollZeros = null;
979
1121
  if (roll) {
980
1122
  const R2 = Dh / 2;
@@ -1010,9 +1152,8 @@ async function createEngineInner(options, holder) {
1010
1152
  const copyScales = kvScaleBytes(kvCapacity);
1011
1153
  device.pushErrorScope("out-of-memory");
1012
1154
  const enc = device.createCommandEncoder();
1013
- const per = kv8 ? 4 : 2;
1014
1155
  const olds = [];
1015
- for (let li = 0; li < A.layers; li++) {
1156
+ for (const li of kvLayers) {
1016
1157
  const nk = device.createBuffer({
1017
1158
  size: newCap * KV * Dh * KVB,
1018
1159
  usage: S_ | CS | CD
@@ -1023,7 +1164,7 @@ async function createEngineInner(options, holder) {
1023
1164
  });
1024
1165
  enc.copyBufferToBuffer(Kc[li], 0, nk, 0, copyBytes);
1025
1166
  enc.copyBufferToBuffer(Vc[li], 0, nv, 0, copyBytes);
1026
- olds.push(Kc[li], Vc[li]);
1167
+ const grp = [Kc[li], Vc[li]];
1027
1168
  Kc[li] = nk;
1028
1169
  Vc[li] = nv;
1029
1170
  if (kv8) {
@@ -1037,31 +1178,32 @@ async function createEngineInner(options, holder) {
1037
1178
  });
1038
1179
  enc.copyBufferToBuffer(Ksc[li], 0, nks, 0, copyScales);
1039
1180
  enc.copyBufferToBuffer(Vsc[li], 0, nvs, 0, copyScales);
1040
- olds.push(Ksc[li], Vsc[li]);
1181
+ grp.push(Ksc[li], Vsc[li]);
1041
1182
  Ksc[li] = nks;
1042
1183
  Vsc[li] = nvs;
1043
1184
  }
1185
+ olds[li] = grp;
1044
1186
  }
1045
1187
  device.queue.submit([enc.finish()]);
1046
1188
  await device.queue.onSubmittedWorkDone();
1047
1189
  const oom = await device.popErrorScope();
1048
1190
  if (oom) {
1049
- for (let li = 0; li < A.layers; li++) {
1191
+ for (const li of kvLayers) {
1050
1192
  Kc[li].destroy();
1051
1193
  Vc[li].destroy();
1052
- Kc[li] = olds[per * li];
1053
- Vc[li] = olds[per * li + 1];
1194
+ Kc[li] = olds[li][0];
1195
+ Vc[li] = olds[li][1];
1054
1196
  if (kv8) {
1055
1197
  Ksc[li].destroy();
1056
1198
  Vsc[li].destroy();
1057
- Ksc[li] = olds[per * li + 2];
1058
- Vsc[li] = olds[per * li + 3];
1199
+ Ksc[li] = olds[li][2];
1200
+ Vsc[li] = olds[li][3];
1059
1201
  }
1060
1202
  }
1061
1203
  poolInvalidate();
1062
1204
  throw new GpuOutOfMemoryError(`KV cache growth to ${newCap} positions failed: ${oom.message}`);
1063
1205
  }
1064
- for (const b of olds) b.destroy();
1206
+ for (const li of kvLayers) for (const b of olds[li]) b.destroy();
1065
1207
  kvCapacity = newCap;
1066
1208
  poolInvalidate();
1067
1209
  }
@@ -1082,7 +1224,7 @@ async function createEngineInner(options, holder) {
1082
1224
  }
1083
1225
  const enc = device.createCommandEncoder();
1084
1226
  const groups = [];
1085
- for (let li = 0; li < A.layers; li++) {
1227
+ for (const li of kvLayers) {
1086
1228
  groups.push([Kc[li], rowK], [Vc[li], rowK]);
1087
1229
  if (kv8) groups.push([Ksc[li], rowS], [Vsc[li], rowS]);
1088
1230
  }
@@ -1123,6 +1265,22 @@ async function createEngineInner(options, holder) {
1123
1265
  return out;
1124
1266
  }
1125
1267
  let FULL = null;
1268
+ let TS_PROFILE = false;
1269
+ let _tsQ = null;
1270
+ let _tsResolve = null;
1271
+ let _tsRead = null;
1272
+ const tsQ = () => _tsQ ??= device.createQuerySet({
1273
+ type: "timestamp",
1274
+ count: 2
1275
+ });
1276
+ const tsResolveBuf = () => _tsResolve ??= device.createBuffer({
1277
+ size: 16,
1278
+ usage: GPUBufferUsage.QUERY_RESOLVE | CS
1279
+ });
1280
+ const tsReadBuf = () => _tsRead ??= device.createBuffer({
1281
+ size: 16,
1282
+ usage: GPUBufferUsage.MAP_READ | CD
1283
+ });
1126
1284
  const isFull = (name) => FULL === null || FULL.has(name) || name === "embed_gather_batch";
1127
1285
  let FORCE_SLOW = false;
1128
1286
  let SMALLM = 0;
@@ -1209,7 +1367,12 @@ async function createEngineInner(options, holder) {
1209
1367
  const f = isFull(name);
1210
1368
  pass.dispatchWorkgroups(f ? wgX : 1, f ? wgY : 1, 1);
1211
1369
  }
1212
- const rms = (pass, x, g, R, Dn, out) => useSG ? runN(pass, "rmsnorm_sg", [
1370
+ const rms = (pass, x, g, R, Dn, out, out16 = false) => out16 ? runN(pass, "rmsnorm_sg_af16", [
1371
+ ["u", R],
1372
+ ["u", Dn],
1373
+ ["f", A.rms_eps],
1374
+ ["u", 0]
1375
+ ], [x, W[g].buf], out, R) : useSG ? runN(pass, "rmsnorm_sg", [
1213
1376
  ["u", R],
1214
1377
  ["u", Dn],
1215
1378
  ["f", A.rms_eps],
@@ -1290,11 +1453,11 @@ async function createEngineInner(options, holder) {
1290
1453
  w.scales
1291
1454
  ], outs, S * Ntot);
1292
1455
  }
1293
- function residMM(pass, w, inBuf, resid, S, out) {
1456
+ function residMM(pass, w, inBuf, resid, S, out, in16 = false) {
1294
1457
  if (useSG && S === 1) {
1295
1458
  const nwg = Math.ceil(w.N / ROWS_MR);
1296
1459
  const gx = Math.min(nwg, 65535);
1297
- runWG(pass, "matmul_resid_mr_sg", [
1460
+ runWG(pass, in16 ? "matmul_resid_mr_sg_af16" : "matmul_resid_mr_sg", [
1298
1461
  ["u", w.N],
1299
1462
  ["u", w.K],
1300
1463
  ["u", w.nb],
@@ -1396,15 +1559,243 @@ async function createEngineInner(options, holder) {
1396
1559
  if (roll) ins.push(rollCosT, rollSinT);
1397
1560
  return ins;
1398
1561
  };
1399
- function layer(pass, li, h, S, posBase, cos, sin) {
1400
- const Ltot = posBase + S;
1562
+ function hybridLayer(pass, li, h, S, posBase, cos, sin) {
1563
+ const hy = manifest.arch.hybrid;
1564
+ const w = (r) => W[`layers.${li}.${r}`];
1565
+ const ls = posBase > 0 ? 1 : 0;
1566
+ const par = hyPar;
1401
1567
  const n1 = actBuf(S * Hd);
1402
1568
  rms(pass, h, `layers.${li}.input_layernorm`, S, Hd, n1);
1569
+ let h2;
1570
+ if (hy.layer_types[li] === "linear") {
1571
+ const mixed = actBuf(S * CONVDIM);
1572
+ fusedMM(pass, w("linear.in_qkv"), n1, S, [
1573
+ mixed,
1574
+ dummy,
1575
+ dummy2
1576
+ ]);
1577
+ const convd = actBuf(S * CONVDIM);
1578
+ const cvSt = (CONVK - 1) * CONVDIM;
1579
+ setup(pass, "conv1d_causal", [
1580
+ ["u", S],
1581
+ ["u", CONVDIM],
1582
+ ["u", CONVK],
1583
+ ["u", ls]
1584
+ ], [
1585
+ mixed,
1586
+ w("linear.conv1d").buf,
1587
+ hyCS[li][par]
1588
+ ], [convd, hyCS[li][par ^ 1]]);
1589
+ {
1590
+ const [gx, gy] = grid2d(Math.ceil((S * CONVDIM + cvSt) / 64));
1591
+ pass.dispatchWorkgroups(gx, gy, 1);
1592
+ }
1593
+ const q = actBuf(S * KEYDIM), k = actBuf(S * KEYDIM), v = actBuf(S * VALDIM);
1594
+ run(pass, "slice_cols", [
1595
+ ["u", S],
1596
+ ["u", KEYDIM],
1597
+ ["u", CONVDIM],
1598
+ ["u", 0]
1599
+ ], [convd], q, S * KEYDIM);
1600
+ run(pass, "slice_cols", [
1601
+ ["u", S],
1602
+ ["u", KEYDIM],
1603
+ ["u", CONVDIM],
1604
+ ["u", KEYDIM]
1605
+ ], [convd], k, S * KEYDIM);
1606
+ run(pass, "slice_cols", [
1607
+ ["u", S],
1608
+ ["u", VALDIM],
1609
+ ["u", CONVDIM],
1610
+ ["u", 2 * KEYDIM]
1611
+ ], [convd], v, S * VALDIM);
1612
+ const a = actBuf(S * NV), b = actBuf(S * NV);
1613
+ fusedMM(pass, w("linear.a"), n1, S, [
1614
+ a,
1615
+ dummy,
1616
+ dummy2
1617
+ ]);
1618
+ fusedMM(pass, w("linear.b"), n1, S, [
1619
+ b,
1620
+ dummy,
1621
+ dummy2
1622
+ ]);
1623
+ const gb = actBuf(2 * S * NV);
1624
+ run(pass, "deltanet_gbeta", [
1625
+ ["u", S],
1626
+ ["u", NV],
1627
+ ["u", 0],
1628
+ ["u", 0]
1629
+ ], [
1630
+ a,
1631
+ b,
1632
+ w("linear.A_log").buf,
1633
+ w("linear.dt_bias").buf
1634
+ ], gb, S * NV);
1635
+ const core = actBuf(S * VALDIM);
1636
+ setup(pass, "deltanet_recur", [
1637
+ ["u", S],
1638
+ ["u", NV],
1639
+ ["u", DKV],
1640
+ ["u", DKV],
1641
+ ["u", NK],
1642
+ ["u", S * NV],
1643
+ ["u", ls],
1644
+ ["u", 0]
1645
+ ], [
1646
+ q,
1647
+ k,
1648
+ v,
1649
+ gb,
1650
+ gb,
1651
+ hyRS[li][par]
1652
+ ], [core, hyRS[li][par ^ 1]]);
1653
+ pass.dispatchWorkgroups(NV);
1654
+ const z = actBuf(S * VALDIM);
1655
+ fusedMM(pass, w("linear.z"), n1, S, [
1656
+ z,
1657
+ dummy,
1658
+ dummy2
1659
+ ]);
1660
+ const normed = actBuf(S * VALDIM);
1661
+ runN(pass, "deltanet_norm_gate", [
1662
+ ["u", S * NV],
1663
+ ["u", DKV],
1664
+ ["f", A.rms_eps],
1665
+ ["u", 0]
1666
+ ], [
1667
+ core,
1668
+ z,
1669
+ w("linear.norm").buf
1670
+ ], normed, S * NV);
1671
+ h2 = actBuf(S * Hd);
1672
+ residMM(pass, w("linear.out_proj"), normed, h, S, h2);
1673
+ } else {
1674
+ const qg = actBuf(S * H * Dh * 2);
1675
+ fusedMM(pass, w("attn.q_proj"), n1, S, [
1676
+ qg,
1677
+ dummy,
1678
+ dummy2
1679
+ ]);
1680
+ const query = actBuf(S * H * Dh), gate = actBuf(S * H * Dh);
1681
+ run(pass, "split_head", [
1682
+ ["u", S],
1683
+ ["u", H],
1684
+ ["u", Dh],
1685
+ ["u", 0]
1686
+ ], [qg], query, S * H * Dh);
1687
+ run(pass, "split_head", [
1688
+ ["u", S],
1689
+ ["u", H],
1690
+ ["u", Dh],
1691
+ ["u", Dh]
1692
+ ], [qg], gate, S * H * Dh);
1693
+ const qn = actBuf(S * H * Dh), qr = actBuf(S * H * Dh);
1694
+ rms(pass, query, `layers.${li}.attn.q_norm`, S * H, Dh, qn);
1695
+ run(pass, "rope_partial", [
1696
+ ["u", S],
1697
+ ["u", H],
1698
+ ["u", Dh],
1699
+ ["u", ROPE_D]
1700
+ ], [
1701
+ qn,
1702
+ cos,
1703
+ sin
1704
+ ], qr, S * H * Dh);
1705
+ const kk = actBuf(S * KV * Dh);
1706
+ fusedMM(pass, w("attn.k_proj"), n1, S, [
1707
+ kk,
1708
+ dummy,
1709
+ dummy2
1710
+ ]);
1711
+ const kn = actBuf(S * KV * Dh), kr = actBuf(S * KV * Dh);
1712
+ rms(pass, kk, `layers.${li}.attn.k_norm`, S * KV, Dh, kn);
1713
+ run(pass, "rope_partial", [
1714
+ ["u", S],
1715
+ ["u", KV],
1716
+ ["u", Dh],
1717
+ ["u", ROPE_D]
1718
+ ], [
1719
+ kn,
1720
+ cos,
1721
+ sin
1722
+ ], kr, S * KV * Dh);
1723
+ const vv = actBuf(S * KV * Dh);
1724
+ fusedMM(pass, w("attn.v_proj"), n1, S, [
1725
+ vv,
1726
+ dummy,
1727
+ dummy2
1728
+ ]);
1729
+ appendKV(pass, kr, 0, li, S * KV, posBase * KV);
1730
+ appendKV(pass, vv, 1, li, S * KV, posBase * KV);
1731
+ const att = actBuf(S * H * Dh);
1732
+ const aP = [
1733
+ ["u", S],
1734
+ ["u", H],
1735
+ ["u", KV],
1736
+ ["u", Dh],
1737
+ ["f", 1 / Math.sqrt(Dh)],
1738
+ ["u", posBase],
1739
+ ["u", 0],
1740
+ ["u", 0]
1741
+ ];
1742
+ if (kv8) runN(pass, "attention_online_cache_kv8", aP, [
1743
+ qr,
1744
+ Kc[li],
1745
+ Ksc[li],
1746
+ Vc[li],
1747
+ Vsc[li]
1748
+ ], att, S * H);
1749
+ else runN(pass, "attention_online_cache", aP, [
1750
+ qr,
1751
+ Kc[li],
1752
+ Vc[li]
1753
+ ], att, S * H);
1754
+ const gated = actBuf(S * H * Dh);
1755
+ run(pass, "gate_sigmoid", [
1756
+ ["u", S * H * Dh],
1757
+ ["u", 0],
1758
+ ["u", 0],
1759
+ ["u", 0]
1760
+ ], [att, gate], gated, S * H * Dh);
1761
+ h2 = actBuf(S * Hd);
1762
+ residMM(pass, w("attn.o_proj"), gated, h, S, h2);
1763
+ }
1764
+ const n2 = actBuf(S * Hd);
1765
+ rms(pass, h2, `layers.${li}.post_attention_layernorm`, S, Hd, n2);
1766
+ const g = actBuf(S * F), u = actBuf(S * F);
1767
+ fusedMM(pass, w("mlp.gate_proj"), n2, S, [
1768
+ g,
1769
+ dummy,
1770
+ dummy2
1771
+ ]);
1772
+ fusedMM(pass, w("mlp.up_proj"), n2, S, [
1773
+ u,
1774
+ dummy,
1775
+ dummy2
1776
+ ]);
1777
+ const sw = actBuf(S * F);
1778
+ run(pass, "swiglu", [
1779
+ ["u", S * F],
1780
+ ["u", 0],
1781
+ ["u", 0],
1782
+ ["u", 0]
1783
+ ], [g, u], sw, S * F);
1784
+ const hn = actBuf(S * Hd);
1785
+ residMM(pass, w("mlp.down_proj"), sw, h2, S, hn);
1786
+ return hn;
1787
+ }
1788
+ function layer(pass, li, h, S, posBase, cos, sin) {
1789
+ const Ltot = posBase + S;
1790
+ if (manifest.arch.hybrid) return hybridLayer(pass, li, h, S, posBase, cos, sin);
1791
+ const af = actF16 && S === 1 && !FORCE_SLOW;
1792
+ const n1 = af ? actBuf16(Hd) : actBuf(S * Hd);
1793
+ rms(pass, h, `layers.${li}.input_layernorm`, S, Hd, n1, af);
1403
1794
  const qkv = W[`layers.${li}.attn.qkv`];
1404
1795
  if (useSG && S === 1 && !FORCE_SLOW) {
1405
1796
  const q = actBuf(H * Dh), k = actBuf(KV * Dh), v = actBuf(KV * Dh);
1406
1797
  const Ntot = qkv.N0 + qkv.N1 + qkv.N2, gx = Math.min(Ntot, 65535);
1407
- runWG(pass, "matmul_split_sg", [
1798
+ runWG(pass, af ? "matmul_split_sg_af16" : "matmul_split_sg", [
1408
1799
  ["u", qkv.K],
1409
1800
  ["u", qkv.nb],
1410
1801
  ["u", qkv.N0],
@@ -1477,10 +1868,10 @@ async function createEngineInner(options, holder) {
1477
1868
  cap(li, "att", att);
1478
1869
  const o = W[`layers.${li}.attn.o_proj`], h2 = actBuf(Hd);
1479
1870
  residMM(pass, o, att, h, 1, h2);
1480
- const n2 = actBuf(Hd);
1481
- rms(pass, h2, `layers.${li}.post_attention_layernorm`, 1, Hd, n2);
1482
- const gu = W[`layers.${li}.mlp.gateup`], sw = actBuf(F), nwgF = Math.ceil(F / ROWS_MR), gxF = Math.min(nwgF, 65535);
1483
- runWG(pass, "matmul_swiglu_mr_sg", [
1871
+ const n2 = af ? actBuf16(Hd) : actBuf(Hd);
1872
+ rms(pass, h2, `layers.${li}.post_attention_layernorm`, 1, Hd, n2, af);
1873
+ const gu = W[`layers.${li}.mlp.gateup`], sw = af ? actBuf16(F) : actBuf(F), nwgF = Math.ceil(F / ROWS_MR), gxF = Math.min(nwgF, 65535);
1874
+ runWG(pass, af ? "matmul_swiglu_mr_sg_af16" : "matmul_swiglu_mr_sg", [
1484
1875
  ["u", gu.K],
1485
1876
  ["u", gu.nb],
1486
1877
  ["u", F],
@@ -1494,7 +1885,7 @@ async function createEngineInner(options, holder) {
1494
1885
  ], [sw], gxF, Math.ceil(nwgF / gxF));
1495
1886
  cap(li, "sw", sw);
1496
1887
  const d = W[`layers.${li}.mlp.down_proj`], hn = actBuf(Hd);
1497
- residMM(pass, d, sw, h2, 1, hn);
1888
+ residMM(pass, d, sw, h2, 1, hn, af);
1498
1889
  return hn;
1499
1890
  }
1500
1891
  const q = actBuf(S * H * Dh), k = actBuf(S * KV * Dh), v = actBuf(S * KV * Dh);
@@ -1627,6 +2018,7 @@ async function createEngineInner(options, holder) {
1627
2018
  cur = layer(pass, li, cur, S, posBase, cos, sin);
1628
2019
  if (li === 0) layer0 = cur;
1629
2020
  }
2021
+ if (A.hybrid) hyPar ^= 1;
1630
2022
  const fn = actBuf(S * Hd);
1631
2023
  rms(pass, cur, FINAL_NORM, S, Hd, fn);
1632
2024
  pass.end();
@@ -1754,7 +2146,8 @@ async function createEngineInner(options, holder) {
1754
2146
  flushTransients();
1755
2147
  const prefillMs = performance.now() - t0;
1756
2148
  const gen = [];
1757
- let recMs = 0, gpuMs = 0, rbMs = 0;
2149
+ let recMs = 0, gpuMs = 0, rbMs = 0, tsNs = 0;
2150
+ const tsOn = TS_PROFILE && hasTS;
1758
2151
  const t1 = performance.now();
1759
2152
  let total = 1;
1760
2153
  const stopSet = ctl?.stopTokens ? new Set(ctl.stopTokens) : null;
@@ -1774,7 +2167,10 @@ async function createEngineInner(options, holder) {
1774
2167
  const enc = device.createCommandEncoder();
1775
2168
  for (let j = 0; j < batch; j++) {
1776
2169
  const idxOut = total + j, pos = slot + j;
1777
- let pass = enc.beginComputePass();
2170
+ let pass = enc.beginComputePass(tsOn && j === 0 ? { timestampWrites: {
2171
+ querySet: tsQ(),
2172
+ beginningOfPassWriteIndex: 0
2173
+ } } : void 0);
1778
2174
  runN(pass, "embed_gather", [
1779
2175
  ["u", Hd],
1780
2176
  ["u", idxOut - 1],
@@ -1791,7 +2187,10 @@ async function createEngineInner(options, holder) {
1791
2187
  const r = stack(enc, embG, 1, pos);
1792
2188
  const last = actBuf(Hd);
1793
2189
  enc.copyBufferToBuffer(r.fn, 0, last, 0, Hd * 4);
1794
- pass = enc.beginComputePass();
2190
+ pass = enc.beginComputePass(tsOn && j === batch - 1 ? { timestampWrites: {
2191
+ querySet: tsQ(),
2192
+ endOfPassWriteIndex: 1
2193
+ } } : void 0);
1795
2194
  lmHead(pass, last, 1, lg);
1796
2195
  runN(pass, "argmax", [
1797
2196
  ["u", vocab],
@@ -1801,11 +2200,21 @@ async function createEngineInner(options, holder) {
1801
2200
  ], [lg], tokBuf, 1);
1802
2201
  pass.end();
1803
2202
  }
2203
+ if (tsOn) {
2204
+ enc.resolveQuerySet(tsQ(), 0, 2, tsResolveBuf(), 0);
2205
+ enc.copyBufferToBuffer(tsResolveBuf(), 0, tsReadBuf(), 0, 16);
2206
+ }
1804
2207
  device.queue.submit([enc.finish()]);
1805
2208
  recMs += performance.now() - t;
1806
2209
  t = performance.now();
1807
2210
  await device.queue.onSubmittedWorkDone();
1808
2211
  gpuMs += performance.now() - t;
2212
+ if (tsOn) {
2213
+ await tsReadBuf().mapAsync(GPUMapMode.READ);
2214
+ const ticks = new BigUint64Array(tsReadBuf().getMappedRange());
2215
+ tsNs += Number(ticks[1] - ticks[0]);
2216
+ tsReadBuf().unmap();
2217
+ }
1809
2218
  t = performance.now();
1810
2219
  const toks = await readbackU32(tokBuf, total + batch);
1811
2220
  rbMs += performance.now() - t;
@@ -1833,7 +2242,8 @@ async function createEngineInner(options, holder) {
1833
2242
  firstArgmax: firstTok,
1834
2243
  recMs: recMs / nd,
1835
2244
  gpuMs: gpuMs / nd,
1836
- rbMs: rbMs / nd
2245
+ rbMs: rbMs / nd,
2246
+ tsMs: tsOn ? tsNs / 1e6 / nd : 0
1837
2247
  };
1838
2248
  } finally {
1839
2249
  poolUse(null);
@@ -2450,9 +2860,10 @@ async function createEngineInner(options, holder) {
2450
2860
  const ck = {};
2451
2861
  for (const [name, b] of Object.entries(DBG0)) ck[name] = await readback(b, b.size / 4);
2452
2862
  const off = pos * KV * Dh;
2453
- if (!kv16 && !kv8) {
2454
- ck.kc = (await readback(Kc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
2455
- ck.vc = (await readback(Vc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
2863
+ if (!kv16 && !kv8 && kvLayers.length) {
2864
+ const dl = kvLayers[0];
2865
+ ck.kc = (await readback(Kc[dl], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
2866
+ ck.vc = (await readback(Vc[dl], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
2456
2867
  }
2457
2868
  ck.fn = await readback(r.fn, Hd);
2458
2869
  ck.logits = await readback(lg, W.lm_head.N);
@@ -2531,6 +2942,7 @@ async function createEngineInner(options, holder) {
2531
2942
  useSubgroups: useSG,
2532
2943
  subgroupSize: sgMax,
2533
2944
  kvCache: kv16 ? "f16" : kv8 ? "q8" : "f32",
2945
+ activation: actF16 ? "f16" : "f32",
2534
2946
  overflow: roll ? "sinks" : "error",
2535
2947
  maxSeqLen,
2536
2948
  adapter: {
@@ -2542,7 +2954,8 @@ async function createEngineInner(options, holder) {
2542
2954
  limits: {
2543
2955
  maxStorageBufferBindingSize: Number(device.limits.maxStorageBufferBindingSize),
2544
2956
  maxComputeWorkgroupStorageSize: device.limits.maxComputeWorkgroupStorageSize
2545
- }
2957
+ },
2958
+ timestampQuery: hasTS
2546
2959
  };
2547
2960
  async function generate(promptTokenIds, genOpts = {}) {
2548
2961
  const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1;
@@ -2685,30 +3098,41 @@ async function createEngineInner(options, holder) {
2685
3098
  }
2686
3099
  const kvRowBytes = KV * Dh * KVB;
2687
3100
  const scRowBytes = kv8 ? KV * (Dh / 32) * 4 : 0;
2688
- const snapshotBytes = (len) => A.layers * 2 * len * (kvRowBytes + scRowBytes);
2689
- async function saveCache() {
3101
+ const snapshotBytes = (len) => (A.hybrid ? kvLayers.length : A.layers) * 2 * len * (kvRowBytes + scRowBytes) + linearLayers.length * (rsSz + csSz);
3102
+ async function saveCache(opts) {
2690
3103
  if (fullHistory.length === 0) return null;
2691
3104
  const len = roll ? cacheLen : fullHistory.length - 1;
2692
- const data = new ArrayBuffer(snapshotBytes(len));
2693
- if (len > 0) {
3105
+ const base = Math.max(0, Math.min(Math.floor(opts?.from ?? 0), len));
3106
+ if (base > 0 && roll) throw new Error("saveCache: delta snapshots ({ from }) are not supported under overflow 'sinks'");
3107
+ if (base > 0 && A.hybrid) throw new Error("saveCache: delta snapshots ({ from }) are not supported for the qwen3_5 hybrid backbone");
3108
+ const count = len - base;
3109
+ const bytes = snapshotBytes(count);
3110
+ const data = new ArrayBuffer(bytes);
3111
+ if (bytes > 0) {
2694
3112
  const rb = device.createBuffer({
2695
- size: snapshotBytes(len),
3113
+ size: bytes,
2696
3114
  usage: GPUBufferUsage.MAP_READ | CD
2697
3115
  });
2698
3116
  const enc = device.createCommandEncoder();
2699
3117
  let off = 0;
2700
- for (let li = 0; li < A.layers; li++) {
2701
- enc.copyBufferToBuffer(Kc[li], 0, rb, off, len * kvRowBytes);
2702
- off += len * kvRowBytes;
2703
- enc.copyBufferToBuffer(Vc[li], 0, rb, off, len * kvRowBytes);
2704
- off += len * kvRowBytes;
3118
+ if (count > 0) for (const li of kvLayers) {
3119
+ enc.copyBufferToBuffer(Kc[li], base * kvRowBytes, rb, off, count * kvRowBytes);
3120
+ off += count * kvRowBytes;
3121
+ enc.copyBufferToBuffer(Vc[li], base * kvRowBytes, rb, off, count * kvRowBytes);
3122
+ off += count * kvRowBytes;
2705
3123
  if (kv8) {
2706
- enc.copyBufferToBuffer(Ksc[li], 0, rb, off, len * scRowBytes);
2707
- off += len * scRowBytes;
2708
- enc.copyBufferToBuffer(Vsc[li], 0, rb, off, len * scRowBytes);
2709
- off += len * scRowBytes;
3124
+ enc.copyBufferToBuffer(Ksc[li], base * scRowBytes, rb, off, count * scRowBytes);
3125
+ off += count * scRowBytes;
3126
+ enc.copyBufferToBuffer(Vsc[li], base * scRowBytes, rb, off, count * scRowBytes);
3127
+ off += count * scRowBytes;
2710
3128
  }
2711
3129
  }
3130
+ for (const li of linearLayers) {
3131
+ enc.copyBufferToBuffer(hyRS[li][hyPar], 0, rb, off, rsSz);
3132
+ off += rsSz;
3133
+ enc.copyBufferToBuffer(hyCS[li][hyPar], 0, rb, off, csSz);
3134
+ off += csSz;
3135
+ }
2712
3136
  device.queue.submit([enc.finish()]);
2713
3137
  await rb.mapAsync(GPUMapMode.READ);
2714
3138
  new Uint8Array(data).set(new Uint8Array(rb.getMappedRange()));
@@ -2726,6 +3150,7 @@ async function createEngineInner(options, holder) {
2726
3150
  vocab: A.vocab
2727
3151
  },
2728
3152
  ids: [...fullHistory],
3153
+ ...base > 0 ? { base } : {},
2729
3154
  ...roll ? { roll: {
2730
3155
  sinkTokens: SINKS,
2731
3156
  cacheLen
@@ -2742,22 +3167,36 @@ async function createEngineInner(options, holder) {
2742
3167
  if (!m || m.layers !== A.layers || m.kvHeads !== KV || m.headDim !== Dh || m.hidden !== Hd || m.vocab !== A.vocab) throw new Error("restoreCache: snapshot is from a different model (architecture mismatch)");
2743
3168
  if (!Array.isArray(snap.ids) || snap.ids.length === 0) throw new Error("restoreCache: snapshot holds no tokens");
2744
3169
  const len = snap.version === 2 ? snap.roll.cacheLen : snap.ids.length - 1;
3170
+ const base = Math.max(0, Math.floor(snap.base ?? 0));
3171
+ if (base > 0 && A.hybrid) throw new Error("restoreCache: delta snapshots are not supported for the qwen3_5 hybrid backbone");
3172
+ const count = len - base;
2745
3173
  if (len + 1 > maxSeqLen) throw new Error(`restoreCache: snapshot needs ${len + 1} cache slots but maxSeqLen is ${maxSeqLen}`);
2746
- if (snap.data.byteLength !== snapshotBytes(len)) throw new Error(`restoreCache: snapshot data is ${snap.data.byteLength} bytes, expected ${snapshotBytes(len)}`);
3174
+ if (snap.data.byteLength !== snapshotBytes(count)) throw new Error(`restoreCache: snapshot data is ${snap.data.byteLength} bytes, expected ${snapshotBytes(count)}`);
3175
+ if (base > 0) {
3176
+ if (cacheLen !== base) throw new Error(`restoreCache: delta snapshot expects the cache at position ${base} (prewarm the shared prefix first); it is at ${cacheLen}`);
3177
+ for (let i = 0; i < base; i++) if (fullHistory[i] !== snap.ids[i]) throw new Error(`restoreCache: delta snapshot prefix does not match the current prewarm (token ${i})`);
3178
+ }
2747
3179
  await ensureKvCapacity(len);
2748
3180
  let off = 0;
2749
- for (let li = 0; li < A.layers; li++) {
2750
- device.queue.writeBuffer(Kc[li], 0, snap.data, off, len * kvRowBytes);
2751
- off += len * kvRowBytes;
2752
- device.queue.writeBuffer(Vc[li], 0, snap.data, off, len * kvRowBytes);
2753
- off += len * kvRowBytes;
3181
+ if (count > 0) for (const li of kvLayers) {
3182
+ device.queue.writeBuffer(Kc[li], base * kvRowBytes, snap.data, off, count * kvRowBytes);
3183
+ off += count * kvRowBytes;
3184
+ device.queue.writeBuffer(Vc[li], base * kvRowBytes, snap.data, off, count * kvRowBytes);
3185
+ off += count * kvRowBytes;
2754
3186
  if (kv8) {
2755
- device.queue.writeBuffer(Ksc[li], 0, snap.data, off, len * scRowBytes);
2756
- off += len * scRowBytes;
2757
- device.queue.writeBuffer(Vsc[li], 0, snap.data, off, len * scRowBytes);
2758
- off += len * scRowBytes;
3187
+ device.queue.writeBuffer(Ksc[li], base * scRowBytes, snap.data, off, count * scRowBytes);
3188
+ off += count * scRowBytes;
3189
+ device.queue.writeBuffer(Vsc[li], base * scRowBytes, snap.data, off, count * scRowBytes);
3190
+ off += count * scRowBytes;
2759
3191
  }
2760
3192
  }
3193
+ for (const li of linearLayers) {
3194
+ device.queue.writeBuffer(hyRS[li][0], 0, snap.data, off, rsSz);
3195
+ off += rsSz;
3196
+ device.queue.writeBuffer(hyCS[li][0], 0, snap.data, off, csSz);
3197
+ off += csSz;
3198
+ }
3199
+ if (A.hybrid) hyPar = 0;
2761
3200
  fullHistory = [...snap.ids];
2762
3201
  cacheLen = len;
2763
3202
  }
@@ -2781,7 +3220,14 @@ async function createEngineInner(options, holder) {
2781
3220
  dispose: () => device.destroy(),
2782
3221
  device,
2783
3222
  adapter,
2784
- profileDecode: (ids, nTokens, full = null, syncN = SYNC_N) => generateImpl(ids, 0, nTokens, full, syncN),
3223
+ profileDecode: async (ids, nTokens, full = null, syncN = SYNC_N) => {
3224
+ TS_PROFILE = hasTS;
3225
+ try {
3226
+ return await generateImpl(ids, 0, nTokens, full, syncN);
3227
+ } finally {
3228
+ TS_PROFILE = false;
3229
+ }
3230
+ },
2785
3231
  debugDecode,
2786
3232
  debugSampler
2787
3233
  };