bitgpu 0.9.0 → 0.11.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
@@ -5,10 +5,19 @@ const SHADERS = {
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
6
  "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
7
  "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
+ "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",
9
+ "attention_sg_kv8": "// attention_sg with a q8 KV cache (kvCache: 'q8'). Keep in lockstep with attention_sg.wgsl: the\n// ONLY difference is Kc/Vc are packed snorm8 words dequantized at the read with their per-block\n// f32 scales (32-element blocks, q8_0-style; see copy_kv8.wgsl). All arithmetic (dot, softmax,\n// accumulation) stays f32. Each lane owns whole packed words, so q is read in matching groups\n// of 4.\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> 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]\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 W4 = p.D / 4u;\n let B32 = p.D / 32u;\n\n var acc: array<vec4<f32>, 8>; // words per lane: W4/SG <= 8 for SG >= 4\n for (var t = 0u; t < 8u; t = t + 1u) { acc[t] = 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) * B32;\n var part = 0.0;\n for (var w = lane; w < W4; w = w + SG) {\n let kw = unpack4x8snorm(Kq[rowQ + w]) * Ks[rowS + (w >> 3u)];\n let qv = vec4<f32>(q[qb + w * 4u], q[qb + w * 4u + 1u], q[qb + w * 4u + 2u], q[qb + w * 4u + 3u]);\n part = part + dot(qv, kw);\n }\n let score = subgroupAdd(part) * inv;\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let wgt = exp(score - mnew);\n l = l * corr + wgt;\n var wi = 0u;\n for (var w = lane; w < W4; w = w + SG) {\n let vw = unpack4x8snorm(Vq[rowQ + w]) * Vs[rowS + (w >> 3u)];\n acc[wi] = acc[wi] * corr + wgt * vw;\n wi = wi + 1u;\n }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n var wi = 0u;\n for (var w = lane; w < W4; w = w + SG) {\n let o = acc[wi] / l;\n out[ob + w * 4u] = o.x;\n out[ob + w * 4u + 1u] = o.y;\n out[ob + w * 4u + 2u] = o.z;\n out[ob + w * 4u + 3u] = o.w;\n wi = wi + 1u;\n }\n}\n",
10
+ "attention_sg_kv8_roll": "// attention_sg_kv8 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_kv8.wgsl: the ONLY\n// difference is the K rotation in the score loop. The cache holds UNROPED quantized keys -\n// the whole point: the packed bytes are immutable, so eviction never requantizes (llama.cpp's\n// K-shift cannot do this on a quantized cache at all). A word's rotate partner is the word\n// D/8 away (all 4 dims of a word share one half), dequantized from global with its own scale.\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] (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]\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 W4 = p.D / 4u;\n let B32 = p.D / 32u;\n let half = p.D / 2u;\n let hw = half / 4u; // words from a word to its rotate partner\n\n var acc: array<vec4<f32>, 8>; // words per lane: W4/SG <= 8 for SG >= 4\n for (var t = 0u; t < 8u; t = t + 1u) { acc[t] = 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) * B32;\n var part = 0.0;\n for (var w = lane; w < W4; w = w + SG) {\n let kw = unpack4x8snorm(Kq[rowQ + w]) * Ks[rowS + (w >> 3u)];\n let wp = select(w - hw, w + hw, w < hw);\n let kp = unpack4x8snorm(Kq[rowQ + wp]) * Ks[rowS + (wp >> 3u)];\n let rot = select(kp, -kp, w < hw);\n let cb = j * half + select(w - hw, w, w < 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 let qv = vec4<f32>(q[qb + w * 4u], q[qb + w * 4u + 1u], q[qb + w * 4u + 2u], q[qb + w * 4u + 3u]);\n part = part + dot(qv, kw * cs + rot * sn);\n }\n let score = subgroupAdd(part) * inv;\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let wgt = exp(score - mnew);\n l = l * corr + wgt;\n var wi = 0u;\n for (var w = lane; w < W4; w = w + SG) {\n let vw = unpack4x8snorm(Vq[rowQ + w]) * Vs[rowS + (w >> 3u)];\n acc[wi] = acc[wi] * corr + wgt * vw;\n wi = wi + 1u;\n }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n var wi = 0u;\n for (var w = lane; w < W4; w = w + SG) {\n let o = acc[wi] / l;\n out[ob + w * 4u] = o.x;\n out[ob + w * 4u + 1u] = o.y;\n out[ob + w * 4u + 2u] = o.z;\n out[ob + w * 4u + 3u] = o.w;\n wi = wi + 1u;\n }\n}\n",
11
+ "attention_sg_roll": "// attention_sg for the rolling-window / attention-sinks mode (overflow: 'sinks'): the cache\n// holds UNROPED keys, and each cached row j is rotated AT READ by its cache-relative position\n// (StreamingLLM-style; the cache bytes are immutable, so eviction compaction never re-rotates\n// or requantizes anything). Keep in lockstep with attention_sg.wgsl: the ONLY difference is\n// the K rotation in the score loop, written as `k*cos + rot*sin` with the same operand order\n// as rmsnorm_rope_sg so the f32 path stays bit-identical to the roped-at-write kernels until\n// the first eviction. cosT/sinT are the aux rope tables, [positions, D/2].\n// Lane math: d = lane + t*SG, partner d±D/2 is (D/2)/SG strides away IN THE SAME LANE (the\n// engine only selects this kernel when SG <= D/2).\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] (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]\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] = 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 * 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
12
  "attention_wg": "// Causal GQA attention, no-subgroup fallback: one workgroup per (query, head); threads split\n// head_dim; flash-style online softmax over the cached positions; the per-position q.k score\n// is tree-reduced via shared memory. Replaces attention_cache on this path: its single thread\n// per (query, head) walked the WHOLE context serially, so fallback decode degraded linearly\n// with conversation length and prefill attention was latency-bound. Mirrors attention_sg with\n// subgroupAdd swapped for the shared-memory reduction. Fixed workgroup of 64: the per-thread\n// accumulator covers head_dim <= 128 (enforced at manifest validation) in 2 strides.\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]\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 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\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 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) { part = part + q[qb + d] * Kc[kb + d]; }\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] consumed before the next position overwrites it\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",
9
13
  "attention_wg_kv16": "// attention_wg with an f16-STORAGE KV cache (kvCache: 'f16'). Keep in lockstep with\n// attention_wg.wgsl: the ONLY difference is Kc/Vc are array<f16>, widened to f32 at the read.\nenable f16;\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]\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 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\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 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) { part = part + q[qb + d] * f32(Kc[kb + d]); }\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;\n workgroupBarrier();\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 * f32(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",
14
+ "attention_wg_kv16_roll": "// attention_wg_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_wg_kv16.wgsl: the ONLY\n// differences are the shared-memory K stage (kk, widened to f32) - the rotate partner d±D/2\n// may live in another thread's stride - and the rotation in the score loop, written as\n// `k*cos + rot*sin` with the same operand order as rmsnorm_rope_sg.\nenable f16;\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]\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] = f32(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;\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 * f32(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",
15
+ "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
+ "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
+ "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",
10
18
  "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",
11
19
  "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",
12
21
  "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",
13
22
  "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",
14
23
  "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",
@@ -30,6 +39,7 @@ const SHADERS = {
30
39
  "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",
31
40
  "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",
32
41
  "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
+ "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",
33
43
  "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",
34
44
  "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",
35
45
  "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",
@@ -312,7 +322,11 @@ async function createEngineInner(options, holder) {
312
322
  const maxSeqLen = Math.max(1, opts.maxSeqLen ?? DEFAULT_MAX_SEQ);
313
323
  const useSG = hasSG && sgMin === sgMax && (sgMax === 16 || sgMax === 32 || sgMax === 64) && A.head_dim % sgMax === 0 && !forceNoSG;
314
324
  const kv16 = opts.kvCache === "f16" && adapter.features.has("shader-f16");
315
- const KVB = kv16 ? 2 : 4;
325
+ const kv8 = opts.kvCache === "q8";
326
+ const roll = opts.overflow === "sinks";
327
+ const SINKS = roll ? Math.max(1, Math.floor(opts.sinkTokens ?? 4)) : 0;
328
+ if (roll && maxSeqLen < SINKS + 64) throw new Error(`bitgpu: overflow 'sinks' needs maxSeqLen >= sinkTokens + 64 (got ${maxSeqLen} with ${SINKS} sinks)`);
329
+ const KVB = kv16 ? 2 : kv8 ? 1 : 4;
316
330
  const features = [];
317
331
  if (useSG) features.push("subgroups");
318
332
  if (kv16) features.push("shader-f16");
@@ -352,6 +366,7 @@ async function createEngineInner(options, holder) {
352
366
  T.embed_tokens.zp,
353
367
  manifest.luts.tgt4
354
368
  ]) track(r.len);
369
+ if (kv8 && A.head_dim % 32 !== 0) throw new Error(`bitgpu: kvCache 'q8' needs head_dim divisible by 32 (got ${A.head_dim}); use 'f16' or 'f32' for this model`);
355
370
  const kvLayerBytes = maxSeqLen * A.kv_heads * A.head_dim * KVB;
356
371
  needBind = Math.max(needBind, kvLayerBytes, PREFILL_SEG * Math.max(A.heads * A.head_dim, A.intermediate) * 4, 32 * A.vocab * 4);
357
372
  const requiredLimits = {};
@@ -442,7 +457,19 @@ async function createEngineInner(options, holder) {
442
457
  if (useSG) for (const n of ["attention_sg_kv16", "rmsnorm_rope_sg_kv16"]) specs.push([n, { SG: sgMax }]);
443
458
  else specs.push(["attention_wg_kv16"]);
444
459
  }
445
- const ATT = kv16 ? useSG ? "attention_sg_kv16" : "attention_wg_kv16" : useSG ? "attention_sg" : "attention_wg";
460
+ if (kv8) {
461
+ specs.push(["copy_kv8"]);
462
+ if (useSG) for (const n of ["attention_sg_kv8", "rmsnorm_rope_sg_kv8"]) specs.push([n, { SG: sgMax }]);
463
+ else specs.push(["attention_wg_kv8"]);
464
+ }
465
+ const rollSG = useSG && sgMax <= A.head_dim / 2;
466
+ if (roll) {
467
+ const rollAtt = kv16 ? "attention_sg_kv16_roll" : kv8 ? "attention_sg_kv8_roll" : "attention_sg_roll";
468
+ const rollAttWg = kv16 ? "attention_wg_kv16_roll" : kv8 ? "attention_wg_kv8_roll" : "attention_wg_roll";
469
+ if (rollSG) specs.push([rollAtt, { SG: sgMax }]);
470
+ else specs.push([rollAttWg]);
471
+ }
472
+ 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";
446
473
  const ROPE_K = kv16 ? "rmsnorm_rope_sg_kv16" : "rmsnorm_rope_sg";
447
474
  const COPY_KV = kv16 ? "copy_kv16" : "copy";
448
475
  await Promise.all(specs.map(([n, c]) => mkPipe(n, c)));
@@ -510,8 +537,10 @@ async function createEngineInner(options, holder) {
510
537
  usage: S_
511
538
  });
512
539
  let fullHistory = [];
540
+ let cacheLen = 0;
513
541
  const resetCache = () => {
514
542
  fullHistory = [];
543
+ cacheLen = 0;
515
544
  };
516
545
  if (manifest.luts.tgt2.src !== "aux") throw new Error("bitgpu: luts.tgt2 must live in the aux file (the streaming loader needs it before the weights arrive)");
517
546
  const tgt2 = readU8(manifest.luts.tgt2);
@@ -789,6 +818,8 @@ async function createEngineInner(options, holder) {
789
818
  const KV = A.kv_heads, Dh = A.head_dim, Hd = A.hidden, H = A.heads, F = A.intermediate;
790
819
  let kvCapacity = Math.min(maxSeqLen, 512);
791
820
  const Kc = [], Vc = [];
821
+ const Ksc = [], Vsc = [];
822
+ const kvScaleBytes = (cap) => cap * KV * (Dh / 32) * 4;
792
823
  for (let li = 0; li < A.layers; li++) {
793
824
  Kc.push(device.createBuffer({
794
825
  size: kvCapacity * KV * Dh * KVB,
@@ -798,6 +829,40 @@ async function createEngineInner(options, holder) {
798
829
  size: kvCapacity * KV * Dh * KVB,
799
830
  usage: S_ | CS | CD
800
831
  }));
832
+ if (kv8) {
833
+ Ksc.push(device.createBuffer({
834
+ size: kvScaleBytes(kvCapacity),
835
+ usage: S_ | CS | CD
836
+ }));
837
+ Vsc.push(device.createBuffer({
838
+ size: kvScaleBytes(kvCapacity),
839
+ usage: S_ | CS | CD
840
+ }));
841
+ }
842
+ }
843
+ let rollCosT = null, rollSinT = null, rollOnes = null, rollZeros = null;
844
+ if (roll) {
845
+ const R2 = Dh / 2;
846
+ rollCosT = device.createBuffer({
847
+ size: maxSeqLen * R2 * 4,
848
+ usage: S_ | CD
849
+ });
850
+ rollSinT = device.createBuffer({
851
+ size: maxSeqLen * R2 * 4,
852
+ usage: S_ | CD
853
+ });
854
+ device.queue.writeBuffer(rollCosT, 0, cosCache.buffer, cosCache.byteOffset, maxSeqLen * R2 * 4);
855
+ device.queue.writeBuffer(rollSinT, 0, sinCache.buffer, sinCache.byteOffset, maxSeqLen * R2 * 4);
856
+ rollOnes = device.createBuffer({
857
+ size: Dh * 4,
858
+ usage: S_ | CD
859
+ });
860
+ rollZeros = device.createBuffer({
861
+ size: Dh * 4,
862
+ usage: S_ | CD
863
+ });
864
+ device.queue.writeBuffer(rollOnes, 0, new Float32Array(Dh).fill(1));
865
+ device.queue.writeBuffer(rollZeros, 0, new Float32Array(Dh));
801
866
  }
802
867
  const loadOom = await device.popErrorScope();
803
868
  const loadVal = await device.popErrorScope();
@@ -807,8 +872,10 @@ async function createEngineInner(options, holder) {
807
872
  if (needed <= kvCapacity) return;
808
873
  const newCap = Math.min(maxSeqLen, Math.max(needed, kvCapacity * 2));
809
874
  const copyBytes = kvCapacity * KV * Dh * KVB;
875
+ const copyScales = kvScaleBytes(kvCapacity);
810
876
  device.pushErrorScope("out-of-memory");
811
877
  const enc = device.createCommandEncoder();
878
+ const per = kv8 ? 4 : 2;
812
879
  const olds = [];
813
880
  for (let li = 0; li < A.layers; li++) {
814
881
  const nk = device.createBuffer({
@@ -824,6 +891,21 @@ async function createEngineInner(options, holder) {
824
891
  olds.push(Kc[li], Vc[li]);
825
892
  Kc[li] = nk;
826
893
  Vc[li] = nv;
894
+ if (kv8) {
895
+ const nks = device.createBuffer({
896
+ size: kvScaleBytes(newCap),
897
+ usage: S_ | CS | CD
898
+ });
899
+ const nvs = device.createBuffer({
900
+ size: kvScaleBytes(newCap),
901
+ usage: S_ | CS | CD
902
+ });
903
+ enc.copyBufferToBuffer(Ksc[li], 0, nks, 0, copyScales);
904
+ enc.copyBufferToBuffer(Vsc[li], 0, nvs, 0, copyScales);
905
+ olds.push(Ksc[li], Vsc[li]);
906
+ Ksc[li] = nks;
907
+ Vsc[li] = nvs;
908
+ }
827
909
  }
828
910
  device.queue.submit([enc.finish()]);
829
911
  await device.queue.onSubmittedWorkDone();
@@ -832,8 +914,14 @@ async function createEngineInner(options, holder) {
832
914
  for (let li = 0; li < A.layers; li++) {
833
915
  Kc[li].destroy();
834
916
  Vc[li].destroy();
835
- Kc[li] = olds[2 * li];
836
- Vc[li] = olds[2 * li + 1];
917
+ Kc[li] = olds[per * li];
918
+ Vc[li] = olds[per * li + 1];
919
+ if (kv8) {
920
+ Ksc[li].destroy();
921
+ Vsc[li].destroy();
922
+ Ksc[li] = olds[per * li + 2];
923
+ Vsc[li] = olds[per * li + 3];
924
+ }
837
925
  }
838
926
  poolInvalidate();
839
927
  throw new GpuOutOfMemoryError(`KV cache growth to ${newCap} positions failed: ${oom.message}`);
@@ -842,6 +930,35 @@ async function createEngineInner(options, holder) {
842
930
  kvCapacity = newCap;
843
931
  poolInvalidate();
844
932
  }
933
+ let evictScratch = null;
934
+ function evict(fill, need) {
935
+ const recent = fill - SINKS;
936
+ const batch = Math.min(recent, Math.max(need, Math.ceil((maxSeqLen - SINKS) / 4)));
937
+ const keep = recent - batch;
938
+ if (keep <= 0) return SINKS;
939
+ const rowK = KV * Dh * KVB;
940
+ const rowS = kv8 ? KV * (Dh / 32) * 4 : 0;
941
+ if (!evictScratch || evictScratch.size < keep * rowK) {
942
+ evictScratch?.destroy();
943
+ evictScratch = device.createBuffer({
944
+ size: keep * rowK,
945
+ usage: CS | CD
946
+ });
947
+ }
948
+ const enc = device.createCommandEncoder();
949
+ const groups = [];
950
+ for (let li = 0; li < A.layers; li++) {
951
+ groups.push([Kc[li], rowK], [Vc[li], rowK]);
952
+ if (kv8) groups.push([Ksc[li], rowS], [Vsc[li], rowS]);
953
+ }
954
+ for (const [buf, row] of groups) {
955
+ enc.copyBufferToBuffer(buf, (SINKS + batch) * row, evictScratch, 0, keep * row);
956
+ enc.copyBufferToBuffer(evictScratch, 0, buf, SINKS * row, keep * row);
957
+ }
958
+ device.queue.submit([enc.finish()]);
959
+ return SINKS + keep;
960
+ }
961
+ const evictFor = (fill, n) => roll && fill + n > maxSeqLen ? evict(fill, fill + n - maxSeqLen) : fill;
845
962
  async function readback(buf, n) {
846
963
  const rb = device.createBuffer({
847
964
  size: n * 4,
@@ -1112,6 +1229,38 @@ async function createEngineInner(options, holder) {
1112
1229
  resid
1113
1230
  ], [out], S * w.N);
1114
1231
  }
1232
+ function appendKV(pass, src, which, li, rows, dstRow0) {
1233
+ const data = which === 0 ? Kc[li] : Vc[li];
1234
+ if (kv8) {
1235
+ setup(pass, "copy_kv8", [
1236
+ ["u", rows],
1237
+ ["u", Dh],
1238
+ ["u", dstRow0],
1239
+ ["u", 0]
1240
+ ], [src], [data, which === 0 ? Ksc[li] : Vsc[li]]);
1241
+ pass.dispatchWorkgroups(isFull("copy_kv8") ? rows : 1);
1242
+ } else run(pass, COPY_KV, [
1243
+ ["u", rows * Dh],
1244
+ ["u", dstRow0 * Dh],
1245
+ ["u", 0],
1246
+ ["u", 0]
1247
+ ], [src], data, rows * Dh);
1248
+ }
1249
+ const attIns = (qr, li) => {
1250
+ const ins = kv8 ? [
1251
+ qr,
1252
+ Kc[li],
1253
+ Vc[li],
1254
+ Ksc[li],
1255
+ Vsc[li]
1256
+ ] : [
1257
+ qr,
1258
+ Kc[li],
1259
+ Vc[li]
1260
+ ];
1261
+ if (roll) ins.push(rollCosT, rollSinT);
1262
+ return ins;
1263
+ };
1115
1264
  function layer(pass, li, h, S, posBase, cos, sin) {
1116
1265
  const Ltot = posBase + S;
1117
1266
  const n1 = actBuf(S * Hd);
@@ -1136,12 +1285,7 @@ async function createEngineInner(options, holder) {
1136
1285
  k,
1137
1286
  v
1138
1287
  ], gx, Math.ceil(Ntot / gx));
1139
- run(pass, COPY_KV, [
1140
- ["u", KV * Dh],
1141
- ["u", posBase * KV * Dh],
1142
- ["u", 0],
1143
- ["u", 0]
1144
- ], [v], Vc[li], KV * Dh);
1288
+ appendKV(pass, v, 1, li, KV, posBase * KV);
1145
1289
  const qr = actBuf(H * Dh);
1146
1290
  runN(pass, "rmsnorm_rope_sg", [
1147
1291
  ["u", H],
@@ -1156,7 +1300,23 @@ async function createEngineInner(options, holder) {
1156
1300
  cos,
1157
1301
  sin
1158
1302
  ], qr, H);
1159
- runN(pass, ROPE_K, [
1303
+ const kcos = roll ? rollOnes : cos, ksin = roll ? rollZeros : sin;
1304
+ if (kv8) {
1305
+ setup(pass, "rmsnorm_rope_sg_kv8", [
1306
+ ["u", KV],
1307
+ ["u", Dh],
1308
+ ["f", A.rms_eps],
1309
+ ["u", posBase * KV],
1310
+ ["u", 0],
1311
+ ["u", 0]
1312
+ ], [
1313
+ k,
1314
+ W[`layers.${li}.attn.k_norm`].buf,
1315
+ kcos,
1316
+ ksin
1317
+ ], [Kc[li], Ksc[li]]);
1318
+ pass.dispatchWorkgroups(isFull("rmsnorm_rope_sg_kv8") ? KV : 1);
1319
+ } else runN(pass, ROPE_K, [
1160
1320
  ["u", KV],
1161
1321
  ["u", Dh],
1162
1322
  ["f", A.rms_eps],
@@ -1166,8 +1326,8 @@ async function createEngineInner(options, holder) {
1166
1326
  ], [
1167
1327
  k,
1168
1328
  W[`layers.${li}.attn.k_norm`].buf,
1169
- cos,
1170
- sin
1329
+ kcos,
1330
+ ksin
1171
1331
  ], Kc[li], KV);
1172
1332
  cap(li, "qr", qr);
1173
1333
  const att = actBuf(H * Dh);
@@ -1178,11 +1338,7 @@ async function createEngineInner(options, holder) {
1178
1338
  ["u", Dh],
1179
1339
  ["u", posBase],
1180
1340
  ["u", Ltot]
1181
- ], [
1182
- qr,
1183
- Kc[li],
1184
- Vc[li]
1185
- ], att, H);
1341
+ ], attIns(qr, li), att, H);
1186
1342
  cap(li, "att", att);
1187
1343
  const o = W[`layers.${li}.attn.o_proj`], h2 = actBuf(Hd);
1188
1344
  residMM(pass, o, att, h, 1, h2);
@@ -1226,7 +1382,7 @@ async function createEngineInner(options, holder) {
1226
1382
  cos,
1227
1383
  sin
1228
1384
  ], qr, S * H * Dh);
1229
- run(pass, "rope", [
1385
+ if (!roll) run(pass, "rope", [
1230
1386
  ["u", S],
1231
1387
  ["u", KV],
1232
1388
  ["u", Dh],
@@ -1236,18 +1392,8 @@ async function createEngineInner(options, holder) {
1236
1392
  cos,
1237
1393
  sin
1238
1394
  ], kr, S * KV * Dh);
1239
- run(pass, COPY_KV, [
1240
- ["u", S * KV * Dh],
1241
- ["u", posBase * KV * Dh],
1242
- ["u", 0],
1243
- ["u", 0]
1244
- ], [kr], Kc[li], S * KV * Dh);
1245
- run(pass, COPY_KV, [
1246
- ["u", S * KV * Dh],
1247
- ["u", posBase * KV * Dh],
1248
- ["u", 0],
1249
- ["u", 0]
1250
- ], [v], Vc[li], S * KV * Dh);
1395
+ appendKV(pass, roll ? kn : kr, 0, li, S * KV, posBase * KV);
1396
+ appendKV(pass, v, 1, li, S * KV, posBase * KV);
1251
1397
  cap(li, "qr", qr);
1252
1398
  const att = actBuf(S * H * Dh);
1253
1399
  runN(pass, ATT, [
@@ -1257,11 +1403,7 @@ async function createEngineInner(options, holder) {
1257
1403
  ["u", Dh],
1258
1404
  ["u", posBase],
1259
1405
  ["u", Ltot]
1260
- ], [
1261
- qr,
1262
- Kc[li],
1263
- Vc[li]
1264
- ], att, S * H);
1406
+ ], attIns(qr, li), att, S * H);
1265
1407
  cap(li, "att", att);
1266
1408
  const o = W[`layers.${li}.attn.o_proj`], h2 = actBuf(S * Hd);
1267
1409
  residMM(pass, o, att, h, S, h2);
@@ -1363,6 +1505,7 @@ async function createEngineInner(options, holder) {
1363
1505
  if (S === 0) throw new Error("forward: no tokens to process");
1364
1506
  if (S > maxSeqLen) throw new Error(`forward: sequence length ${S} exceeds maxSeqLen ${maxSeqLen}`);
1365
1507
  fullHistory = [];
1508
+ cacheLen = 0;
1366
1509
  await ensureKvCapacity(S);
1367
1510
  const vocab = W.lm_head.N;
1368
1511
  const embed = new Float32Array(S * Hd), layer0 = new Float32Array(S * Hd), finalnorm = new Float32Array(S * Hd), logits = new Float32Array(S * vocab);
@@ -1408,6 +1551,7 @@ async function createEngineInner(options, holder) {
1408
1551
  for (let off = 0; off < ids.length; off += PREFILL_SEG) {
1409
1552
  if (off > 0 && signal?.aborted) {
1410
1553
  fullHistory = [];
1554
+ cacheLen = 0;
1411
1555
  return null;
1412
1556
  }
1413
1557
  const seg = ids.slice(off, off + PREFILL_SEG);
@@ -1485,14 +1629,16 @@ async function createEngineInner(options, holder) {
1485
1629
  ctl?.onToken?.(firstTok);
1486
1630
  }
1487
1631
  poolInvalidate();
1632
+ let slot = posBase + ids.length;
1488
1633
  while (total < nTokens && !stopped) {
1489
1634
  if (ctl?.signal?.aborted) break;
1490
1635
  const batch = Math.min(syncN, nTokens - total);
1636
+ slot = evictFor(slot, batch);
1491
1637
  poolUse("decode");
1492
1638
  let t = performance.now();
1493
1639
  const enc = device.createCommandEncoder();
1494
1640
  for (let j = 0; j < batch; j++) {
1495
- const idxOut = total + j, pos = posBase + ids.length + idxOut - 1;
1641
+ const idxOut = total + j, pos = slot + j;
1496
1642
  let pass = enc.beginComputePass();
1497
1643
  runN(pass, "embed_gather", [
1498
1644
  ["u", Hd],
@@ -1528,17 +1674,21 @@ async function createEngineInner(options, holder) {
1528
1674
  t = performance.now();
1529
1675
  const toks = await readbackU32(tokBuf, total + batch);
1530
1676
  rbMs += performance.now() - t;
1677
+ let fed = batch;
1531
1678
  for (let j = 0; j < batch; j++) {
1532
1679
  const tk = toks[total + j];
1533
1680
  if (stopSet?.has(tk)) {
1534
1681
  stopped = true;
1682
+ fed = j;
1535
1683
  break;
1536
1684
  }
1537
1685
  gen.push(tk);
1538
1686
  ctl?.onToken?.(tk);
1539
1687
  }
1540
1688
  total += batch;
1689
+ slot += fed;
1541
1690
  }
1691
+ cacheLen = slot;
1542
1692
  const decodeMs = performance.now() - t1, nd = Math.max(1, gen.length - 1);
1543
1693
  return {
1544
1694
  prefillMs,
@@ -1766,10 +1916,12 @@ async function createEngineInner(options, holder) {
1766
1916
  const t1 = performance.now();
1767
1917
  let total = 1;
1768
1918
  poolInvalidate();
1919
+ let slot = posBase + ids.length;
1769
1920
  while (total < nTokens && !stopped) {
1770
1921
  if (signal?.aborted) break;
1771
1922
  poolUse("decode");
1772
- const idxOut = total, pos = posBase + ids.length + idxOut - 1;
1923
+ slot = evictFor(slot, 1);
1924
+ const idxOut = total, pos = slot;
1773
1925
  let t = performance.now();
1774
1926
  const { affLen, banLen } = writeAffBan(history);
1775
1927
  const enc = device.createCommandEncoder();
@@ -1813,7 +1965,9 @@ async function createEngineInner(options, holder) {
1813
1965
  recordLp(ci, cv, lse);
1814
1966
  onToken?.(tk);
1815
1967
  device.queue.writeBuffer(tokBuf, idxOut * 4, new Uint32Array([tk]));
1968
+ slot += 1;
1816
1969
  }
1970
+ cacheLen = slot;
1817
1971
  const decodeMs = performance.now() - t1;
1818
1972
  const nd = Math.max(1, gen.length - 1);
1819
1973
  return {
@@ -1995,6 +2149,7 @@ async function createEngineInner(options, holder) {
1995
2149
  const t1 = performance.now();
1996
2150
  while (total < nTokens && !stopped) {
1997
2151
  if (signal?.aborted) break;
2152
+ pos = evictFor(pos, maxDraft + 1);
1998
2153
  const kMax = Math.min(maxDraft, nTokens - total - 1, maxSeqLen - 1 - pos);
1999
2154
  const drafts = kMax > 0 ? draftNgram(history, ngramSize, kMax) : [];
2000
2155
  const S = drafts.length + 1;
@@ -2098,6 +2253,7 @@ async function createEngineInner(options, holder) {
2098
2253
  pos += emitted.length;
2099
2254
  tLast = emitted[emitted.length - 1];
2100
2255
  }
2256
+ cacheLen = pos;
2101
2257
  const decodeMs = performance.now() - t1;
2102
2258
  const nd = Math.max(1, gen.length - 1);
2103
2259
  return {
@@ -2159,7 +2315,7 @@ async function createEngineInner(options, holder) {
2159
2315
  const ck = {};
2160
2316
  for (const [name, b] of Object.entries(DBG0)) ck[name] = await readback(b, b.size / 4);
2161
2317
  const off = pos * KV * Dh;
2162
- if (!kv16) {
2318
+ if (!kv16 && !kv8) {
2163
2319
  ck.kc = (await readback(Kc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
2164
2320
  ck.vc = (await readback(Vc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
2165
2321
  }
@@ -2239,7 +2395,8 @@ async function createEngineInner(options, holder) {
2239
2395
  const capabilities = {
2240
2396
  useSubgroups: useSG,
2241
2397
  subgroupSize: sgMax,
2242
- kvCache: kv16 ? "f16" : "f32",
2398
+ kvCache: kv16 ? "f16" : kv8 ? "q8" : "f32",
2399
+ overflow: roll ? "sinks" : "error",
2243
2400
  maxSeqLen,
2244
2401
  adapter: {
2245
2402
  vendor: info.vendor,
@@ -2267,12 +2424,18 @@ async function createEngineInner(options, holder) {
2267
2424
  readbackMs: 0
2268
2425
  }
2269
2426
  };
2270
- const posBase = reuse ? fullHistory.length - 1 : 0;
2427
+ let posBase = reuse ? roll ? cacheLen : fullHistory.length - 1 : 0;
2271
2428
  const prefillTokens = reuse ? [fullHistory[fullHistory.length - 1], ...promptTokenIds] : promptTokenIds;
2272
2429
  if (prefillTokens.length === 0) throw new Error("generate: no tokens to process");
2430
+ if (roll && posBase + prefillTokens.length + 1 > maxSeqLen) {
2431
+ if (SINKS + prefillTokens.length + 1 > maxSeqLen) throw new Error(`generate: prompt length ${prefillTokens.length} exceeds the rolling window (maxSeqLen ${maxSeqLen} minus ${SINKS} sinks); trim the prompt`);
2432
+ await ensureKvCapacity(Math.min(maxSeqLen, posBase + prefillTokens.length));
2433
+ posBase = evict(posBase, posBase + prefillTokens.length + 1 - maxSeqLen);
2434
+ cacheLen = posBase;
2435
+ }
2273
2436
  const room = maxSeqLen - posBase - prefillTokens.length;
2274
2437
  if (room < 1) throw new Error(`generate: prompt length ${posBase + prefillTokens.length} exceeds maxSeqLen ${maxSeqLen}; trim history or raise maxSeqLen`);
2275
- const maxTokens = Math.min(genOpts.maxTokens ?? 256, room);
2438
+ const maxTokens = roll ? genOpts.maxTokens ?? 256 : Math.min(genOpts.maxTokens ?? 256, room);
2276
2439
  if (reuse) fullHistory.push(...promptTokenIds);
2277
2440
  else fullHistory = [...promptTokenIds];
2278
2441
  if (maxTokens < 1) {
@@ -2282,6 +2445,7 @@ async function createEngineInner(options, holder) {
2282
2445
  const t0 = performance.now();
2283
2446
  await runPrefill(prefillTokens, posBase, genOpts.signal);
2284
2447
  await device.queue.onSubmittedWorkDone();
2448
+ cacheLen = posBase + prefillTokens.length - 1;
2285
2449
  return {
2286
2450
  tokens: [],
2287
2451
  prefillMs: performance.now() - t0,
@@ -2377,12 +2541,91 @@ async function createEngineInner(options, holder) {
2377
2541
  await runPrefill(ids, 0);
2378
2542
  await device.queue.onSubmittedWorkDone();
2379
2543
  fullHistory = [...ids];
2544
+ cacheLen = ids.length - 1;
2380
2545
  return { prefillMs: performance.now() - t0 };
2381
2546
  } finally {
2382
2547
  flushTransients();
2383
2548
  transients = null;
2384
2549
  }
2385
2550
  }
2551
+ const kvRowBytes = KV * Dh * KVB;
2552
+ const scRowBytes = kv8 ? KV * (Dh / 32) * 4 : 0;
2553
+ const snapshotBytes = (len) => A.layers * 2 * len * (kvRowBytes + scRowBytes);
2554
+ async function saveCache() {
2555
+ if (fullHistory.length === 0) return null;
2556
+ const len = roll ? cacheLen : fullHistory.length - 1;
2557
+ const data = new ArrayBuffer(snapshotBytes(len));
2558
+ if (len > 0) {
2559
+ const rb = device.createBuffer({
2560
+ size: snapshotBytes(len),
2561
+ usage: GPUBufferUsage.MAP_READ | CD
2562
+ });
2563
+ const enc = device.createCommandEncoder();
2564
+ let off = 0;
2565
+ for (let li = 0; li < A.layers; li++) {
2566
+ enc.copyBufferToBuffer(Kc[li], 0, rb, off, len * kvRowBytes);
2567
+ off += len * kvRowBytes;
2568
+ enc.copyBufferToBuffer(Vc[li], 0, rb, off, len * kvRowBytes);
2569
+ off += len * kvRowBytes;
2570
+ if (kv8) {
2571
+ enc.copyBufferToBuffer(Ksc[li], 0, rb, off, len * scRowBytes);
2572
+ off += len * scRowBytes;
2573
+ enc.copyBufferToBuffer(Vsc[li], 0, rb, off, len * scRowBytes);
2574
+ off += len * scRowBytes;
2575
+ }
2576
+ }
2577
+ device.queue.submit([enc.finish()]);
2578
+ await rb.mapAsync(GPUMapMode.READ);
2579
+ new Uint8Array(data).set(new Uint8Array(rb.getMappedRange()));
2580
+ rb.unmap();
2581
+ rb.destroy();
2582
+ }
2583
+ return {
2584
+ version: roll ? 2 : 1,
2585
+ kvCache: capabilities.kvCache,
2586
+ model: {
2587
+ layers: A.layers,
2588
+ kvHeads: KV,
2589
+ headDim: Dh,
2590
+ hidden: Hd,
2591
+ vocab: A.vocab
2592
+ },
2593
+ ids: [...fullHistory],
2594
+ ...roll ? { roll: {
2595
+ sinkTokens: SINKS,
2596
+ cacheLen
2597
+ } } : {},
2598
+ data
2599
+ };
2600
+ }
2601
+ async function restoreCache(snap) {
2602
+ if (!snap || snap.version !== 1 && snap.version !== 2) throw new Error(`restoreCache: unsupported snapshot version ${snap?.version}`);
2603
+ if (snap.version === 2 !== roll) throw new Error(snap.version === 2 ? "restoreCache: snapshot was saved under overflow 'sinks' (unroped keys); this engine runs overflow 'error'" : "restoreCache: snapshot was saved under overflow 'error' (roped keys); this engine runs overflow 'sinks'");
2604
+ if (snap.version === 2 && snap.roll?.sinkTokens !== SINKS) throw new Error(`restoreCache: snapshot uses ${snap.roll?.sinkTokens} sink tokens but this engine uses ${SINKS}`);
2605
+ if (snap.kvCache !== capabilities.kvCache) throw new Error(`restoreCache: snapshot was saved under kvCache '${snap.kvCache}' but this engine runs '${capabilities.kvCache}' - snapshots do not convert across modes`);
2606
+ const m = snap.model;
2607
+ 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)");
2608
+ if (!Array.isArray(snap.ids) || snap.ids.length === 0) throw new Error("restoreCache: snapshot holds no tokens");
2609
+ const len = snap.version === 2 ? snap.roll.cacheLen : snap.ids.length - 1;
2610
+ if (len + 1 > maxSeqLen) throw new Error(`restoreCache: snapshot needs ${len + 1} cache slots but maxSeqLen is ${maxSeqLen}`);
2611
+ if (snap.data.byteLength !== snapshotBytes(len)) throw new Error(`restoreCache: snapshot data is ${snap.data.byteLength} bytes, expected ${snapshotBytes(len)}`);
2612
+ await ensureKvCapacity(len);
2613
+ let off = 0;
2614
+ for (let li = 0; li < A.layers; li++) {
2615
+ device.queue.writeBuffer(Kc[li], 0, snap.data, off, len * kvRowBytes);
2616
+ off += len * kvRowBytes;
2617
+ device.queue.writeBuffer(Vc[li], 0, snap.data, off, len * kvRowBytes);
2618
+ off += len * kvRowBytes;
2619
+ if (kv8) {
2620
+ device.queue.writeBuffer(Ksc[li], 0, snap.data, off, len * scRowBytes);
2621
+ off += len * scRowBytes;
2622
+ device.queue.writeBuffer(Vsc[li], 0, snap.data, off, len * scRowBytes);
2623
+ off += len * scRowBytes;
2624
+ }
2625
+ }
2626
+ fullHistory = [...snap.ids];
2627
+ cacheLen = len;
2628
+ }
2386
2629
  let opChain = Promise.resolve();
2387
2630
  const serialize = (fn) => {
2388
2631
  return (...args) => {
@@ -2395,6 +2638,8 @@ async function createEngineInner(options, holder) {
2395
2638
  generate: serialize(generate),
2396
2639
  prefill: serialize(prefill),
2397
2640
  forward: serialize(forward),
2641
+ saveCache: serialize(saveCache),
2642
+ restoreCache: serialize(restoreCache),
2398
2643
  resetCache,
2399
2644
  capabilities,
2400
2645
  lost,