bitgpu 0.9.0 → 0.10.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.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as ForwardResult, c as LoadProgress, i as EngineOptions, l as TokenLogprobs, n as Engine, o as GenerateOptions, r as EngineCapabilities, s as GenerateResult, t as DeviceLostInfo } from "./types-C5f2IKgm.js";
1
+ import { a as ForwardResult, c as KvSnapshot, i as EngineOptions, l as LoadProgress, n as Engine, o as GenerateOptions, r as EngineCapabilities, s as GenerateResult, t as DeviceLostInfo, u as TokenLogprobs } from "./types-CcgsXirU.js";
2
2
 
3
3
  //#region src/engine.d.ts
4
4
  /** Load a 1-bit model and return an {@link Engine}. Pass a model URL string for defaults. */
@@ -20,5 +20,5 @@ declare class GpuOutOfMemoryError extends Error {
20
20
  constructor(message: string);
21
21
  }
22
22
  //#endregion
23
- export { type DeviceLostInfo, type Engine, type EngineCapabilities, type EngineOptions, type ForwardResult, type GenerateOptions, type GenerateResult, GpuOutOfMemoryError, type LoadProgress, type TokenLogprobs, WebGPUUnavailableError, createEngine };
23
+ export { type DeviceLostInfo, type Engine, type EngineCapabilities, type EngineOptions, type ForwardResult, type GenerateOptions, type GenerateResult, GpuOutOfMemoryError, type KvSnapshot, type LoadProgress, type TokenLogprobs, WebGPUUnavailableError, createEngine };
24
24
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -5,10 +5,13 @@ 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_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",
8
9
  "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
10
  "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",
11
+ "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",
10
12
  "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
13
  "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",
14
+ "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
15
  "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
16
  "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
17
  "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 +33,7 @@ const SHADERS = {
30
33
  "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
34
  "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
35
  "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",
36
+ "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
37
  "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
38
  "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
39
  "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 +316,8 @@ async function createEngineInner(options, holder) {
312
316
  const maxSeqLen = Math.max(1, opts.maxSeqLen ?? DEFAULT_MAX_SEQ);
313
317
  const useSG = hasSG && sgMin === sgMax && (sgMax === 16 || sgMax === 32 || sgMax === 64) && A.head_dim % sgMax === 0 && !forceNoSG;
314
318
  const kv16 = opts.kvCache === "f16" && adapter.features.has("shader-f16");
315
- const KVB = kv16 ? 2 : 4;
319
+ const kv8 = opts.kvCache === "q8";
320
+ const KVB = kv16 ? 2 : kv8 ? 1 : 4;
316
321
  const features = [];
317
322
  if (useSG) features.push("subgroups");
318
323
  if (kv16) features.push("shader-f16");
@@ -352,6 +357,7 @@ async function createEngineInner(options, holder) {
352
357
  T.embed_tokens.zp,
353
358
  manifest.luts.tgt4
354
359
  ]) track(r.len);
360
+ 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
361
  const kvLayerBytes = maxSeqLen * A.kv_heads * A.head_dim * KVB;
356
362
  needBind = Math.max(needBind, kvLayerBytes, PREFILL_SEG * Math.max(A.heads * A.head_dim, A.intermediate) * 4, 32 * A.vocab * 4);
357
363
  const requiredLimits = {};
@@ -442,7 +448,12 @@ async function createEngineInner(options, holder) {
442
448
  if (useSG) for (const n of ["attention_sg_kv16", "rmsnorm_rope_sg_kv16"]) specs.push([n, { SG: sgMax }]);
443
449
  else specs.push(["attention_wg_kv16"]);
444
450
  }
445
- const ATT = kv16 ? useSG ? "attention_sg_kv16" : "attention_wg_kv16" : useSG ? "attention_sg" : "attention_wg";
451
+ if (kv8) {
452
+ specs.push(["copy_kv8"]);
453
+ if (useSG) for (const n of ["attention_sg_kv8", "rmsnorm_rope_sg_kv8"]) specs.push([n, { SG: sgMax }]);
454
+ else specs.push(["attention_wg_kv8"]);
455
+ }
456
+ const ATT = kv16 ? useSG ? "attention_sg_kv16" : "attention_wg_kv16" : kv8 ? useSG ? "attention_sg_kv8" : "attention_wg_kv8" : useSG ? "attention_sg" : "attention_wg";
446
457
  const ROPE_K = kv16 ? "rmsnorm_rope_sg_kv16" : "rmsnorm_rope_sg";
447
458
  const COPY_KV = kv16 ? "copy_kv16" : "copy";
448
459
  await Promise.all(specs.map(([n, c]) => mkPipe(n, c)));
@@ -789,6 +800,8 @@ async function createEngineInner(options, holder) {
789
800
  const KV = A.kv_heads, Dh = A.head_dim, Hd = A.hidden, H = A.heads, F = A.intermediate;
790
801
  let kvCapacity = Math.min(maxSeqLen, 512);
791
802
  const Kc = [], Vc = [];
803
+ const Ksc = [], Vsc = [];
804
+ const kvScaleBytes = (cap) => cap * KV * (Dh / 32) * 4;
792
805
  for (let li = 0; li < A.layers; li++) {
793
806
  Kc.push(device.createBuffer({
794
807
  size: kvCapacity * KV * Dh * KVB,
@@ -798,6 +811,16 @@ async function createEngineInner(options, holder) {
798
811
  size: kvCapacity * KV * Dh * KVB,
799
812
  usage: S_ | CS | CD
800
813
  }));
814
+ if (kv8) {
815
+ Ksc.push(device.createBuffer({
816
+ size: kvScaleBytes(kvCapacity),
817
+ usage: S_ | CS | CD
818
+ }));
819
+ Vsc.push(device.createBuffer({
820
+ size: kvScaleBytes(kvCapacity),
821
+ usage: S_ | CS | CD
822
+ }));
823
+ }
801
824
  }
802
825
  const loadOom = await device.popErrorScope();
803
826
  const loadVal = await device.popErrorScope();
@@ -807,8 +830,10 @@ async function createEngineInner(options, holder) {
807
830
  if (needed <= kvCapacity) return;
808
831
  const newCap = Math.min(maxSeqLen, Math.max(needed, kvCapacity * 2));
809
832
  const copyBytes = kvCapacity * KV * Dh * KVB;
833
+ const copyScales = kvScaleBytes(kvCapacity);
810
834
  device.pushErrorScope("out-of-memory");
811
835
  const enc = device.createCommandEncoder();
836
+ const per = kv8 ? 4 : 2;
812
837
  const olds = [];
813
838
  for (let li = 0; li < A.layers; li++) {
814
839
  const nk = device.createBuffer({
@@ -824,6 +849,21 @@ async function createEngineInner(options, holder) {
824
849
  olds.push(Kc[li], Vc[li]);
825
850
  Kc[li] = nk;
826
851
  Vc[li] = nv;
852
+ if (kv8) {
853
+ const nks = device.createBuffer({
854
+ size: kvScaleBytes(newCap),
855
+ usage: S_ | CS | CD
856
+ });
857
+ const nvs = device.createBuffer({
858
+ size: kvScaleBytes(newCap),
859
+ usage: S_ | CS | CD
860
+ });
861
+ enc.copyBufferToBuffer(Ksc[li], 0, nks, 0, copyScales);
862
+ enc.copyBufferToBuffer(Vsc[li], 0, nvs, 0, copyScales);
863
+ olds.push(Ksc[li], Vsc[li]);
864
+ Ksc[li] = nks;
865
+ Vsc[li] = nvs;
866
+ }
827
867
  }
828
868
  device.queue.submit([enc.finish()]);
829
869
  await device.queue.onSubmittedWorkDone();
@@ -832,8 +872,14 @@ async function createEngineInner(options, holder) {
832
872
  for (let li = 0; li < A.layers; li++) {
833
873
  Kc[li].destroy();
834
874
  Vc[li].destroy();
835
- Kc[li] = olds[2 * li];
836
- Vc[li] = olds[2 * li + 1];
875
+ Kc[li] = olds[per * li];
876
+ Vc[li] = olds[per * li + 1];
877
+ if (kv8) {
878
+ Ksc[li].destroy();
879
+ Vsc[li].destroy();
880
+ Ksc[li] = olds[per * li + 2];
881
+ Vsc[li] = olds[per * li + 3];
882
+ }
837
883
  }
838
884
  poolInvalidate();
839
885
  throw new GpuOutOfMemoryError(`KV cache growth to ${newCap} positions failed: ${oom.message}`);
@@ -1112,6 +1158,34 @@ async function createEngineInner(options, holder) {
1112
1158
  resid
1113
1159
  ], [out], S * w.N);
1114
1160
  }
1161
+ function appendKV(pass, src, which, li, rows, dstRow0) {
1162
+ const data = which === 0 ? Kc[li] : Vc[li];
1163
+ if (kv8) {
1164
+ setup(pass, "copy_kv8", [
1165
+ ["u", rows],
1166
+ ["u", Dh],
1167
+ ["u", dstRow0],
1168
+ ["u", 0]
1169
+ ], [src], [data, which === 0 ? Ksc[li] : Vsc[li]]);
1170
+ pass.dispatchWorkgroups(isFull("copy_kv8") ? rows : 1);
1171
+ } else run(pass, COPY_KV, [
1172
+ ["u", rows * Dh],
1173
+ ["u", dstRow0 * Dh],
1174
+ ["u", 0],
1175
+ ["u", 0]
1176
+ ], [src], data, rows * Dh);
1177
+ }
1178
+ const attIns = (qr, li) => kv8 ? [
1179
+ qr,
1180
+ Kc[li],
1181
+ Vc[li],
1182
+ Ksc[li],
1183
+ Vsc[li]
1184
+ ] : [
1185
+ qr,
1186
+ Kc[li],
1187
+ Vc[li]
1188
+ ];
1115
1189
  function layer(pass, li, h, S, posBase, cos, sin) {
1116
1190
  const Ltot = posBase + S;
1117
1191
  const n1 = actBuf(S * Hd);
@@ -1136,12 +1210,7 @@ async function createEngineInner(options, holder) {
1136
1210
  k,
1137
1211
  v
1138
1212
  ], 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);
1213
+ appendKV(pass, v, 1, li, KV, posBase * KV);
1145
1214
  const qr = actBuf(H * Dh);
1146
1215
  runN(pass, "rmsnorm_rope_sg", [
1147
1216
  ["u", H],
@@ -1156,7 +1225,22 @@ async function createEngineInner(options, holder) {
1156
1225
  cos,
1157
1226
  sin
1158
1227
  ], qr, H);
1159
- runN(pass, ROPE_K, [
1228
+ if (kv8) {
1229
+ setup(pass, "rmsnorm_rope_sg_kv8", [
1230
+ ["u", KV],
1231
+ ["u", Dh],
1232
+ ["f", A.rms_eps],
1233
+ ["u", posBase * KV],
1234
+ ["u", 0],
1235
+ ["u", 0]
1236
+ ], [
1237
+ k,
1238
+ W[`layers.${li}.attn.k_norm`].buf,
1239
+ cos,
1240
+ sin
1241
+ ], [Kc[li], Ksc[li]]);
1242
+ pass.dispatchWorkgroups(isFull("rmsnorm_rope_sg_kv8") ? KV : 1);
1243
+ } else runN(pass, ROPE_K, [
1160
1244
  ["u", KV],
1161
1245
  ["u", Dh],
1162
1246
  ["f", A.rms_eps],
@@ -1178,11 +1262,7 @@ async function createEngineInner(options, holder) {
1178
1262
  ["u", Dh],
1179
1263
  ["u", posBase],
1180
1264
  ["u", Ltot]
1181
- ], [
1182
- qr,
1183
- Kc[li],
1184
- Vc[li]
1185
- ], att, H);
1265
+ ], attIns(qr, li), att, H);
1186
1266
  cap(li, "att", att);
1187
1267
  const o = W[`layers.${li}.attn.o_proj`], h2 = actBuf(Hd);
1188
1268
  residMM(pass, o, att, h, 1, h2);
@@ -1236,18 +1316,8 @@ async function createEngineInner(options, holder) {
1236
1316
  cos,
1237
1317
  sin
1238
1318
  ], 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);
1319
+ appendKV(pass, kr, 0, li, S * KV, posBase * KV);
1320
+ appendKV(pass, v, 1, li, S * KV, posBase * KV);
1251
1321
  cap(li, "qr", qr);
1252
1322
  const att = actBuf(S * H * Dh);
1253
1323
  runN(pass, ATT, [
@@ -1257,11 +1327,7 @@ async function createEngineInner(options, holder) {
1257
1327
  ["u", Dh],
1258
1328
  ["u", posBase],
1259
1329
  ["u", Ltot]
1260
- ], [
1261
- qr,
1262
- Kc[li],
1263
- Vc[li]
1264
- ], att, S * H);
1330
+ ], attIns(qr, li), att, S * H);
1265
1331
  cap(li, "att", att);
1266
1332
  const o = W[`layers.${li}.attn.o_proj`], h2 = actBuf(S * Hd);
1267
1333
  residMM(pass, o, att, h, S, h2);
@@ -2159,7 +2225,7 @@ async function createEngineInner(options, holder) {
2159
2225
  const ck = {};
2160
2226
  for (const [name, b] of Object.entries(DBG0)) ck[name] = await readback(b, b.size / 4);
2161
2227
  const off = pos * KV * Dh;
2162
- if (!kv16) {
2228
+ if (!kv16 && !kv8) {
2163
2229
  ck.kc = (await readback(Kc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
2164
2230
  ck.vc = (await readback(Vc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
2165
2231
  }
@@ -2239,7 +2305,7 @@ async function createEngineInner(options, holder) {
2239
2305
  const capabilities = {
2240
2306
  useSubgroups: useSG,
2241
2307
  subgroupSize: sgMax,
2242
- kvCache: kv16 ? "f16" : "f32",
2308
+ kvCache: kv16 ? "f16" : kv8 ? "q8" : "f32",
2243
2309
  maxSeqLen,
2244
2310
  adapter: {
2245
2311
  vendor: info.vendor,
@@ -2383,6 +2449,77 @@ async function createEngineInner(options, holder) {
2383
2449
  transients = null;
2384
2450
  }
2385
2451
  }
2452
+ const kvRowBytes = KV * Dh * KVB;
2453
+ const scRowBytes = kv8 ? KV * (Dh / 32) * 4 : 0;
2454
+ const snapshotBytes = (len) => A.layers * 2 * len * (kvRowBytes + scRowBytes);
2455
+ async function saveCache() {
2456
+ if (fullHistory.length === 0) return null;
2457
+ const len = fullHistory.length - 1;
2458
+ const data = new ArrayBuffer(snapshotBytes(len));
2459
+ if (len > 0) {
2460
+ const rb = device.createBuffer({
2461
+ size: snapshotBytes(len),
2462
+ usage: GPUBufferUsage.MAP_READ | CD
2463
+ });
2464
+ const enc = device.createCommandEncoder();
2465
+ let off = 0;
2466
+ for (let li = 0; li < A.layers; li++) {
2467
+ enc.copyBufferToBuffer(Kc[li], 0, rb, off, len * kvRowBytes);
2468
+ off += len * kvRowBytes;
2469
+ enc.copyBufferToBuffer(Vc[li], 0, rb, off, len * kvRowBytes);
2470
+ off += len * kvRowBytes;
2471
+ if (kv8) {
2472
+ enc.copyBufferToBuffer(Ksc[li], 0, rb, off, len * scRowBytes);
2473
+ off += len * scRowBytes;
2474
+ enc.copyBufferToBuffer(Vsc[li], 0, rb, off, len * scRowBytes);
2475
+ off += len * scRowBytes;
2476
+ }
2477
+ }
2478
+ device.queue.submit([enc.finish()]);
2479
+ await rb.mapAsync(GPUMapMode.READ);
2480
+ new Uint8Array(data).set(new Uint8Array(rb.getMappedRange()));
2481
+ rb.unmap();
2482
+ rb.destroy();
2483
+ }
2484
+ return {
2485
+ version: 1,
2486
+ kvCache: capabilities.kvCache,
2487
+ model: {
2488
+ layers: A.layers,
2489
+ kvHeads: KV,
2490
+ headDim: Dh,
2491
+ hidden: Hd,
2492
+ vocab: A.vocab
2493
+ },
2494
+ ids: [...fullHistory],
2495
+ data
2496
+ };
2497
+ }
2498
+ async function restoreCache(snap) {
2499
+ if (!snap || snap.version !== 1) throw new Error(`restoreCache: unsupported snapshot version ${snap?.version}`);
2500
+ 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`);
2501
+ const m = snap.model;
2502
+ 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)");
2503
+ if (!Array.isArray(snap.ids) || snap.ids.length === 0) throw new Error("restoreCache: snapshot holds no tokens");
2504
+ if (snap.ids.length > maxSeqLen) throw new Error(`restoreCache: snapshot length ${snap.ids.length} exceeds maxSeqLen ${maxSeqLen}`);
2505
+ const len = snap.ids.length - 1;
2506
+ if (snap.data.byteLength !== snapshotBytes(len)) throw new Error(`restoreCache: snapshot data is ${snap.data.byteLength} bytes, expected ${snapshotBytes(len)}`);
2507
+ await ensureKvCapacity(len);
2508
+ let off = 0;
2509
+ for (let li = 0; li < A.layers; li++) {
2510
+ device.queue.writeBuffer(Kc[li], 0, snap.data, off, len * kvRowBytes);
2511
+ off += len * kvRowBytes;
2512
+ device.queue.writeBuffer(Vc[li], 0, snap.data, off, len * kvRowBytes);
2513
+ off += len * kvRowBytes;
2514
+ if (kv8) {
2515
+ device.queue.writeBuffer(Ksc[li], 0, snap.data, off, len * scRowBytes);
2516
+ off += len * scRowBytes;
2517
+ device.queue.writeBuffer(Vsc[li], 0, snap.data, off, len * scRowBytes);
2518
+ off += len * scRowBytes;
2519
+ }
2520
+ }
2521
+ fullHistory = [...snap.ids];
2522
+ }
2386
2523
  let opChain = Promise.resolve();
2387
2524
  const serialize = (fn) => {
2388
2525
  return (...args) => {
@@ -2395,6 +2532,8 @@ async function createEngineInner(options, holder) {
2395
2532
  generate: serialize(generate),
2396
2533
  prefill: serialize(prefill),
2397
2534
  forward: serialize(forward),
2535
+ saveCache: serialize(saveCache),
2536
+ restoreCache: serialize(restoreCache),
2398
2537
  resetCache,
2399
2538
  capabilities,
2400
2539
  lost,