bitgpu 0.8.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.js CHANGED
@@ -5,12 +5,16 @@ 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",
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",
14
18
  "matmul_binary_vec4": "// Binary matmul, vectorized: y[M,N] = x[M,K] @ W[N,K]^T, W = (+/-1) * per-block scale.\n// One thread per output; the K loop processes a 32-bit sign word at a time and the\n// activations as vec4 via dot() (4 weights per FMA instead of 1 scalar op). M-agnostic\n// (works for prefill M=S and decode M=1). x is bound as vec4 (K must be a multiple of 4).\nstruct Params { M: u32, N: u32, K: u32, nb: u32, block: u32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4]\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [M, N]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (idx >= p.M * p.N) { return; }\n let m = idx / p.N;\n let n = idx % p.N;\n let xRow = m * (p.K / 4u);\n let wRow = n * (p.K / 32u);\n let sbase = n * p.nb;\n let wordsPerBlock = p.block / 32u; // 4 for block=128\n\n var acc = 0.0;\n for (var b = 0u; b < p.nb; b = b + 1u) {\n var bsum = 0.0;\n for (var w = 0u; w < wordsPerBlock; w = w + 1u) {\n let word = signbits[wRow + b * wordsPerBlock + w];\n let xb = xRow + b * (p.block / 4u) + w * 8u; // vec4 base for this word (32 weights = 8 vec4)\n for (var g = 0u; g < 8u; g = g + 1u) {\n let bits4 = (word >> (g * 4u)) & 0xfu;\n let sv = vec4<f32>(\n select(-1.0, 1.0, (bits4 & 1u) != 0u),\n select(-1.0, 1.0, (bits4 & 2u) != 0u),\n select(-1.0, 1.0, (bits4 & 4u) != 0u),\n select(-1.0, 1.0, (bits4 & 8u) != 0u),\n );\n bsum = bsum + dot(x[xb + g], sv);\n }\n }\n acc = acc + bsum * scales[sbase + b];\n }\n y[idx] = acc;\n}\n",
15
19
  "matmul_q2": "// 2-bit dequant matmul (lm_head): y[M,N] = x[M,K] @ W[N,K]^T, W[n,k] = (code - zp) * scale[n, k/block].\n// codes are 2-bit, 4 per byte, packed into u32 words. Correctness-first (one thread per output, fp32).\nstruct Params { M: u32, N: u32, K: u32, nb: u32, block: u32, zp: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [M, K]\n@group(0) @binding(2) var<storage, read> codes: array<u32>; // [N, K/4] bytes packed as u32\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [M, N]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (idx >= p.M * p.N) { return; }\n let m = idx / p.N;\n let n = idx % p.N;\n let xbase = m * p.K;\n let cbyteBase = n * (p.K / 4u); // byte offset of row n in the codes stream\n let sbase = n * p.nb;\n let zpf = f32(p.zp);\n\n var acc = 0.0;\n for (var b = 0u; b < p.nb; b = b + 1u) {\n var bsum = 0.0;\n let k0 = b * p.block;\n for (var j = 0u; j < p.block; j = j + 1u) {\n let k = k0 + j;\n let byteIdx = cbyteBase + (k >> 2u);\n let word = codes[byteIdx >> 2u];\n let byte = (word >> (8u * (byteIdx & 3u))) & 0xffu;\n let code = (byte >> (2u * (k & 3u))) & 3u;\n bsum = bsum + (f32(code) - zpf) * x[xbase + k];\n }\n acc = acc + bsum * scales[sbase + b];\n }\n y[idx] = acc;\n}\n",
16
20
  "matmul_q2_sg": "// Subgroup split-K GEMV for the 2-bit lm_head (M=1 decode). One subgroup per output column,\n// lanes split K (vec4), reduce with subgroupAdd. value = (code - zp) * per-block scale.\n// 2D dispatch since N (vocab) > 65535.\nenable subgroups;\noverride SG: u32 = 32u;\nstruct Params { N: u32, K: u32, nb: u32, zp: u32, gridX: u32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\n@group(0) @binding(2) var<storage, read> codes: array<u32>; // [N, K/4] bytes packed as u32\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [N]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let n = wg.y * p.gridX + wg.x;\n if (n >= p.N) { return; }\n let cbase = n * (p.K / 4u); // byte offset of row n in the codes stream\n let sbase = n * p.nb;\n let zpf = f32(p.zp);\n let Kvec = p.K / 4u;\n\n var acc = 0.0;\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\n let byteIdx = cbase + gi;\n let word = codes[byteIdx >> 2u];\n let byte = (word >> (8u * (byteIdx & 3u))) & 0xffu;\n let cv = vec4<f32>(f32(byte & 3u) - zpf, f32((byte >> 2u) & 3u) - zpf,\n f32((byte >> 4u) & 3u) - zpf, f32((byte >> 6u) & 3u) - zpf);\n acc = acc + dot(x[gi], cv) * scales[sbase + (gi >> 5u)]; // block = (gi*4)/128 = gi/32\n }\n let total = subgroupAdd(acc);\n if (lane == 0u) { y[n] = total; }\n}\n",
@@ -29,6 +33,7 @@ const SHADERS = {
29
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",
30
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",
31
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",
32
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",
33
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",
34
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",
@@ -311,7 +316,8 @@ async function createEngineInner(options, holder) {
311
316
  const maxSeqLen = Math.max(1, opts.maxSeqLen ?? DEFAULT_MAX_SEQ);
312
317
  const useSG = hasSG && sgMin === sgMax && (sgMax === 16 || sgMax === 32 || sgMax === 64) && A.head_dim % sgMax === 0 && !forceNoSG;
313
318
  const kv16 = opts.kvCache === "f16" && adapter.features.has("shader-f16");
314
- const KVB = kv16 ? 2 : 4;
319
+ const kv8 = opts.kvCache === "q8";
320
+ const KVB = kv16 ? 2 : kv8 ? 1 : 4;
315
321
  const features = [];
316
322
  if (useSG) features.push("subgroups");
317
323
  if (kv16) features.push("shader-f16");
@@ -351,6 +357,7 @@ async function createEngineInner(options, holder) {
351
357
  T.embed_tokens.zp,
352
358
  manifest.luts.tgt4
353
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`);
354
361
  const kvLayerBytes = maxSeqLen * A.kv_heads * A.head_dim * KVB;
355
362
  needBind = Math.max(needBind, kvLayerBytes, PREFILL_SEG * Math.max(A.heads * A.head_dim, A.intermediate) * 4, 32 * A.vocab * 4);
356
363
  const requiredLimits = {};
@@ -407,7 +414,8 @@ async function createEngineInner(options, holder) {
407
414
  ["embed_gather"],
408
415
  ["embed_gather_batch"],
409
416
  ["sampler_penalty"],
410
- ["argmax_masked"]
417
+ ["argmax_masked"],
418
+ ["logsumexp"]
411
419
  ];
412
420
  if (useSG) {
413
421
  for (const n of [
@@ -440,7 +448,12 @@ async function createEngineInner(options, holder) {
440
448
  if (useSG) for (const n of ["attention_sg_kv16", "rmsnorm_rope_sg_kv16"]) specs.push([n, { SG: sgMax }]);
441
449
  else specs.push(["attention_wg_kv16"]);
442
450
  }
443
- 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";
444
457
  const ROPE_K = kv16 ? "rmsnorm_rope_sg_kv16" : "rmsnorm_rope_sg";
445
458
  const COPY_KV = kv16 ? "copy_kv16" : "copy";
446
459
  await Promise.all(specs.map(([n, c]) => mkPipe(n, c)));
@@ -787,6 +800,8 @@ async function createEngineInner(options, holder) {
787
800
  const KV = A.kv_heads, Dh = A.head_dim, Hd = A.hidden, H = A.heads, F = A.intermediate;
788
801
  let kvCapacity = Math.min(maxSeqLen, 512);
789
802
  const Kc = [], Vc = [];
803
+ const Ksc = [], Vsc = [];
804
+ const kvScaleBytes = (cap) => cap * KV * (Dh / 32) * 4;
790
805
  for (let li = 0; li < A.layers; li++) {
791
806
  Kc.push(device.createBuffer({
792
807
  size: kvCapacity * KV * Dh * KVB,
@@ -796,6 +811,16 @@ async function createEngineInner(options, holder) {
796
811
  size: kvCapacity * KV * Dh * KVB,
797
812
  usage: S_ | CS | CD
798
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
+ }
799
824
  }
800
825
  const loadOom = await device.popErrorScope();
801
826
  const loadVal = await device.popErrorScope();
@@ -805,8 +830,10 @@ async function createEngineInner(options, holder) {
805
830
  if (needed <= kvCapacity) return;
806
831
  const newCap = Math.min(maxSeqLen, Math.max(needed, kvCapacity * 2));
807
832
  const copyBytes = kvCapacity * KV * Dh * KVB;
833
+ const copyScales = kvScaleBytes(kvCapacity);
808
834
  device.pushErrorScope("out-of-memory");
809
835
  const enc = device.createCommandEncoder();
836
+ const per = kv8 ? 4 : 2;
810
837
  const olds = [];
811
838
  for (let li = 0; li < A.layers; li++) {
812
839
  const nk = device.createBuffer({
@@ -822,6 +849,21 @@ async function createEngineInner(options, holder) {
822
849
  olds.push(Kc[li], Vc[li]);
823
850
  Kc[li] = nk;
824
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
+ }
825
867
  }
826
868
  device.queue.submit([enc.finish()]);
827
869
  await device.queue.onSubmittedWorkDone();
@@ -830,8 +872,14 @@ async function createEngineInner(options, holder) {
830
872
  for (let li = 0; li < A.layers; li++) {
831
873
  Kc[li].destroy();
832
874
  Vc[li].destroy();
833
- Kc[li] = olds[2 * li];
834
- 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
+ }
835
883
  }
836
884
  poolInvalidate();
837
885
  throw new GpuOutOfMemoryError(`KV cache growth to ${newCap} positions failed: ${oom.message}`);
@@ -1110,6 +1158,34 @@ async function createEngineInner(options, holder) {
1110
1158
  resid
1111
1159
  ], [out], S * w.N);
1112
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
+ ];
1113
1189
  function layer(pass, li, h, S, posBase, cos, sin) {
1114
1190
  const Ltot = posBase + S;
1115
1191
  const n1 = actBuf(S * Hd);
@@ -1134,12 +1210,7 @@ async function createEngineInner(options, holder) {
1134
1210
  k,
1135
1211
  v
1136
1212
  ], gx, Math.ceil(Ntot / gx));
1137
- run(pass, COPY_KV, [
1138
- ["u", KV * Dh],
1139
- ["u", posBase * KV * Dh],
1140
- ["u", 0],
1141
- ["u", 0]
1142
- ], [v], Vc[li], KV * Dh);
1213
+ appendKV(pass, v, 1, li, KV, posBase * KV);
1143
1214
  const qr = actBuf(H * Dh);
1144
1215
  runN(pass, "rmsnorm_rope_sg", [
1145
1216
  ["u", H],
@@ -1154,7 +1225,22 @@ async function createEngineInner(options, holder) {
1154
1225
  cos,
1155
1226
  sin
1156
1227
  ], qr, H);
1157
- 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, [
1158
1244
  ["u", KV],
1159
1245
  ["u", Dh],
1160
1246
  ["f", A.rms_eps],
@@ -1176,11 +1262,7 @@ async function createEngineInner(options, holder) {
1176
1262
  ["u", Dh],
1177
1263
  ["u", posBase],
1178
1264
  ["u", Ltot]
1179
- ], [
1180
- qr,
1181
- Kc[li],
1182
- Vc[li]
1183
- ], att, H);
1265
+ ], attIns(qr, li), att, H);
1184
1266
  cap(li, "att", att);
1185
1267
  const o = W[`layers.${li}.attn.o_proj`], h2 = actBuf(Hd);
1186
1268
  residMM(pass, o, att, h, 1, h2);
@@ -1234,18 +1316,8 @@ async function createEngineInner(options, holder) {
1234
1316
  cos,
1235
1317
  sin
1236
1318
  ], kr, S * KV * Dh);
1237
- run(pass, COPY_KV, [
1238
- ["u", S * KV * Dh],
1239
- ["u", posBase * KV * Dh],
1240
- ["u", 0],
1241
- ["u", 0]
1242
- ], [kr], Kc[li], S * KV * Dh);
1243
- run(pass, COPY_KV, [
1244
- ["u", S * KV * Dh],
1245
- ["u", posBase * KV * Dh],
1246
- ["u", 0],
1247
- ["u", 0]
1248
- ], [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);
1249
1321
  cap(li, "qr", qr);
1250
1322
  const att = actBuf(S * H * Dh);
1251
1323
  runN(pass, ATT, [
@@ -1255,11 +1327,7 @@ async function createEngineInner(options, holder) {
1255
1327
  ["u", Dh],
1256
1328
  ["u", posBase],
1257
1329
  ["u", Ltot]
1258
- ], [
1259
- qr,
1260
- Kc[li],
1261
- Vc[li]
1262
- ], att, S * H);
1330
+ ], attIns(qr, li), att, S * H);
1263
1331
  cap(li, "att", att);
1264
1332
  const o = W[`layers.${li}.attn.o_proj`], h2 = actBuf(S * Hd);
1265
1333
  residMM(pass, o, att, h, S, h2);
@@ -1563,6 +1631,8 @@ async function createEngineInner(options, holder) {
1563
1631
  const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1;
1564
1632
  const vocab = W.lm_head.N;
1565
1633
  const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab));
1634
+ const lpN = Math.max(0, Math.min(Math.floor(genOpts.logprobs ?? 0), 32, vocab));
1635
+ const KT = Math.max(K, lpN);
1566
1636
  const temperature = genOpts.temperature ?? 1;
1567
1637
  const penalty = genOpts.repetitionPenalty ?? 1;
1568
1638
  const ngramN = genOpts.noRepeatNgramSize ?? 0;
@@ -1579,11 +1649,15 @@ async function createEngineInner(options, holder) {
1579
1649
  usage: S_ | CS
1580
1650
  });
1581
1651
  const candIds = device.createBuffer({
1582
- size: K * 4,
1652
+ size: KT * 4,
1583
1653
  usage: S_ | CS
1584
1654
  });
1585
1655
  const candVals = device.createBuffer({
1586
- size: K * 4,
1656
+ size: KT * 4,
1657
+ usage: S_ | CS
1658
+ });
1659
+ const lseBuf = device.createBuffer({
1660
+ size: 4,
1587
1661
  usage: S_ | CS
1588
1662
  });
1589
1663
  const affBuf = device.createBuffer({
@@ -1595,7 +1669,7 @@ async function createEngineInner(options, holder) {
1595
1669
  usage: S_ | CD
1596
1670
  });
1597
1671
  const rbBuf = device.createBuffer({
1598
- size: K * 8,
1672
+ size: KT * 8 + (lpN ? 4 : 0),
1599
1673
  usage: GPUBufferUsage.MAP_READ | CD
1600
1674
  });
1601
1675
  const embG = device.createBuffer({
@@ -1620,7 +1694,16 @@ async function createEngineInner(options, holder) {
1620
1694
  ["u", 4286578688]
1621
1695
  ], [affBuf, banBuf], [lg]);
1622
1696
  pass.dispatchWorkgroups(1);
1623
- for (let r = 0; r < K; r++) {
1697
+ if (lpN) {
1698
+ setup(pass, "logsumexp", [
1699
+ ["u", vocab],
1700
+ ["u", 0],
1701
+ ["u", 0],
1702
+ ["u", 0]
1703
+ ], [lg], [lseBuf]);
1704
+ pass.dispatchWorkgroups(1);
1705
+ }
1706
+ for (let r = 0; r < KT; r++) {
1624
1707
  setup(pass, "argmax_masked", [
1625
1708
  ["u", vocab],
1626
1709
  ["u", r],
@@ -1630,21 +1713,50 @@ async function createEngineInner(options, holder) {
1630
1713
  pass.dispatchWorkgroups(1);
1631
1714
  }
1632
1715
  };
1716
+ const copyCands = (enc) => {
1717
+ enc.copyBufferToBuffer(candIds, 0, rbBuf, 0, KT * 4);
1718
+ enc.copyBufferToBuffer(candVals, 0, rbBuf, KT * 4, KT * 4);
1719
+ if (lpN) enc.copyBufferToBuffer(lseBuf, 0, rbBuf, KT * 8, 4);
1720
+ };
1633
1721
  const readCands = async () => {
1634
1722
  await rbBuf.mapAsync(GPUMapMode.READ);
1635
1723
  const mapped = rbBuf.getMappedRange();
1636
- const ci = new Uint32Array(mapped.slice(0, K * 4));
1637
- const cv = new Float32Array(mapped.slice(K * 4, K * 8));
1724
+ const ci = new Uint32Array(mapped.slice(0, KT * 4));
1725
+ const cv = new Float32Array(mapped.slice(KT * 4, KT * 8));
1726
+ const lse = lpN ? new Float32Array(mapped.slice(KT * 8, KT * 8 + 4))[0] : 0;
1638
1727
  rbBuf.unmap();
1639
1728
  return {
1640
1729
  ci,
1641
- cv
1730
+ cv,
1731
+ lse
1642
1732
  };
1643
1733
  };
1644
- const pick = (ci, cv) => sampled ? sampleFromCandidates(ci, cv, temperature, rng) : ci[0];
1734
+ let chosenLogit = 0;
1735
+ const lpOut = lpN ? [] : null;
1736
+ const recordLp = (ci, cv, lse) => {
1737
+ if (!lpOut) return;
1738
+ const top = [];
1739
+ for (let i = 0; i < lpN; i++) top.push({
1740
+ id: ci[i],
1741
+ logprob: cv[i] - lse
1742
+ });
1743
+ lpOut.push({
1744
+ logprob: chosenLogit - lse,
1745
+ top
1746
+ });
1747
+ };
1748
+ const pick = (ciAll, cvAll) => {
1749
+ const ci = ciAll.subarray(0, K);
1750
+ const cv = cvAll.subarray(0, K);
1751
+ const tk = sampled ? sampleFromCandidates(ci, cv, temperature, rng) : ci[0];
1752
+ chosenLogit = cv[ci.indexOf(tk)];
1753
+ return tk;
1754
+ };
1645
1755
  const filter = genOpts.candidateFilter;
1646
- const chooseToken = async (ci, cv) => {
1647
- if (!filter) return pick(ci, cv);
1756
+ const chooseToken = async (ciAll, cvAll) => {
1757
+ if (!filter) return pick(ciAll, cvAll);
1758
+ const ci = ciAll.subarray(0, K);
1759
+ const cv = cvAll.subarray(0, K);
1648
1760
  const perm = new Set(filter(ci, cv));
1649
1761
  if (perm.size > 0) {
1650
1762
  const pIds = [];
@@ -1653,9 +1765,12 @@ async function createEngineInner(options, holder) {
1653
1765
  pIds.push(ci[i]);
1654
1766
  pVals.push(cv[i]);
1655
1767
  }
1656
- return sampled ? sampleFromCandidates(pIds, pVals, temperature, rng) : pIds[0];
1768
+ const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng) : pIds[0];
1769
+ chosenLogit = pVals[pIds.indexOf(tk)];
1770
+ return tk;
1657
1771
  }
1658
1772
  const all = await readback(lg, vocab);
1773
+ for (let i = 0; i < ciAll.length; i++) all[ciAll[i]] = cvAll[i];
1659
1774
  const order = Array.from(all.keys()).sort((a, b) => all[b] - all[a] || a - b);
1660
1775
  const pIds = [];
1661
1776
  const pVals = [];
@@ -1671,7 +1786,9 @@ async function createEngineInner(options, holder) {
1671
1786
  }
1672
1787
  }
1673
1788
  if (pIds.length === 0) throw new Error("bitgpu: candidateFilter permitted no token in the entire vocabulary");
1674
- return sampled ? sampleFromCandidates(pIds, pVals, temperature, rng) : pIds[0];
1789
+ const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng) : pIds[0];
1790
+ chosenLogit = pVals[pIds.indexOf(tk)];
1791
+ return tk;
1675
1792
  };
1676
1793
  transients = [];
1677
1794
  try {
@@ -1696,8 +1813,7 @@ async function createEngineInner(options, holder) {
1696
1813
  lmHead(pass, lastP, 1, lg);
1697
1814
  samplerChain(pass, pf.affLen, pf.banLen);
1698
1815
  pass.end();
1699
- encP.copyBufferToBuffer(candIds, 0, rbBuf, 0, K * 4);
1700
- encP.copyBufferToBuffer(candVals, 0, rbBuf, K * 4, K * 4);
1816
+ copyCands(encP);
1701
1817
  device.queue.submit([encP.finish()]);
1702
1818
  const first = await readCands();
1703
1819
  const firstTok = await chooseToken(first.ci, first.cv);
@@ -1708,6 +1824,7 @@ async function createEngineInner(options, holder) {
1708
1824
  if (!stopped) {
1709
1825
  gen.push(firstTok);
1710
1826
  history.push(firstTok);
1827
+ recordLp(first.ci, first.cv, first.lse);
1711
1828
  onToken?.(firstTok);
1712
1829
  device.queue.writeBuffer(tokBuf, 0, new Uint32Array([firstTok]));
1713
1830
  }
@@ -1743,12 +1860,11 @@ async function createEngineInner(options, holder) {
1743
1860
  lmHead(p2, last, 1, lg);
1744
1861
  samplerChain(p2, affLen, banLen);
1745
1862
  p2.end();
1746
- enc.copyBufferToBuffer(candIds, 0, rbBuf, 0, K * 4);
1747
- enc.copyBufferToBuffer(candVals, 0, rbBuf, K * 4, K * 4);
1863
+ copyCands(enc);
1748
1864
  device.queue.submit([enc.finish()]);
1749
1865
  recMs += performance.now() - t;
1750
1866
  t = performance.now();
1751
- const { ci, cv } = await readCands();
1867
+ const { ci, cv, lse } = await readCands();
1752
1868
  gpuMs += performance.now() - t;
1753
1869
  t = performance.now();
1754
1870
  const tk = await chooseToken(ci, cv);
@@ -1760,6 +1876,7 @@ async function createEngineInner(options, holder) {
1760
1876
  }
1761
1877
  gen.push(tk);
1762
1878
  history.push(tk);
1879
+ recordLp(ci, cv, lse);
1763
1880
  onToken?.(tk);
1764
1881
  device.queue.writeBuffer(tokBuf, idxOut * 4, new Uint32Array([tk]));
1765
1882
  }
@@ -1774,7 +1891,8 @@ async function createEngineInner(options, holder) {
1774
1891
  recMs: recMs / nd,
1775
1892
  gpuMs: gpuMs / nd,
1776
1893
  rbMs: rbMs / nd,
1777
- rng
1894
+ rng,
1895
+ ...lpOut ? { lp: lpOut } : {}
1778
1896
  };
1779
1897
  } finally {
1780
1898
  poolUse(null);
@@ -1785,6 +1903,7 @@ async function createEngineInner(options, holder) {
1785
1903
  lg,
1786
1904
  candIds,
1787
1905
  candVals,
1906
+ lseBuf,
1788
1907
  affBuf,
1789
1908
  banBuf,
1790
1909
  rbBuf,
@@ -2106,7 +2225,7 @@ async function createEngineInner(options, holder) {
2106
2225
  const ck = {};
2107
2226
  for (const [name, b] of Object.entries(DBG0)) ck[name] = await readback(b, b.size / 4);
2108
2227
  const off = pos * KV * Dh;
2109
- if (!kv16) {
2228
+ if (!kv16 && !kv8) {
2110
2229
  ck.kc = (await readback(Kc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
2111
2230
  ck.vc = (await readback(Vc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
2112
2231
  }
@@ -2186,7 +2305,7 @@ async function createEngineInner(options, holder) {
2186
2305
  const capabilities = {
2187
2306
  useSubgroups: useSG,
2188
2307
  subgroupSize: sgMax,
2189
- kvCache: kv16 ? "f16" : "f32",
2308
+ kvCache: kv16 ? "f16" : kv8 ? "q8" : "f32",
2190
2309
  maxSeqLen,
2191
2310
  adapter: {
2192
2311
  vendor: info.vendor,
@@ -2245,7 +2364,7 @@ async function createEngineInner(options, holder) {
2245
2364
  transients = null;
2246
2365
  }
2247
2366
  }
2248
- const hasFilter = !!genOpts.candidateFilter;
2367
+ const hasFilter = !!genOpts.candidateFilter || (genOpts.logprobs ?? 0) > 0;
2249
2368
  let r;
2250
2369
  if (!hasFilter && genOpts.promptLookup === "auto" && maxTokens > 24) {
2251
2370
  const r1 = await generatePldImpl(prefillTokens, posBase, 24, genOpts, fullHistory);
@@ -2310,7 +2429,8 @@ async function createEngineInner(options, holder) {
2310
2429
  gpuMs: r.gpuMs,
2311
2430
  readbackMs: r.rbMs
2312
2431
  },
2313
- ...r.spec ? { speculation: r.spec } : {}
2432
+ ...r.spec ? { speculation: r.spec } : {},
2433
+ ...r.lp ? { logprobs: r.lp } : {}
2314
2434
  };
2315
2435
  }
2316
2436
  async function prefill(ids) {
@@ -2329,6 +2449,77 @@ async function createEngineInner(options, holder) {
2329
2449
  transients = null;
2330
2450
  }
2331
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
+ }
2332
2523
  let opChain = Promise.resolve();
2333
2524
  const serialize = (fn) => {
2334
2525
  return (...args) => {
@@ -2341,6 +2532,8 @@ async function createEngineInner(options, holder) {
2341
2532
  generate: serialize(generate),
2342
2533
  prefill: serialize(prefill),
2343
2534
  forward: serialize(forward),
2535
+ saveCache: serialize(saveCache),
2536
+ restoreCache: serialize(restoreCache),
2344
2537
  resetCache,
2345
2538
  capabilities,
2346
2539
  lost,