bitgpu 0.12.0 → 0.13.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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/shaders.generated.ts","../src/errors.ts","../src/pld.ts","../src/sampler.ts","../src/engine.ts"],"sourcesContent":["// AUTO-GENERATED by scripts/gen-shaders.ts from shaders/*.wgsl. Do not edit by hand.\nexport const SHADERS: Record<string, string> = {\n \"add\": \"// Elementwise residual add: y[i] = a[i] + b[i].\\nstruct Params { n: u32, _p0: u32, _p1: u32, _p2: u32 };\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> a: array<f32>;\\n@group(0) @binding(2) var<storage, read> b: array<f32>;\\n@group(0) @binding(3) var<storage, read_write> y: array<f32>;\\n\\n@compute @workgroup_size(64)\\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\\n if (i >= p.n) { return; }\\n y[i] = a[i] + b[i];\\n}\\n\",\n \"argmax\": \"// GPU argmax over the logits, writing one token id into a GPU buffer so the token never leaves the\\n// GPU (enables the deferred-sync decode loop). Single workgroup, WG threads strided-scan the N\\n// logits tracking (maxVal, maxIdx), then a shared-mem tree reduction. Tie-break = LOWEST index, to\\n// match the CPU argmax (strict > keeps the first max). No subgroup ops -> all devices.\\noverride WG: u32 = 256u;\\nstruct Params { N: u32, outIdx: u32, _0: u32, _1: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> logits: array<f32>;\\n@group(0) @binding(2) var<storage, read_write> outTok: array<u32>; // outTok[p.outIdx] = argmax\\n\\nvar<workgroup> sval: array<f32, 256>;\\nvar<workgroup> sidx: array<u32, 256>;\\n\\n@compute @workgroup_size(WG)\\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\\n let tid = lid.x;\\n var bv = -3.4e38;\\n var bi = 0u;\\n for (var i = tid; i < p.N; i = i + WG) {\\n let v = logits[i];\\n if (v > bv) { bv = v; bi = i; } // strict > keeps the lowest index within this thread's stride\\n }\\n sval[tid] = bv; sidx[tid] = bi;\\n workgroupBarrier();\\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\\n if (tid < s) {\\n let ov = sval[tid + s]; let oi = sidx[tid + s];\\n if (ov > sval[tid] || (ov == sval[tid] && oi < sidx[tid])) { sval[tid] = ov; sidx[tid] = oi; }\\n }\\n workgroupBarrier();\\n }\\n if (tid == 0u) { outTok[p.outIdx] = sidx[0]; }\\n}\\n\",\n \"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\",\n \"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\",\n \"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\",\n \"attention_sg_kv16_roll\": \"// attention_sg_kv16 for the rolling-window / attention-sinks mode (see attention_sg_roll.wgsl\\n// for the rope-at-read scheme). Keep in lockstep with attention_sg_kv16.wgsl: the ONLY\\n// difference is the K rotation in the score loop; each cached f16 value is widened to f32 at\\n// the read and rotated with the same `k*cos + rot*sin` operand order as rmsnorm_rope_sg.\\n// The engine only selects this kernel when SG <= D/2 (partner dim stays in-lane).\\nenable subgroups;\\nenable f16;\\noverride SG: u32 = 32u;\\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\\n@group(0) @binding(2) var<storage, read> Kc: array<f16>; // [Ltot, KV, D] UNROPED\\n@group(0) @binding(3) var<storage, read> Vc: array<f16>; // [Ltot, KV, D]\\n@group(0) @binding(4) var<storage, read> cosT: array<f32>; // [positions, D/2]\\n@group(0) @binding(5) var<storage, read> sinT: array<f32>; // [positions, D/2]\\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\\n\\n@compute @workgroup_size(SG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\\n let idx = wg.x;\\n if (idx >= p.S * p.H) { return; }\\n let h = idx % p.H;\\n let qi = idx / p.H;\\n let pos = p.posBase + qi;\\n let kvh = h / (p.H / p.KV);\\n let qb = (qi * p.H + h) * p.D;\\n let inv = 1.0 / sqrt(f32(p.D));\\n let dper = p.D / SG;\\n let half = p.D / 2u;\\n let hs = half / SG; // strides from a dim to its rotate partner\\n\\n var acc: array<f32, 8>;\\n for (var t = 0u; t < dper; t = t + 1u) { acc[t] = 0.0; }\\n var m = -1e30;\\n var l = 0.0;\\n for (var j = 0u; j <= pos; j = j + 1u) {\\n let kb = (j * p.KV + kvh) * p.D;\\n var kd: array<f32, 8>;\\n for (var t = 0u; t < dper; t = t + 1u) { kd[t] = f32(Kc[kb + lane + t * SG]); }\\n var part = 0.0;\\n for (var t = 0u; t < dper; t = t + 1u) {\\n let d = lane + t * SG;\\n var rot: f32;\\n if (d < half) { rot = -kd[t + hs]; } else { rot = kd[t - hs]; }\\n let rb = j * half + (d % half);\\n part = part + q[qb + d] * (kd[t] * cosT[rb] + rot * sinT[rb]);\\n }\\n let score = subgroupAdd(part) * inv;\\n let mnew = max(m, score);\\n let corr = exp(m - mnew);\\n let w = exp(score - mnew);\\n l = l * corr + w;\\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; acc[t] = acc[t] * corr + w * f32(Vc[kb + d]); }\\n m = mnew;\\n }\\n let ob = (qi * p.H + h) * p.D;\\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; out[ob + d] = acc[t] / l; }\\n}\\n\",\n \"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\",\n \"attention_sg_kv8_roll\": \"// attention_sg_kv8 for the rolling-window / attention-sinks mode (see attention_sg_roll.wgsl\\n// for the rope-at-read scheme). Keep in lockstep with attention_sg_kv8.wgsl: the ONLY\\n// difference is the K rotation in the score loop. The cache holds UNROPED quantized keys -\\n// the whole point: the packed bytes are immutable, so eviction never requantizes (llama.cpp's\\n// K-shift cannot do this on a quantized cache at all). A word's rotate partner is the word\\n// D/8 away (all 4 dims of a word share one half), dequantized from global with its own scale.\\nenable subgroups;\\noverride SG: u32 = 32u;\\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\\n@group(0) @binding(2) var<storage, read> Kq: array<u32>; // [Ltot, KV, D/4] packed snorm8, UNROPED\\n@group(0) @binding(3) var<storage, read> Vq: array<u32>; // [Ltot, KV, D/4] packed snorm8\\n@group(0) @binding(4) var<storage, read> Ks: array<f32>; // [Ltot, KV, D/32] block scales\\n@group(0) @binding(5) var<storage, read> Vs: array<f32>; // [Ltot, KV, D/32] block scales\\n@group(0) @binding(6) var<storage, read> cosT: array<f32>; // [positions, D/2]\\n@group(0) @binding(7) var<storage, read> sinT: array<f32>; // [positions, D/2]\\n@group(0) @binding(8) var<storage, read_write> out: array<f32>; // [S, H, D]\\n\\n@compute @workgroup_size(SG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\\n let idx = wg.x;\\n if (idx >= p.S * p.H) { return; }\\n let h = idx % p.H;\\n let qi = idx / p.H;\\n let pos = p.posBase + qi;\\n let kvh = h / (p.H / p.KV);\\n let qb = (qi * p.H + h) * p.D;\\n let inv = 1.0 / sqrt(f32(p.D));\\n let W4 = p.D / 4u;\\n let B32 = p.D / 32u;\\n let half = p.D / 2u;\\n let hw = half / 4u; // words from a word to its rotate partner\\n\\n var acc: array<vec4<f32>, 8>; // words per lane: W4/SG <= 8 for SG >= 4\\n for (var t = 0u; t < 8u; t = t + 1u) { acc[t] = vec4<f32>(0.0); }\\n var m = -1e30;\\n var l = 0.0;\\n for (var j = 0u; j <= pos; j = j + 1u) {\\n let rowQ = (j * p.KV + kvh) * W4;\\n let rowS = (j * p.KV + kvh) * B32;\\n var part = 0.0;\\n for (var w = lane; w < W4; w = w + SG) {\\n let kw = unpack4x8snorm(Kq[rowQ + w]) * Ks[rowS + (w >> 3u)];\\n let wp = select(w - hw, w + hw, w < hw);\\n let kp = unpack4x8snorm(Kq[rowQ + wp]) * Ks[rowS + (wp >> 3u)];\\n let rot = select(kp, -kp, w < hw);\\n let cb = j * half + select(w - hw, w, w < hw) * 4u;\\n let cs = vec4<f32>(cosT[cb], cosT[cb + 1u], cosT[cb + 2u], cosT[cb + 3u]);\\n let sn = vec4<f32>(sinT[cb], sinT[cb + 1u], sinT[cb + 2u], sinT[cb + 3u]);\\n let qv = vec4<f32>(q[qb + w * 4u], q[qb + w * 4u + 1u], q[qb + w * 4u + 2u], q[qb + w * 4u + 3u]);\\n part = part + dot(qv, kw * cs + rot * sn);\\n }\\n let score = subgroupAdd(part) * inv;\\n let mnew = max(m, score);\\n let corr = exp(m - mnew);\\n let wgt = exp(score - mnew);\\n l = l * corr + wgt;\\n var wi = 0u;\\n for (var w = lane; w < W4; w = w + SG) {\\n let vw = unpack4x8snorm(Vq[rowQ + w]) * Vs[rowS + (w >> 3u)];\\n acc[wi] = acc[wi] * corr + wgt * vw;\\n wi = wi + 1u;\\n }\\n m = mnew;\\n }\\n let ob = (qi * p.H + h) * p.D;\\n var wi = 0u;\\n for (var w = lane; w < W4; w = w + SG) {\\n let o = acc[wi] / l;\\n out[ob + w * 4u] = o.x;\\n out[ob + w * 4u + 1u] = o.y;\\n out[ob + w * 4u + 2u] = o.z;\\n out[ob + w * 4u + 3u] = o.w;\\n wi = wi + 1u;\\n }\\n}\\n\",\n \"attention_sg_roll\": \"// attention_sg for the rolling-window / attention-sinks mode (overflow: 'sinks'): the cache\\n// holds UNROPED keys, and each cached row j is rotated AT READ by its cache-relative position\\n// (StreamingLLM-style; the cache bytes are immutable, so eviction compaction never re-rotates\\n// or requantizes anything). Keep in lockstep with attention_sg.wgsl: the ONLY difference is\\n// the K rotation in the score loop, written as `k*cos + rot*sin` with the same operand order\\n// as rmsnorm_rope_sg so the f32 path stays bit-identical to the roped-at-write kernels until\\n// the first eviction. cosT/sinT are the aux rope tables, [positions, D/2].\\n// Lane math: d = lane + t*SG, partner d±D/2 is (D/2)/SG strides away IN THE SAME LANE (the\\n// engine only selects this kernel when SG <= D/2).\\nenable subgroups;\\noverride SG: u32 = 32u;\\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\\n@group(0) @binding(2) var<storage, read> Kc: array<f32>; // [Ltot, KV, D] UNROPED\\n@group(0) @binding(3) var<storage, read> Vc: array<f32>; // [Ltot, KV, D]\\n@group(0) @binding(4) var<storage, read> cosT: array<f32>; // [positions, D/2]\\n@group(0) @binding(5) var<storage, read> sinT: array<f32>; // [positions, D/2]\\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\\n\\n@compute @workgroup_size(SG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\\n let idx = wg.x;\\n if (idx >= p.S * p.H) { return; }\\n let h = idx % p.H;\\n let qi = idx / p.H;\\n let pos = p.posBase + qi;\\n let kvh = h / (p.H / p.KV);\\n let qb = (qi * p.H + h) * p.D;\\n let inv = 1.0 / sqrt(f32(p.D));\\n let dper = p.D / SG;\\n let half = p.D / 2u;\\n let hs = half / SG; // strides from a dim to its rotate partner\\n\\n var acc: array<f32, 8>;\\n for (var t = 0u; t < dper; t = t + 1u) { acc[t] = 0.0; }\\n var m = -1e30;\\n var l = 0.0;\\n for (var j = 0u; j <= pos; j = j + 1u) {\\n let kb = (j * p.KV + kvh) * p.D;\\n var kd: array<f32, 8>;\\n for (var t = 0u; t < dper; t = t + 1u) { kd[t] = Kc[kb + lane + t * SG]; }\\n var part = 0.0;\\n for (var t = 0u; t < dper; t = t + 1u) {\\n let d = lane + t * SG;\\n var rot: f32;\\n if (d < half) { rot = -kd[t + hs]; } else { rot = kd[t - hs]; }\\n let rb = j * half + (d % half);\\n part = part + q[qb + d] * (kd[t] * cosT[rb] + rot * sinT[rb]);\\n }\\n let score = subgroupAdd(part) * inv;\\n let mnew = max(m, score);\\n let corr = exp(m - mnew);\\n let w = exp(score - mnew);\\n l = l * corr + w;\\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; acc[t] = acc[t] * corr + w * Vc[kb + d]; }\\n m = mnew;\\n }\\n let ob = (qi * p.H + h) * p.D;\\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; out[ob + d] = acc[t] / l; }\\n}\\n\",\n \"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\",\n \"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\",\n \"attention_wg_kv16_roll\": \"// attention_wg_kv16 for the rolling-window / attention-sinks mode (see attention_sg_roll.wgsl\\n// for the rope-at-read scheme). Keep in lockstep with attention_wg_kv16.wgsl: the ONLY\\n// differences are the shared-memory K stage (kk, widened to f32) - the rotate partner d±D/2\\n// may live in another thread's stride - and the rotation in the score loop, written as\\n// `k*cos + rot*sin` with the same operand order as rmsnorm_rope_sg.\\nenable f16;\\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\\n@group(0) @binding(2) var<storage, read> Kc: array<f16>; // [Ltot, KV, D] UNROPED\\n@group(0) @binding(3) var<storage, read> Vc: array<f16>; // [Ltot, KV, D]\\n@group(0) @binding(4) var<storage, read> cosT: array<f32>; // [positions, D/2]\\n@group(0) @binding(5) var<storage, read> sinT: array<f32>; // [positions, D/2]\\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\\nvar<workgroup> red: array<f32, 64>;\\nvar<workgroup> kk: array<f32, 128>;\\n\\n@compute @workgroup_size(64)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\\n if (idx >= p.S * p.H) { return; }\\n let tid = lid.x;\\n let h = idx % p.H;\\n let qi = idx / p.H;\\n let pos = p.posBase + qi;\\n let kvh = h / (p.H / p.KV);\\n let qb = (qi * p.H + h) * p.D;\\n let inv = 1.0 / sqrt(f32(p.D));\\n let half = p.D / 2u;\\n\\n var acc: array<f32, 2>;\\n acc[0] = 0.0;\\n acc[1] = 0.0;\\n var m = -1e30;\\n var l = 0.0;\\n for (var j = 0u; j <= pos; j = j + 1u) {\\n let kb = (j * p.KV + kvh) * p.D;\\n for (var t = 0u; t < 2u; t = t + 1u) {\\n let d = tid + t * 64u;\\n if (d < p.D) { kk[d] = f32(Kc[kb + d]); }\\n }\\n workgroupBarrier();\\n var part = 0.0;\\n for (var t = 0u; t < 2u; t = t + 1u) {\\n let d = tid + t * 64u;\\n if (d < p.D) {\\n var rot: f32;\\n if (d < half) { rot = -kk[d + half]; } else { rot = kk[d - half]; }\\n let rb = j * half + (d % half);\\n part = part + q[qb + d] * (kk[d] * cosT[rb] + rot * sinT[rb]);\\n }\\n }\\n red[tid] = part;\\n workgroupBarrier();\\n for (var s = 32u; s > 0u; s = s >> 1u) {\\n if (tid < s) { red[tid] = red[tid] + red[tid + s]; }\\n workgroupBarrier();\\n }\\n let score = red[0] * inv;\\n workgroupBarrier(); // red[0] + kk consumed before the next position overwrites them\\n let mnew = max(m, score);\\n let corr = exp(m - mnew);\\n let w = exp(score - mnew);\\n l = l * corr + w;\\n for (var t = 0u; t < 2u; t = t + 1u) {\\n let d = tid + t * 64u;\\n if (d < p.D) { acc[t] = acc[t] * corr + w * f32(Vc[kb + d]); }\\n }\\n m = mnew;\\n }\\n let ob = (qi * p.H + h) * p.D;\\n for (var t = 0u; t < 2u; t = t + 1u) {\\n let d = tid + t * 64u;\\n if (d < p.D) { out[ob + d] = acc[t] / l; }\\n }\\n}\\n\",\n \"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\",\n \"attention_wg_kv8_roll\": \"// attention_wg_kv8 for the rolling-window / attention-sinks mode: the no-subgroup fallback of\\n// attention_sg_kv8_roll (see there and attention_sg_roll.wgsl for the rope-at-read scheme).\\n// Keep in lockstep with attention_wg_kv8.wgsl: the ONLY difference is the K rotation in the\\n// score loop; each thread's word rotates against its partner word D/8 away, dequantized from\\n// global with its own scale.\\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\\n@group(0) @binding(2) var<storage, read> Kq: array<u32>; // [Ltot, KV, D/4] packed snorm8, UNROPED\\n@group(0) @binding(3) var<storage, read> Vq: array<u32>; // [Ltot, KV, D/4] packed snorm8\\n@group(0) @binding(4) var<storage, read> Ks: array<f32>; // [Ltot, KV, D/32] block scales\\n@group(0) @binding(5) var<storage, read> Vs: array<f32>; // [Ltot, KV, D/32] block scales\\n@group(0) @binding(6) var<storage, read> cosT: array<f32>; // [positions, D/2]\\n@group(0) @binding(7) var<storage, read> sinT: array<f32>; // [positions, D/2]\\n@group(0) @binding(8) var<storage, read_write> out: array<f32>; // [S, H, D]\\nvar<workgroup> red: array<f32, 64>;\\n\\n@compute @workgroup_size(64)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\\n if (idx >= p.S * p.H) { return; }\\n let t = lid.x;\\n let h = idx % p.H;\\n let qi = idx / p.H;\\n let pos = p.posBase + qi;\\n let kvh = h / (p.H / p.KV);\\n let qb = (qi * p.H + h) * p.D;\\n let inv = 1.0 / sqrt(f32(p.D));\\n let W4 = p.D / 4u;\\n let half = p.D / 2u;\\n let hw = half / 4u; // words from a word to its rotate partner\\n\\n var qv = vec4<f32>(0.0);\\n if (t < W4) {\\n qv = vec4<f32>(q[qb + t * 4u], q[qb + t * 4u + 1u], q[qb + t * 4u + 2u], q[qb + t * 4u + 3u]);\\n }\\n var acc = vec4<f32>(0.0);\\n var m = -1e30;\\n var l = 0.0;\\n for (var j = 0u; j <= pos; j = j + 1u) {\\n let rowQ = (j * p.KV + kvh) * W4;\\n let rowS = (j * p.KV + kvh) * (p.D / 32u);\\n var part = 0.0;\\n if (t < W4) {\\n let kw = unpack4x8snorm(Kq[rowQ + t]) * Ks[rowS + (t >> 3u)];\\n let wp = select(t - hw, t + hw, t < hw);\\n let kp = unpack4x8snorm(Kq[rowQ + wp]) * Ks[rowS + (wp >> 3u)];\\n let rot = select(kp, -kp, t < hw);\\n let cb = j * half + select(t - hw, t, t < hw) * 4u;\\n let cs = vec4<f32>(cosT[cb], cosT[cb + 1u], cosT[cb + 2u], cosT[cb + 3u]);\\n let sn = vec4<f32>(sinT[cb], sinT[cb + 1u], sinT[cb + 2u], sinT[cb + 3u]);\\n part = dot(qv, kw * cs + rot * sn);\\n }\\n red[t] = part;\\n workgroupBarrier();\\n for (var s = 32u; s > 0u; s = s >> 1u) {\\n if (t < s) { red[t] = red[t] + red[t + s]; }\\n workgroupBarrier();\\n }\\n let score = red[0] * inv;\\n workgroupBarrier();\\n let mnew = max(m, score);\\n let corr = exp(m - mnew);\\n let wgt = exp(score - mnew);\\n l = l * corr + wgt;\\n if (t < W4) {\\n let vw = unpack4x8snorm(Vq[rowQ + t]) * Vs[rowS + (t >> 3u)];\\n acc = acc * corr + wgt * vw;\\n }\\n m = mnew;\\n }\\n if (t < W4) {\\n let ob = (qi * p.H + h) * p.D;\\n let o = acc / l;\\n out[ob + t * 4u] = o.x;\\n out[ob + t * 4u + 1u] = o.y;\\n out[ob + t * 4u + 2u] = o.z;\\n out[ob + t * 4u + 3u] = o.w;\\n }\\n}\\n\",\n \"attention_wg_roll\": \"// attention_wg for the rolling-window / attention-sinks mode: no-subgroup fallback of\\n// attention_sg_roll (see there for the rope-at-read scheme). Keep in lockstep with\\n// attention_wg.wgsl: the ONLY differences are the shared-memory K stage (kk) - the rotate\\n// partner d±D/2 may live in another thread's stride - and the rotation in the score loop,\\n// written as `k*cos + rot*sin` with the same operand order as rmsnorm_rope_sg.\\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\\n@group(0) @binding(2) var<storage, read> Kc: array<f32>; // [Ltot, KV, D] UNROPED\\n@group(0) @binding(3) var<storage, read> Vc: array<f32>; // [Ltot, KV, D]\\n@group(0) @binding(4) var<storage, read> cosT: array<f32>; // [positions, D/2]\\n@group(0) @binding(5) var<storage, read> sinT: array<f32>; // [positions, D/2]\\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\\nvar<workgroup> red: array<f32, 64>;\\nvar<workgroup> kk: array<f32, 128>;\\n\\n@compute @workgroup_size(64)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\\n if (idx >= p.S * p.H) { return; }\\n let tid = lid.x;\\n let h = idx % p.H;\\n let qi = idx / p.H;\\n let pos = p.posBase + qi;\\n let kvh = h / (p.H / p.KV);\\n let qb = (qi * p.H + h) * p.D;\\n let inv = 1.0 / sqrt(f32(p.D));\\n let half = p.D / 2u;\\n\\n var acc: array<f32, 2>;\\n acc[0] = 0.0;\\n acc[1] = 0.0;\\n var m = -1e30;\\n var l = 0.0;\\n for (var j = 0u; j <= pos; j = j + 1u) {\\n let kb = (j * p.KV + kvh) * p.D;\\n for (var t = 0u; t < 2u; t = t + 1u) {\\n let d = tid + t * 64u;\\n if (d < p.D) { kk[d] = Kc[kb + d]; }\\n }\\n workgroupBarrier();\\n var part = 0.0;\\n for (var t = 0u; t < 2u; t = t + 1u) {\\n let d = tid + t * 64u;\\n if (d < p.D) {\\n var rot: f32;\\n if (d < half) { rot = -kk[d + half]; } else { rot = kk[d - half]; }\\n let rb = j * half + (d % half);\\n part = part + q[qb + d] * (kk[d] * cosT[rb] + rot * sinT[rb]);\\n }\\n }\\n red[tid] = part;\\n workgroupBarrier();\\n for (var s = 32u; s > 0u; s = s >> 1u) {\\n if (tid < s) { red[tid] = red[tid] + red[tid + s]; }\\n workgroupBarrier();\\n }\\n let score = red[0] * inv; // full q.k dot, visible to all threads\\n workgroupBarrier(); // red[0] + kk consumed before the next position overwrites them\\n let mnew = max(m, score);\\n let corr = exp(m - mnew);\\n let w = exp(score - mnew);\\n l = l * corr + w;\\n for (var t = 0u; t < 2u; t = t + 1u) {\\n let d = tid + t * 64u;\\n if (d < p.D) { acc[t] = acc[t] * corr + w * Vc[kb + d]; }\\n }\\n m = mnew;\\n }\\n let ob = (qi * p.H + h) * p.D;\\n for (var t = 0u; t < 2u; t = t + 1u) {\\n let d = tid + t * 64u;\\n if (d < p.D) { out[ob + d] = acc[t] / l; }\\n }\\n}\\n\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"matmul_q2_sm\": \"// Small-batch (M = 2..9) subgroup split-K GEMV for the 2-bit lm_head: the speculative-decode\\n// verify pass needs logits for every drafted row, and the scalar M-row kernel re-reads the\\n// ~77 MB code stream per output thread. Here each code word is loaded once per (column,\\n// k-chunk) and dotted with all M rows. Per row the loop stride and accumulation expression\\n// match matmul_q2_sg, so each row is bit-identical to the M=1 decode path.\\nenable subgroups;\\noverride SG: u32 = 32u;\\nstruct Params { N: u32, K: u32, nb: u32, zp: u32, gridX: u32, M: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4] row-major\\n@group(0) @binding(2) var<storage, read> 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(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);\\n let sbase = n * p.nb;\\n let zpf = f32(p.zp);\\n let Kvec = p.K / 4u;\\n\\n var acc: array<f32, 9>; // M <= 9\\n for (var m = 0u; m < p.M; m = m + 1u) { acc[m] = 0.0; }\\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\\n let 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 let s = scales[sbase + (gi >> 5u)]; // block = (gi*4)/128 = gi/32\\n for (var m = 0u; m < p.M; m = m + 1u) {\\n acc[m] = acc[m] + dot(x[m * Kvec + gi], cv) * s;\\n }\\n }\\n for (var m = 0u; m < p.M; m = m + 1u) {\\n let total = subgroupAdd(acc[m]);\\n if (lane == 0u) { y[m * p.N + n] = total; }\\n }\\n}\\n\",\n \"matmul_q2_wg\": \"// No-subgroup fallback: 2-bit lm_head GEMV for decode (M=1), workgroup-shared-memory reduction.\\n// One workgroup per output column; WG threads split K and tree-reduce. value = (code - zp) * scale.\\n// 2D dispatch since N (vocab) > 65535. This is the v1 path's biggest cost (scalar was ~48ms/token).\\noverride WG: u32 = 64u;\\nstruct Params { N: u32, K: u32, nb: u32, zp: u32, gridX: u32, _pad: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\\n@group(0) @binding(2) var<storage, read> codes: array<u32>; // [N, K/4] bytes packed as u32\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [N]\\nvar<workgroup> sdata: array<f32, 256>;\\n\\n@compute @workgroup_size(WG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\\n let n = wg.y * p.gridX + wg.x;\\n if (n >= p.N) { return; }\\n let tid = lid.x;\\n let cbase = n * (p.K / 4u);\\n let sbase = n * p.nb;\\n let zpf = f32(p.zp);\\n let Kvec = p.K / 4u;\\n var acc = 0.0;\\n for (var gi = tid; gi < Kvec; gi = gi + WG) {\\n let byteIdx = cbase + gi;\\n let word = codes[byteIdx >> 2u];\\n let byte = (word >> (8u * (byteIdx & 3u))) & 0xffu;\\n let cv = vec4<f32>(f32(byte & 3u) - zpf, f32((byte >> 2u) & 3u) - zpf,\\n f32((byte >> 4u) & 3u) - zpf, f32((byte >> 6u) & 3u) - zpf);\\n acc = acc + dot(x[gi], cv) * scales[sbase + (gi >> 5u)];\\n }\\n sdata[tid] = acc;\\n workgroupBarrier();\\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\\n if (tid < s) { sdata[tid] = sdata[tid] + sdata[tid + s]; }\\n workgroupBarrier();\\n }\\n if (tid == 0u) { y[n] = sdata[0]; }\\n}\\n\",\n \"matmul_resid\": \"// Binary matmul with a fused residual add: y[M,N] = x[M,K] @ W[N,K]^T + resid[M,N].\\n// Folds the residual add into o_proj / down_proj so it's not a separate dispatch.\\nstruct Params { M: u32, N: u32, K: u32, nb: u32, block: u32, _pad: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4]\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\\n@group(0) @binding(4) var<storage, read> resid: array<f32>; // [M, N]\\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [M, N]\\n\\n@compute @workgroup_size(64)\\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\\n if (idx >= p.M * p.N) { return; }\\n let n = idx % p.N;\\n let xRow = (idx / p.N) * (p.K / 4u);\\n let wRow = n * (p.K / 32u);\\n let sbase = n * p.nb;\\n\\n var acc = 0.0;\\n for (var b = 0u; b < p.nb; b = b + 1u) {\\n var bsum = 0.0;\\n for (var w = 0u; w < 4u; w = w + 1u) {\\n let word = signbits[wRow + b * 4u + w];\\n let xb = xRow + b * 32u + w * 8u;\\n for (var g = 0u; g < 8u; g = g + 1u) {\\n let bits4 = (word >> (g * 4u)) & 0xfu;\\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\\n bsum = bsum + dot(x[xb + g], sv);\\n }\\n }\\n acc = acc + bsum * scales[sbase + b];\\n }\\n y[idx] = acc + resid[idx];\\n}\\n\",\n \"matmul_resid_mr_sg\": \"// Multi-row subgroup GEMV for decode (M=1) with fused residual. Same as matmul_resid_sg but each\\n// workgroup computes ROWS output columns at once: per K-step it issues ROWS independent weight\\n// loads before the dots, giving the memory system more in-flight requests (memory-level\\n// parallelism) to hide latency on the bandwidth-bound decode GEMV. One subgroup per workgroup;\\n// lanes split K; ROWS accumulators reduced with subgroupAdd. value = sign * per-block scale.\\nenable subgroups;\\noverride SG: u32 = 32u;\\noverride ROWS: u32 = 4u;\\nstruct Params { N: u32, K: u32, nb: u32, gridX: u32, _p0: u32, _p1: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\\n@group(0) @binding(4) var<storage, read> resid: array<f32>; // [N]\\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [N]\\n\\n@compute @workgroup_size(SG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\\n let rowBase = (wg.y * p.gridX + wg.x) * ROWS;\\n let Kvec = p.K / 4u;\\n let wStride = p.K / 32u;\\n\\n var acc: array<f32, 8>; // ROWS <= 8\\n for (var r = 0u; r < ROWS; r = r + 1u) { acc[r] = 0.0; }\\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\\n let k = gi * 4u;\\n let xv = x[gi];\\n let widx = k >> 5u;\\n let sh = k & 31u;\\n let sc = k / 128u;\\n for (var r = 0u; r < ROWS; r = r + 1u) {\\n let n = rowBase + r;\\n if (n < p.N) {\\n let w = (signbits[n * wStride + widx] >> sh) & 0xfu;\\n let sv = vec4<f32>(select(-1.0, 1.0, (w & 1u) != 0u), select(-1.0, 1.0, (w & 2u) != 0u),\\n select(-1.0, 1.0, (w & 4u) != 0u), select(-1.0, 1.0, (w & 8u) != 0u));\\n acc[r] = acc[r] + dot(xv, sv) * scales[n * p.nb + sc];\\n }\\n }\\n }\\n for (var r = 0u; r < ROWS; r = r + 1u) {\\n let n = rowBase + r;\\n let total = subgroupAdd(acc[r]); // collective: called for every r by all lanes\\n if (lane == 0u && n < p.N) { y[n] = total + resid[n]; }\\n }\\n}\\n\",\n \"matmul_resid_sm\": \"// Small-batch (M = 2..9) subgroup split-K GEMV with fused residual add (o_proj / down_proj in\\n// the speculative-decode verify pass). One workgroup per output column; each weight word is\\n// loaded once and dotted with all M activation rows. Per row the loop stride and accumulation\\n// expression match the validated M=1 kernels, so results are row-wise bit-identical to them.\\nenable subgroups;\\noverride SG: u32 = 32u;\\nstruct Params { N: u32, K: u32, nb: u32, gridX: u32, M: u32, _pad: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4] row-major\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\\n@group(0) @binding(4) var<storage, read> resid: array<f32>; // [M, N]\\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [M, N]\\n\\n@compute @workgroup_size(SG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\\n let n = wg.y * p.gridX + wg.x;\\n if (n >= p.N) { return; }\\n let wRow = n * (p.K / 32u);\\n let sbase = n * p.nb;\\n let Kvec = p.K / 4u;\\n\\n var acc: array<f32, 9>; // M <= 9\\n for (var m = 0u; m < p.M; m = m + 1u) { acc[m] = 0.0; }\\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\\n let k = gi * 4u;\\n let word = signbits[wRow + (k >> 5u)];\\n let bits4 = (word >> (k & 31u)) & 0xfu;\\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\\n let s = scales[sbase + (k / 128u)];\\n for (var m = 0u; m < p.M; m = m + 1u) {\\n acc[m] = acc[m] + dot(x[m * Kvec + gi], sv) * s;\\n }\\n }\\n for (var m = 0u; m < p.M; m = m + 1u) {\\n let total = subgroupAdd(acc[m]);\\n if (lane == 0u) { y[m * p.N + n] = total + resid[m * p.N + n]; }\\n }\\n}\\n\",\n \"matmul_resid_tiled\": \"// Tiled register-blocked binary GEMM with fused residual, for PREFILL (M>1), vec4 K-accumulation:\\n// y[M,N] = x[M,K] @ W[N,K]^T + resid[M,N], W binary {-1,+1} sign-packed, per-128-block fp32 scale.\\n// 64x64 output tile per workgroup, 16x16 threads each computing a 4x4 register tile, BK=16 K-step.\\n// Activation + decoded/scaled weight tiles are staged in shared memory as vec4 (4 K per element);\\n// each inner step is a dot() of vec4s, and one weight load decodes a whole nibble (4 signs) at once.\\n// No subgroup ops -> all devices. Near-bit-exact (f32 accum; tiled K-order differs in last ULPs).\\nconst BM: u32 = 64u;\\nconst BN: u32 = 64u;\\nconst BKV: u32 = 4u; // BK / 4 (BK = 16)\\nstruct Params { M: u32, N: u32, K: u32, nb: u32, _0: u32, _1: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4]\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\\n@group(0) @binding(4) var<storage, read> resid: array<f32>; // [M, N]\\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [M, N]\\n\\nvar<workgroup> xs: array<vec4<f32>, 256>; // BM*BKV\\nvar<workgroup> ws: array<vec4<f32>, 256>; // BN*BKV\\n\\n@compute @workgroup_size(256)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\\n let tid = lid.x;\\n let tileM = wg.y * BM;\\n let tileN = wg.x * BN;\\n let tr = (tid / 16u) * 4u;\\n let tc = (tid % 16u) * 4u;\\n let Kv = p.K / 4u;\\n var acc: array<f32, 16>;\\n for (var i = 0u; i < 16u; i = i + 1u) { acc[i] = 0.0; }\\n\\n let Ksteps = Kv / BKV;\\n for (var ks = 0u; ks < Ksteps; ks = ks + 1u) {\\n let k0v = ks * BKV;\\n for (var e = tid; e < BM * BKV; e = e + 256u) { // stage activation tile (vec4)\\n let m = e / BKV; let kv = e % BKV; let gm = tileM + m;\\n xs[e] = select(vec4<f32>(0.0), x[gm * Kv + (k0v + kv)], gm < p.M);\\n }\\n for (var e = tid; e < BN * BKV; e = e + 256u) { // stage decoded+scaled weight tile (vec4)\\n let n = e / BKV; let kv = e % BKV; let gn = tileN + n; let k = (k0v + kv) * 4u;\\n var wv = vec4<f32>(0.0);\\n if (gn < p.N) {\\n let bits4 = (signbits[gn * (p.K / 32u) + (k >> 5u)] >> (k & 31u)) & 0xfu;\\n let s = scales[gn * p.nb + (k / 128u)];\\n wv = vec4<f32>(select(-s, s, (bits4 & 1u) != 0u), select(-s, s, (bits4 & 2u) != 0u),\\n select(-s, s, (bits4 & 4u) != 0u), select(-s, s, (bits4 & 8u) != 0u));\\n }\\n ws[e] = wv;\\n }\\n workgroupBarrier();\\n for (var kv = 0u; kv < BKV; kv = kv + 1u) {\\n var xr: array<vec4<f32>, 4>;\\n for (var tm = 0u; tm < 4u; tm = tm + 1u) { xr[tm] = xs[(tr + tm) * BKV + kv]; }\\n for (var tn = 0u; tn < 4u; tn = tn + 1u) {\\n let w = ws[(tc + tn) * BKV + kv];\\n for (var tm = 0u; tm < 4u; tm = tm + 1u) { acc[tm * 4u + tn] = acc[tm * 4u + tn] + dot(xr[tm], w); }\\n }\\n }\\n workgroupBarrier();\\n }\\n\\n for (var tm = 0u; tm < 4u; tm = tm + 1u) {\\n let gm = tileM + tr + tm;\\n if (gm < p.M) {\\n for (var tn = 0u; tn < 4u; tn = tn + 1u) {\\n let gn = tileN + tc + tn;\\n if (gn < p.N) { let idx = gm * p.N + gn; y[idx] = acc[tm * 4u + tn] + resid[idx]; }\\n }\\n }\\n }\\n}\\n\",\n \"matmul_resid_wg\": \"// No-subgroup fallback: split-K GEMV for decode (M=1) with fused residual, workgroup-shared-memory\\n// reduction. One workgroup per output column; WG threads split K and tree-reduce. Used for o_proj/down.\\noverride WG: u32 = 64u;\\nstruct Params { N: u32, K: u32, nb: u32, gridX: u32, _p0: u32, _p1: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\\n@group(0) @binding(4) var<storage, read> resid: array<f32>; // [N]\\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [N]\\nvar<workgroup> sdata: array<f32, 256>;\\n\\n@compute @workgroup_size(WG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\\n let n = wg.y * p.gridX + wg.x;\\n if (n >= p.N) { return; }\\n let tid = lid.x;\\n let wRow = n * (p.K / 32u);\\n let sbase = n * p.nb;\\n let Kvec = p.K / 4u;\\n var acc = 0.0;\\n for (var gi = tid; gi < Kvec; gi = gi + WG) {\\n let k = gi * 4u;\\n let word = signbits[wRow + (k >> 5u)];\\n let bits4 = (word >> (k & 31u)) & 0xfu;\\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\\n acc = acc + dot(x[gi], sv) * scales[sbase + (k / 128u)];\\n }\\n sdata[tid] = acc;\\n workgroupBarrier();\\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\\n if (tid < s) { sdata[tid] = sdata[tid] + sdata[tid + s]; }\\n workgroupBarrier();\\n }\\n if (tid == 0u) { y[n] = sdata[0] + resid[n]; }\\n}\\n\",\n \"matmul_split\": \"// Fused binary matmul writing to up to 3 output buffers (qkv or gate/up in one dispatch).\\n// Weights for the outputs are concatenated along N (rows N0 | N1 | N2). One thread per\\n// output column n routes its result to out0/out1/out2 by range. Vectorized like matmul_binary_vec4.\\nstruct Params { M: u32, K: u32, nb: u32, N0: u32, N1: u32, N2: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4]\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\\n\\n@compute @workgroup_size(64)\\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\\n let Ntot = p.N0 + p.N1 + p.N2;\\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\\n if (idx >= p.M * Ntot) { return; }\\n let row = idx / Ntot;\\n let n = idx % Ntot;\\n let xRow = row * (p.K / 4u);\\n let wRow = n * (p.K / 32u);\\n let sbase = n * p.nb;\\n\\n var acc = 0.0;\\n for (var b = 0u; b < p.nb; b = b + 1u) {\\n var bsum = 0.0;\\n for (var w = 0u; w < 4u; w = w + 1u) {\\n let word = signbits[wRow + b * 4u + w];\\n let xb = xRow + b * 32u + w * 8u;\\n for (var g = 0u; g < 8u; g = g + 1u) {\\n let bits4 = (word >> (g * 4u)) & 0xfu;\\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\\n bsum = bsum + dot(x[xb + g], sv);\\n }\\n }\\n acc = acc + bsum * scales[sbase + b];\\n }\\n\\n if (n < p.N0) { out0[row * p.N0 + n] = acc; }\\n else if (n < p.N0 + p.N1) { out1[row * p.N1 + (n - p.N0)] = acc; }\\n else { out2[row * p.N2 + (n - p.N0 - p.N1)] = acc; }\\n}\\n\",\n \"matmul_split_sg\": \"// Subgroup split-K GEMV for decode (M=1), fused: one subgroup (= one workgroup) per output\\n// column; lanes split the K dimension and reduce with subgroupAdd (register-only, no barriers).\\n// Cuts each matmul's latency ~SG-fold vs one-thread-per-output (the real decode bottleneck:\\n// kernels run at full latency in the dependent chain). Routes to out0/out1/out2 by range (qkv / gate-up).\\nenable subgroups;\\noverride SG: u32 = 32u;\\nstruct Params { K: u32, nb: u32, N0: u32, N1: u32, N2: u32, gridX: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\\n\\n@compute @workgroup_size(SG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\\n let Ntot = p.N0 + p.N1 + p.N2;\\n let n = wg.y * p.gridX + wg.x;\\n if (n >= Ntot) { return; }\\n let wRow = n * (p.K / 32u);\\n let sbase = n * p.nb;\\n let Kvec = p.K / 4u;\\n\\n var acc = 0.0;\\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\\n let k = gi * 4u;\\n let word = signbits[wRow + (k >> 5u)];\\n let bits4 = (word >> (k & 31u)) & 0xfu;\\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\\n acc = acc + dot(x[gi], sv) * scales[sbase + (k / 128u)];\\n }\\n let total = subgroupAdd(acc);\\n if (lane == 0u) {\\n if (n < p.N0) { out0[n] = total; }\\n else if (n < p.N0 + p.N1) { out1[n - p.N0] = total; }\\n else { out2[n - p.N0 - p.N1] = total; }\\n }\\n}\\n\",\n \"matmul_split_sm\": \"// Small-batch (M = 2..9) subgroup split-K GEMV, fused qkv / gate-up. The speculative-decode\\n// verify pass computes M drafted rows in one forward; the scalar prefill kernels re-read the\\n// weights per output thread, so a k-row pass cost ~k GEMVs. Here each weight word is loaded\\n// ONCE per (column, k-chunk) and dotted with all M activation rows (activations are ~8 KB/row,\\n// cache-resident). Per row the loop stride and accumulation expression are IDENTICAL to\\n// matmul_split_sg, so each row's partials - and therefore the subgroupAdd result - match the\\n// M=1 decode path bit-for-bit.\\nenable subgroups;\\noverride SG: u32 = 32u;\\nstruct Params { K: u32, nb: u32, N0: u32, N1: u32, N2: u32, gridX: u32, M: u32, _pad: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4] row-major\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>; // [M, N0]\\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>; // [M, N1]\\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>; // [M, N2]\\n\\n@compute @workgroup_size(SG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\\n let Ntot = p.N0 + p.N1 + p.N2;\\n let n = wg.y * p.gridX + wg.x;\\n if (n >= Ntot) { return; } // uniform per workgroup: the whole subgroup exits together\\n let wRow = n * (p.K / 32u);\\n let sbase = n * p.nb;\\n let Kvec = p.K / 4u;\\n\\n var acc: array<f32, 9>; // M <= 9\\n for (var m = 0u; m < p.M; m = m + 1u) { acc[m] = 0.0; }\\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\\n let k = gi * 4u;\\n let word = signbits[wRow + (k >> 5u)];\\n let bits4 = (word >> (k & 31u)) & 0xfu;\\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\\n let s = scales[sbase + (k / 128u)];\\n for (var m = 0u; m < p.M; m = m + 1u) {\\n acc[m] = acc[m] + dot(x[m * Kvec + gi], sv) * s;\\n }\\n }\\n for (var m = 0u; m < p.M; m = m + 1u) { // p.M is uniform: collective calls stay uniform\\n let total = subgroupAdd(acc[m]);\\n if (lane == 0u) {\\n if (n < p.N0) { out0[m * p.N0 + n] = total; }\\n else if (n < p.N0 + p.N1) { out1[m * p.N1 + (n - p.N0)] = total; }\\n else { out2[m * p.N2 + (n - p.N0 - p.N1)] = total; }\\n }\\n }\\n}\\n\",\n \"matmul_split_tiled\": \"// Tiled register-blocked binary GEMM to 3 outputs (qkv or gate/up), PREFILL (M>1), vec4 K-accum.\\n// Weights concatenated along N (N0|N1|N2); each output element routes individually to\\n// out0/out1/out2 by its global column, so N0/N1/N2 need no alignment. Same vec4 design as\\n// matmul_resid_tiled.\\nconst BM: u32 = 64u;\\nconst BN: u32 = 64u;\\nconst BKV: u32 = 4u; // BK / 4 (BK = 16)\\nstruct Params { M: u32, K: u32, nb: u32, N0: u32, N1: u32, N2: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4]\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\\n\\nvar<workgroup> xs: array<vec4<f32>, 256>;\\nvar<workgroup> ws: array<vec4<f32>, 256>;\\n\\n@compute @workgroup_size(256)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\\n let Ntot = p.N0 + p.N1 + p.N2;\\n let tid = lid.x;\\n let tileM = wg.y * BM;\\n let tileN = wg.x * BN;\\n let tr = (tid / 16u) * 4u;\\n let tc = (tid % 16u) * 4u;\\n let Kv = p.K / 4u;\\n var acc: array<f32, 16>;\\n for (var i = 0u; i < 16u; i = i + 1u) { acc[i] = 0.0; }\\n\\n let Ksteps = Kv / BKV;\\n for (var ks = 0u; ks < Ksteps; ks = ks + 1u) {\\n let k0v = ks * BKV;\\n for (var e = tid; e < BM * BKV; e = e + 256u) {\\n let m = e / BKV; let kv = e % BKV; let gm = tileM + m;\\n xs[e] = select(vec4<f32>(0.0), x[gm * Kv + (k0v + kv)], gm < p.M);\\n }\\n for (var e = tid; e < BN * BKV; e = e + 256u) {\\n let n = e / BKV; let kv = e % BKV; let gn = tileN + n; let k = (k0v + kv) * 4u;\\n var wv = vec4<f32>(0.0);\\n if (gn < Ntot) {\\n let bits4 = (signbits[gn * (p.K / 32u) + (k >> 5u)] >> (k & 31u)) & 0xfu;\\n let s = scales[gn * p.nb + (k / 128u)];\\n wv = vec4<f32>(select(-s, s, (bits4 & 1u) != 0u), select(-s, s, (bits4 & 2u) != 0u),\\n select(-s, s, (bits4 & 4u) != 0u), select(-s, s, (bits4 & 8u) != 0u));\\n }\\n ws[e] = wv;\\n }\\n workgroupBarrier();\\n for (var kv = 0u; kv < BKV; kv = kv + 1u) {\\n var xr: array<vec4<f32>, 4>;\\n for (var tm = 0u; tm < 4u; tm = tm + 1u) { xr[tm] = xs[(tr + tm) * BKV + kv]; }\\n for (var tn = 0u; tn < 4u; tn = tn + 1u) {\\n let w = ws[(tc + tn) * BKV + kv];\\n for (var tm = 0u; tm < 4u; tm = tm + 1u) { acc[tm * 4u + tn] = acc[tm * 4u + tn] + dot(xr[tm], w); }\\n }\\n }\\n workgroupBarrier();\\n }\\n\\n for (var tm = 0u; tm < 4u; tm = tm + 1u) {\\n let gm = tileM + tr + tm;\\n if (gm >= p.M) { continue; }\\n for (var tn = 0u; tn < 4u; tn = tn + 1u) {\\n let gn = tileN + tc + tn;\\n if (gn >= Ntot) { continue; }\\n let v = acc[tm * 4u + tn];\\n if (gn < p.N0) { out0[gm * p.N0 + gn] = v; }\\n else if (gn < p.N0 + p.N1) { out1[gm * p.N1 + (gn - p.N0)] = v; }\\n else { out2[gm * p.N2 + (gn - p.N0 - p.N1)] = v; }\\n }\\n }\\n}\\n\",\n \"matmul_split_wg\": \"// No-subgroup fallback: split-K GEMV for decode (M=1), workgroup-shared-memory reduction instead\\n// of subgroupAdd. One workgroup per output column; WG threads split K and tree-reduce via shared\\n// memory + barriers. ~WG-fold faster than one-thread-per-output (the v1 path). Routes qkv / gate-up.\\noverride WG: u32 = 64u;\\nstruct Params { K: u32, nb: u32, N0: u32, N1: u32, N2: u32, gridX: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\\nvar<workgroup> sdata: array<f32, 256>; // >= max WG\\n\\n@compute @workgroup_size(WG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\\n let Ntot = p.N0 + p.N1 + p.N2;\\n let n = wg.y * p.gridX + wg.x; // uniform across the workgroup -> early return is barrier-safe\\n if (n >= Ntot) { return; }\\n let tid = lid.x;\\n let wRow = n * (p.K / 32u);\\n let sbase = n * p.nb;\\n let Kvec = p.K / 4u;\\n var acc = 0.0;\\n for (var gi = tid; gi < Kvec; gi = gi + WG) {\\n let k = gi * 4u;\\n let word = signbits[wRow + (k >> 5u)];\\n let bits4 = (word >> (k & 31u)) & 0xfu;\\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\\n acc = acc + dot(x[gi], sv) * scales[sbase + (k / 128u)];\\n }\\n sdata[tid] = acc;\\n workgroupBarrier();\\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\\n if (tid < s) { sdata[tid] = sdata[tid] + sdata[tid + s]; }\\n workgroupBarrier();\\n }\\n if (tid == 0u) {\\n let total = sdata[0];\\n if (n < p.N0) { out0[n] = total; }\\n else if (n < p.N0 + p.N1) { out1[n - p.N0] = total; }\\n else { out2[n - p.N0 - p.N1] = total; }\\n }\\n}\\n\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"sampler_penalty\": \"// GPU logits pre-filter for sampling: applies repetition_penalty then no_repeat_ngram bans in place\\n// on the full vocab logit buffer, so only a tiny top-K candidate set has to be read back (not all\\n// ~151k logits). Matches transformers.js exactly: rep_penalty over the DEDUPED prompt+generated id\\n// set (logit<0 ? *penalty : /penalty), then ngram-banned next-tokens set to -Infinity. Both id lists\\n// are computed on the CPU each step (exact, since at syncN=1 the full history is known) and uploaded.\\n// Temperature is NOT applied here: top-k is invariant under the monotonic divide, so temperature is\\n// applied on the CPU to just the K candidate values before softmax (bit-identical, one less pass).\\n// Single workgroup, no subgroup ops -> all devices. The storageBarrier guarantees every penalty\\n// write lands before any ban write, so a token that is both repeated and ngram-banned ends at -inf\\n// (ban wins, matching the reference order rep_penalty -> ngram).\\noverride WG: u32 = 256u;\\n// negInf carries the -Infinity bit pattern (0xff800000) from the host: bitcasting it at RUNTIME yields\\n// -inf, whereas bitcast<f32>(0xff800000u) is a const-expression evaluating to inf, which is a WGSL\\n// shader-creation error. (Runtime inf is fine; only const/override inf/nan is rejected.)\\nstruct Params { affectedLen: u32, banLen: u32, penalty: f32, negInf: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> affectedIds: array<u32>; // deduped prompt+generated ids\\n@group(0) @binding(2) var<storage, read> banIds: array<u32>; // ngram-banned next-token ids\\n@group(0) @binding(3) var<storage, read_write> logits: array<f32>; // [vocab], modified in place\\n\\n@compute @workgroup_size(WG)\\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\\n let tid = lid.x;\\n for (var i = tid; i < p.affectedLen; i = i + WG) {\\n let t = affectedIds[i];\\n let v = logits[t];\\n if (v < 0.0) { logits[t] = v * p.penalty; } else { logits[t] = v / p.penalty; }\\n }\\n storageBarrier(); // all penalty writes before any ban write\\n for (var i = tid; i < p.banLen; i = i + WG) {\\n logits[banIds[i]] = bitcast<f32>(p.negInf); // -Infinity (runtime bitcast)\\n }\\n}\\n\",\n \"swiglu\": \"// SwiGLU gate: y[i] = silu(gate[i]) * up[i], silu(g) = g * sigmoid(g). One invocation per element.\\nstruct Params { n: u32, _p0: u32, _p1: u32, _p2: u32 };\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> gate: array<f32>;\\n@group(0) @binding(2) var<storage, read> up: array<f32>;\\n@group(0) @binding(3) var<storage, read_write> y: array<f32>;\\n\\n@compute @workgroup_size(64)\\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\\n if (i >= p.n) { return; }\\n let g = gate[i];\\n y[i] = (g / (1.0 + exp(-g))) * up[i];\\n}\\n\",\n}\n","/** Thrown when WebGPU is unavailable: no `navigator.gpu` (unsupported browser, or a\n * non-secure context) or no adapter could be acquired. Catch this to render a\n * \"your browser doesn't support WebGPU yet\" fallback instead of crashing. */\nexport class WebGPUUnavailableError extends Error {\n override readonly name = 'WebGPUUnavailableError'\n constructor(message: string) {\n super(message)\n }\n}\n\n/** Thrown when the GPU reports out-of-memory while the engine allocates weights or grows the\n * KV cache. Without this check the allocation \"succeeds\" with invalid buffers and every later\n * generate() returns garbage. Catch it to fall back (smaller maxSeqLen, or a no-LLM mode). */\nexport class GpuOutOfMemoryError extends Error {\n override readonly name = 'GpuOutOfMemoryError'\n constructor(message: string) {\n super(message)\n }\n}\n","// Prompt-lookup drafting (the CPU half of speculative decoding). No draft model: the draft is\n// the continuation that followed the most recent prior occurrence of the sequence's trailing\n// n-gram. High hit rate whenever the model repeats sequence content (quoting RAG context,\n// lists, code); zero cost when nothing matches (no draft -> a normal single-token step).\n\n/** Return up to `maxDraft` draft tokens: the continuation after the most recent prior occurrence\n * of the trailing g-gram, trying g = ngramSize down to 2 (1-grams draft too noisily to pay off).\n * Empty when nothing matches. */\nexport function draftNgram(seq: readonly number[], ngramSize: number, maxDraft: number): number[] {\n if (maxDraft <= 0) return []\n for (let g = Math.min(ngramSize, seq.length - 1); g >= 2; g--) {\n const start = seq.length - g // the trailing g-gram lives at [start, seq.length)\n outer: for (let i = start - 1; i >= 0; i--) {\n for (let j = 0; j < g; j++) if (seq[i + j] !== seq[start + j]) continue outer\n const from = i + g // i <= start-1, so from <= seq.length-1: at least one token follows\n return seq.slice(from, Math.min(from + maxDraft, seq.length))\n }\n }\n return []\n}\n\n/** Number of tokens promptLookup:'auto' emits through the PLD path before deciding whether\n * speculating actually pays on this content. */\nexport const PLD_PROBATION = 24\n\n/** The auto-bail decision after the probation window: keep speculating only when the measured\n * tokens-per-verify-step clears the break-even against PLAIN decoding, which differs by mode.\n * Each PLD step costs one batched verify forward plus a per-step CPU sync; plain GREEDY chains\n * several steps per sync (GPU-resident argmax), so its break-even is high (~2.0 tokens/step,\n * measured), while plain SAMPLED syncs every token anyway (~1.5). Below the bar, the rest of\n * the turn runs the plain path - output is identical either way, only speed changes. */\nexport function pldWorthIt(emitted: number, steps: number, sampled: boolean): boolean {\n if (steps <= 0) return false\n return emitted / steps >= (sampled ? 1.5 : 2.0)\n}\n","// CPU side of the sampler. All the correctness-bearing probability math lives here (not in WGSL) so\n// it can be bit-checked against transformers.js in Node. The GPU only pre-filters logits\n// (repetition_penalty + no_repeat_ngram bans) and reduces to the top-K; this module computes the\n// CPU-side inputs (deduped id set, ngram ban list) and does the final temperature + softmax +\n// multinomial draw over the K candidates. Faithful port of transformers.js v4.2.0 semantics:\n// chain: repetition_penalty -> no_repeat_ngram -> temperature -> top_k -> softmax -> multinomial\n// (top_p, top_k warper, bad_words, min_length are not applied in that version).\n\n/** Mersenne Twister 19937, matching transformers.js utils/random.js (= Python's random.Random). */\nexport class MT19937 {\n private mt = new Uint32Array(624)\n private idx = 625\n\n constructor(seed?: number) {\n this.seed(seed)\n }\n\n seed(n?: number): void {\n if (n === undefined || n === null) {\n const buf = new Uint32Array(1)\n crypto.getRandomValues(buf)\n n = buf[0]\n }\n const mt = this.mt\n const u = (a: number, b: number): number => Math.imul(a, b) >>> 0\n const key: number[] = []\n for (let v = n || 0; v > 0; v = Math.floor(v / 0x100000000)) key.push(v & 0xffffffff)\n if (!key.length) key.push(0)\n mt[0] = 19650218\n for (let k = 1; k < 624; ++k) mt[k] = (u(1812433253, mt[k - 1] ^ (mt[k - 1] >>> 30)) + k) >>> 0\n let i = 1\n let j = 0\n for (let k = Math.max(624, key.length); k > 0; --k, ++i, ++j) {\n if (i >= 624) {\n mt[0] = mt[623]\n i = 1\n }\n if (j >= key.length) j = 0\n mt[i] = ((mt[i] ^ u(mt[i - 1] ^ (mt[i - 1] >>> 30), 1664525)) + key[j] + j) >>> 0\n }\n for (let k = 623; k > 0; --k, ++i) {\n if (i >= 624) {\n mt[0] = mt[623]\n i = 1\n }\n mt[i] = ((mt[i] ^ u(mt[i - 1] ^ (mt[i - 1] >>> 30), 1566083941)) - i) >>> 0\n }\n mt[0] = 0x80000000\n this.idx = 624\n }\n\n private int32(): number {\n const mt = this.mt\n if (this.idx >= 624) {\n for (let k = 0; k < 624; ++k) {\n const y = (mt[k] & 0x80000000) | (mt[(k + 1) % 624] & 0x7fffffff)\n mt[k] = (mt[(k + 397) % 624] ^ (y >>> 1) ^ (y & 1 ? 0x9908b0df : 0)) >>> 0\n }\n this.idx = 0\n }\n let y = mt[this.idx++]\n y ^= y >>> 11\n y ^= (y << 7) & 0x9d2c5680\n y ^= (y << 15) & 0xefc60000\n y ^= y >>> 18\n return y >>> 0\n }\n\n /** Uniform float in [0, 1), matching Python's random.random(). */\n random(): number {\n return ((this.int32() >>> 5) * 67108864.0 + (this.int32() >>> 6)) / 9007199254740992.0\n }\n}\n\n/** Deduped set of token ids that repetition_penalty applies to (the full prompt+generated history). */\nexport function affectedIds(history: number[]): Uint32Array {\n return Uint32Array.from(new Set(history))\n}\n\n/** no_repeat_ngram banned next-tokens for the current step. Faithful port of\n * NoRepeatNGramLogitsProcessor.calcBannedNgramTokens (transformers.js v4.2.0). */\nexport function ngramBans(history: number[], n: number): number[] {\n if (history.length + 1 < n) return []\n const generated = new Map<string, number[]>()\n for (let j = 0; j < history.length + 1 - n; ++j) {\n const ngram: number[] = []\n for (let k = 0; k < n; ++k) ngram.push(history[j + k])\n const key = JSON.stringify(ngram.slice(0, n - 1))\n const arr = generated.get(key) ?? []\n arr.push(ngram[n - 1])\n generated.set(key, arr)\n }\n const idx = history.slice(history.length + 1 - n, history.length)\n return generated.get(JSON.stringify(idx)) ?? []\n}\n\n/** Stable softmax (max-subtract), matching transformers.js utils/maths.js softmax. */\nfunction softmax(arr: Float32Array | number[]): number[] {\n let maxVal = arr[0]\n for (let i = 1; i < arr.length; ++i) if (arr[i] > maxVal) maxVal = arr[i]\n const exps = Array.from(arr, (x) => Math.exp(x - maxVal))\n let sum = 0\n for (const e of exps) sum += e\n return exps.map((x) => x / sum)\n}\n\n/** Final sampling tail. `candVals` are the K largest PENALTY-FILTERED logits (descending), `candIds`\n * their token ids. Applies temperature to the K values, softmaxes, then draws via the exact\n * transformers.js inverse-CDF weighted pick (x = random()*sum; subtract until <0). Returns a token id. */\nexport function sampleFromCandidates(candIds: Uint32Array | number[], candVals: Float32Array | number[], temperature: number, rng: MT19937): number {\n const k = candVals.length\n const tv = new Float32Array(k)\n for (let i = 0; i < k; ++i) tv[i] = candVals[i] / temperature // divide (exact for any T), matches TemperatureLogitsWarper\n const probs = softmax(tv)\n let sum = 0\n for (const pr of probs) sum += pr\n let x = rng.random() * sum\n for (let i = 0; i < k; ++i) {\n x -= probs[i]\n if (x < 0) return candIds[i]\n }\n return candIds[k - 1] // floating-point guard, matches _weightedIndexWith\n}\n","// WebGPU runtime for 1-bit Qwen3-family models (Bonsai 1.7B/4B/8B and any q1 export whose\n// manifest passes the load-time contract). Loads binary (1-bit) weights via the manifest,\n// runs the forward with the validated kernels, keeps a persistent KV cache, and generates\n// autoregressively. Decode is dispatch-overhead-bound, so the matmuls are fused (q/k/v in one\n// dispatch, gate/up in one, the residual add folded into o_proj/down_proj) and the decode loop\n// is GPU-resident (GPU argmax + embedding gather) with deferred CPU sync + pooled resources.\n//\n// This is a faithful port of the validated engine.js: the kernel sequence and numerics are\n// unchanged (bit-exact). Only the shader source (now inlined, not fetched), the configuration\n// (now typed options, not URL params), and the public surface differ.\nimport { SHADERS } from './shaders.generated'\nimport { GpuOutOfMemoryError, WebGPUUnavailableError } from './errors'\nimport { draftNgram, pldWorthIt, PLD_PROBATION } from './pld'\nimport { MT19937, affectedIds, ngramBans, sampleFromCandidates } from './sampler'\nimport type {\n DeviceLostInfo,\n Engine,\n EngineCapabilities,\n EngineOptions,\n ForwardResult,\n GenerateOptions,\n GenerateResult,\n KvSnapshot,\n TokenLogprobs,\n} from './types'\n\ntype Field = ['f' | 'u', number]\n\ninterface Ref {\n src?: string\n dtype: string\n off: number\n len: number\n}\ninterface MTensor {\n kind?: string\n N?: number\n K?: number\n rows?: number\n cols?: number\n block?: number\n /** v2 manifests: 'q1_0' marks a tensor whose weight ref covers an interleaved GGUF\n * Q1_0 region ([f16 scale][16 sign bytes] per 128-weight block); the loader demuxes\n * it in-flight into the planar sign/scale buffers the kernels consume. */\n container?: string\n /** normalized at load: the raw interleaved region of a container tensor */\n q1_0?: Ref\n weight?: Ref\n scales?: Ref\n zp?: Ref\n // cos_cache / sin_cache are stored as bare refs:\n src?: string\n dtype?: string\n off?: number\n len?: number\n}\ninterface Arch {\n layers: number\n hidden: number\n intermediate: number\n heads: number\n kv_heads: number\n head_dim: number\n rms_eps: number\n vocab: number\n eos: number\n act: string\n /** rope parameters for manifests without baked cos/sin caches (v2/GGUF) */\n rope?: { rope_theta: number; rope_type?: string; factor?: number; original_max_position_embeddings?: number }\n /** position cap for synthesized rope (GGUF context_length) */\n max_positions?: number\n}\ninterface Manifest {\n version?: number\n data_file: string\n aux_file: string\n arch: Arch\n luts: Record<string, Ref>\n tensors: Record<string, MTensor>\n}\n\ninterface GpuWeight {\n buf?: GPUBuffer\n sign?: GPUBuffer\n scales?: GPUBuffer\n codes?: GPUBuffer\n N?: number\n K?: number\n nb?: number\n N0?: number\n N1?: number\n N2?: number\n zp?: number\n}\n\ninterface RawGenResult {\n prefillMs: number\n decodeMs: number\n tokPerSec: number\n tokens: number[]\n firstArgmax: number\n recMs: number\n gpuMs: number\n rbMs: number\n spec?: { steps: number; drafted: number; accepted: number; bailed?: boolean }\n /** The sampler RNG as it stands after this call - promptLookup:'auto' hands it to the plain\n * continuation so the draw stream continues exactly where the probation left off. */\n rng?: MT19937\n /** Per-emitted-token logprob records (sampled path only, when GenerateOptions.logprobs set). */\n lp?: TokenLogprobs[]\n}\n\n/** Internal engine handle: the public {@link Engine} surface plus diagnostics used by the\n * correctness/benchmark harness. The diagnostics are intentionally not in the public type. */\ninterface EngineInternal extends Engine {\n device: GPUDevice\n adapter: GPUAdapter\n /** Raw decode with the per-kernel profiling switch (`full`) and sync depth exposed. */\n profileDecode(ids: number[], nTokens: number, full?: Set<string> | null, syncN?: number): Promise<RawGenResult>\n /** Differential debug: one decode step through the fast and slow paths, checkpoint by checkpoint. */\n debugDecode(prefillIds: number[]): Promise<{ fast: Record<string, Float32Array>; slow: Record<string, Float32Array> }>\n /** Debug: GPU base + penalized logits + top-K for a prefill, to diff the sampler kernels vs CPU math. */\n debugSampler(ids: number[], genOpts: GenerateOptions): Promise<{ base: Float32Array; penalized: Float32Array; candIds: Uint32Array; candVals: Float32Array }>\n}\n\ntype TypedArrayCtor = Float32ArrayConstructor | Uint8ArrayConstructor | Uint16ArrayConstructor\nconst VIEW: Record<string, TypedArrayCtor> = { FLOAT: Float32Array, UINT8: Uint8Array, FLOAT16: Uint16Array }\nconst WGSLS = ['matmul_split', 'matmul_resid', 'matmul_q2', 'rope', 'swiglu', 'copy']\nconst DEFAULT_MAX_SEQ = 2048\nconst PREFILL_SEG = 256 // prefill segment length; see runPrefill for why prefills are segmented\n\nconst PARAM_AB = new ArrayBuffer(64)\nconst PARAM_DV = new DataView(PARAM_AB)\nconst PARAM_U8 = new Uint8Array(PARAM_AB)\nfunction makeParams(fields: Field[]): Uint8Array {\n // fills a reused buffer (no per-dispatch alloc)\n for (let i = 0; i < fields.length; i++) {\n const f = fields[i]\n if (f[0] === 'f') PARAM_DV.setFloat32(i * 4, f[1], true)\n else PARAM_DV.setUint32(i * 4, f[1] >>> 0, true)\n }\n return PARAM_U8.subarray(0, Math.ceil(fields.length / 4) * 16)\n}\nconst eqBytes = (a: Uint8Array, b: Uint8Array): boolean => {\n for (let i = 0; i < b.length; i++) if (a[i] !== b[i]) return false\n return true\n}\n/** Synthesize f32 rope tables ([positions, head_dim/2]) from arch.rope for manifests without\n * baked caches (v2/GGUF). Plain rope or YaRN (transformers formula: beta_fast 32, beta_slow 1,\n * mscale = 0.1*ln(factor)+1). Angles accumulate in f64 and round once to f32 per entry -\n * tools/reference.py implements the identical recipe for fixture generation. */\nfunction synthRope(A: { head_dim: number; rope?: { rope_theta: number; rope_type?: string; factor?: number; original_max_position_embeddings?: number } }, positions: number): [Float32Array, Float32Array] {\n const half = A.head_dim / 2\n const rope = A.rope!\n const base = rope.rope_theta\n const factor = rope.rope_type === 'yarn' ? (rope.factor ?? 1) : 1\n const inv = new Float64Array(half)\n // YaRN ramp bounds (only used when factor > 1): dims below lo keep the original\n // frequencies (extrapolation), dims above hi interpolate by 1/factor, between them blends.\n const orig = rope.original_max_position_embeddings ?? 0\n const lo = factor === 1 ? 0 : Math.max(0, Math.floor((A.head_dim * Math.log(orig / (32 * 2 * Math.PI))) / (2 * Math.log(base))))\n const hi = factor === 1 ? 0 : Math.min(half - 1, Math.ceil((A.head_dim * Math.log(orig / (2 * Math.PI))) / (2 * Math.log(base))))\n for (let j = 0; j < half; j++) {\n const pf = base ** ((2 * j) / A.head_dim)\n if (factor === 1) {\n inv[j] = 1 / pf\n continue\n }\n const ramp = Math.min(1, Math.max(0, (j - lo) / (hi - lo)))\n inv[j] = (1 / (factor * pf)) * ramp + (1 / pf) * (1 - ramp)\n }\n const mscale = factor === 1 ? 1 : Math.fround(0.1 * Math.log(factor) + 1)\n const cos = new Float32Array(positions * half)\n const sin = new Float32Array(positions * half)\n for (let p = 0; p < positions; p++)\n for (let j = 0; j < half; j++) {\n const a = p * inv[j]\n cos[p * half + j] = Math.fround(Math.cos(a) * mscale)\n sin[p * half + j] = Math.fround(Math.sin(a) * mscale)\n }\n return [cos, sin]\n}\n/** Load a 1-bit model and return an {@link Engine}. Pass a model URL string for defaults. */\nexport async function createEngine(options: EngineOptions | string): Promise<Engine> {\n // Any load failure after the device exists (WGSL compile error, manifest validation, truncated\n // download, allocation OOM) must destroy the device, or the partially-loaded weights stay\n // resident until GC collects the GPUDevice - undermining the catch-OOM-and-retry-smaller advice\n // in errors.ts, since the retry contends with the dead engine's VRAM.\n const holder: { device?: GPUDevice } = {}\n try {\n return await createEngineInner(options, holder)\n } catch (e) {\n holder.device?.destroy()\n throw e\n }\n}\nasync function createEngineInner(options: EngineOptions | string, holder: { device?: GPUDevice }): Promise<Engine> {\n const opts: EngineOptions = typeof options === 'string' ? { modelUrl: options } : options\n const modelDir = opts.modelUrl ? opts.modelUrl.replace(/\\/$/, '') : null\n if (!modelDir && !opts.manifestUrl) throw new Error('createEngine: provide modelUrl or manifestUrl')\n const powerPreference = opts.powerPreference ?? 'high-performance'\n const fetchJson =\n opts.fetchJson ??\n (async (url: string) => {\n const res = await fetch(url)\n if (!res.ok) throw new Error(`bitgpu: fetch ${url} failed: HTTP ${res.status}`)\n if ((res.headers.get('content-type') ?? '').includes('text/html'))\n throw new Error(`bitgpu: ${url} returned HTML, not JSON (a SPA fallback is probably serving index.html for missing model files)`)\n return res.json()\n })\n const fetchBytes =\n opts.fetchArrayBuffer ??\n (async (url: string) => {\n const res = await fetch(url)\n if (!res.ok) throw new Error(`bitgpu: fetch ${url} failed: HTTP ${res.status}`)\n const total = Number(res.headers.get('content-length') ?? 0)\n if (!res.body || !total) return res.arrayBuffer()\n // Stream so onProgress can report the (multi-hundred-MB) weights download.\n const reader = res.body.getReader()\n const chunks: Uint8Array[] = []\n let loaded = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n chunks.push(value)\n loaded += value.byteLength\n opts.onProgress?.({ phase: 'weights', loaded, total })\n }\n const out = new Uint8Array(loaded)\n let p = 0\n for (const c of chunks) {\n out.set(c, p)\n p += c.byteLength\n }\n return out.buffer\n })\n\n if (typeof navigator === 'undefined' || !navigator.gpu) {\n throw new WebGPUUnavailableError('WebGPU is not available (no navigator.gpu). Use a WebGPU-capable browser over a secure context.')\n }\n\n opts.onProgress?.({ phase: 'manifest' })\n const manifest = (await fetchJson(opts.manifestUrl ?? `${modelDir}/manifest.json`)) as Manifest\n opts.onProgress?.({ phase: 'weights' })\n const dataUrl = opts.dataUrl ?? `${modelDir}/${manifest.data_file}`\n const auxUrl = opts.auxUrl ?? `${modelDir}/${manifest.aux_file}`\n // Only the SMALL aux file (LUTs, ~160KB) is buffered; the ~290MB data file STREAMS through\n // per-tensor routes straight into GPU buffers further down (see the streaming weight loader).\n let aux = await fetchBytes(auxUrl)\n const A = manifest.arch\n const T = manifest.tensors\n // Fail loud on manifests the kernels cannot run, instead of producing silent garbage: the WGSL\n // assumes silu activation, head_dim <= 128 (per-thread register arrays), and 128-wide scale blocks.\n const FINAL_NORM = `layers.${A.layers}.final_norm_layernorm`\n if (A.act !== 'silu') throw new Error(`bitgpu: unsupported activation '${A.act}' (kernels implement silu/SwiGLU)`)\n if (A.head_dim > 128) throw new Error(`bitgpu: unsupported head_dim ${A.head_dim} (kernels assume <= 128)`)\n if (A.heads % A.kv_heads !== 0) throw new Error(`bitgpu: heads ${A.heads} not divisible by kv_heads ${A.kv_heads} (GQA kernels assume an integer group size)`)\n if (!T[FINAL_NORM]) throw new Error(`bitgpu: manifest is missing the final norm tensor '${FINAL_NORM}'`)\n if (manifest.version !== undefined && manifest.version !== 1 && manifest.version !== 2)\n throw new Error(`bitgpu: unsupported manifest version ${manifest.version} (this engine reads versions 1 and 2)`)\n // Rope comes either baked (cos_cache/sin_cache refs, ONNX exports: exact parity with the\n // exporter) or synthesized at load from arch.rope (v2/GGUF manifests, which bake no tables).\n if (!T.cos_cache !== !T.sin_cache) throw new Error('bitgpu: manifest has only one of cos_cache/sin_cache')\n if (!T.cos_cache && !(A.rope && A.rope.rope_theta))\n throw new Error('bitgpu: manifest has neither baked cos_cache/sin_cache RoPE tensors nor arch.rope parameters')\n for (const [name, t] of Object.entries(T)) {\n if (t.block !== undefined && t.block !== 128) throw new Error(`bitgpu: tensor ${name} has block ${t.block} (kernels assume 128)`)\n // v2 container tensors: keep the raw interleaved region aside (q1_0) and synthesize\n // PLANAR weight/scales refs carrying the byte lengths the kernels consume, so all the\n // size computations below (limits, buffer creation, fusion) stay container-blind. The\n // streaming loader demuxes the region into both sinks in-flight (see wireQ10).\n if (t.container === undefined) continue\n if (t.container !== 'q1_0') throw new Error(`bitgpu: tensor ${name} has unknown container '${t.container}'`)\n const N = t.N ?? t.rows\n const K = t.K ?? t.cols\n if (!N || !K || K % 128 !== 0) throw new Error(`bitgpu: tensor ${name}: q1_0 container needs N/K (or rows/cols) with K a multiple of 128`)\n const r = t.weight\n if (!r || r.src !== 'data' || r.len !== N * (K / 128) * 18)\n throw new Error(`bitgpu: tensor ${name}: q1_0 region is ${r?.len} bytes in '${r?.src}', expected ${N * (K / 128) * 18} in the data file`)\n t.q1_0 = r\n t.weight = { dtype: 'UINT8', src: r.src, off: r.off, len: N * (K / 8) }\n t.scales = { dtype: 'FLOAT', src: r.src, off: r.off, len: N * (K / 128) * 4 }\n t.zp = undefined // no zp tensor in the container; the 1-bit recipe's midpoints are constants\n }\n\n const readRef = (ref: Ref): Float32Array | Uint8Array | Uint16Array => {\n if (ref.src !== 'aux') throw new Error('bitgpu: internal - readRef reads aux-file refs; data-file tensors stream through routes')\n if (ref.off + ref.len > aux.byteLength)\n throw new Error(`bitgpu: tensor range ${ref.off}+${ref.len} exceeds the aux file (${aux.byteLength} bytes); the download is truncated or the manifest does not match it`)\n const V = VIEW[ref.dtype]!\n if (V === Uint8Array) return new Uint8Array(aux, ref.off, ref.len)\n const bpe = V.BYTES_PER_ELEMENT\n if (ref.off % bpe === 0) return new V(aux, ref.off, ref.len / bpe)\n return new V(aux.slice(ref.off, ref.off + ref.len))\n }\n const readU8 = (ref: Ref): Uint8Array => readRef(ref) as Uint8Array\n\n const adapter = await navigator.gpu.requestAdapter({ powerPreference }) // pick the discrete GPU on multi-GPU machines, not the weak iGPU\n if (!adapter) throw new WebGPUUnavailableError('No suitable WebGPU adapter was found.')\n const hasSG = adapter.features.has('subgroups' as GPUFeatureName)\n const info = (adapter.info ?? {}) as GPUAdapterInfo & { subgroupMinSize?: number; subgroupMaxSize?: number } // subgroup sizes live on GPUAdapterInfo\n const sgMax = info.subgroupMaxSize ?? 32\n const sgMin = info.subgroupMinSize ?? sgMax\n const forceNoSG = opts.forceNoSubgroups ?? false\n // No-subgroup reduction workgroup size. Snapped to a power of two in [32, 256]: the _wg kernels'\n // tree reductions halve the stride each step, so any other size silently drops partial sums.\n const WG_NS = Math.min(256, Math.max(32, 1 << Math.round(Math.log2(opts.noSubgroupWorkgroupSize ?? 64))))\n const NOTILE = opts.prefillTiling === 'never' // force the scalar prefill GEMM (A/B)\n const FORCETILE = opts.prefillTiling === 'always' // use tiled even for short prompts (validation)\n const tiledPrefill = (S: number): boolean => FORCETILE || (!NOTILE && S >= 64) // tiled GEMM wins only once it fills its 64-row tiles\n const SYNC_N = Math.max(1, opts.syncSteps ?? 4) // decode: chain N steps per CPU sync\n const maxSeqLen = Math.max(1, opts.maxSeqLen ?? DEFAULT_MAX_SEQ) // KV-cache length cap (VRAM ~ maxSeqLen x layers x kv_heads x head_dim x KVB)\n // uniform 16/32/64 (16 = Arm Mali) -> head_dim/SG<=8. The subgroup attention kernel covers\n // dimension lane + t*SG for t in [0, D/SG), so head_dim must divide evenly (128 always does;\n // an exotic head_dim like 80 takes the strided _wg fallback instead of silently dropping dims).\n const useSG = hasSG && sgMin === sgMax && (sgMax === 16 || sgMax === 32 || sgMax === 64) && A.head_dim % sgMax === 0 && !forceNoSG\n // f16 KV STORAGE (math stays f32; one rounding at cache-write). 'f16' silently falls back to\n // f32 where shader-f16 is missing, so callers can request it unconditionally.\n const kv16 = opts.kvCache === 'f16' && adapter.features.has('shader-f16' as GPUFeatureName)\n // q8: packed snorm8 K/V with one f32 scale per 32-element block (q8_0-style). Pure core WGSL\n // (pack4x8snorm), so unlike f16 it needs no adapter feature - available everywhere.\n const kv8 = opts.kvCache === 'q8'\n // Rolling window with attention sinks (StreamingLLM): keys cached UNROPED, rotated at read\n // by cache-relative position, middle evicted in batches. See the attention_*_roll shaders.\n const roll = opts.overflow === 'sinks'\n const SINKS = roll ? Math.max(1, Math.floor(opts.sinkTokens ?? 4)) : 0\n if (roll && maxSeqLen < SINKS + 64)\n throw new Error(`bitgpu: overflow 'sinks' needs maxSeqLen >= sinkTokens + 64 (got ${maxSeqLen} with ${SINKS} sinks)`)\n const KVB = kv16 ? 2 : kv8 ? 1 : 4 // bytes per cached K/V element (q8 block scales tracked separately)\n const features: GPUFeatureName[] = []\n if (useSG) features.push('subgroups' as GPUFeatureName)\n if (kv16) features.push('shader-f16' as GPUFeatureName)\n // ---- device limits negotiation ----\n // Run at WebGPU's guaranteed-minimum limits whenever the model fits them (low-end/mobile devices\n // keep working exactly as before), and request precisely the raised limits a bigger model needs,\n // gated on what the adapter can grant. Every buffer the loader will create is sized here FROM THE\n // MANIFEST, before the device is requested: a model this adapter cannot hold fails loudly now,\n // instead of \"loading fine\" with invalid buffers and generating garbage (binding-limit violations\n // are deferred VALIDATION errors, which no out-of-memory scope ever catches).\n const DEFAULT_BINDING = 134217728 // maxStorageBufferBindingSize guaranteed minimum (128 MiB)\n const DEFAULT_BUFFER = 268435456 // maxBufferSize guaranteed minimum (256 MiB)\n let needBind = 0 // largest single storage buffer/binding the loader will create\n let weightBytes = 0 // total weight VRAM, for the OOM message\n const track = (bytes: number): void => {\n const b = (bytes + 3) & ~3 // gbuf pads to 4\n needBind = Math.max(needBind, b)\n weightBytes += b\n }\n for (const t of Object.values(T)) {\n if (t.kind === 'q2') {\n track(t.weight!.len * 2) // q2 codes expand 1 -> 2 bytes at load (wireQ2)\n track(t.scales!.len)\n } else if (t.kind === 'f32' && t.weight) track(t.weight.len)\n }\n const fusedLen = (names: string[], f: 'weight' | 'scales'): number => names.reduce((n, nm) => n + T[nm][f]!.len, 0)\n for (let li = 0; li < A.layers; li++) {\n const groups = [\n [`layers.${li}.attn.q_proj`, `layers.${li}.attn.k_proj`, `layers.${li}.attn.v_proj`],\n [`layers.${li}.mlp.gate_proj`, `layers.${li}.mlp.up_proj`],\n [`layers.${li}.attn.o_proj`],\n [`layers.${li}.mlp.down_proj`],\n ]\n for (const g of groups) {\n track(fusedLen(g, 'weight'))\n track(fusedLen(g, 'scales'))\n }\n }\n // embed zp: from the manifest ref, or synthesized for container tensors (2 blocks/byte)\n const embZpLen = T.embed_tokens.zp?.len ?? (T.embed_tokens.rows! * (T.embed_tokens.cols! / 128)) / 2\n for (const r of [T.embed_tokens.weight!, T.embed_tokens.scales!, manifest.luts.tgt4]) track(r.len)\n track(embZpLen)\n if (kv8 && A.head_dim % 32 !== 0)\n throw new Error(`bitgpu: kvCache 'q8' needs head_dim divisible by 32 (got ${A.head_dim}); use 'f16' or 'f32' for this model`)\n // Non-weight bindings that also count against the limit: a per-layer KV buffer at full\n // maxSeqLen capacity, the largest prefill-segment activation, and the widest logits scratch.\n const kvLayerBytes = maxSeqLen * A.kv_heads * A.head_dim * KVB\n needBind = Math.max(needBind, kvLayerBytes, PREFILL_SEG * Math.max(A.heads * A.head_dim, A.intermediate) * 4, 32 * A.vocab * 4)\n const requiredLimits: Record<string, number> = {}\n if (needBind > DEFAULT_BINDING) {\n if (needBind > adapter.limits.maxStorageBufferBindingSize)\n throw new GpuOutOfMemoryError(\n `this model needs a ${Math.ceil(needBind / 1048576)} MiB storage binding but the adapter's maxStorageBufferBindingSize is ${Math.floor(adapter.limits.maxStorageBufferBindingSize / 1048576)} MiB`,\n )\n requiredLimits.maxStorageBufferBindingSize = needBind\n }\n if (needBind > DEFAULT_BUFFER) {\n if (needBind > adapter.limits.maxBufferSize)\n throw new GpuOutOfMemoryError(\n `this model needs a ${Math.ceil(needBind / 1048576)} MiB buffer but the adapter's maxBufferSize is ${Math.floor(adapter.limits.maxBufferSize / 1048576)} MiB`,\n )\n requiredLimits.maxBufferSize = needBind\n }\n const device = await adapter.requestDevice({\n requiredFeatures: features,\n requiredLimits: Object.keys(requiredLimits).length ? requiredLimits : undefined,\n })\n holder.device = device // createEngine destroys it if anything below throws\n // awareness: shared mem <=8KB < 16KB min, WG <=256; binding sizes negotiated above\n\n // Surface device loss (driver reset, OS reclaim) instead of hanging: consumers get a promise +\n // an optional callback. dispose() also resolves it, with reason 'destroyed' (no callback then).\n const lost: Promise<DeviceLostInfo> = device.lost.then((info) => {\n const li = { reason: String(info.reason ?? 'unknown'), message: info.message }\n if (li.reason !== 'destroyed') opts.onDeviceLost?.(li)\n return li\n })\n device.addEventListener('uncapturederror', (ev) => {\n console.error(`[bitgpu] uncaptured WebGPU error: ${(ev as GPUUncapturedErrorEvent).error.message}`)\n })\n\n opts.onProgress?.({ phase: 'pipelines' })\n const pipelines: Record<string, GPUComputePipeline> = {}\n // async pipeline creation: compile in parallel, non-blocking -> faster, stall-free cold start (MDN-recommended)\n const mkPipe = async (name: string, constants?: Record<string, number>): Promise<void> => {\n const code = SHADERS[name]\n if (code === undefined) throw new Error(`shader not found: ${name}`)\n const module = device.createShaderModule({ code, label: name }) // label so errors name the shader\n const info = await module.getCompilationInfo()\n const err = info.messages.find((m) => m.type === 'error')\n if (err) throw new Error(`WGSL compile error in ${name} (L${err.lineNum}:${err.linePos}): ${err.message}`)\n pipelines[name] = await device.createComputePipelineAsync({ layout: 'auto', compute: { module, entryPoint: 'main', constants } })\n }\n const ROWS_MR = 4 // output rows per workgroup in the multi-row GEMV\n const specs: Array<[string, Record<string, number>?]> = [...WGSLS.map((n): [string] => [n]), ['matmul_split_tiled'], ['matmul_resid_tiled'], ['argmax'], ['embed_gather'], ['embed_gather_batch'], ['sampler_penalty'], ['argmax_masked'], ['logsumexp']]\n if (useSG) {\n for (const n of ['rmsnorm_sg', 'attention_sg', 'matmul_split_sg', 'matmul_q2_sg', 'rmsnorm_rope_sg']) specs.push([n, { SG: sgMax }])\n for (const n of ['matmul_split_sm', 'matmul_resid_sm', 'matmul_q2_sm']) specs.push([n, { SG: sgMax }]) // small-batch (M=2..9) verify-pass GEMVs\n for (const n of ['matmul_resid_mr_sg', 'matmul_swiglu_mr_sg']) specs.push([n, { SG: sgMax, ROWS: ROWS_MR }])\n } else {\n for (const n of ['matmul_split_wg', 'matmul_resid_wg', 'matmul_q2_wg', 'rmsnorm_wg']) specs.push([n, { WG: WG_NS }])\n specs.push(['attention_wg']) // fixed 64-thread workgroup (per-thread acc covers head_dim <= 128)\n }\n if (kv16) {\n // f16-KV variants (compiled only when the device has shader-f16; `enable f16;` fails otherwise)\n specs.push(['copy_kv16'])\n if (useSG) for (const n of ['attention_sg_kv16', 'rmsnorm_rope_sg_kv16']) specs.push([n, { SG: sgMax }])\n else specs.push(['attention_wg_kv16'])\n }\n if (kv8) {\n // q8-KV variants (pure core WGSL: pack4x8snorm; no adapter feature needed)\n specs.push(['copy_kv8'])\n if (useSG) for (const n of ['attention_sg_kv8', 'rmsnorm_rope_sg_kv8']) specs.push([n, { SG: sgMax }])\n else specs.push(['attention_wg_kv8'])\n }\n // Rolling-window (sinks) attention reads rotate K at read time, so it has its own kernel per\n // mode+path. The sg roll kernels keep the rotate partner in-lane only when SG <= head_dim/2;\n // outside that geometry the wg roll kernel takes over (attention only - everything else\n // keeps the sg path).\n const rollSG = useSG && sgMax <= A.head_dim / 2\n if (roll) {\n const rollAtt = kv16 ? 'attention_sg_kv16_roll' : kv8 ? 'attention_sg_kv8_roll' : 'attention_sg_roll'\n const rollAttWg = kv16 ? 'attention_wg_kv16_roll' : kv8 ? 'attention_wg_kv8_roll' : 'attention_wg_roll'\n if (rollSG) specs.push([rollAtt, { SG: sgMax }])\n else specs.push([rollAttWg])\n }\n // Cache-touching kernel names resolve once by KV storage mode. q8's writers need extra\n // bindings (the block-scale buffers), so its call sites branch instead of renaming.\n const ATT =\n roll ?\n kv16 ? (rollSG ? 'attention_sg_kv16_roll' : 'attention_wg_kv16_roll')\n : kv8 ? (rollSG ? 'attention_sg_kv8_roll' : 'attention_wg_kv8_roll')\n : rollSG ? 'attention_sg_roll' : 'attention_wg_roll'\n : kv16 ? (useSG ? 'attention_sg_kv16' : 'attention_wg_kv16')\n : kv8 ? (useSG ? 'attention_sg_kv8' : 'attention_wg_kv8')\n : useSG ? 'attention_sg' : 'attention_wg'\n const ROPE_K = kv16 ? 'rmsnorm_rope_sg_kv16' : 'rmsnorm_rope_sg' // fused-path K write into the cache (f32/f16; q8 branches)\n const COPY_KV = kv16 ? 'copy_kv16' : 'copy' // K/V append into the cache (f32/f16; q8 branches)\n await Promise.all(specs.map(([n, c]) => mkPipe(n, c))) // parallel compile of all pipelines\n\n const S_ = GPUBufferUsage.STORAGE,\n CD = GPUBufferUsage.COPY_DST,\n CS = GPUBufferUsage.COPY_SRC,\n U = GPUBufferUsage.UNIFORM\n // Per-call transient tracking: generate/prefill/forward set `transients = []` so every scratch\n // buffer they create (activations, per-dispatch uniforms, prompt embeddings) is destroyed as soon\n // as its submission completes, instead of lingering until GC. A long prefill otherwise holds\n // ~S x 4.3 MB of dead VRAM (2+ GB for a 512-token prompt) - real memory pressure on 8 GB devices.\n let transients: GPUBuffer[] | null = null\n const flushTransients = (): void => {\n if (!transients) return\n for (const b of transients) b.destroy()\n transients = []\n }\n const upload = (typed: ArrayBufferView, usage: number = S_ | CD): GPUBuffer => {\n const b = device.createBuffer({ size: typed.byteLength, usage })\n device.queue.writeBuffer(b, 0, typed as BufferSource)\n transients?.push(b)\n return b\n }\n // Decode resource pool: in the decode loop the dispatch sequence is identical every batch, so reuse\n // the scratch + uniform buffers across batches (createBuffer is the dominant per-token record cost).\n // Counters increment per call and reset per batch, so within a batch every dispatch still gets its\n // own buffer (no aliasing of in-flight work); reuse happens only across batches (after the sync).\n interface DispSlot {\n uni: GPUBuffer\n bg: GPUBindGroup | null\n last: Uint8Array | null\n }\n // NAMED pools: each distinct dispatch sequence gets its own slot array ('decode' = the fused\n // token loop, 'pld1' / 'pldm' = speculative single-token and verify steps). Selecting a pool\n // also resets the slot indices (the old per-batch poolReset).\n interface Pool { buf: GPUBuffer[]; disp: DispSlot[] }\n const pools: Record<string, Pool> = {}\n let pool: Pool | null = null\n let bufIdx = 0\n let dispIdx = 0\n // Verify-step rounding: buffer sizes are S x per-row elements, so rounding S up to a fixed row\n // count gives every draft length identical buffer sizes - and therefore stable buffer\n // identities, which the cached bind groups depend on. n / from * to is exact by construction.\n let poolRoundFrom = 0\n let poolRoundTo = 0\n const poolUse = (name: string | null, roundFrom = 0, roundTo = 0): void => {\n pool = name ? (pools[name] ??= { buf: [], disp: [] }) : null\n poolRoundFrom = roundFrom\n poolRoundTo = roundTo\n bufIdx = 0\n dispIdx = 0\n }\n // The cached bind groups reference this generate() call's buffers (tokBuf/lg/candIds/... are created\n // per call). A later call creates new buffers, so the cache MUST be rebuilt at each decode entry or it\n // would bind the previous call's (dead) buffers - or, across greedy<->sampled, a different pipeline's\n // auto-layout bind group (a validation error). Buffers are stable within a call, so one rebuild suffices.\n const poolInvalidate = (): void => {\n for (const p of Object.values(pools)) {\n for (const s of p.disp) {\n s.bg = null\n s.last = null\n }\n }\n }\n const actBuf = (n: number): GPUBuffer => {\n if (!pool) {\n const b = device.createBuffer({ size: n * 4, usage: S_ | CS | CD })\n transients?.push(b)\n return b\n }\n const alloc = poolRoundFrom > 0 ? (n / poolRoundFrom) * poolRoundTo : n\n let b = pool.buf[bufIdx]\n if (!b || b.size !== alloc * 4) {\n b = device.createBuffer({ size: alloc * 4, usage: S_ | CS | CD })\n pool.buf[bufIdx] = b\n }\n bufIdx++\n return b\n }\n const dummy = device.createBuffer({ size: 16, usage: S_ })\n\n // Cross-turn state. fullHistory is the entire conversation's token sequence (prompt turns + replies),\n // needed because the sampler's repetition_penalty / no_repeat_ngram see the FULL sequence (like\n // transformers.js, independent of the KV cache). Derived from it: the cache fill length is\n // fullHistory.length - 1 (the last token's K/V is never written during decode), and that last token\n // is re-fed when resuming so its K/V gets written. The persistent Kc/Vc (below) hold the cached K/V.\n let fullHistory: number[] = []\n // Sink-mode bookkeeping: filled cache SLOTS. Diverges from fullHistory.length-1 once the\n // window rolls (fullHistory keeps the whole conversation for penalties/PLD; the cache holds\n // sinks + recent). Maintained by the decode loops; meaningless while overflow is 'error'.\n let cacheLen = 0\n const resetCache = (): void => {\n fullHistory = []\n cacheLen = 0\n }\n\n if (manifest.luts.tgt2.src !== 'aux')\n throw new Error('bitgpu: luts.tgt2 must live in the aux file (the streaming loader needs it before the weights arrive)')\n const tgt2 = readU8(manifest.luts.tgt2) // load-time only (sign table + q2 expansion); not captured by any closure\n const signTable = new Uint8Array(256)\n for (let b = 0; b < 256; b++) {\n let bits = 0\n for (let j = 0; j < 8; j++) bits |= ((((tgt2[2 * b + (j >> 2)] >> (2 * (j & 3))) & 3) >> 1) & 1) << j\n signTable[b] = bits\n }\n\n // ---- streaming weight loader ----\n // Every data-file tensor is wired as a ROUTE: a byte range of the file feeding a GPU buffer\n // (optionally through a per-byte transform: the binary sign table, or the 1->2 q2 code\n // expansion) and/or a CPU array. The file then streams through the routes in ONE sequential\n // pass, so the ~290MB download never exists in memory at once. (The old path materialized the\n // whole file plus an expanded lm_head transient: a CPU peak that read as \"loads fine, then the\n // OS kills the tab at the first keyboard\" on phones.) aux-file refs are tiny and feed the same\n // sinks synchronously from the aux buffer at wiring time.\n interface Route { off: number; len: number; push: (b: Uint8Array) => void; finish: () => void }\n const routes: Route[] = []\n const gbuf = (len: number): GPUBuffer => device.createBuffer({ size: (len + 3) & ~3, usage: S_ | CD })\n const gpuSink = (buf: GPUBuffer, base: number): { push: (b: Uint8Array) => void; finish: () => void } => {\n let written = 0\n let carry = new Uint8Array(0) // writeBuffer needs 4-byte-aligned offsets/sizes; chunks split anywhere\n return {\n push(bytes: Uint8Array): void {\n let all = bytes\n if (carry.length) {\n all = new Uint8Array(carry.length + bytes.length)\n all.set(carry)\n all.set(bytes, carry.length)\n }\n const n = all.length & ~3\n if (n) device.queue.writeBuffer(buf, base + written, all, 0, n) // writeBuffer copies synchronously\n carry = all.subarray(n).slice()\n written += n\n },\n finish(): void {\n if (!carry.length) return\n const pad = new Uint8Array(4)\n pad.set(carry)\n device.queue.writeBuffer(buf, base + written, pad) // gbuf pads buffers to 4 bytes\n written += 4\n carry = new Uint8Array(0)\n },\n }\n }\n // Wire a ref to a sink: data-file refs register a stream route; aux refs feed the sink NOW.\n const wire = (ref: Ref, push: (b: Uint8Array) => void, finish: () => void): void => {\n if (ref.src === 'aux') {\n push(new Uint8Array(readRef(ref).buffer, ref.off, ref.len))\n finish()\n } else routes.push({ off: ref.off, len: ref.len, push, finish })\n }\n const wireRaw = (ref: Ref, buf: GPUBuffer, base = 0): void => {\n const s = gpuSink(buf, base)\n wire(ref, s.push, s.finish)\n }\n // Per-byte weight transforms, shared by the planar (ONNX) and q1_0-container (GGUF)\n // routes - the sign-byte stream is identical across the two containers.\n const xfSign =\n (push: (b: Uint8Array) => void) =>\n (b: Uint8Array): void => {\n const o = new Uint8Array(b.length)\n for (let i = 0; i < b.length; i++) o[i] = signTable[b[i]]\n push(o)\n }\n const xfQ2 =\n (push: (b: Uint8Array) => void) =>\n (b: Uint8Array): void => {\n const o = new Uint8Array(b.length * 2)\n for (let i = 0; i < b.length; i++) {\n o[2 * i] = tgt2[2 * b[i]]\n o[2 * i + 1] = tgt2[2 * b[i] + 1]\n }\n push(o)\n }\n const wireSign = (ref: Ref, buf: GPUBuffer, base = 0): void => {\n const s = gpuSink(buf, base)\n wire(ref, xfSign(s.push), s.finish)\n }\n const wireQ2 = (ref: Ref, buf: GPUBuffer): void => {\n const s = gpuSink(buf, 0)\n wire(ref, xfQ2(s.push), s.finish)\n }\n // f16 -> f32, exact (every f16 value is exactly representable in f32)\n const f16f32 = (h: number): number => {\n const s = h & 0x8000 ? -1 : 1\n const e = (h >> 10) & 31\n const m = h & 1023\n if (e === 0) return s * m * 2 ** -24\n if (e === 31) return m ? NaN : s * Infinity\n return s * (1024 + m) * 2 ** (e - 25)\n }\n // container 'q1_0' (GGUF): ONE region streams BOTH planar outputs. Each 18-byte block is\n // [f16 scale][16 sign bytes]; the scale converts to f32 into the scales sink, the sign\n // bytes feed the weight sink (through the same transform the planar path uses). Block\n // phase carries across pushed chunks, which split anywhere - including mid-scale.\n const wireQ10 = (region: Ref, signPush: (b: Uint8Array) => void, signFinish: () => void, scalePush: (b: Uint8Array) => void, scaleFinish: () => void): void => {\n let phase = 0 // byte position inside the current 18-byte block\n let scaleLo = 0 // pending low byte of a scale straddling a chunk boundary\n const push = (b: Uint8Array): void => {\n const signs = new Uint8Array(b.length)\n const scales = new Float32Array((b.length >> 4) + 2)\n let sn = 0\n let cn = 0\n for (let i = 0; i < b.length; i++) {\n if (phase === 0) {\n scaleLo = b[i]\n phase = 1\n } else if (phase === 1) {\n scales[cn++] = f16f32(scaleLo | (b[i] << 8))\n phase = 2\n } else {\n signs[sn++] = b[i]\n phase = phase === 17 ? 0 : phase + 1\n }\n }\n if (sn) signPush(signs.subarray(0, sn))\n if (cn) scalePush(new Uint8Array(scales.buffer, 0, cn * 4))\n }\n routes.push({ off: region.off, len: region.len, push, finish: () => { signFinish(); scaleFinish() } })\n }\n const wireCpu = (ref: Ref): Uint8Array => {\n const dst = new Uint8Array(ref.len)\n let w = 0\n wire(\n ref,\n (b) => {\n dst.set(b, w)\n w += b.length\n },\n () => undefined,\n )\n return dst\n }\n // WebGPU allocation errors are DEFERRED: without an error scope the ~300 MB of weight buffers\n // \"succeed\" as invalid buffers on VRAM-poor devices and every later generate returns garbage.\n // The validation scope backstops the limits negotiation above: any load-time validation error\n // (e.g. a buffer over a granted limit) fails createEngine loudly instead of console noise.\n device.pushErrorScope('validation')\n device.pushErrorScope('out-of-memory')\n const W: Record<string, GpuWeight> = {}\n // Deferred zero-point checks: q2 zp tensors stream with the weights, so their bytes are only\n // complete after the streaming pass; each closure then validates and installs the real value.\n const zpChecks: Array<() => void> = []\n for (const [name, t] of Object.entries(T)) {\n if (t.kind === 'q2') {\n const codes = gbuf(t.weight!.len * 2) // 1 byte of q2 data expands to 2 code bytes\n const scales = gbuf(t.scales!.len)\n if (t.q1_0) {\n const cs = gpuSink(codes, 0)\n const ss = gpuSink(scales, 0)\n wireQ10(t.q1_0, xfQ2(cs.push), cs.finish, ss.push, ss.finish)\n } else {\n wireQ2(t.weight!, codes)\n wireRaw(t.scales!, scales)\n }\n const w: GpuWeight = { N: t.N!, K: t.K!, nb: t.K! / 128, zp: 2, codes, scales }\n // The q2 kernels take ONE zero-point for the whole tensor (a uniform, not a per-block\n // buffer read in the hottest GEMV): the q1 recipe always emits the 2-bit midpoint. Read\n // the manifest's zp tensor and derive the scalar from it, failing loudly on a non-uniform\n // export instead of silently dequantizing with the wrong zero-points.\n if (t.zp) {\n const zpBytes = wireCpu(t.zp)\n zpChecks.push(() => {\n const b0 = zpBytes[0]\n for (let i = 1; i < zpBytes.length; i++)\n if (zpBytes[i] !== b0) throw new Error(`bitgpu: tensor ${name} has non-uniform 2-bit zero-points (the q2 kernels assume one zp for the whole tensor)`)\n const zp = b0 & 3\n if (b0 !== zp * 0b01010101) throw new Error(`bitgpu: tensor ${name} has non-uniform 2-bit zero-points within a byte (the q2 kernels assume one zp for the whole tensor)`)\n w.zp = zp\n })\n }\n W[name] = w\n } else if (t.kind === 'f32' && t.weight) {\n const buf = gbuf(t.weight.len)\n wireRaw(t.weight, buf)\n W[name] = { buf }\n }\n }\n // fuse per-layer matmul weights: qkv (3), gate/up (2); o_proj + down_proj stay individual\n // (residual-folded). Fusion needs no CPU concat: each part streams into its fused-buffer slice.\n const fuse = (parts: MTensor[]): { sign: GPUBuffer; scales: GPUBuffer } => {\n const sign = gbuf(parts.reduce((n, p) => n + p.weight!.len, 0))\n const scales = gbuf(parts.reduce((n, p) => n + p.scales!.len, 0))\n let so = 0\n let co = 0\n for (const p of parts) {\n if (p.q1_0) {\n const ws = gpuSink(sign, so)\n const ss = gpuSink(scales, co)\n wireQ10(p.q1_0, xfSign(ws.push), ws.finish, ss.push, ss.finish)\n } else {\n wireSign(p.weight!, sign, so)\n wireRaw(p.scales!, scales, co)\n }\n so += p.weight!.len\n co += p.scales!.len\n }\n return { sign, scales }\n }\n for (let li = 0; li < A.layers; li++) {\n const q = T[`layers.${li}.attn.q_proj`],\n k = T[`layers.${li}.attn.k_proj`],\n v = T[`layers.${li}.attn.v_proj`]\n W[`layers.${li}.attn.qkv`] = { K: q.K!, nb: q.K! / 128, N0: q.N!, N1: k.N!, N2: v.N!, ...fuse([q, k, v]) }\n const g = T[`layers.${li}.mlp.gate_proj`],\n u = T[`layers.${li}.mlp.up_proj`]\n W[`layers.${li}.mlp.gateup`] = { K: g.K!, nb: g.K! / 128, N0: g.N!, N1: u.N!, N2: 0, ...fuse([g, u]) }\n for (const nm of [`layers.${li}.attn.o_proj`, `layers.${li}.mlp.down_proj`]) {\n const r = T[nm]\n W[nm] = { N: r.N!, K: r.K!, nb: r.K! / 128, ...fuse([r]) }\n }\n }\n\n // Embedding tables are GPU-ONLY: decode gathers one token (embed_gather.wgsl) and prefill\n // gathers a whole segment (embed_gather_batch.wgsl) straight from the packed tables, so no\n // CPU copy exists (~50-100 MB RAM saved per model; uint8 arrays are uploaded as bytes and\n // read as u32, byte-extracted). cos/sin caches are CPU-only.\n const wireGpu = (ref: Ref): GPUBuffer => {\n const buf = gbuf(ref.len)\n wireRaw(ref, buf)\n return buf\n }\n let embWqG: GPUBuffer\n let embScalesG: GPUBuffer\n let embZpG: GPUBuffer\n if (T.embed_tokens.q1_0) {\n embWqG = gbuf(T.embed_tokens.weight!.len)\n embScalesG = gbuf(T.embed_tokens.scales!.len)\n const ws = gpuSink(embWqG, 0)\n const ss = gpuSink(embScalesG, 0)\n wireQ10(T.embed_tokens.q1_0, ws.push, ws.finish, ss.push, ss.finish)\n // q4 zero-points: the 1-bit recipe's 4-bit codes sit at {7,9} around the midpoint 8. A\n // q1_0 container carries no zp tensor, so synthesize the constant table the gather\n // kernels read (two 4-bit 8s per byte, one nibble per 128-wide block).\n embZpG = gbuf(embZpLen)\n device.queue.writeBuffer(embZpG, 0, new Uint8Array((embZpLen + 3) & ~3).fill(0x88))\n } else {\n embWqG = wireGpu(T.embed_tokens.weight!)\n embScalesG = wireGpu(T.embed_tokens.scales!)\n embZpG = wireGpu(T.embed_tokens.zp!)\n }\n const tgt4G = wireGpu(manifest.luts.tgt4)\n let cosCache: Float32Array\n let sinCache: Float32Array\n if (T.cos_cache) {\n const cosBytes = wireCpu(T.cos_cache as Ref)\n const sinBytes = wireCpu(T.sin_cache as Ref)\n cosCache = new Float32Array(cosBytes.buffer)\n sinCache = new Float32Array(sinBytes.buffer)\n // The caches are baked per export ([positions, head_dim/2]); positions beyond them would read\n // undefined -> NaN into every rope buffer, silent garbage. Cap maxSeqLen at load, loudly.\n const ropePositions = cosCache.length / (A.head_dim / 2)\n if (maxSeqLen > ropePositions)\n throw new Error(`bitgpu: maxSeqLen ${maxSeqLen} exceeds the model's baked RoPE cache (${ropePositions} positions); lower maxSeqLen or re-export with a longer cache`)\n } else {\n // v2/GGUF manifests bake no rope tables: synthesize f32 cos/sin for exactly maxSeqLen\n // positions from arch.rope (plain or YaRN) - the same recipe tools/reference.py runs\n // when it generates fixtures, so the reference forward uses the tables the engine uses.\n const cap = A.max_positions ?? 40960\n if (maxSeqLen > cap)\n throw new Error(`bitgpu: maxSeqLen ${maxSeqLen} exceeds the model's max_positions (${cap})`)\n ;[cosCache, sinCache] = synthRope(A, maxSeqLen)\n }\n\n // ONE sequential pass of the data file through the routes. Tied tensors (e.g. lm_head sharing\n // the embedding bytes) produce EXACT-duplicate ranges: those fan out to every consumer; partial\n // overlaps have no defined streaming order and stay fatal.\n routes.sort((a, b) => a.off - b.off || a.len - b.len)\n const merged: Route[] = []\n for (const r of routes) {\n const last = merged[merged.length - 1]\n if (last && last.off === r.off && last.len === r.len) {\n const lp = last.push,\n lf = last.finish\n last.push = (b): void => {\n lp(b)\n r.push(b)\n }\n last.finish = (): void => {\n lf()\n r.finish()\n }\n } else if (last && r.off < last.off + last.len) {\n throw new Error('bitgpu: partially overlapping data-file tensor ranges (unsupported by the streaming loader)')\n } else merged.push(r)\n }\n const needed = merged.length ? merged[merged.length - 1].off + merged[merged.length - 1].len : 0\n const dataStream = opts.fetchStream\n ? await opts.fetchStream(dataUrl)\n : opts.fetchArrayBuffer\n ? (new Response(await opts.fetchArrayBuffer(dataUrl)).body as ReadableStream<Uint8Array>)\n : await (async () => {\n const res = await fetch(dataUrl)\n if (!res.ok) throw new Error(`bitgpu: fetch ${dataUrl} failed: HTTP ${res.status}`)\n return res.body ?? (new Response(await res.arrayBuffer()).body as ReadableStream<Uint8Array>)\n })()\n const reader = dataStream.getReader()\n let cursor = 0\n let ri = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n let bo = 0\n while (bo < value.byteLength && ri < merged.length) {\n const r = merged[ri]\n if (cursor >= r.off + r.len) {\n ri++\n continue\n }\n if (cursor < r.off) {\n const skip = Math.min(r.off - cursor, value.byteLength - bo)\n cursor += skip\n bo += skip\n continue\n }\n const n = Math.min(r.off + r.len - cursor, value.byteLength - bo)\n r.push(value.subarray(bo, bo + n))\n cursor += n\n bo += n\n if (cursor === r.off + r.len) {\n r.finish()\n ri++\n }\n }\n cursor += value.byteLength - bo\n opts.onProgress?.({ phase: 'weights', loaded: Math.min(cursor, needed), total: needed })\n }\n if (cursor < needed)\n throw new Error(`bitgpu: the data file ended at ${cursor} bytes but tensors extend to ${needed}; the download is truncated or the manifest does not match it`)\n for (const check of zpChecks) check()\n zpChecks.length = 0\n aux = null as unknown as ArrayBuffer\n\n // GPU embedding gather for a batch of prompt tokens: upload S u32 ids (bytes, not S*H floats)\n // and dequantize the rows on the GPU (embed_gather_batch.wgsl - same math as the decode\n // gather). The returned activation holds [S, H] and belongs to the caller's transient scope.\n function embedBatch(enc: GPUCommandEncoder, ids: number[]): GPUBuffer {\n const idBuf = upload(new Uint32Array(ids))\n const out = actBuf(ids.length * Hd)\n const pass = enc.beginComputePass()\n run(pass, 'embed_gather_batch', [['u', ids.length], ['u', Hd], ['u', 0], ['u', 0]], [idBuf, embWqG, tgt4G, embScalesG, embZpG], out, ids.length * Hd)\n pass.end()\n return out\n }\n function ropeBufs(posBase: number, S: number): { cos: GPUBuffer; sin: GPUBuffer } {\n const D = A.head_dim,\n R = D / 2, // rotary halves: caches store [seq, D/2]; the full vector is concat(half, half)\n cos = new Float32Array(S * D),\n sin = new Float32Array(S * D)\n for (let s = 0; s < S; s++)\n for (let d = 0; d < D; d++) {\n cos[s * D + d] = cosCache[(posBase + s) * R + (d % R)]\n sin[s * D + d] = sinCache[(posBase + s) * R + (d % R)]\n }\n const cb = actBuf(S * D),\n sb = actBuf(S * D)\n device.queue.writeBuffer(cb, 0, cos)\n device.queue.writeBuffer(sb, 0, sin)\n return { cos: cb, sin: sb }\n }\n\n const KV = A.kv_heads,\n Dh = A.head_dim,\n Hd = A.hidden,\n H = A.heads,\n F = A.intermediate\n // The KV cache GROWS on demand (doubling, up to maxSeqLen) instead of pinning the full maxSeqLen\n // up front: a short conversation keeps a small cache (~KV_INITIAL positions), so idle VRAM stays\n // low on memory-constrained devices (a full 2048-position f32 cache is ~448 MB at 28 layers,\n // ~576 MB at 36; the 512 floor is a quarter of that).\n // ensureKvCapacity() reallocates + copies the existing K/V when a turn needs more room.\n const KV_INITIAL = 512\n let kvCapacity = Math.min(maxSeqLen, KV_INITIAL)\n const Kc: GPUBuffer[] = [],\n Vc: GPUBuffer[] = []\n // q8 block scales: one f32 per 32 cached elements, per layer, alongside Kc/Vc (empty otherwise)\n const Ksc: GPUBuffer[] = [],\n Vsc: GPUBuffer[] = []\n const kvScaleBytes = (cap: number): number => cap * KV * (Dh / 32) * 4\n for (let li = 0; li < A.layers; li++) {\n Kc.push(device.createBuffer({ size: kvCapacity * KV * Dh * KVB, usage: S_ | CS | CD }))\n Vc.push(device.createBuffer({ size: kvCapacity * KV * Dh * KVB, usage: S_ | CS | CD }))\n if (kv8) {\n Ksc.push(device.createBuffer({ size: kvScaleBytes(kvCapacity), usage: S_ | CS | CD }))\n Vsc.push(device.createBuffer({ size: kvScaleBytes(kvCapacity), usage: S_ | CS | CD }))\n }\n }\n // Sink-mode statics: the aux rope tables ([window, Dh/2]) for the read-time K rotation, and\n // cos=1/sin=0 stand-ins so the K WRITE kernels store the un-roped rmsnorm output unchanged\n // (nd*1 + rot*0 == nd; no separate no-rope kernel variants needed).\n let rollCosT: GPUBuffer | null = null,\n rollSinT: GPUBuffer | null = null,\n rollOnes: GPUBuffer | null = null,\n rollZeros: GPUBuffer | null = null\n if (roll) {\n const R2 = Dh / 2\n rollCosT = device.createBuffer({ size: maxSeqLen * R2 * 4, usage: S_ | CD })\n rollSinT = device.createBuffer({ size: maxSeqLen * R2 * 4, usage: S_ | CD })\n device.queue.writeBuffer(rollCosT, 0, cosCache.buffer, cosCache.byteOffset, maxSeqLen * R2 * 4)\n device.queue.writeBuffer(rollSinT, 0, sinCache.buffer, sinCache.byteOffset, maxSeqLen * R2 * 4)\n rollOnes = device.createBuffer({ size: Dh * 4, usage: S_ | CD })\n rollZeros = device.createBuffer({ size: Dh * 4, usage: S_ | CD })\n device.queue.writeBuffer(rollOnes, 0, new Float32Array(Dh).fill(1))\n device.queue.writeBuffer(rollZeros, 0, new Float32Array(Dh))\n }\n const loadOom = await device.popErrorScope()\n const loadVal = await device.popErrorScope()\n if (loadOom) throw new GpuOutOfMemoryError(`GPU allocation failed while loading weights (~${Math.round(weightBytes / 1048576)} MB VRAM needed): ${loadOom.message}`)\n if (loadVal) throw new Error(`bitgpu: WebGPU validation error while loading weights: ${loadVal.message}`)\n // Grow every layer's K/V buffer to hold at least `needed` positions, preserving the cached content\n // (so a cross-turn reuse mid-conversation survives a growth). Rare (only when crossing a capacity\n // threshold); the copy is GPU-side and bounded geometrically. Invalidates cached decode bind groups\n // since they referenced the old buffers.\n async function ensureKvCapacity(needed: number): Promise<void> {\n if (needed <= kvCapacity) return\n const newCap = Math.min(maxSeqLen, Math.max(needed, kvCapacity * 2))\n const copyBytes = kvCapacity * KV * Dh * KVB // preserve all currently-allocated K/V\n const copyScales = kvScaleBytes(kvCapacity)\n device.pushErrorScope('out-of-memory')\n const enc = device.createCommandEncoder()\n // Every cache buffer this layer set held before the growth, in [K, V, (Ksc, Vsc)] groups.\n const per = kv8 ? 4 : 2\n const olds: GPUBuffer[] = []\n for (let li = 0; li < A.layers; li++) {\n const nk = device.createBuffer({ size: newCap * KV * Dh * KVB, usage: S_ | CS | CD })\n const nv = device.createBuffer({ size: newCap * KV * Dh * KVB, usage: S_ | CS | CD })\n enc.copyBufferToBuffer(Kc[li], 0, nk, 0, copyBytes)\n enc.copyBufferToBuffer(Vc[li], 0, nv, 0, copyBytes)\n olds.push(Kc[li], Vc[li])\n Kc[li] = nk\n Vc[li] = nv\n if (kv8) {\n const nks = device.createBuffer({ size: kvScaleBytes(newCap), usage: S_ | CS | CD })\n const nvs = device.createBuffer({ size: kvScaleBytes(newCap), usage: S_ | CS | CD })\n enc.copyBufferToBuffer(Ksc[li], 0, nks, 0, copyScales)\n enc.copyBufferToBuffer(Vsc[li], 0, nvs, 0, copyScales)\n olds.push(Ksc[li], Vsc[li])\n Ksc[li] = nks\n Vsc[li] = nvs\n }\n }\n device.queue.submit([enc.finish()])\n await device.queue.onSubmittedWorkDone()\n const oom = await device.popErrorScope()\n if (oom) {\n // Roll back to the old (still valid) buffers so the engine stays usable at its current size.\n for (let li = 0; li < A.layers; li++) {\n Kc[li].destroy()\n Vc[li].destroy()\n Kc[li] = olds[per * li]\n Vc[li] = olds[per * li + 1]\n if (kv8) {\n Ksc[li].destroy()\n Vsc[li].destroy()\n Ksc[li] = olds[per * li + 2]\n Vsc[li] = olds[per * li + 3]\n }\n }\n poolInvalidate()\n throw new GpuOutOfMemoryError(`KV cache growth to ${newCap} positions failed: ${oom.message}`)\n }\n for (const b of olds) b.destroy()\n kvCapacity = newCap\n poolInvalidate()\n }\n\n // ---- sink-mode eviction (overflow: 'sinks') ----\n // Batched StreamingLLM compaction: keep the SINKS anchor positions plus the most recent\n // block, drop the middle. Cache bytes only MOVE (same-buffer copies are forbidden in WebGPU,\n // so each region bounces through one lazily-kept scratch buffer); nothing is re-roped or\n // requantized - the roll attention kernels rotate K by cache slot at read, so a moved row\n // simply reads as \"closer\". Queue order makes the copies land before any later dispatch, so\n // no CPU sync is needed. Called only from inside a turn (the op is already serialized).\n let evictScratch: GPUBuffer | null = null\n function evict(fill: number, need: number): number {\n // free at least `need` slots plus a quarter-of-recent batch, so events stay rare\n const recent = fill - SINKS\n const batch = Math.min(recent, Math.max(need, Math.ceil((maxSeqLen - SINKS) / 4)))\n const keep = recent - batch\n if (keep <= 0) return SINKS // nothing recent survives (giant need): sinks only\n const rowK = KV * Dh * KVB\n const rowS = kv8 ? KV * (Dh / 32) * 4 : 0\n if (!evictScratch || evictScratch.size < keep * rowK) {\n evictScratch?.destroy()\n evictScratch = device.createBuffer({ size: keep * rowK, usage: CS | CD })\n }\n const enc = device.createCommandEncoder()\n const groups: Array<[GPUBuffer, number]> = []\n for (let li = 0; li < A.layers; li++) {\n groups.push([Kc[li], rowK], [Vc[li], rowK])\n if (kv8) groups.push([Ksc[li], rowS], [Vsc[li], rowS])\n }\n for (const [buf, row] of groups) {\n enc.copyBufferToBuffer(buf, (SINKS + batch) * row, evictScratch, 0, keep * row)\n enc.copyBufferToBuffer(evictScratch, 0, buf, SINKS * row, keep * row)\n }\n device.queue.submit([enc.finish()])\n return SINKS + keep\n }\n // Make room for `n` more rows before recording a batch; returns the (possibly reduced) fill.\n const evictFor = (fill: number, n: number): number => (roll && fill + n > maxSeqLen ? evict(fill, fill + n - maxSeqLen) : fill)\n\n async function readback(buf: GPUBuffer, n: number): Promise<Float32Array> {\n const rb = device.createBuffer({ size: n * 4, usage: GPUBufferUsage.MAP_READ | CD })\n const enc = device.createCommandEncoder()\n enc.copyBufferToBuffer(buf, 0, rb, 0, n * 4)\n device.queue.submit([enc.finish()])\n await rb.mapAsync(GPUMapMode.READ)\n const out = new Float32Array(rb.getMappedRange().slice(0))\n rb.unmap()\n rb.destroy()\n return out\n }\n async function readbackU32(buf: GPUBuffer, n: number): Promise<Uint32Array> {\n const rb = device.createBuffer({ size: n * 4, usage: GPUBufferUsage.MAP_READ | CD })\n const enc = device.createCommandEncoder()\n enc.copyBufferToBuffer(buf, 0, rb, 0, n * 4)\n device.queue.submit([enc.finish()])\n await rb.mapAsync(GPUMapMode.READ)\n const out = new Uint32Array(rb.getMappedRange().slice(0))\n rb.unmap()\n rb.destroy()\n return out\n }\n\n // diagnostic: FULL = null -> every kernel at real size; FULL = Set(names) -> only those at real size,\n // all others dispatched as 1 workgroup. Lets us measure each kernel type's true in-context cost.\n let FULL: Set<string> | null = null\n // embed_gather_batch is exempt from profiling skeletons: it produces the PREFILL INPUT (the\n // CPU used to), and skeleton-skipping it feeds NaN/garbage activations into every profiled\n // kernel - numerically meaningless and, on GPUs with slow non-finite handling, much slower.\n const isFull = (name: string): boolean => FULL === null || FULL.has(name) || name === 'embed_gather_batch'\n // differential debug: FORCE_SLOW routes S=1 through the prefill (known-good) path; DBG0 collects\n // layer-0 checkpoint buffers so a fused step and a slow step can be compared kernel by kernel.\n let FORCE_SLOW = false\n // Small-batch routing: when set to S (2..9, subgroup path only), the matmuls of an S-row pass\n // use the _sm kernels, which read each weight word once for all S rows - the lever that makes\n // the speculative-decode verify pass profitable. 0 = off (scalar/tiled prefill kernels).\n // Set ONLY around the PLD verify-step encode; every shipped non-PLD path keeps its kernels.\n let SMALLM = 0\n let DBG0: Record<string, GPUBuffer> | null = null\n const cap = (li: number, name: string, buf: GPUBuffer): void => {\n if (li === 0 && DBG0) DBG0[name] = buf\n }\n // set pipeline + bind group for a dispatch. When pooling (decode loop), the uniform buffer AND the\n // bind group are cached per dispatch slot, so only writeBuffer of the changed params runs per token.\n function setup(pass: GPUComputePassEncoder, name: string, fields: Field[], ins: GPUBuffer[], outs: GPUBuffer[]): void {\n pass.setPipeline(pipelines[name])\n if (pool) {\n let slot = pool.disp[dispIdx]\n if (!slot) {\n slot = { uni: device.createBuffer({ size: 64, usage: U | CD }), bg: null, last: null }\n pool.disp[dispIdx] = slot\n }\n const data2 = makeParams(fields) // reused view; only writeBuffer when the params changed\n if (!slot.last || !eqBytes(slot.last, data2)) {\n device.queue.writeBuffer(slot.uni, 0, data2 as BufferSource)\n slot.last = data2.slice()\n }\n if (!slot.bg) {\n const entries: GPUBindGroupEntry[] = [{ binding: 0, resource: { buffer: slot.uni } }]\n ins.forEach((b, i) => entries.push({ binding: i + 1, resource: { buffer: b } }))\n outs.forEach((b, i) => entries.push({ binding: 1 + ins.length + i, resource: { buffer: b } }))\n slot.bg = device.createBindGroup({ layout: pipelines[name].getBindGroupLayout(0), entries })\n }\n pass.setBindGroup(0, slot.bg)\n dispIdx++\n } else {\n const entries: GPUBindGroupEntry[] = [{ binding: 0, resource: { buffer: upload(makeParams(fields), U | CD) } }]\n ins.forEach((b, i) => entries.push({ binding: i + 1, resource: { buffer: b } }))\n outs.forEach((b, i) => entries.push({ binding: 1 + ins.length + i, resource: { buffer: b } }))\n pass.setBindGroup(0, device.createBindGroup({ layout: pipelines[name].getBindGroupLayout(0), entries }))\n }\n }\n // Split a 1D workgroup count into a 2D grid so no dimension exceeds WebGPU's 65535 cap (a long\n // prefill can need >65535 workgroups, e.g. the swiglu kernel does ceil(S*6144/64) = S*96). The flat\n // kernels reconstruct the linear index as (wid.y*num_workgroups.x + wid.x)*64 + lid.x, which equals\n // global_invocation_id.x when the grid is 1D (y=1) - so it stays correct for the common small case.\n const grid2d = (wg: number): [number, number] => {\n const y = Math.ceil(wg / 65535)\n return [Math.ceil(wg / y), y]\n }\n function runIO(pass: GPUComputePassEncoder, name: string, fields: Field[], ins: GPUBuffer[], outs: GPUBuffer[], threads: number): void {\n setup(pass, name, fields, ins, outs)\n if (!isFull(name)) return void pass.dispatchWorkgroups(1)\n const [x, y] = grid2d(Math.ceil(threads / 64))\n pass.dispatchWorkgroups(x, y, 1)\n }\n const run = (pass: GPUComputePassEncoder, name: string, fields: Field[], ins: GPUBuffer[], out: GPUBuffer, threads: number): void =>\n runIO(pass, name, fields, ins, [out], threads)\n // dispatch exactly nWG workgroups (subgroup kernels: one workgroup per row / per (query,head))\n function runN(pass: GPUComputePassEncoder, name: string, fields: Field[], ins: GPUBuffer[], out: GPUBuffer, nWG: number): void {\n setup(pass, name, fields, ins, [out])\n pass.dispatchWorkgroups(isFull(name) ? nWG : 1)\n }\n // 2D workgroup dispatch (subgroup GEMV: one workgroup per output column)\n function runWG(pass: GPUComputePassEncoder, name: string, fields: Field[], ins: GPUBuffer[], outs: GPUBuffer[], wgX: number, wgY: number): void {\n setup(pass, name, fields, ins, outs)\n const f = isFull(name)\n pass.dispatchWorkgroups(f ? wgX : 1, f ? wgY : 1, 1)\n }\n const rms = (pass: GPUComputePassEncoder, x: GPUBuffer, g: string, R: number, Dn: number, out: GPUBuffer): void =>\n useSG\n ? runN(pass, 'rmsnorm_sg', [['u', R], ['u', Dn], ['f', A.rms_eps], ['u', 0]], [x, W[g].buf!], out, R)\n : runN(pass, 'rmsnorm_wg', [['u', R], ['u', Dn], ['f', A.rms_eps], ['u', 0]], [x, W[g].buf!], out, R)\n // fused q/k/v or gate/up matmul\n function fusedMM(pass: GPUComputePassEncoder, w: GpuWeight, inBuf: GPUBuffer, S: number, outs: GPUBuffer[]): void {\n const Ntot = w.N0! + w.N1! + w.N2!\n if (useSG && S === 1) {\n const gx = Math.min(Ntot, 65535)\n runWG(pass, 'matmul_split_sg', [['u', w.K!], ['u', w.nb!], ['u', w.N0!], ['u', w.N1!], ['u', w.N2!], ['u', gx]], [inBuf, w.sign!, w.scales!], outs, gx, Math.ceil(Ntot / gx))\n } else if (S === 1) {\n const gx = Math.min(Ntot, 65535) // no-subgroup decode: workgroup-reduction GEMV\n runWG(pass, 'matmul_split_wg', [['u', w.K!], ['u', w.nb!], ['u', w.N0!], ['u', w.N1!], ['u', w.N2!], ['u', gx]], [inBuf, w.sign!, w.scales!], outs, gx, Math.ceil(Ntot / gx))\n } else if (useSG && S === SMALLM) {\n const gx = Math.min(Ntot, 65535) // small-batch GEMV: weights read once for all S rows\n runWG(pass, 'matmul_split_sm', [['u', w.K!], ['u', w.nb!], ['u', w.N0!], ['u', w.N1!], ['u', w.N2!], ['u', gx], ['u', S]], [inBuf, w.sign!, w.scales!], outs, gx, Math.ceil(Ntot / gx))\n } else if (tiledPrefill(S)) {\n runWG(pass, 'matmul_split_tiled', [['u', S], ['u', w.K!], ['u', w.nb!], ['u', w.N0!], ['u', w.N1!], ['u', w.N2!]], [inBuf, w.sign!, w.scales!], outs, Math.ceil(Ntot / 64), Math.ceil(S / 64)) // long-prompt prefill: tiled GEMM\n } else {\n runIO(pass, 'matmul_split', [['u', S], ['u', w.K!], ['u', w.nb!], ['u', w.N0!], ['u', w.N1!], ['u', w.N2!]], [inBuf, w.sign!, w.scales!], outs, S * Ntot)\n }\n }\n // o_proj / down_proj matmul with fused residual add\n function residMM(pass: GPUComputePassEncoder, w: GpuWeight, inBuf: GPUBuffer, resid: GPUBuffer, S: number, out: GPUBuffer): void {\n if (useSG && S === 1) {\n const nwg = Math.ceil(w.N! / ROWS_MR) // multi-row GEMV: ROWS_MR output cols per workgroup\n const gx = Math.min(nwg, 65535)\n runWG(pass, 'matmul_resid_mr_sg', [['u', w.N!], ['u', w.K!], ['u', w.nb!], ['u', gx], ['u', 0], ['u', 0]], [inBuf, w.sign!, w.scales!, resid], [out], gx, Math.ceil(nwg / gx))\n } else if (S === 1) {\n const gx = Math.min(w.N!, 65535) // no-subgroup decode: workgroup-reduction GEMV + residual\n runWG(pass, 'matmul_resid_wg', [['u', w.N!], ['u', w.K!], ['u', w.nb!], ['u', gx], ['u', 0], ['u', 0]], [inBuf, w.sign!, w.scales!, resid], [out], gx, Math.ceil(w.N! / gx))\n } else if (useSG && S === SMALLM) {\n const gx = Math.min(w.N!, 65535) // small-batch GEMV + residual\n runWG(pass, 'matmul_resid_sm', [['u', w.N!], ['u', w.K!], ['u', w.nb!], ['u', gx], ['u', S], ['u', 0]], [inBuf, w.sign!, w.scales!, resid], [out], gx, Math.ceil(w.N! / gx))\n } else if (tiledPrefill(S)) {\n runWG(pass, 'matmul_resid_tiled', [['u', S], ['u', w.N!], ['u', w.K!], ['u', w.nb!], ['u', 0], ['u', 0]], [inBuf, w.sign!, w.scales!, resid], [out], Math.ceil(w.N! / 64), Math.ceil(S / 64)) // long-prompt prefill: tiled GEMM\n } else {\n runIO(pass, 'matmul_resid', [['u', S], ['u', w.N!], ['u', w.K!], ['u', w.nb!], ['u', 128], ['u', 0]], [inBuf, w.sign!, w.scales!, resid], [out], S * w.N!)\n }\n }\n\n // Append `rows` rows of Dh f32 values into layer li's K (which=0) or V (which=1) cache at row\n // dstRow0, quantizing under q8 (copy_kv8 is a per-row workgroup kernel with two outputs, so it\n // cannot ride the flat COPY_KV dispatch).\n function appendKV(pass: GPUComputePassEncoder, src: GPUBuffer, which: 0 | 1, li: number, rows: number, dstRow0: number): void {\n const data = which === 0 ? Kc[li] : Vc[li]\n if (kv8) {\n setup(pass, 'copy_kv8', [['u', rows], ['u', Dh], ['u', dstRow0], ['u', 0]], [src], [data, which === 0 ? Ksc[li] : Vsc[li]])\n pass.dispatchWorkgroups(isFull('copy_kv8') ? rows : 1)\n } else {\n run(pass, COPY_KV, [['u', rows * Dh], ['u', dstRow0 * Dh], ['u', 0], ['u', 0]], [src], data, rows * Dh)\n }\n }\n // The attention kernel's cache bindings by KV mode (q8 adds the block-scale buffers).\n const attIns = (qr: GPUBuffer, li: number): GPUBuffer[] => {\n const ins = kv8 ? [qr, Kc[li], Vc[li], Ksc[li], Vsc[li]] : [qr, Kc[li], Vc[li]]\n if (roll) ins.push(rollCosT!, rollSinT!) // read-time K rotation tables\n return ins\n }\n\n function layer(pass: GPUComputePassEncoder, li: number, h: GPUBuffer, S: number, posBase: number, cos: GPUBuffer, sin: GPUBuffer): GPUBuffer {\n const Ltot = posBase + S\n const n1 = actBuf(S * Hd)\n rms(pass, h, `layers.${li}.input_layernorm`, S, Hd, n1)\n const qkv = W[`layers.${li}.attn.qkv`]\n\n if (useSG && S === 1 && !FORCE_SLOW) {\n // fused decode path: fold copies and elementwise ops into the matmul/norm kernels.\n const q = actBuf(H * Dh),\n k = actBuf(KV * Dh),\n v = actBuf(KV * Dh)\n const Ntot = qkv.N0! + qkv.N1! + qkv.N2!,\n gx = Math.min(Ntot, 65535)\n runWG(pass, 'matmul_split_sg', [['u', qkv.K!], ['u', qkv.nb!], ['u', qkv.N0!], ['u', qkv.N1!], ['u', qkv.N2!], ['u', gx]], [n1, qkv.sign!, qkv.scales!], [q, k, v], gx, Math.ceil(Ntot / gx))\n appendKV(pass, v, 1, li, KV, posBase * KV)\n const qr = actBuf(H * Dh)\n runN(pass, 'rmsnorm_rope_sg', [['u', H], ['u', Dh], ['f', A.rms_eps], ['u', 0], ['u', Dh], ['u', 0]], [q, W[`layers.${li}.attn.q_norm`].buf!, cos, sin], qr, H)\n // Sink mode stores K UNROPED (rotation happens at attention read): bind cos=1/sin=0 so\n // the same write kernels store the plain rmsnorm output.\n const kcos = roll ? rollOnes! : cos,\n ksin = roll ? rollZeros! : sin\n if (kv8) {\n // fused K write, quantizing into the cache (extra scale binding -> its own dispatch)\n setup(pass, 'rmsnorm_rope_sg_kv8', [['u', KV], ['u', Dh], ['f', A.rms_eps], ['u', posBase * KV], ['u', 0], ['u', 0]], [k, W[`layers.${li}.attn.k_norm`].buf!, kcos, ksin], [Kc[li], Ksc[li]])\n pass.dispatchWorkgroups(isFull('rmsnorm_rope_sg_kv8') ? KV : 1)\n } else {\n runN(pass, ROPE_K, [['u', KV], ['u', Dh], ['f', A.rms_eps], ['u', posBase * KV * Dh], ['u', Dh], ['u', 0]], [k, W[`layers.${li}.attn.k_norm`].buf!, kcos, ksin], Kc[li], KV)\n }\n cap(li, 'qr', qr)\n const att = actBuf(H * Dh)\n runN(pass, ATT, [['u', 1], ['u', H], ['u', KV], ['u', Dh], ['u', posBase], ['u', Ltot]], attIns(qr, li), att, H)\n cap(li, 'att', att)\n const o = W[`layers.${li}.attn.o_proj`],\n h2 = actBuf(Hd)\n residMM(pass, o, att, h, 1, h2)\n const n2 = actBuf(Hd)\n rms(pass, h2, `layers.${li}.post_attention_layernorm`, 1, Hd, n2)\n const gu = W[`layers.${li}.mlp.gateup`],\n sw = actBuf(F),\n nwgF = Math.ceil(F / ROWS_MR),\n gxF = Math.min(nwgF, 65535)\n runWG(pass, 'matmul_swiglu_mr_sg', [['u', gu.K!], ['u', gu.nb!], ['u', F], ['u', gxF], ['u', 0], ['u', 0]], [n2, gu.sign!, gu.scales!], [sw], gxF, Math.ceil(nwgF / gxF))\n cap(li, 'sw', sw)\n const d = W[`layers.${li}.mlp.down_proj`],\n hn = actBuf(Hd)\n residMM(pass, d, sw, h2, 1, hn)\n return hn\n }\n\n // prefill / no-subgroup path: separate kernels (kept verbatim; validates correctness end to end)\n const q = actBuf(S * H * Dh),\n k = actBuf(S * KV * Dh),\n v = actBuf(S * KV * Dh)\n fusedMM(pass, qkv, n1, S, [q, k, v])\n const qn = actBuf(S * H * Dh),\n kn = actBuf(S * KV * Dh)\n rms(pass, q, `layers.${li}.attn.q_norm`, S * H, Dh, qn)\n rms(pass, k, `layers.${li}.attn.k_norm`, S * KV, Dh, kn)\n const qr = actBuf(S * H * Dh),\n kr = actBuf(S * KV * Dh)\n run(pass, 'rope', [['u', S], ['u', H], ['u', Dh], ['u', 0]], [qn, cos, sin], qr, S * H * Dh)\n if (!roll) run(pass, 'rope', [['u', S], ['u', KV], ['u', Dh], ['u', 0]], [kn, cos, sin], kr, S * KV * Dh)\n appendKV(pass, roll ? kn : kr, 0, li, S * KV, posBase * KV) // sink mode caches K unroped\n appendKV(pass, v, 1, li, S * KV, posBase * KV)\n cap(li, 'qr', qr)\n const att = actBuf(S * H * Dh)\n const attF: Field[] = [['u', S], ['u', H], ['u', KV], ['u', Dh], ['u', posBase], ['u', Ltot]]\n runN(pass, ATT, attF, attIns(qr, li), att, S * H)\n cap(li, 'att', att)\n const o = W[`layers.${li}.attn.o_proj`],\n h2 = actBuf(S * Hd)\n residMM(pass, o, att, h, S, h2)\n const n2 = actBuf(S * Hd)\n rms(pass, h2, `layers.${li}.post_attention_layernorm`, S, Hd, n2)\n const gu = W[`layers.${li}.mlp.gateup`],\n g = actBuf(S * F),\n u = actBuf(S * F)\n fusedMM(pass, gu, n2, S, [g, u, dummy])\n const sw = actBuf(S * F)\n run(pass, 'swiglu', [['u', S * F], ['u', 0], ['u', 0], ['u', 0]], [g, u], sw, S * F)\n cap(li, 'sw', sw)\n const d = W[`layers.${li}.mlp.down_proj`],\n hn = actBuf(S * Hd)\n residMM(pass, d, sw, h2, S, hn)\n return hn\n }\n function lmHead(pass: GPUComputePassEncoder, fn: GPUBuffer, M: number, out: GPUBuffer): void {\n const lm = W.lm_head\n if (useSG && M === 1) {\n const gx = Math.min(lm.N!, 65535)\n runWG(pass, 'matmul_q2_sg', [['u', lm.N!], ['u', lm.K!], ['u', lm.nb!], ['u', lm.zp!], ['u', gx], ['u', 0]], [fn, lm.codes!, lm.scales!], [out], gx, Math.ceil(lm.N! / gx))\n } else if (M === 1) {\n const gx = Math.min(lm.N!, 65535) // no-subgroup decode: workgroup-reduction 2-bit GEMV\n runWG(pass, 'matmul_q2_wg', [['u', lm.N!], ['u', lm.K!], ['u', lm.nb!], ['u', lm.zp!], ['u', gx], ['u', 0]], [fn, lm.codes!, lm.scales!], [out], gx, Math.ceil(lm.N! / gx))\n } else if (useSG && M === SMALLM) {\n const gx = Math.min(lm.N!, 65535) // small-batch 2-bit GEMV: the code stream read once for all M rows\n runWG(pass, 'matmul_q2_sm', [['u', lm.N!], ['u', lm.K!], ['u', lm.nb!], ['u', lm.zp!], ['u', gx], ['u', M]], [fn, lm.codes!, lm.scales!], [out], gx, Math.ceil(lm.N! / gx))\n } else {\n run(pass, 'matmul_q2', [['u', M], ['u', lm.N!], ['u', lm.K!], ['u', lm.nb!], ['u', 128], ['u', lm.zp!]], [fn, lm.codes!, lm.scales!], out, M * lm.N!)\n }\n }\n\n function stack(enc: GPUCommandEncoder, h: GPUBuffer, S: number, posBase: number): { fn: GPUBuffer; layer0: GPUBuffer | null } {\n const { cos, sin } = ropeBufs(posBase, S)\n const pass = enc.beginComputePass()\n let cur = h,\n layer0: GPUBuffer | null = null\n for (let li = 0; li < A.layers; li++) {\n cur = layer(pass, li, cur, S, posBase, cos, sin)\n if (li === 0) layer0 = cur\n }\n const fn = actBuf(S * Hd)\n rms(pass, cur, FINAL_NORM, S, Hd, fn)\n pass.end()\n return { fn, layer0 }\n }\n\n async function forward(ids: number[]): Promise<ForwardResult> {\n const S = ids.length\n if (S === 0) throw new Error('forward: no tokens to process')\n if (S > maxSeqLen) throw new Error(`forward: sequence length ${S} exceeds maxSeqLen ${maxSeqLen}`)\n // forward() overwrites K/V at positions 0..S-1 of every layer: whatever conversation the cache\n // held is gone, so nothing may reuse it. Same rule as an aborted prefill.\n fullHistory = []\n cacheLen = 0\n await ensureKvCapacity(S)\n const vocab = W.lm_head.N!\n // Segmented like runPrefill (bit-exact by the same composition the reuse gates prove), so a\n // long forward() neither dispatches >65535 workgroups in one dimension (S*heads at full\n // maxSeqLen) nor binds an S x vocab logits buffer beyond the negotiated binding limit.\n const embed = new Float32Array(S * Hd),\n layer0 = new Float32Array(S * Hd),\n finalnorm = new Float32Array(S * Hd),\n logits = new Float32Array(S * vocab)\n transients = []\n try {\n for (let off = 0; off < S; off += PREFILL_SEG) {\n const seg = ids.slice(off, off + PREFILL_SEG)\n const enc = device.createCommandEncoder()\n const embedOut = embedBatch(enc, seg)\n const { fn, layer0: l0 } = stack(enc, embedOut, seg.length, off)\n const lg = device.createBuffer({ size: seg.length * vocab * 4, usage: S_ | CS })\n transients.push(lg)\n const pass = enc.beginComputePass()\n lmHead(pass, fn, seg.length, lg)\n pass.end()\n device.queue.submit([enc.finish()])\n await device.queue.onSubmittedWorkDone()\n embed.set(await readback(embedOut, seg.length * Hd), off * Hd)\n layer0.set(await readback(l0!, seg.length * Hd), off * Hd)\n finalnorm.set(await readback(fn, seg.length * Hd), off * Hd)\n logits.set(await readback(lg, seg.length * vocab), off * vocab)\n flushTransients() // this segment's scratch is dead; the peak stays at one segment\n }\n return { embed, layer0, finalnorm, logits, vocab, sequenceLength: S }\n } finally {\n flushTransients()\n transients = null\n }\n }\n\n // Long prefills run in SEGMENTS. One submission holding all layers' scratch for S tokens keeps\n // ~S x 4.3 MB of VRAM in flight (a 1000-token prompt ~4 GB): on unified-memory devices that\n // stalls the whole system, especially with other models resident. Segments cap the spike at one\n // segment's scratch (flushed between them), stay bit-exact by the same composition the\n // reuse-prefill gates prove (each segment writes K/V at its offset and attends to everything\n // before it), and give an abort a place to land mid-prompt, so a superseded turn no longer\n // blocks the GPU for whole seconds. Returns the LAST segment's final-norm buffer + the final\n // token's row within it, or null when aborted (fullHistory is cleared: K/V is only partially\n // written, so nothing may reuse the sequence).\n async function runPrefill(ids: number[], posBase: number, signal?: AbortSignal): Promise<{ fn: GPUBuffer; lastRow: number } | null> {\n let fn: GPUBuffer | null = null\n let lastRow = 0\n for (let off = 0; off < ids.length; off += PREFILL_SEG) {\n if (off > 0 && signal?.aborted) {\n fullHistory = []\n cacheLen = 0\n return null\n }\n const seg = ids.slice(off, off + PREFILL_SEG)\n const enc = device.createCommandEncoder()\n fn = stack(enc, embedBatch(enc, seg), seg.length, posBase + off).fn\n lastRow = seg.length - 1\n device.queue.submit([enc.finish()])\n if (off + PREFILL_SEG < ids.length) {\n await device.queue.onSubmittedWorkDone()\n flushTransients() // this segment's scratch is dead; the peak stays at one segment\n }\n }\n return { fn: fn!, lastRow }\n }\n\n // GPU-resident decode: argmax + embedding gather run on the GPU so the token id never leaves it;\n // chain syncN steps per CPU sync (deferred readback). Bit-exact: only the readback timing changes.\n async function generateImpl(ids: number[], posBase: number, nTokens: number, full: Set<string> | null = null, syncN: number = SYNC_N, ctl?: { stopTokens?: number[]; onToken?: (id: number) => void; signal?: AbortSignal }): Promise<RawGenResult> {\n await ensureKvCapacity(posBase + ids.length + nTokens)\n FULL = full\n const vocab = W.lm_head.N!\n const tokBuf = device.createBuffer({ size: Math.max(1, nTokens) * 4, usage: S_ | CS }) // GPU-resident token ids\n const embG = device.createBuffer({ size: Hd * 4, usage: S_ | CS | CD }) // GPU embedding of the current token (lives across the whole call)\n const lg = device.createBuffer({ size: vocab * 4, usage: S_ | CS })\n transients = [] // track prefill scratch so it can be destroyed once the prefill completes\n try {\n const t0 = performance.now()\n // prefill (CPU embed of the known prompt, segmented) -> last hidden -> lm_head -> GPU argmax\n const pfx = await runPrefill(ids, posBase, ctl?.signal)\n if (!pfx) return { prefillMs: performance.now() - t0, decodeMs: 0, tokPerSec: 0, tokens: [], firstArgmax: -1, recMs: 0, gpuMs: 0, rbMs: 0 }\n const encP = device.createCommandEncoder()\n const lastP = actBuf(Hd)\n encP.copyBufferToBuffer(pfx.fn, pfx.lastRow * Hd * 4, lastP, 0, Hd * 4)\n let pp = encP.beginComputePass()\n lmHead(pp, lastP, 1, lg)\n pp.end()\n pp = encP.beginComputePass()\n runN(pp, 'argmax', [['u', vocab], ['u', 0], ['u', 0], ['u', 0]], [lg], tokBuf, 1)\n pp.end()\n device.queue.submit([encP.finish()])\n await device.queue.onSubmittedWorkDone()\n const firstTok = (await readbackU32(tokBuf, 1))[0]\n flushTransients() // the last segment's scratch is dead now\n const prefillMs = performance.now() - t0\n\n const gen: number[] = []\n let recMs = 0,\n gpuMs = 0,\n rbMs = 0\n const t1 = performance.now()\n let total = 1 // decode positions consumed (incl. prefill's first)\n const stopSet = ctl?.stopTokens ? new Set(ctl.stopTokens) : null\n let stopped = stopSet?.has(firstTok) ?? false\n if (!stopped) {\n gen.push(firstTok) // a stop token is never emitted, even at position 0\n ctl?.onToken?.(firstTok)\n }\n poolInvalidate() // rebuild cached bind groups against this call's buffers\n let slot = posBase + ids.length // cache slot where the next fed token's K/V lands\n while (total < nTokens && !stopped) {\n if (ctl?.signal?.aborted) break\n const batch = Math.min(syncN, nTokens - total)\n slot = evictFor(slot, batch) // sink mode: roll the window before the batch needs the room\n poolUse('decode') // reuse decode scratch + uniforms across batches; resets the slot indices\n let t = performance.now()\n const enc = device.createCommandEncoder()\n for (let j = 0; j < batch; j++) {\n const idxOut = total + j,\n pos = slot + j\n let pass = enc.beginComputePass()\n runN(pass, 'embed_gather', [['u', Hd], ['u', idxOut - 1], ['u', 0], ['u', 0]], [tokBuf, embWqG, tgt4G, embScalesG, embZpG], embG, 1)\n pass.end()\n const r = stack(enc, embG, 1, pos)\n const last = actBuf(Hd)\n enc.copyBufferToBuffer(r.fn, 0, last, 0, Hd * 4)\n pass = enc.beginComputePass()\n lmHead(pass, last, 1, lg)\n runN(pass, 'argmax', [['u', vocab], ['u', idxOut], ['u', 0], ['u', 0]], [lg], tokBuf, 1)\n pass.end()\n }\n device.queue.submit([enc.finish()])\n recMs += performance.now() - t\n t = performance.now()\n await device.queue.onSubmittedWorkDone()\n gpuMs += performance.now() - t\n t = performance.now()\n const toks = await readbackU32(tokBuf, total + batch)\n rbMs += performance.now() - t\n let fed = batch // slots that belong to the history (EOS discards the rest of the batch)\n for (let j = 0; j < batch; j++) {\n const tk = toks[total + j]\n if (stopSet?.has(tk)) { stopped = true; fed = j; break } // EOS lands at the batch boundary (greedy)\n gen.push(tk)\n ctl?.onToken?.(tk)\n }\n total += batch\n slot += fed\n }\n cacheLen = slot // sink-mode bookkeeping: the last history token's (re-feed) slot\n const decodeMs = performance.now() - t1,\n nd = Math.max(1, gen.length - 1)\n return { prefillMs, decodeMs, tokPerSec: nd / (decodeMs / 1000), tokens: gen, firstArgmax: firstTok, recMs: recMs / nd, gpuMs: gpuMs / nd, rbMs: rbMs / nd }\n } finally {\n // Restore the shared flags even when a step throws (a stuck active pool would corrupt every\n // later call), and release this call's GPU scratch instead of waiting on GC.\n poolUse(null)\n FULL = null\n flushTransients()\n transients = null\n tokBuf.destroy()\n embG.destroy()\n lg.destroy()\n }\n }\n\n // Sampled decode (do_sample): the GPU pre-filters the logits in place (repetition_penalty +\n // no_repeat_ngram bans) and selects the top-K via K masked-argmax passes; only K (id, logit) pairs\n // are read back, and the CPU does temperature + softmax + MT19937 multinomial (exact transformers.js\n // semantics). Per-step (syncN=1) because the chosen token is picked on the CPU and feeds the next\n // step's embed gather. A GREEDY turn with processors (repetition_penalty / no_repeat_ngram) also\n // runs here - the chain filters, then pick() takes the penalized argmax without touching the RNG.\n // Plain greedy decode (generateImpl) is the separate, untouched GPU-resident path.\n async function generateSampledImpl(ids: number[], posBase: number, nTokens: number, genOpts: GenerateOptions, history: number[], rngIn?: MT19937): Promise<RawGenResult> {\n await ensureKvCapacity(posBase + ids.length + nTokens)\n // `ids` = the tokens to prefill this turn (the whole prompt, or [lastToken, ...delta] on reuse).\n // `history` = the FULL conversation token sequence (shared, mutated): the sampler's penalty/ngram\n // see the entire sequence, like transformers.js; generated tokens are pushed onto it.\n const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1\n const vocab = W.lm_head.N!\n const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab))\n // logprobs: run extra argmax rounds when N exceeds the sampling top-K, but NEVER let it widen\n // the sampling pool - the draw stays over the first K candidates, bit-identical with or\n // without logprobs on.\n const lpN = Math.max(0, Math.min(Math.floor(genOpts.logprobs ?? 0), 32, vocab))\n const KT = Math.max(K, lpN)\n const temperature = genOpts.temperature ?? 1\n const penalty = genOpts.repetitionPenalty ?? 1\n const ngramN = genOpts.noRepeatNgramSize ?? 0\n const stopSet = genOpts.stopTokens ? new Set(genOpts.stopTokens) : null\n const onToken = genOpts.onToken\n const signal = genOpts.signal\n const rng = rngIn ?? new MT19937(genOpts.seed)\n\n // persistent buffers (stable across steps for bind-group caching; not via actBuf)\n const tokBuf = device.createBuffer({ size: Math.max(1, nTokens) * 4, usage: S_ | CS | CD })\n const lg = device.createBuffer({ size: vocab * 4, usage: S_ | CS })\n const candIds = device.createBuffer({ size: KT * 4, usage: S_ | CS })\n const candVals = device.createBuffer({ size: KT * 4, usage: S_ | CS })\n const lseBuf = device.createBuffer({ size: 4, usage: S_ | CS }) // log-sum-exp normalizer (logprobs)\n const affBuf = device.createBuffer({ size: maxSeqLen * 4, usage: S_ | CD }) // upper bound = full vocab can't exceed seq len\n const banBuf = device.createBuffer({ size: maxSeqLen * 4, usage: S_ | CD })\n const rbBuf = device.createBuffer({ size: KT * 8 + (lpN ? 4 : 0), usage: GPUBufferUsage.MAP_READ | CD })\n const embG = device.createBuffer({ size: Hd * 4, usage: S_ | CS | CD })\n\n // upload the CPU-computed deduped id set + ngram bans for the current history; return their lengths\n const writeAffBan = (history: number[]): { affLen: number; banLen: number } => {\n const aff = penalty !== 1 ? affectedIds(history) : new Uint32Array(0)\n if (aff.length) device.queue.writeBuffer(affBuf, 0, aff)\n const ban = ngramN > 0 ? ngramBans(history, ngramN) : []\n if (ban.length) device.queue.writeBuffer(banBuf, 0, Uint32Array.from(ban))\n return { affLen: aff.length, banLen: ban.length }\n }\n // penalty pre-filter (+ logprobs normalizer) + KT masked-argmax, all in the given pass (after\n // lm_head wrote lg). The log-sum-exp runs BEFORE the argmax rounds: those mask their winners\n // in lg in place, which would corrupt the sum.\n const samplerChain = (pass: GPUComputePassEncoder, affLen: number, banLen: number): void => {\n setup(pass, 'sampler_penalty', [['u', affLen], ['u', banLen], ['f', penalty], ['u', 0xff800000]], [affBuf, banBuf], [lg])\n pass.dispatchWorkgroups(1)\n if (lpN) {\n setup(pass, 'logsumexp', [['u', vocab], ['u', 0], ['u', 0], ['u', 0]], [lg], [lseBuf])\n pass.dispatchWorkgroups(1)\n }\n for (let r = 0; r < KT; r++) {\n setup(pass, 'argmax_masked', [['u', vocab], ['u', r], ['u', 0], ['u', 0]], [lg], [candIds, candVals])\n pass.dispatchWorkgroups(1)\n }\n }\n const copyCands = (enc: GPUCommandEncoder): void => {\n enc.copyBufferToBuffer(candIds, 0, rbBuf, 0, KT * 4)\n enc.copyBufferToBuffer(candVals, 0, rbBuf, KT * 4, KT * 4)\n if (lpN) enc.copyBufferToBuffer(lseBuf, 0, rbBuf, KT * 8, 4)\n }\n const readCands = async (): Promise<{ ci: Uint32Array; cv: Float32Array; lse: number }> => {\n await rbBuf.mapAsync(GPUMapMode.READ)\n const mapped = rbBuf.getMappedRange()\n const ci = new Uint32Array(mapped.slice(0, KT * 4))\n const cv = new Float32Array(mapped.slice(KT * 4, KT * 8))\n const lse = lpN ? new Float32Array(mapped.slice(KT * 8, KT * 8 + 4))[0] : 0\n rbBuf.unmap()\n return { ci, cv, lse }\n }\n // logprobs bookkeeping: the chosen token's logit (set by every chooseToken path) and the\n // per-emitted-token records (aligned with the returned tokens)\n let chosenLogit = 0\n const lpOut: TokenLogprobs[] | null = lpN ? [] : null\n const recordLp = (ci: Uint32Array, cv: Float32Array, lse: number): void => {\n if (!lpOut) return\n const top: { id: number; logprob: number }[] = []\n for (let i = 0; i < lpN; i++) top.push({ id: ci[i], logprob: cv[i] - lse })\n lpOut.push({ logprob: chosenLogit - lse, top })\n }\n // candidates are descending, so ci[0] is the argmax of the penalized logits (greedy+processors);\n // sampling and filtering see only the first K candidates (KT > K rounds exist for logprobs only)\n const pick = (ciAll: Uint32Array, cvAll: Float32Array): number => {\n const ci = ciAll.subarray(0, K)\n const cv = cvAll.subarray(0, K)\n const tk = sampled ? sampleFromCandidates(ci, cv, temperature, rng) : ci[0]\n chosenLogit = cv[ci.indexOf(tk)]\n return tk\n }\n const filter = genOpts.candidateFilter\n // Constrained pick (candidateFilter): keep the permitted subset in rank order and pick within\n // it - greedy takes the best permitted, sampling renormalizes the draw over them (exactly one\n // RNG draw per emitted token, like the unconstrained path). When the whole top-K is rejected,\n // walk the FULL vocabulary in logit order (rare: valid grammars almost always admit a top-K\n // token) and rebuild up to K permitted candidates; a grammar that admits nothing is a bug in\n // the filter and fails loudly.\n const chooseToken = async (ciAll: Uint32Array, cvAll: Float32Array): Promise<number> => {\n if (!filter) return pick(ciAll, cvAll)\n const ci = ciAll.subarray(0, K)\n const cv = cvAll.subarray(0, K)\n const perm = new Set(filter(ci, cv))\n if (perm.size > 0) {\n const pIds: number[] = []\n const pVals: number[] = []\n for (let i = 0; i < ci.length; i++)\n if (perm.has(ci[i])) {\n pIds.push(ci[i])\n pVals.push(cv[i])\n }\n const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng) : pIds[0]\n chosenLogit = pVals[pIds.indexOf(tk)]\n return tk\n }\n const all = await readback(lg, vocab) // penalized logits; every argmax round masked its winner in place\n // Restore the masked entries from the candidates already read back: the filter-rejected\n // top-K re-check and fail again (filters are deterministic), and the extra logprobs-only\n // rounds (K..KT) must stay reachable or logprobs would change constrained output.\n for (let i = 0; i < ciAll.length; i++) all[ciAll[i]] = cvAll[i]\n const order = Array.from(all.keys()).sort((a, b) => all[b] - all[a] || a - b)\n const pIds: number[] = []\n const pVals: number[] = []\n const B = 512\n for (let i = 0; i < order.length && pIds.length < K; i += B) {\n if (all[order[i]] === -Infinity) break // sorted: only masked/banned entries remain\n const batch = order.slice(i, i + B).filter((id) => all[id] !== -Infinity)\n const ok = new Set(filter(Uint32Array.from(batch), Float32Array.from(batch.map((id) => all[id]))))\n for (const id of batch) {\n if (ok.has(id)) {\n pIds.push(id)\n pVals.push(all[id])\n if (pIds.length >= K) break\n }\n }\n }\n if (pIds.length === 0) throw new Error('bitgpu: candidateFilter permitted no token in the entire vocabulary')\n const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng) : pIds[0]\n chosenLogit = pVals[pIds.indexOf(tk)]\n return tk\n }\n\n transients = [] // track prefill scratch so it can be destroyed once the prefill completes\n try {\n const t0 = performance.now()\n // prefill (segmented) -> last hidden -> lm_head -> sampler chain, CPU samples the first token\n const pfx = await runPrefill(ids, posBase, signal)\n if (!pfx) return { prefillMs: performance.now() - t0, decodeMs: 0, tokPerSec: 0, tokens: [], firstArgmax: -1, recMs: 0, gpuMs: 0, rbMs: 0, rng }\n const encP = device.createCommandEncoder()\n const lastP = actBuf(Hd)\n encP.copyBufferToBuffer(pfx.fn, pfx.lastRow * Hd * 4, lastP, 0, Hd * 4)\n const pf = writeAffBan(history)\n let pass = encP.beginComputePass()\n lmHead(pass, lastP, 1, lg)\n samplerChain(pass, pf.affLen, pf.banLen)\n pass.end()\n copyCands(encP)\n device.queue.submit([encP.finish()])\n const first = await readCands() // mapAsync waits for the submitted work; no separate sync needed\n const firstTok = await chooseToken(first.ci, first.cv)\n flushTransients() // the last segment's scratch is dead now (the map wait proved the GPU is done with it)\n const prefillMs = performance.now() - t0\n\n const gen: number[] = []\n let stopped = stopSet?.has(firstTok) ?? false\n if (!stopped) {\n gen.push(firstTok) // a stop token is never emitted or recorded, even at position 0\n history.push(firstTok)\n recordLp(first.ci, first.cv, first.lse)\n onToken?.(firstTok)\n device.queue.writeBuffer(tokBuf, 0, new Uint32Array([firstTok]))\n }\n\n let recMs = 0, gpuMs = 0, rbMs = 0\n const t1 = performance.now()\n let total = 1\n poolInvalidate() // rebuild cached bind groups against this call's buffers\n let slot = posBase + ids.length // cache slot where the next fed token's K/V lands\n while (total < nTokens && !stopped) {\n if (signal?.aborted) break\n poolUse('decode')\n slot = evictFor(slot, 1) // sink mode: roll the window before this step needs the room\n const idxOut = total, pos = slot\n let t = performance.now()\n const { affLen, banLen } = writeAffBan(history)\n const enc = device.createCommandEncoder()\n let p2 = enc.beginComputePass()\n runN(p2, 'embed_gather', [['u', Hd], ['u', idxOut - 1], ['u', 0], ['u', 0]], [tokBuf, embWqG, tgt4G, embScalesG, embZpG], embG, 1)\n p2.end()\n const r = stack(enc, embG, 1, pos)\n const last = actBuf(Hd)\n enc.copyBufferToBuffer(r.fn, 0, last, 0, Hd * 4)\n p2 = enc.beginComputePass()\n lmHead(p2, last, 1, lg)\n samplerChain(p2, affLen, banLen)\n p2.end()\n copyCands(enc)\n device.queue.submit([enc.finish()])\n recMs += performance.now() - t\n t = performance.now()\n // ONE sync per token: mapAsync on the readback buffer already waits for the submitted\n // work its copy depends on, so a separate onSubmittedWorkDone is a second full CPU-GPU\n // round-trip for nothing. The map wait is dominated by GPU time, so it is attributed to\n // gpuMs; the post-map array slicing is microseconds (rbMs stays for API stability).\n const { ci, cv, lse } = await readCands()\n gpuMs += performance.now() - t\n t = performance.now()\n const tk = await chooseToken(ci, cv)\n rbMs += performance.now() - t\n total += 1\n if (stopSet?.has(tk)) { stopped = true; break } // EOS: stop without emitting the stop token\n gen.push(tk)\n history.push(tk)\n recordLp(ci, cv, lse)\n onToken?.(tk)\n device.queue.writeBuffer(tokBuf, idxOut * 4, new Uint32Array([tk])) // feed the next step's embed gather\n slot += 1\n }\n cacheLen = slot // sink-mode bookkeeping (filled slots; the last emitted token is unfed)\n const decodeMs = performance.now() - t1\n const nd = Math.max(1, gen.length - 1)\n return { prefillMs, decodeMs, tokPerSec: nd / (decodeMs / 1000), tokens: gen, firstArgmax: firstTok, recMs: recMs / nd, gpuMs: gpuMs / nd, rbMs: rbMs / nd, rng, ...(lpOut ? { lp: lpOut } : {}) }\n } finally {\n // Restore the shared flags even when a step throws, and release this call's GPU buffers.\n poolUse(null)\n flushTransients()\n transients = null\n for (const b of [tokBuf, lg, candIds, candVals, lseBuf, affBuf, banBuf, rbBuf, embG]) b.destroy()\n }\n }\n\n // Prompt-lookup speculative decoding, greedy AND sampled. Each step drafts the continuation\n // from an n-gram match in the sequence so far (draftNgram; no draft model), then verifies all\n // drafts in ONE batched forward through the prefill path: it writes K/V for every drafted\n // position and yields logits for every row, so the accepted prefix plus one model-chosen token\n // are emitted for the cost of a single pass. K/V written for rejected positions is overwritten\n // by later steps before anything ever attends to it (attention at position p reads only 0..p).\n // Exactness: row j is only consumed when drafts 0..j-1 were accepted, so its logits (and, when\n // sampling, its penalty/ban lists, computed assuming those drafts) describe the true sequence;\n // the sampler draws sequentially on the CPU, so the MT19937 stream advances exactly one draw\n // per EMITTED token, in order - the output equals non-speculative decoding for the same seed.\n // With no match the step degenerates to a normal single-token pass (S=1 keeps the fused path).\n async function generatePldImpl(ids: number[], posBase: number, nTokens: number, genOpts: GenerateOptions, history: number[], rngIn?: MT19937): Promise<RawGenResult> {\n await ensureKvCapacity(posBase + ids.length + nTokens)\n const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1\n const vocab = W.lm_head.N!\n const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab))\n const temperature = genOpts.temperature ?? 1\n const penalty = genOpts.repetitionPenalty ?? 1\n const ngramN = genOpts.noRepeatNgramSize ?? 0\n const pl = typeof genOpts.promptLookup === 'object' && genOpts.promptLookup !== null ? genOpts.promptLookup : {}\n const ngramSize = Math.max(2, pl.ngramSize ?? 3)\n const maxDraft = Math.max(1, pl.maxDraft ?? 8)\n const stopSet = genOpts.stopTokens ? new Set(genOpts.stopTokens) : null\n const onToken = genOpts.onToken\n const signal = genOpts.signal\n const rng = rngIn ?? new MT19937(genOpts.seed)\n // Greedy with processors (repetition_penalty / no_repeat_ngram) also needs the per-row sampler\n // chain - the penalties see each row's history - but picks the penalized argmax, no RNG draw.\n const useChain = sampled || penalty !== 1 || ngramN > 0\n\n const lg = device.createBuffer({ size: vocab * 4, usage: S_ | CS | CD }) // one row, target of the per-row copy\n const lgAll = device.createBuffer({ size: (maxDraft + 1) * vocab * 4, usage: S_ | CS }) // lm_head over all rows\n const idsOut = device.createBuffer({ size: (maxDraft + 1) * 4, usage: S_ | CS }) // greedy: argmax per row\n const candIds = device.createBuffer({ size: K * 4, usage: S_ | CS })\n const candVals = device.createBuffer({ size: K * 4, usage: S_ | CS })\n const affBuf = device.createBuffer({ size: (maxSeqLen + maxDraft + 1) * 4, usage: S_ | CD })\n const banBuf = device.createBuffer({ size: (maxSeqLen + maxDraft + 1) * 4, usage: S_ | CD })\n const rbAll = device.createBuffer({ size: (maxDraft + 1) * K * 8, usage: GPUBufferUsage.MAP_READ | CD })\n // Step input token ids + their gathered embeddings, written per step (never re-created: the\n // pooled bind groups cache buffer identities, so a per-step upload would go stale the moment\n // it was destroyed). The embeddings are gathered ON the GPU (embed_gather_batch) from the\n // uploaded ids - only S u32s cross the bus per step, and no CPU embedding tables exist.\n const pldIds = device.createBuffer({ size: (maxDraft + 1) * 4, usage: S_ | CD })\n const embIn = device.createBuffer({ size: (maxDraft + 1) * Hd * 4, usage: S_ | CD })\n\n const writeAffBan = (h: number[]): { affLen: number; banLen: number } => {\n const aff = penalty !== 1 ? affectedIds(h) : new Uint32Array(0)\n if (aff.length) device.queue.writeBuffer(affBuf, 0, aff)\n const ban = ngramN > 0 ? ngramBans(h, ngramN) : []\n if (ban.length) device.queue.writeBuffer(banBuf, 0, Uint32Array.from(ban))\n return { affLen: aff.length, banLen: ban.length }\n }\n const samplerChain = (pass: GPUComputePassEncoder, affLen: number, banLen: number): void => {\n setup(pass, 'sampler_penalty', [['u', affLen], ['u', banLen], ['f', penalty], ['u', 0xff800000]], [affBuf, banBuf], [lg])\n pass.dispatchWorkgroups(1)\n for (let r = 0; r < K; r++) {\n setup(pass, 'argmax_masked', [['u', vocab], ['u', r], ['u', 0], ['u', 0]], [lg], [candIds, candVals])\n pass.dispatchWorkgroups(1)\n }\n }\n // draw the row-j candidates from a mapped copy of rbAll (candidates are descending, so\n // index 0 is the penalized argmax for a greedy-with-processors turn - no RNG draw)\n const rowDraw = (m: ArrayBuffer, j: number): number =>\n sampled\n ? sampleFromCandidates(new Uint32Array(m, j * K * 8, K), new Float32Array(m, j * K * 8 + K * 4, K), temperature, rng)\n : new Uint32Array(m, j * K * 8, 1)[0]\n\n transients = []\n try {\n const t0 = performance.now()\n // prefill (segmented) -> last hidden -> lm_head -> argmax (greedy) or sampler chain (sampled)\n const pfx = await runPrefill(ids, posBase, signal)\n if (!pfx) return { prefillMs: performance.now() - t0, decodeMs: 0, tokPerSec: 0, tokens: [], firstArgmax: -1, recMs: 0, gpuMs: 0, rbMs: 0, spec: { steps: 0, drafted: 0, accepted: 0 }, rng }\n const encP = device.createCommandEncoder()\n const lastP = actBuf(Hd)\n encP.copyBufferToBuffer(pfx.fn, pfx.lastRow * Hd * 4, lastP, 0, Hd * 4)\n const pf = useChain ? writeAffBan(history) : null\n let pass = encP.beginComputePass()\n lmHead(pass, lastP, 1, lg)\n if (pf) samplerChain(pass, pf.affLen, pf.banLen)\n else runN(pass, 'argmax', [['u', vocab], ['u', 0], ['u', 0], ['u', 0]], [lg], idsOut, 1)\n pass.end()\n if (pf) {\n encP.copyBufferToBuffer(candIds, 0, rbAll, 0, K * 4)\n encP.copyBufferToBuffer(candVals, 0, rbAll, K * 4, K * 4)\n }\n device.queue.submit([encP.finish()])\n await device.queue.onSubmittedWorkDone()\n let firstTok: number\n if (pf) {\n await rbAll.mapAsync(GPUMapMode.READ)\n const m = rbAll.getMappedRange().slice(0)\n rbAll.unmap()\n firstTok = rowDraw(m, 0)\n } else {\n firstTok = (await readbackU32(idsOut, 1))[0]\n }\n flushTransients()\n const prefillMs = performance.now() - t0\n\n const gen: number[] = []\n let stopped = stopSet?.has(firstTok) ?? false\n if (!stopped) {\n gen.push(firstTok)\n history.push(firstTok)\n onToken?.(firstTok)\n }\n poolInvalidate() // rebuild cached bind groups against THIS call's persistent buffers\n let total = 1\n let tLast = firstTok\n let pos = posBase + ids.length // where tLast's K/V lands on the next step\n let specSteps = 0,\n drafted = 0,\n accepted = 0\n let recMs = 0,\n gpuMs = 0,\n rbMs = 0\n const t1 = performance.now()\n while (total < nTokens && !stopped) {\n if (signal?.aborted) break\n pos = evictFor(pos, maxDraft + 1) // sink mode: roll before a full drafting step needs the room\n const kMax = Math.min(maxDraft, nTokens - total - 1, maxSeqLen - 1 - pos)\n const drafts = kMax > 0 ? draftNgram(history, ngramSize, kMax) : []\n const S = drafts.length + 1\n await ensureKvCapacity(pos + S)\n let t = performance.now()\n // Pools: 'pld1' = the fused single-token sequence, 'pldm' = the verify sequence (identical\n // dispatch order for every S in 2..9; buffers rounded to 9 rows so sizes are S-invariant).\n // S > 9 (a raised maxDraft) falls back to unpooled scalar kernels - correct, just slower.\n if (S === 1) poolUse('pld1')\n else if (useSG && S <= 9) poolUse('pldm', S, 9)\n else poolUse(null)\n device.queue.writeBuffer(pldIds, 0, new Uint32Array([tLast, ...drafts]))\n // shared forward: [tLast, ...drafts] at pos -> K/V for pos..pos+S-1 + logits for every row.\n // Routed through the small-batch kernels (weights read once for all S rows); S=1 keeps\n // the fused decode path via the S===1 branches.\n SMALLM = useSG && S >= 2 && S <= 9 ? S : 0\n const enc = device.createCommandEncoder()\n const gp = enc.beginComputePass()\n run(gp, 'embed_gather_batch', [['u', S], ['u', Hd], ['u', 0], ['u', 0]], [pldIds, embWqG, tgt4G, embScalesG, embZpG], embIn, S * Hd)\n gp.end()\n const r = stack(enc, embIn, S, pos)\n pass = enc.beginComputePass()\n lmHead(pass, r.fn, S, lgAll)\n pass.end()\n SMALLM = 0\n if (!useChain) {\n for (let j = 0; j < S; j++) {\n enc.copyBufferToBuffer(lgAll, j * vocab * 4, lg, 0, vocab * 4)\n const p = enc.beginComputePass()\n runN(p, 'argmax', [['u', vocab], ['u', j], ['u', 0], ['u', 0]], [lg], idsOut, 1)\n p.end()\n }\n device.queue.submit([enc.finish()])\n } else {\n device.queue.submit([enc.finish()])\n // per row: upload that row's penalty state (queue order puts it before the row's\n // dispatches), copy the row into lg, run the chain, stash the K candidates in rbAll\n for (let j = 0; j < S; j++) {\n const rowHist = j === 0 ? history : [...history, ...drafts.slice(0, j)]\n const { affLen, banLen } = writeAffBan(rowHist)\n const e2 = device.createCommandEncoder()\n e2.copyBufferToBuffer(lgAll, j * vocab * 4, lg, 0, vocab * 4)\n const p = e2.beginComputePass()\n samplerChain(p, affLen, banLen)\n p.end()\n e2.copyBufferToBuffer(candIds, 0, rbAll, j * K * 8, K * 4)\n e2.copyBufferToBuffer(candVals, 0, rbAll, j * K * 8 + K * 4, K * 4)\n device.queue.submit([e2.finish()])\n }\n }\n recMs += performance.now() - t\n t = performance.now()\n await device.queue.onSubmittedWorkDone()\n gpuMs += performance.now() - t\n t = performance.now()\n // acceptance: emit row draws in order while they agree with the drafts; the first\n // disagreement is itself a valid emission (it came from the true distribution)\n const emitted: number[] = []\n if (!useChain) {\n const outs = await readbackU32(idsOut, S)\n for (let j = 0; j < S; j++) {\n const tk = outs[j]\n if (stopSet?.has(tk)) { stopped = true; break }\n emitted.push(tk)\n if (j < drafts.length && tk !== drafts[j]) break\n }\n } else {\n await rbAll.mapAsync(GPUMapMode.READ)\n const m = rbAll.getMappedRange().slice(0)\n rbAll.unmap()\n for (let j = 0; j < S; j++) {\n const tk = rowDraw(m, j) // draws only for rows actually reached: one per emitted token\n if (stopSet?.has(tk)) { stopped = true; break }\n emitted.push(tk)\n if (j < drafts.length && tk !== drafts[j]) break\n }\n }\n rbMs += performance.now() - t\n specSteps++\n drafted += drafts.length\n accepted += Math.max(0, emitted.length - 1)\n for (const tk of emitted) {\n gen.push(tk)\n history.push(tk)\n onToken?.(tk)\n }\n total += emitted.length\n flushTransients()\n if (emitted.length === 0) break // stop token at row 0\n pos += emitted.length\n tLast = emitted[emitted.length - 1]\n }\n cacheLen = pos // sink-mode bookkeeping: the last history token's (re-feed) slot\n const decodeMs = performance.now() - t1\n const nd = Math.max(1, gen.length - 1)\n return {\n prefillMs,\n decodeMs,\n tokPerSec: nd / (decodeMs / 1000),\n tokens: gen,\n firstArgmax: firstTok,\n recMs: recMs / nd,\n gpuMs: gpuMs / nd,\n rbMs: rbMs / nd,\n spec: { steps: specSteps, drafted, accepted },\n rng,\n }\n } finally {\n SMALLM = 0 // encode-time flag; a throw mid-encode must not leak it into other paths\n poolUse(null)\n flushTransients()\n transients = null\n for (const b of [lg, lgAll, idsOut, candIds, candVals, affBuf, banBuf, rbAll, embIn, pldIds]) b.destroy()\n }\n }\n\n // Run ONE decode step at the same position through the fused path and the slow (known-good) path\n // and return layer-0 checkpoints + final norm + logits for each, so a divergence pinpoints the\n // first fused kernel that differs.\n async function debugDecode(prefillIds: number[]): Promise<{ fast: Record<string, Float32Array>; slow: Record<string, Float32Array> }> {\n await ensureKvCapacity(prefillIds.length + 1)\n const encP = device.createCommandEncoder()\n stack(encP, embedBatch(encP, prefillIds), prefillIds.length, 0)\n device.queue.submit([encP.finish()])\n await device.queue.onSubmittedWorkDone()\n const pos = prefillIds.length,\n tok = prefillIds[prefillIds.length - 1]\n const runStep = async (forceSlow: boolean): Promise<Record<string, Float32Array>> => {\n FORCE_SLOW = forceSlow\n DBG0 = {}\n const enc = device.createCommandEncoder()\n const r = stack(enc, embedBatch(enc, [tok]), 1, pos)\n const lg = device.createBuffer({ size: W.lm_head.N! * 4, usage: S_ | CS })\n const pass = enc.beginComputePass()\n lmHead(pass, r.fn, 1, lg)\n pass.end()\n device.queue.submit([enc.finish()])\n await device.queue.onSubmittedWorkDone()\n const ck: Record<string, Float32Array> = {}\n for (const [name, b] of Object.entries(DBG0)) ck[name] = await readback(b, b.size / 4)\n const off = pos * KV * Dh\n if (!kv16 && !kv8) {\n // f32-mode only: readback() types the bytes as f32, which is wrong for an f16/q8 cache\n ck.kc = (await readback(Kc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh) // kvCapacity, not maxSeqLen: the cache may not have grown yet\n ck.vc = (await readback(Vc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh)\n }\n ck.fn = await readback(r.fn, Hd)\n ck.logits = await readback(lg, W.lm_head.N!)\n FORCE_SLOW = false\n DBG0 = null\n return ck\n }\n const fast = await runStep(false),\n slow = await runStep(true)\n return { fast, slow }\n }\n\n // Debug hook for the browser harness: run a prefill for `ids` (history = ids), then return the GPU\n // lm_head logits (base, pre-penalty), the GPU penalized logits, and the GPU top-K. The page penalizes\n // `base` on the CPU and diffs vs `penalized` (exact, same input), and compares its top-K vs candIds,\n // validating sampler_penalty.wgsl and argmax_masked.wgsl in isolation against the headless-checked math.\n async function debugSampler(ids: number[], genOpts: GenerateOptions): Promise<{ base: Float32Array; penalized: Float32Array; candIds: Uint32Array; candVals: Float32Array }> {\n const vocab = W.lm_head.N!\n const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab))\n const penalty = genOpts.repetitionPenalty ?? 1\n const ngramN = genOpts.noRepeatNgramSize ?? 0\n const lg = device.createBuffer({ size: vocab * 4, usage: S_ | CS })\n const candIds = device.createBuffer({ size: K * 4, usage: S_ | CS })\n const candVals = device.createBuffer({ size: K * 4, usage: S_ | CS })\n const aff = penalty !== 1 ? affectedIds(ids) : new Uint32Array(0)\n const ban = ngramN > 0 ? ngramBans(ids, ngramN) : []\n const affBuf = upload(aff.length ? aff : new Uint32Array(1), S_ | CD)\n const banBuf = upload(ban.length ? Uint32Array.from(ban) : new Uint32Array(1), S_ | CD)\n // pass 1: prefill -> lm_head -> base logits\n const enc1 = device.createCommandEncoder()\n const { fn } = stack(enc1, embedBatch(enc1, ids), ids.length, 0)\n const lastP = device.createBuffer({ size: Hd * 4, usage: S_ | CS | CD })\n enc1.copyBufferToBuffer(fn, (ids.length - 1) * Hd * 4, lastP, 0, Hd * 4)\n let pass = enc1.beginComputePass()\n lmHead(pass, lastP, 1, lg)\n pass.end()\n device.queue.submit([enc1.finish()])\n await device.queue.onSubmittedWorkDone()\n const base = await readback(lg, vocab)\n // pass 2: penalty (in place on lg) + K masked-argmax\n const enc2 = device.createCommandEncoder()\n pass = enc2.beginComputePass()\n setup(pass, 'sampler_penalty', [['u', aff.length], ['u', ban.length], ['f', penalty], ['u', 0xff800000]], [affBuf, banBuf], [lg])\n pass.dispatchWorkgroups(1)\n for (let r = 0; r < K; r++) {\n setup(pass, 'argmax_masked', [['u', vocab], ['u', r], ['u', 0], ['u', 0]], [lg], [candIds, candVals])\n pass.dispatchWorkgroups(1)\n }\n pass.end()\n device.queue.submit([enc2.finish()])\n await device.queue.onSubmittedWorkDone()\n return { base, penalized: await readback(lg, vocab), candIds: await readbackU32(candIds, K), candVals: await readback(candVals, K) }\n }\n\n const capabilities: EngineCapabilities = {\n useSubgroups: useSG,\n subgroupSize: sgMax,\n kvCache: kv16 ? 'f16' : kv8 ? 'q8' : 'f32',\n overflow: roll ? 'sinks' : 'error',\n maxSeqLen,\n adapter: { vendor: info.vendor, architecture: info.architecture, device: info.device, description: info.description },\n limits: {\n // the DEVICE limits (what dispatches are actually validated against), not the adapter's maximums\n maxStorageBufferBindingSize: Number(device.limits.maxStorageBufferBindingSize),\n maxComputeWorkgroupStorageSize: device.limits.maxComputeWorkgroupStorageSize,\n },\n }\n\n // Public generate: routes to sampled decode when a sampling temperature is set, else greedy.\n // Both honor stopTokens / onToken / signal. With reuseCache, `promptTokenIds` is the DELTA to append\n // to the cached conversation (the prior turn's last token is re-fed so its K/V lands); otherwise the\n // cache resets and `promptTokenIds` is the full prompt. The KV cache lives across calls in Kc/Vc.\n async function generate(promptTokenIds: number[], genOpts: GenerateOptions = {}): Promise<GenerateResult> {\n const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1\n // transformers.js applies repetition_penalty / no_repeat_ngram under greedy search too, so a\n // greedy turn that requests them routes through the sampler-chain path (which picks the\n // penalized argmax instead of drawing); the plain GPU-resident greedy loop can't see history.\n const hasProcessors = (genOpts.repetitionPenalty ?? 1) !== 1 || (genOpts.noRepeatNgramSize ?? 0) > 0\n const reuse = (genOpts.reuseCache ?? false) && fullHistory.length > 0\n if (genOpts.signal?.aborted) {\n // aborted before any work: don't touch fullHistory (the cache still matches it)\n return { tokens: [], prefillMs: 0, decodeMs: 0, tokensPerSecond: 0, timing: { recordMs: 0, gpuMs: 0, readbackMs: 0 } }\n }\n\n // Validate BEFORE mutating fullHistory: a throw must leave the reuse state exactly as it was,\n // or a caller that catches and retries decodes against K/V that was never written.\n // Sink mode: the cache slot no longer tracks fullHistory once the window has rolled, so\n // posBase comes from cacheLen; if the incoming turn does not fit, evict FIRST (the prompt\n // itself must still fit the window - prompt-side trimming stays the caller's job).\n let posBase = reuse ? (roll ? cacheLen : fullHistory.length - 1) : 0 // reuse: the prior last token (uncached) is re-fed, then the delta\n const prefillTokens = reuse ? [fullHistory[fullHistory.length - 1], ...promptTokenIds] : promptTokenIds\n if (prefillTokens.length === 0) throw new Error('generate: no tokens to process')\n if (roll && posBase + prefillTokens.length + 1 > maxSeqLen) {\n if (SINKS + prefillTokens.length + 1 > maxSeqLen)\n throw new Error(`generate: prompt length ${prefillTokens.length} exceeds the rolling window (maxSeqLen ${maxSeqLen} minus ${SINKS} sinks); trim the prompt`)\n await ensureKvCapacity(Math.min(maxSeqLen, posBase + prefillTokens.length)) // eviction copies within allocated rows\n posBase = evict(posBase, posBase + prefillTokens.length + 1 - maxSeqLen)\n cacheLen = posBase\n }\n const room = maxSeqLen - posBase - prefillTokens.length // decode positions left in the KV window\n if (room < 1) throw new Error(`generate: prompt length ${posBase + prefillTokens.length} exceeds maxSeqLen ${maxSeqLen}; trim history or raise maxSeqLen`)\n // In sink mode the window rolls mid-turn, so maxTokens is honored as-is (no window clamp).\n const maxTokens = roll ? (genOpts.maxTokens ?? 256) : Math.min(genOpts.maxTokens ?? 256, room) // clamp instead of throwing: fill the window, stop there\n if (reuse) fullHistory.push(...promptTokenIds) // the delta is now part of the conversation (last token already present)\n else fullHistory = [...promptTokenIds]\n\n if (maxTokens < 1) {\n // maxTokens: 0 - behave like prefill(): write K/V for the prompt (so a later reuseCache\n // turn continues correctly), record the history above, emit nothing. Previously this\n // emitted one token anyway.\n await ensureKvCapacity(posBase + prefillTokens.length)\n transients = []\n try {\n const t0 = performance.now()\n await runPrefill(prefillTokens, posBase, genOpts.signal)\n await device.queue.onSubmittedWorkDone()\n cacheLen = posBase + prefillTokens.length - 1 // sink-mode bookkeeping (last token re-feeds)\n return { tokens: [], prefillMs: performance.now() - t0, decodeMs: 0, tokensPerSecond: 0, timing: { recordMs: 0, gpuMs: 0, readbackMs: 0 } }\n } finally {\n flushTransients()\n transients = null\n }\n }\n\n // A candidateFilter needs the per-step sampler-chain path (candidates on the CPU every\n // token) and cannot speculate (draft verification has no per-row filter state) - so it\n // forces that path and disables promptLookup, as documented on the option. logprobs need\n // the same per-step candidate readback, so they route identically.\n const hasFilter = !!genOpts.candidateFilter || (genOpts.logprobs ?? 0) > 0\n let r: RawGenResult\n if (!hasFilter && genOpts.promptLookup === 'auto' && maxTokens > PLD_PROBATION) {\n // Probation: speculate for the first PLD_PROBATION tokens, then keep PLD only if the\n // measured tokens-per-verify-step clears the plain-decode break-even for this mode;\n // otherwise the rest of the turn runs the plain path. Output is IDENTICAL either way:\n // the continuation re-feeds the last emitted token at its position (the composition the\n // reuse gates prove bit-exact), and a sampled continuation takes over the probation's\n // RNG mid-stream, so the draw sequence is exactly a single run's.\n const r1 = await generatePldImpl(prefillTokens, posBase, PLD_PROBATION, genOpts, fullHistory)\n const E = r1.tokens.length\n if (E < PLD_PROBATION) {\n r = r1 // stopped or aborted inside the window: nothing left to decide\n } else {\n const keep = pldWorthIt(E, r1.spec?.steps ?? 0, sampled || hasProcessors)\n const ids2 = [r1.tokens[E - 1]] // re-feed the last emitted token (its K/V is unwritten)\n const pos2 = posBase + prefillTokens.length + E - 1\n const n2 = maxTokens - E\n let r2: RawGenResult\n if (keep) {\n r2 = await generatePldImpl(ids2, pos2, n2, genOpts, fullHistory, r1.rng)\n } else if (sampled || hasProcessors) {\n r2 = await generateSampledImpl(ids2, pos2, n2, genOpts, fullHistory, r1.rng)\n } else {\n const hist = fullHistory\n r2 = await generateImpl(ids2, pos2, n2, null, SYNC_N, { stopTokens: genOpts.stopTokens, onToken: genOpts.onToken, signal: genOpts.signal })\n hist.push(...r2.tokens) // plain greedy does not touch history; the PLD/sampled impls push their own\n }\n const total = E + r2.tokens.length\n const decodeMs = r1.decodeMs + r2.prefillMs + r2.decodeMs // the 1-token re-feed is decode work\n const w1 = Math.max(1, E - 1)\n const w2 = Math.max(0, r2.tokens.length)\n r = {\n prefillMs: r1.prefillMs,\n decodeMs,\n tokPerSec: Math.max(1, total - 1) / (decodeMs / 1000),\n tokens: [...r1.tokens, ...r2.tokens],\n firstArgmax: r1.firstArgmax,\n recMs: (r1.recMs * w1 + r2.recMs * w2) / (w1 + w2),\n gpuMs: (r1.gpuMs * w1 + r2.gpuMs * w2) / (w1 + w2),\n rbMs: (r1.rbMs * w1 + r2.rbMs * w2) / (w1 + w2),\n spec: {\n steps: (r1.spec?.steps ?? 0) + (r2.spec?.steps ?? 0),\n drafted: (r1.spec?.drafted ?? 0) + (r2.spec?.drafted ?? 0),\n accepted: (r1.spec?.accepted ?? 0) + (r2.spec?.accepted ?? 0),\n bailed: !keep,\n },\n }\n }\n } else if (!hasFilter && genOpts.promptLookup) {\n r = await generatePldImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory) // pushes generated tokens onto fullHistory\n } else if (sampled || hasProcessors || hasFilter) {\n r = await generateSampledImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory) // pushes generated tokens onto fullHistory\n } else {\n // Capture the history array like the sampled/PLD paths do: a resetCache() racing this turn\n // installs a fresh array, and these tokens must land on the OLD one (then next turn falls\n // back to a clean full prefill) instead of populating the reset history against stale K/V.\n const hist = fullHistory\n r = await generateImpl(prefillTokens, posBase, maxTokens, null, SYNC_N, { stopTokens: genOpts.stopTokens, onToken: genOpts.onToken, signal: genOpts.signal })\n hist.push(...r.tokens) // greedy doesn't touch history; record the generated tokens for the next turn\n }\n return {\n tokens: r.tokens,\n prefillMs: r.prefillMs,\n decodeMs: r.decodeMs,\n tokensPerSecond: r.tokPerSec,\n timing: { recordMs: r.recMs, gpuMs: r.gpuMs, readbackMs: r.rbMs },\n ...(r.spec ? { speculation: r.spec } : {}),\n ...(r.lp ? { logprobs: r.lp } : {}),\n }\n }\n\n // Prefill a prompt PREFIX into the KV cache without decoding, then stop. A later\n // generate(delta, {reuseCache:true}) continues from it, so a static system prompt can be warmed at\n // load and the user's first turn becomes a cheap cache-append instead of a full prefill. Like a\n // non-reuse generate's prefill it resets the cache (this prefix becomes the whole history); it\n // writes K/V for EVERY prefilled position, so the reuse path's re-fed last token just overwrites\n // position len-1 idempotently and the result is identical to a cold full prefill.\n async function prefill(ids: number[]): Promise<{ prefillMs: number }> {\n if (ids.length === 0) throw new Error('prefill: no tokens to process')\n if (ids.length > maxSeqLen) throw new Error(`prefill: sequence length ${ids.length} exceeds maxSeqLen ${maxSeqLen}`)\n await ensureKvCapacity(ids.length)\n transients = []\n try {\n const t0 = performance.now()\n await runPrefill(ids, 0) // posBase 0: fresh prefix; writes K/V for every position (segmented)\n await device.queue.onSubmittedWorkDone()\n fullHistory = [...ids]\n cacheLen = ids.length - 1 // sink-mode bookkeeping (last token re-feeds)\n return { prefillMs: performance.now() - t0 }\n } finally {\n flushTransients()\n transients = null\n }\n }\n\n // ---- KV snapshot / restore ----\n // The engine's entire cross-turn state is fullHistory plus the first (fullHistory.length - 1)\n // cached positions of each layer's K/V (the last token's K/V is re-written by the reuse path's\n // re-fed token; see the fullHistory comment). A snapshot captures exactly that, packed into one\n // ArrayBuffer, so restoring it - into this engine or a fresh one on the same model + mode - is\n // bit-identical to having kept the conversation alive. Layout: per layer, K then V region\n // (then Ksc, Vsc under q8), each sized len positions; all region sizes are multiples of 4.\n const kvRowBytes = KV * Dh * KVB // one position of K (or V), per layer\n const scRowBytes = kv8 ? KV * (Dh / 32) * 4 : 0 // one position of q8 block scales\n const snapshotBytes = (len: number): number => A.layers * 2 * len * (kvRowBytes + scRowBytes)\n\n async function saveCache(): Promise<KvSnapshot | null> {\n if (fullHistory.length === 0) return null\n const len = roll ? cacheLen : fullHistory.length - 1 // rolled cache: slots, not history\n const data = new ArrayBuffer(snapshotBytes(len))\n if (len > 0) {\n const rb = device.createBuffer({ size: snapshotBytes(len), usage: GPUBufferUsage.MAP_READ | CD })\n const enc = device.createCommandEncoder()\n let off = 0\n for (let li = 0; li < A.layers; li++) {\n enc.copyBufferToBuffer(Kc[li], 0, rb, off, len * kvRowBytes)\n off += len * kvRowBytes\n enc.copyBufferToBuffer(Vc[li], 0, rb, off, len * kvRowBytes)\n off += len * kvRowBytes\n if (kv8) {\n enc.copyBufferToBuffer(Ksc[li], 0, rb, off, len * scRowBytes)\n off += len * scRowBytes\n enc.copyBufferToBuffer(Vsc[li], 0, rb, off, len * scRowBytes)\n off += len * scRowBytes\n }\n }\n device.queue.submit([enc.finish()])\n await rb.mapAsync(GPUMapMode.READ)\n new Uint8Array(data).set(new Uint8Array(rb.getMappedRange()))\n rb.unmap()\n rb.destroy()\n }\n return {\n version: roll ? 2 : 1, // v2 = unroped keys + rolled window; only restores into sink mode\n kvCache: capabilities.kvCache,\n model: { layers: A.layers, kvHeads: KV, headDim: Dh, hidden: Hd, vocab: A.vocab },\n ids: [...fullHistory],\n ...(roll ? { roll: { sinkTokens: SINKS, cacheLen } } : {}),\n data,\n }\n }\n\n async function restoreCache(snap: KvSnapshot): Promise<void> {\n if (!snap || (snap.version !== 1 && snap.version !== 2)) throw new Error(`restoreCache: unsupported snapshot version ${snap?.version}`)\n if ((snap.version === 2) !== roll)\n throw new Error(\n snap.version === 2 ?\n \"restoreCache: snapshot was saved under overflow 'sinks' (unroped keys); this engine runs overflow 'error'\"\n : \"restoreCache: snapshot was saved under overflow 'error' (roped keys); this engine runs overflow 'sinks'\",\n )\n if (snap.version === 2 && snap.roll?.sinkTokens !== SINKS)\n throw new Error(`restoreCache: snapshot uses ${snap.roll?.sinkTokens} sink tokens but this engine uses ${SINKS}`)\n if (snap.kvCache !== capabilities.kvCache)\n throw new Error(`restoreCache: snapshot was saved under kvCache '${snap.kvCache}' but this engine runs '${capabilities.kvCache}' - snapshots do not convert across modes`)\n const m = snap.model\n if (!m || m.layers !== A.layers || m.kvHeads !== KV || m.headDim !== Dh || m.hidden !== Hd || m.vocab !== A.vocab)\n throw new Error('restoreCache: snapshot is from a different model (architecture mismatch)')\n if (!Array.isArray(snap.ids) || snap.ids.length === 0) throw new Error('restoreCache: snapshot holds no tokens')\n const len = snap.version === 2 ? snap.roll!.cacheLen : snap.ids.length - 1\n if (len + 1 > maxSeqLen)\n throw new Error(`restoreCache: snapshot needs ${len + 1} cache slots but maxSeqLen is ${maxSeqLen}`)\n if (snap.data.byteLength !== snapshotBytes(len))\n throw new Error(`restoreCache: snapshot data is ${snap.data.byteLength} bytes, expected ${snapshotBytes(len)}`)\n await ensureKvCapacity(len)\n let off = 0\n for (let li = 0; li < A.layers; li++) {\n device.queue.writeBuffer(Kc[li], 0, snap.data, off, len * kvRowBytes)\n off += len * kvRowBytes\n device.queue.writeBuffer(Vc[li], 0, snap.data, off, len * kvRowBytes)\n off += len * kvRowBytes\n if (kv8) {\n device.queue.writeBuffer(Ksc[li], 0, snap.data, off, len * scRowBytes)\n off += len * scRowBytes\n device.queue.writeBuffer(Vsc[li], 0, snap.data, off, len * scRowBytes)\n off += len * scRowBytes\n }\n }\n fullHistory = [...snap.ids]\n cacheLen = len\n }\n\n // The engine shares one KV cache, buffer pool, and flag set across calls, so concurrent\n // generate/prefill/forward would corrupt each other. Serialize them: overlapping calls queue\n // instead of interleaving (npm consumers do not all have the app's single-flight worker).\n let opChain: Promise<unknown> = Promise.resolve()\n const serialize = <Args extends unknown[], R>(fn: (...args: Args) => Promise<R>): ((...args: Args) => Promise<R>) => {\n return (...args: Args) => {\n const run = opChain.then(\n () => fn(...args),\n () => fn(...args), // a failed predecessor must not poison the queue\n )\n opChain = run.catch(() => undefined)\n return run\n }\n }\n\n const api: EngineInternal = {\n generate: serialize(generate),\n prefill: serialize(prefill),\n forward: serialize(forward),\n saveCache: serialize(saveCache),\n restoreCache: serialize(restoreCache),\n resetCache,\n capabilities,\n lost,\n dispose: () => device.destroy(),\n device,\n adapter,\n profileDecode: (ids, nTokens, full = null, syncN = SYNC_N) => generateImpl(ids, 0, nTokens, full, syncN),\n debugDecode,\n debugSampler,\n }\n return api\n}\n"],"mappings":";AACA,MAAa,UAAkC;CAC7C,OAAO;CACP,UAAU;CACV,iBAAiB;CACjB,gBAAgB;CAChB,qBAAqB;CACrB,0BAA0B;CAC1B,oBAAoB;CACpB,yBAAyB;CACzB,qBAAqB;CACrB,gBAAgB;CAChB,qBAAqB;CACrB,0BAA0B;CAC1B,oBAAoB;CACpB,yBAAyB;CACzB,qBAAqB;CACrB,QAAQ;CACR,aAAa;CACb,YAAY;CACZ,gBAAgB;CAChB,sBAAsB;CACtB,aAAa;CACb,sBAAsB;CACtB,aAAa;CACb,gBAAgB;CAChB,gBAAgB;CAChB,gBAAgB;CAChB,gBAAgB;CAChB,sBAAsB;CACtB,mBAAmB;CACnB,sBAAsB;CACtB,mBAAmB;CACnB,gBAAgB;CAChB,mBAAmB;CACnB,mBAAmB;CACnB,sBAAsB;CACtB,mBAAmB;CACnB,uBAAuB;CACvB,mBAAmB;CACnB,wBAAwB;CACxB,uBAAuB;CACvB,cAAc;CACd,cAAc;CACd,QAAQ;CACR,mBAAmB;CACnB,UAAU;AACZ;;;;;;AC5CA,IAAa,yBAAb,cAA4C,MAAM;CAChD,OAAyB;CACzB,YAAY,SAAiB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,QAAQ,MAAM;GACpC,OAAO,MAAM,YAAY,GAAG,KAAK,GAAG,KAAK,MAAM,KAAK,MAAM,UAAU;GACpE,OAAO,MAAM;GACb,OAAO,MAAM,YAAY,GAAG,KAAK,GAAG,KAAK,MAAM,KAAK,MAAM,UAAU;GACpE,OAAO,MAAM;GACb,IAAI,KAAK;IACP,OAAO,MAAM,YAAY,IAAI,KAAK,GAAG,KAAK,MAAM,KAAK,MAAM,UAAU;IACrE,OAAO,MAAM;IACb,OAAO,MAAM,YAAY,IAAI,KAAK,GAAG,KAAK,MAAM,KAAK,MAAM,UAAU;IACrE,OAAO,MAAM;GACf;EACF;EACA,cAAc,CAAC,GAAG,KAAK,GAAG;EAC1B,WAAW;CACb;CAKA,IAAI,UAA4B,QAAQ,QAAQ;CAChD,MAAM,aAAwC,OAAuE;EACnH,QAAQ,GAAG,SAAe;GACxB,MAAM,MAAM,QAAQ,WACZ,GAAG,GAAG,IAAI,SACV,GAAG,GAAG,IAAI,CAClB;GACA,UAAU,IAAI,YAAY,KAAA,CAAS;GACnC,OAAO;EACT;CACF;CAkBA,OAAO;EAfL,UAAU,UAAU,QAAQ;EAC5B,SAAS,UAAU,OAAO;EAC1B,SAAS,UAAU,OAAO;EAC1B,WAAW,UAAU,SAAS;EAC9B,cAAc,UAAU,YAAY;EACpC;EACA;EACA;EACA,eAAe,OAAO,QAAQ;EAC9B;EACA;EACA,gBAAgB,KAAK,SAAS,OAAO,MAAM,QAAQ,WAAW,aAAa,KAAK,GAAG,SAAS,MAAM,KAAK;EACvG;EACA;CAEO;AACX"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/shaders.generated.ts","../src/errors.ts","../src/pld.ts","../src/sampler.ts","../src/engine.ts"],"sourcesContent":["// AUTO-GENERATED by scripts/gen-shaders.ts from shaders/*.wgsl. Do not edit by hand.\nexport const SHADERS: Record<string, string> = {\n \"add\": \"// Elementwise residual add: y[i] = a[i] + b[i].\\nstruct Params { n: u32, _p0: u32, _p1: u32, _p2: u32 };\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> a: array<f32>;\\n@group(0) @binding(2) var<storage, read> b: array<f32>;\\n@group(0) @binding(3) var<storage, read_write> y: array<f32>;\\n\\n@compute @workgroup_size(64)\\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\\n if (i >= p.n) { return; }\\n y[i] = a[i] + b[i];\\n}\\n\",\n \"argmax\": \"// GPU argmax over the logits, writing one token id into a GPU buffer so the token never leaves the\\n// GPU (enables the deferred-sync decode loop). Single workgroup, WG threads strided-scan the N\\n// logits tracking (maxVal, maxIdx), then a shared-mem tree reduction. Tie-break = LOWEST index, to\\n// match the CPU argmax (strict > keeps the first max). No subgroup ops -> all devices.\\noverride WG: u32 = 256u;\\nstruct Params { N: u32, outIdx: u32, _0: u32, _1: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> logits: array<f32>;\\n@group(0) @binding(2) var<storage, read_write> outTok: array<u32>; // outTok[p.outIdx] = argmax\\n\\nvar<workgroup> sval: array<f32, 256>;\\nvar<workgroup> sidx: array<u32, 256>;\\n\\n@compute @workgroup_size(WG)\\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\\n let tid = lid.x;\\n var bv = -3.4e38;\\n var bi = 0u;\\n for (var i = tid; i < p.N; i = i + WG) {\\n let v = logits[i];\\n if (v > bv) { bv = v; bi = i; } // strict > keeps the lowest index within this thread's stride\\n }\\n sval[tid] = bv; sidx[tid] = bi;\\n workgroupBarrier();\\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\\n if (tid < s) {\\n let ov = sval[tid + s]; let oi = sidx[tid + s];\\n if (ov > sval[tid] || (ov == sval[tid] && oi < sidx[tid])) { sval[tid] = ov; sidx[tid] = oi; }\\n }\\n workgroupBarrier();\\n }\\n if (tid == 0u) { outTok[p.outIdx] = sidx[0]; }\\n}\\n\",\n \"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\",\n \"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\",\n \"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\",\n \"attention_sg_kv16_roll\": \"// attention_sg_kv16 for the rolling-window / attention-sinks mode (see attention_sg_roll.wgsl\\n// for the rope-at-read scheme). Keep in lockstep with attention_sg_kv16.wgsl: the ONLY\\n// difference is the K rotation in the score loop; each cached f16 value is widened to f32 at\\n// the read and rotated with the same `k*cos + rot*sin` operand order as rmsnorm_rope_sg.\\n// The engine only selects this kernel when SG <= D/2 (partner dim stays in-lane).\\nenable subgroups;\\nenable f16;\\noverride SG: u32 = 32u;\\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\\n@group(0) @binding(2) var<storage, read> Kc: array<f16>; // [Ltot, KV, D] UNROPED\\n@group(0) @binding(3) var<storage, read> Vc: array<f16>; // [Ltot, KV, D]\\n@group(0) @binding(4) var<storage, read> cosT: array<f32>; // [positions, D/2]\\n@group(0) @binding(5) var<storage, read> sinT: array<f32>; // [positions, D/2]\\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\\n\\n@compute @workgroup_size(SG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\\n let idx = wg.x;\\n if (idx >= p.S * p.H) { return; }\\n let h = idx % p.H;\\n let qi = idx / p.H;\\n let pos = p.posBase + qi;\\n let kvh = h / (p.H / p.KV);\\n let qb = (qi * p.H + h) * p.D;\\n let inv = 1.0 / sqrt(f32(p.D));\\n let dper = p.D / SG;\\n let half = p.D / 2u;\\n let hs = half / SG; // strides from a dim to its rotate partner\\n\\n var acc: array<f32, 8>;\\n for (var t = 0u; t < dper; t = t + 1u) { acc[t] = 0.0; }\\n var m = -1e30;\\n var l = 0.0;\\n for (var j = 0u; j <= pos; j = j + 1u) {\\n let kb = (j * p.KV + kvh) * p.D;\\n var kd: array<f32, 8>;\\n for (var t = 0u; t < dper; t = t + 1u) { kd[t] = f32(Kc[kb + lane + t * SG]); }\\n var part = 0.0;\\n for (var t = 0u; t < dper; t = t + 1u) {\\n let d = lane + t * SG;\\n var rot: f32;\\n if (d < half) { rot = -kd[t + hs]; } else { rot = kd[t - hs]; }\\n let rb = j * half + (d % half);\\n part = part + q[qb + d] * (kd[t] * cosT[rb] + rot * sinT[rb]);\\n }\\n let score = subgroupAdd(part) * inv;\\n let mnew = max(m, score);\\n let corr = exp(m - mnew);\\n let w = exp(score - mnew);\\n l = l * corr + w;\\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; acc[t] = acc[t] * corr + w * f32(Vc[kb + d]); }\\n m = mnew;\\n }\\n let ob = (qi * p.H + h) * p.D;\\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; out[ob + d] = acc[t] / l; }\\n}\\n\",\n \"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\",\n \"attention_sg_kv8_roll\": \"// attention_sg_kv8 for the rolling-window / attention-sinks mode (see attention_sg_roll.wgsl\\n// for the rope-at-read scheme). Keep in lockstep with attention_sg_kv8.wgsl: the ONLY\\n// difference is the K rotation in the score loop. The cache holds UNROPED quantized keys -\\n// the whole point: the packed bytes are immutable, so eviction never requantizes (llama.cpp's\\n// K-shift cannot do this on a quantized cache at all). A word's rotate partner is the word\\n// D/8 away (all 4 dims of a word share one half), dequantized from global with its own scale.\\nenable subgroups;\\noverride SG: u32 = 32u;\\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\\n@group(0) @binding(2) var<storage, read> Kq: array<u32>; // [Ltot, KV, D/4] packed snorm8, UNROPED\\n@group(0) @binding(3) var<storage, read> Vq: array<u32>; // [Ltot, KV, D/4] packed snorm8\\n@group(0) @binding(4) var<storage, read> Ks: array<f32>; // [Ltot, KV, D/32] block scales\\n@group(0) @binding(5) var<storage, read> Vs: array<f32>; // [Ltot, KV, D/32] block scales\\n@group(0) @binding(6) var<storage, read> cosT: array<f32>; // [positions, D/2]\\n@group(0) @binding(7) var<storage, read> sinT: array<f32>; // [positions, D/2]\\n@group(0) @binding(8) var<storage, read_write> out: array<f32>; // [S, H, D]\\n\\n@compute @workgroup_size(SG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\\n let idx = wg.x;\\n if (idx >= p.S * p.H) { return; }\\n let h = idx % p.H;\\n let qi = idx / p.H;\\n let pos = p.posBase + qi;\\n let kvh = h / (p.H / p.KV);\\n let qb = (qi * p.H + h) * p.D;\\n let inv = 1.0 / sqrt(f32(p.D));\\n let W4 = p.D / 4u;\\n let B32 = p.D / 32u;\\n let half = p.D / 2u;\\n let hw = half / 4u; // words from a word to its rotate partner\\n\\n var acc: array<vec4<f32>, 8>; // words per lane: W4/SG <= 8 for SG >= 4\\n for (var t = 0u; t < 8u; t = t + 1u) { acc[t] = vec4<f32>(0.0); }\\n var m = -1e30;\\n var l = 0.0;\\n for (var j = 0u; j <= pos; j = j + 1u) {\\n let rowQ = (j * p.KV + kvh) * W4;\\n let rowS = (j * p.KV + kvh) * B32;\\n var part = 0.0;\\n for (var w = lane; w < W4; w = w + SG) {\\n let kw = unpack4x8snorm(Kq[rowQ + w]) * Ks[rowS + (w >> 3u)];\\n let wp = select(w - hw, w + hw, w < hw);\\n let kp = unpack4x8snorm(Kq[rowQ + wp]) * Ks[rowS + (wp >> 3u)];\\n let rot = select(kp, -kp, w < hw);\\n let cb = j * half + select(w - hw, w, w < hw) * 4u;\\n let cs = vec4<f32>(cosT[cb], cosT[cb + 1u], cosT[cb + 2u], cosT[cb + 3u]);\\n let sn = vec4<f32>(sinT[cb], sinT[cb + 1u], sinT[cb + 2u], sinT[cb + 3u]);\\n let qv = vec4<f32>(q[qb + w * 4u], q[qb + w * 4u + 1u], q[qb + w * 4u + 2u], q[qb + w * 4u + 3u]);\\n part = part + dot(qv, kw * cs + rot * sn);\\n }\\n let score = subgroupAdd(part) * inv;\\n let mnew = max(m, score);\\n let corr = exp(m - mnew);\\n let wgt = exp(score - mnew);\\n l = l * corr + wgt;\\n var wi = 0u;\\n for (var w = lane; w < W4; w = w + SG) {\\n let vw = unpack4x8snorm(Vq[rowQ + w]) * Vs[rowS + (w >> 3u)];\\n acc[wi] = acc[wi] * corr + wgt * vw;\\n wi = wi + 1u;\\n }\\n m = mnew;\\n }\\n let ob = (qi * p.H + h) * p.D;\\n var wi = 0u;\\n for (var w = lane; w < W4; w = w + SG) {\\n let o = acc[wi] / l;\\n out[ob + w * 4u] = o.x;\\n out[ob + w * 4u + 1u] = o.y;\\n out[ob + w * 4u + 2u] = o.z;\\n out[ob + w * 4u + 3u] = o.w;\\n wi = wi + 1u;\\n }\\n}\\n\",\n \"attention_sg_roll\": \"// attention_sg for the rolling-window / attention-sinks mode (overflow: 'sinks'): the cache\\n// holds UNROPED keys, and each cached row j is rotated AT READ by its cache-relative position\\n// (StreamingLLM-style; the cache bytes are immutable, so eviction compaction never re-rotates\\n// or requantizes anything). Keep in lockstep with attention_sg.wgsl: the ONLY difference is\\n// the K rotation in the score loop, written as `k*cos + rot*sin` with the same operand order\\n// as rmsnorm_rope_sg so the f32 path stays bit-identical to the roped-at-write kernels until\\n// the first eviction. cosT/sinT are the aux rope tables, [positions, D/2].\\n// Lane math: d = lane + t*SG, partner d±D/2 is (D/2)/SG strides away IN THE SAME LANE (the\\n// engine only selects this kernel when SG <= D/2).\\nenable subgroups;\\noverride SG: u32 = 32u;\\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\\n@group(0) @binding(2) var<storage, read> Kc: array<f32>; // [Ltot, KV, D] UNROPED\\n@group(0) @binding(3) var<storage, read> Vc: array<f32>; // [Ltot, KV, D]\\n@group(0) @binding(4) var<storage, read> cosT: array<f32>; // [positions, D/2]\\n@group(0) @binding(5) var<storage, read> sinT: array<f32>; // [positions, D/2]\\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\\n\\n@compute @workgroup_size(SG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\\n let idx = wg.x;\\n if (idx >= p.S * p.H) { return; }\\n let h = idx % p.H;\\n let qi = idx / p.H;\\n let pos = p.posBase + qi;\\n let kvh = h / (p.H / p.KV);\\n let qb = (qi * p.H + h) * p.D;\\n let inv = 1.0 / sqrt(f32(p.D));\\n let dper = p.D / SG;\\n let half = p.D / 2u;\\n let hs = half / SG; // strides from a dim to its rotate partner\\n\\n var acc: array<f32, 8>;\\n for (var t = 0u; t < dper; t = t + 1u) { acc[t] = 0.0; }\\n var m = -1e30;\\n var l = 0.0;\\n for (var j = 0u; j <= pos; j = j + 1u) {\\n let kb = (j * p.KV + kvh) * p.D;\\n var kd: array<f32, 8>;\\n for (var t = 0u; t < dper; t = t + 1u) { kd[t] = Kc[kb + lane + t * SG]; }\\n var part = 0.0;\\n for (var t = 0u; t < dper; t = t + 1u) {\\n let d = lane + t * SG;\\n var rot: f32;\\n if (d < half) { rot = -kd[t + hs]; } else { rot = kd[t - hs]; }\\n let rb = j * half + (d % half);\\n part = part + q[qb + d] * (kd[t] * cosT[rb] + rot * sinT[rb]);\\n }\\n let score = subgroupAdd(part) * inv;\\n let mnew = max(m, score);\\n let corr = exp(m - mnew);\\n let w = exp(score - mnew);\\n l = l * corr + w;\\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; acc[t] = acc[t] * corr + w * Vc[kb + d]; }\\n m = mnew;\\n }\\n let ob = (qi * p.H + h) * p.D;\\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; out[ob + d] = acc[t] / l; }\\n}\\n\",\n \"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\",\n \"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\",\n \"attention_wg_kv16_roll\": \"// attention_wg_kv16 for the rolling-window / attention-sinks mode (see attention_sg_roll.wgsl\\n// for the rope-at-read scheme). Keep in lockstep with attention_wg_kv16.wgsl: the ONLY\\n// differences are the shared-memory K stage (kk, widened to f32) - the rotate partner d±D/2\\n// may live in another thread's stride - and the rotation in the score loop, written as\\n// `k*cos + rot*sin` with the same operand order as rmsnorm_rope_sg.\\nenable f16;\\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\\n@group(0) @binding(2) var<storage, read> Kc: array<f16>; // [Ltot, KV, D] UNROPED\\n@group(0) @binding(3) var<storage, read> Vc: array<f16>; // [Ltot, KV, D]\\n@group(0) @binding(4) var<storage, read> cosT: array<f32>; // [positions, D/2]\\n@group(0) @binding(5) var<storage, read> sinT: array<f32>; // [positions, D/2]\\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\\nvar<workgroup> red: array<f32, 64>;\\nvar<workgroup> kk: array<f32, 128>;\\n\\n@compute @workgroup_size(64)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\\n if (idx >= p.S * p.H) { return; }\\n let tid = lid.x;\\n let h = idx % p.H;\\n let qi = idx / p.H;\\n let pos = p.posBase + qi;\\n let kvh = h / (p.H / p.KV);\\n let qb = (qi * p.H + h) * p.D;\\n let inv = 1.0 / sqrt(f32(p.D));\\n let half = p.D / 2u;\\n\\n var acc: array<f32, 2>;\\n acc[0] = 0.0;\\n acc[1] = 0.0;\\n var m = -1e30;\\n var l = 0.0;\\n for (var j = 0u; j <= pos; j = j + 1u) {\\n let kb = (j * p.KV + kvh) * p.D;\\n for (var t = 0u; t < 2u; t = t + 1u) {\\n let d = tid + t * 64u;\\n if (d < p.D) { kk[d] = f32(Kc[kb + d]); }\\n }\\n workgroupBarrier();\\n var part = 0.0;\\n for (var t = 0u; t < 2u; t = t + 1u) {\\n let d = tid + t * 64u;\\n if (d < p.D) {\\n var rot: f32;\\n if (d < half) { rot = -kk[d + half]; } else { rot = kk[d - half]; }\\n let rb = j * half + (d % half);\\n part = part + q[qb + d] * (kk[d] * cosT[rb] + rot * sinT[rb]);\\n }\\n }\\n red[tid] = part;\\n workgroupBarrier();\\n for (var s = 32u; s > 0u; s = s >> 1u) {\\n if (tid < s) { red[tid] = red[tid] + red[tid + s]; }\\n workgroupBarrier();\\n }\\n let score = red[0] * inv;\\n workgroupBarrier(); // red[0] + kk consumed before the next position overwrites them\\n let mnew = max(m, score);\\n let corr = exp(m - mnew);\\n let w = exp(score - mnew);\\n l = l * corr + w;\\n for (var t = 0u; t < 2u; t = t + 1u) {\\n let d = tid + t * 64u;\\n if (d < p.D) { acc[t] = acc[t] * corr + w * f32(Vc[kb + d]); }\\n }\\n m = mnew;\\n }\\n let ob = (qi * p.H + h) * p.D;\\n for (var t = 0u; t < 2u; t = t + 1u) {\\n let d = tid + t * 64u;\\n if (d < p.D) { out[ob + d] = acc[t] / l; }\\n }\\n}\\n\",\n \"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\",\n \"attention_wg_kv8_roll\": \"// attention_wg_kv8 for the rolling-window / attention-sinks mode: the no-subgroup fallback of\\n// attention_sg_kv8_roll (see there and attention_sg_roll.wgsl for the rope-at-read scheme).\\n// Keep in lockstep with attention_wg_kv8.wgsl: the ONLY difference is the K rotation in the\\n// score loop; each thread's word rotates against its partner word D/8 away, dequantized from\\n// global with its own scale.\\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\\n@group(0) @binding(2) var<storage, read> Kq: array<u32>; // [Ltot, KV, D/4] packed snorm8, UNROPED\\n@group(0) @binding(3) var<storage, read> Vq: array<u32>; // [Ltot, KV, D/4] packed snorm8\\n@group(0) @binding(4) var<storage, read> Ks: array<f32>; // [Ltot, KV, D/32] block scales\\n@group(0) @binding(5) var<storage, read> Vs: array<f32>; // [Ltot, KV, D/32] block scales\\n@group(0) @binding(6) var<storage, read> cosT: array<f32>; // [positions, D/2]\\n@group(0) @binding(7) var<storage, read> sinT: array<f32>; // [positions, D/2]\\n@group(0) @binding(8) var<storage, read_write> out: array<f32>; // [S, H, D]\\nvar<workgroup> red: array<f32, 64>;\\n\\n@compute @workgroup_size(64)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\\n if (idx >= p.S * p.H) { return; }\\n let t = lid.x;\\n let h = idx % p.H;\\n let qi = idx / p.H;\\n let pos = p.posBase + qi;\\n let kvh = h / (p.H / p.KV);\\n let qb = (qi * p.H + h) * p.D;\\n let inv = 1.0 / sqrt(f32(p.D));\\n let W4 = p.D / 4u;\\n let half = p.D / 2u;\\n let hw = half / 4u; // words from a word to its rotate partner\\n\\n var qv = vec4<f32>(0.0);\\n if (t < W4) {\\n qv = vec4<f32>(q[qb + t * 4u], q[qb + t * 4u + 1u], q[qb + t * 4u + 2u], q[qb + t * 4u + 3u]);\\n }\\n var acc = vec4<f32>(0.0);\\n var m = -1e30;\\n var l = 0.0;\\n for (var j = 0u; j <= pos; j = j + 1u) {\\n let rowQ = (j * p.KV + kvh) * W4;\\n let rowS = (j * p.KV + kvh) * (p.D / 32u);\\n var part = 0.0;\\n if (t < W4) {\\n let kw = unpack4x8snorm(Kq[rowQ + t]) * Ks[rowS + (t >> 3u)];\\n let wp = select(t - hw, t + hw, t < hw);\\n let kp = unpack4x8snorm(Kq[rowQ + wp]) * Ks[rowS + (wp >> 3u)];\\n let rot = select(kp, -kp, t < hw);\\n let cb = j * half + select(t - hw, t, t < hw) * 4u;\\n let cs = vec4<f32>(cosT[cb], cosT[cb + 1u], cosT[cb + 2u], cosT[cb + 3u]);\\n let sn = vec4<f32>(sinT[cb], sinT[cb + 1u], sinT[cb + 2u], sinT[cb + 3u]);\\n part = dot(qv, kw * cs + rot * sn);\\n }\\n red[t] = part;\\n workgroupBarrier();\\n for (var s = 32u; s > 0u; s = s >> 1u) {\\n if (t < s) { red[t] = red[t] + red[t + s]; }\\n workgroupBarrier();\\n }\\n let score = red[0] * inv;\\n workgroupBarrier();\\n let mnew = max(m, score);\\n let corr = exp(m - mnew);\\n let wgt = exp(score - mnew);\\n l = l * corr + wgt;\\n if (t < W4) {\\n let vw = unpack4x8snorm(Vq[rowQ + t]) * Vs[rowS + (t >> 3u)];\\n acc = acc * corr + wgt * vw;\\n }\\n m = mnew;\\n }\\n if (t < W4) {\\n let ob = (qi * p.H + h) * p.D;\\n let o = acc / l;\\n out[ob + t * 4u] = o.x;\\n out[ob + t * 4u + 1u] = o.y;\\n out[ob + t * 4u + 2u] = o.z;\\n out[ob + t * 4u + 3u] = o.w;\\n }\\n}\\n\",\n \"attention_wg_roll\": \"// attention_wg for the rolling-window / attention-sinks mode: no-subgroup fallback of\\n// attention_sg_roll (see there for the rope-at-read scheme). Keep in lockstep with\\n// attention_wg.wgsl: the ONLY differences are the shared-memory K stage (kk) - the rotate\\n// partner d±D/2 may live in another thread's stride - and the rotation in the score loop,\\n// written as `k*cos + rot*sin` with the same operand order as rmsnorm_rope_sg.\\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\\n@group(0) @binding(2) var<storage, read> Kc: array<f32>; // [Ltot, KV, D] UNROPED\\n@group(0) @binding(3) var<storage, read> Vc: array<f32>; // [Ltot, KV, D]\\n@group(0) @binding(4) var<storage, read> cosT: array<f32>; // [positions, D/2]\\n@group(0) @binding(5) var<storage, read> sinT: array<f32>; // [positions, D/2]\\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\\nvar<workgroup> red: array<f32, 64>;\\nvar<workgroup> kk: array<f32, 128>;\\n\\n@compute @workgroup_size(64)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\\n if (idx >= p.S * p.H) { return; }\\n let tid = lid.x;\\n let h = idx % p.H;\\n let qi = idx / p.H;\\n let pos = p.posBase + qi;\\n let kvh = h / (p.H / p.KV);\\n let qb = (qi * p.H + h) * p.D;\\n let inv = 1.0 / sqrt(f32(p.D));\\n let half = p.D / 2u;\\n\\n var acc: array<f32, 2>;\\n acc[0] = 0.0;\\n acc[1] = 0.0;\\n var m = -1e30;\\n var l = 0.0;\\n for (var j = 0u; j <= pos; j = j + 1u) {\\n let kb = (j * p.KV + kvh) * p.D;\\n for (var t = 0u; t < 2u; t = t + 1u) {\\n let d = tid + t * 64u;\\n if (d < p.D) { kk[d] = Kc[kb + d]; }\\n }\\n workgroupBarrier();\\n var part = 0.0;\\n for (var t = 0u; t < 2u; t = t + 1u) {\\n let d = tid + t * 64u;\\n if (d < p.D) {\\n var rot: f32;\\n if (d < half) { rot = -kk[d + half]; } else { rot = kk[d - half]; }\\n let rb = j * half + (d % half);\\n part = part + q[qb + d] * (kk[d] * cosT[rb] + rot * sinT[rb]);\\n }\\n }\\n red[tid] = part;\\n workgroupBarrier();\\n for (var s = 32u; s > 0u; s = s >> 1u) {\\n if (tid < s) { red[tid] = red[tid] + red[tid + s]; }\\n workgroupBarrier();\\n }\\n let score = red[0] * inv; // full q.k dot, visible to all threads\\n workgroupBarrier(); // red[0] + kk consumed before the next position overwrites them\\n let mnew = max(m, score);\\n let corr = exp(m - mnew);\\n let w = exp(score - mnew);\\n l = l * corr + w;\\n for (var t = 0u; t < 2u; t = t + 1u) {\\n let d = tid + t * 64u;\\n if (d < p.D) { acc[t] = acc[t] * corr + w * Vc[kb + d]; }\\n }\\n m = mnew;\\n }\\n let ob = (qi * p.H + h) * p.D;\\n for (var t = 0u; t < 2u; t = t + 1u) {\\n let d = tid + t * 64u;\\n if (d < p.D) { out[ob + d] = acc[t] / l; }\\n }\\n}\\n\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"matmul_q2_sm\": \"// Small-batch (M = 2..9) subgroup split-K GEMV for the 2-bit lm_head: the speculative-decode\\n// verify pass needs logits for every drafted row, and the scalar M-row kernel re-reads the\\n// ~77 MB code stream per output thread. Here each code word is loaded once per (column,\\n// k-chunk) and dotted with all M rows. Per row the loop stride and accumulation expression\\n// match matmul_q2_sg, so each row is bit-identical to the M=1 decode path.\\nenable subgroups;\\noverride SG: u32 = 32u;\\nstruct Params { N: u32, K: u32, nb: u32, zp: u32, gridX: u32, M: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4] row-major\\n@group(0) @binding(2) var<storage, read> 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(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);\\n let sbase = n * p.nb;\\n let zpf = f32(p.zp);\\n let Kvec = p.K / 4u;\\n\\n var acc: array<f32, 9>; // M <= 9\\n for (var m = 0u; m < p.M; m = m + 1u) { acc[m] = 0.0; }\\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\\n let 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 let s = scales[sbase + (gi >> 5u)]; // block = (gi*4)/128 = gi/32\\n for (var m = 0u; m < p.M; m = m + 1u) {\\n acc[m] = acc[m] + dot(x[m * Kvec + gi], cv) * s;\\n }\\n }\\n for (var m = 0u; m < p.M; m = m + 1u) {\\n let total = subgroupAdd(acc[m]);\\n if (lane == 0u) { y[m * p.N + n] = total; }\\n }\\n}\\n\",\n \"matmul_q2_wg\": \"// No-subgroup fallback: 2-bit lm_head GEMV for decode (M=1), workgroup-shared-memory reduction.\\n// One workgroup per output column; WG threads split K and tree-reduce. value = (code - zp) * scale.\\n// 2D dispatch since N (vocab) > 65535. This is the v1 path's biggest cost (scalar was ~48ms/token).\\noverride WG: u32 = 64u;\\nstruct Params { N: u32, K: u32, nb: u32, zp: u32, gridX: u32, _pad: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\\n@group(0) @binding(2) var<storage, read> codes: array<u32>; // [N, K/4] bytes packed as u32\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [N]\\nvar<workgroup> sdata: array<f32, 256>;\\n\\n@compute @workgroup_size(WG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\\n let n = wg.y * p.gridX + wg.x;\\n if (n >= p.N) { return; }\\n let tid = lid.x;\\n let cbase = n * (p.K / 4u);\\n let sbase = n * p.nb;\\n let zpf = f32(p.zp);\\n let Kvec = p.K / 4u;\\n var acc = 0.0;\\n for (var gi = tid; gi < Kvec; gi = gi + WG) {\\n let byteIdx = cbase + gi;\\n let word = codes[byteIdx >> 2u];\\n let byte = (word >> (8u * (byteIdx & 3u))) & 0xffu;\\n let cv = vec4<f32>(f32(byte & 3u) - zpf, f32((byte >> 2u) & 3u) - zpf,\\n f32((byte >> 4u) & 3u) - zpf, f32((byte >> 6u) & 3u) - zpf);\\n acc = acc + dot(x[gi], cv) * scales[sbase + (gi >> 5u)];\\n }\\n sdata[tid] = acc;\\n workgroupBarrier();\\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\\n if (tid < s) { sdata[tid] = sdata[tid] + sdata[tid + s]; }\\n workgroupBarrier();\\n }\\n if (tid == 0u) { y[n] = sdata[0]; }\\n}\\n\",\n \"matmul_resid\": \"// Binary matmul with a fused residual add: y[M,N] = x[M,K] @ W[N,K]^T + resid[M,N].\\n// Folds the residual add into o_proj / down_proj so it's not a separate dispatch.\\nstruct Params { M: u32, N: u32, K: u32, nb: u32, block: u32, _pad: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4]\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\\n@group(0) @binding(4) var<storage, read> resid: array<f32>; // [M, N]\\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [M, N]\\n\\n@compute @workgroup_size(64)\\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\\n if (idx >= p.M * p.N) { return; }\\n let n = idx % p.N;\\n let xRow = (idx / p.N) * (p.K / 4u);\\n let wRow = n * (p.K / 32u);\\n let sbase = n * p.nb;\\n\\n var acc = 0.0;\\n for (var b = 0u; b < p.nb; b = b + 1u) {\\n var bsum = 0.0;\\n for (var w = 0u; w < 4u; w = w + 1u) {\\n let word = signbits[wRow + b * 4u + w];\\n let xb = xRow + b * 32u + w * 8u;\\n for (var g = 0u; g < 8u; g = g + 1u) {\\n let bits4 = (word >> (g * 4u)) & 0xfu;\\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\\n bsum = bsum + dot(x[xb + g], sv);\\n }\\n }\\n acc = acc + bsum * scales[sbase + b];\\n }\\n y[idx] = acc + resid[idx];\\n}\\n\",\n \"matmul_resid_mr_sg\": \"// Multi-row subgroup GEMV for decode (M=1) with fused residual. Same as matmul_resid_sg but each\\n// workgroup computes ROWS output columns at once: per K-step it issues ROWS independent weight\\n// loads before the dots, giving the memory system more in-flight requests (memory-level\\n// parallelism) to hide latency on the bandwidth-bound decode GEMV. One subgroup per workgroup;\\n// lanes split K; ROWS accumulators reduced with subgroupAdd. value = sign * per-block scale.\\nenable subgroups;\\noverride SG: u32 = 32u;\\noverride ROWS: u32 = 4u;\\nstruct Params { N: u32, K: u32, nb: u32, gridX: u32, _p0: u32, _p1: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\\n@group(0) @binding(4) var<storage, read> resid: array<f32>; // [N]\\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [N]\\n\\n@compute @workgroup_size(SG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\\n let rowBase = (wg.y * p.gridX + wg.x) * ROWS;\\n let Kvec = p.K / 4u;\\n let wStride = p.K / 32u;\\n\\n var acc: array<f32, 8>; // ROWS <= 8\\n for (var r = 0u; r < ROWS; r = r + 1u) { acc[r] = 0.0; }\\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\\n let k = gi * 4u;\\n let xv = x[gi];\\n let widx = k >> 5u;\\n let sh = k & 31u;\\n let sc = k / 128u;\\n for (var r = 0u; r < ROWS; r = r + 1u) {\\n let n = rowBase + r;\\n if (n < p.N) {\\n let w = (signbits[n * wStride + widx] >> sh) & 0xfu;\\n let sv = vec4<f32>(select(-1.0, 1.0, (w & 1u) != 0u), select(-1.0, 1.0, (w & 2u) != 0u),\\n select(-1.0, 1.0, (w & 4u) != 0u), select(-1.0, 1.0, (w & 8u) != 0u));\\n acc[r] = acc[r] + dot(xv, sv) * scales[n * p.nb + sc];\\n }\\n }\\n }\\n for (var r = 0u; r < ROWS; r = r + 1u) {\\n let n = rowBase + r;\\n let total = subgroupAdd(acc[r]); // collective: called for every r by all lanes\\n if (lane == 0u && n < p.N) { y[n] = total + resid[n]; }\\n }\\n}\\n\",\n \"matmul_resid_sm\": \"// Small-batch (M = 2..9) subgroup split-K GEMV with fused residual add (o_proj / down_proj in\\n// the speculative-decode verify pass). One workgroup per output column; each weight word is\\n// loaded once and dotted with all M activation rows. Per row the loop stride and accumulation\\n// expression match the validated M=1 kernels, so results are row-wise bit-identical to them.\\nenable subgroups;\\noverride SG: u32 = 32u;\\nstruct Params { N: u32, K: u32, nb: u32, gridX: u32, M: u32, _pad: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4] row-major\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\\n@group(0) @binding(4) var<storage, read> resid: array<f32>; // [M, N]\\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [M, N]\\n\\n@compute @workgroup_size(SG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\\n let n = wg.y * p.gridX + wg.x;\\n if (n >= p.N) { return; }\\n let wRow = n * (p.K / 32u);\\n let sbase = n * p.nb;\\n let Kvec = p.K / 4u;\\n\\n var acc: array<f32, 9>; // M <= 9\\n for (var m = 0u; m < p.M; m = m + 1u) { acc[m] = 0.0; }\\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\\n let k = gi * 4u;\\n let word = signbits[wRow + (k >> 5u)];\\n let bits4 = (word >> (k & 31u)) & 0xfu;\\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\\n let s = scales[sbase + (k / 128u)];\\n for (var m = 0u; m < p.M; m = m + 1u) {\\n acc[m] = acc[m] + dot(x[m * Kvec + gi], sv) * s;\\n }\\n }\\n for (var m = 0u; m < p.M; m = m + 1u) {\\n let total = subgroupAdd(acc[m]);\\n if (lane == 0u) { y[m * p.N + n] = total + resid[m * p.N + n]; }\\n }\\n}\\n\",\n \"matmul_resid_tiled\": \"// Tiled register-blocked binary GEMM with fused residual, for PREFILL (M>1), vec4 K-accumulation:\\n// y[M,N] = x[M,K] @ W[N,K]^T + resid[M,N], W binary {-1,+1} sign-packed, per-128-block fp32 scale.\\n// 64x64 output tile per workgroup, 16x16 threads each computing a 4x4 register tile, BK=16 K-step.\\n// Activation + decoded/scaled weight tiles are staged in shared memory as vec4 (4 K per element);\\n// each inner step is a dot() of vec4s, and one weight load decodes a whole nibble (4 signs) at once.\\n// No subgroup ops -> all devices. Near-bit-exact (f32 accum; tiled K-order differs in last ULPs).\\nconst BM: u32 = 64u;\\nconst BN: u32 = 64u;\\nconst BKV: u32 = 4u; // BK / 4 (BK = 16)\\nstruct Params { M: u32, N: u32, K: u32, nb: u32, _0: u32, _1: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4]\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\\n@group(0) @binding(4) var<storage, read> resid: array<f32>; // [M, N]\\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [M, N]\\n\\nvar<workgroup> xs: array<vec4<f32>, 256>; // BM*BKV\\nvar<workgroup> ws: array<vec4<f32>, 256>; // BN*BKV\\n\\n@compute @workgroup_size(256)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\\n let tid = lid.x;\\n let tileM = wg.y * BM;\\n let tileN = wg.x * BN;\\n let tr = (tid / 16u) * 4u;\\n let tc = (tid % 16u) * 4u;\\n let Kv = p.K / 4u;\\n var acc: array<f32, 16>;\\n for (var i = 0u; i < 16u; i = i + 1u) { acc[i] = 0.0; }\\n\\n let Ksteps = Kv / BKV;\\n for (var ks = 0u; ks < Ksteps; ks = ks + 1u) {\\n let k0v = ks * BKV;\\n for (var e = tid; e < BM * BKV; e = e + 256u) { // stage activation tile (vec4)\\n let m = e / BKV; let kv = e % BKV; let gm = tileM + m;\\n xs[e] = select(vec4<f32>(0.0), x[gm * Kv + (k0v + kv)], gm < p.M);\\n }\\n for (var e = tid; e < BN * BKV; e = e + 256u) { // stage decoded+scaled weight tile (vec4)\\n let n = e / BKV; let kv = e % BKV; let gn = tileN + n; let k = (k0v + kv) * 4u;\\n var wv = vec4<f32>(0.0);\\n if (gn < p.N) {\\n let bits4 = (signbits[gn * (p.K / 32u) + (k >> 5u)] >> (k & 31u)) & 0xfu;\\n let s = scales[gn * p.nb + (k / 128u)];\\n wv = vec4<f32>(select(-s, s, (bits4 & 1u) != 0u), select(-s, s, (bits4 & 2u) != 0u),\\n select(-s, s, (bits4 & 4u) != 0u), select(-s, s, (bits4 & 8u) != 0u));\\n }\\n ws[e] = wv;\\n }\\n workgroupBarrier();\\n for (var kv = 0u; kv < BKV; kv = kv + 1u) {\\n var xr: array<vec4<f32>, 4>;\\n for (var tm = 0u; tm < 4u; tm = tm + 1u) { xr[tm] = xs[(tr + tm) * BKV + kv]; }\\n for (var tn = 0u; tn < 4u; tn = tn + 1u) {\\n let w = ws[(tc + tn) * BKV + kv];\\n for (var tm = 0u; tm < 4u; tm = tm + 1u) { acc[tm * 4u + tn] = acc[tm * 4u + tn] + dot(xr[tm], w); }\\n }\\n }\\n workgroupBarrier();\\n }\\n\\n for (var tm = 0u; tm < 4u; tm = tm + 1u) {\\n let gm = tileM + tr + tm;\\n if (gm < p.M) {\\n for (var tn = 0u; tn < 4u; tn = tn + 1u) {\\n let gn = tileN + tc + tn;\\n if (gn < p.N) { let idx = gm * p.N + gn; y[idx] = acc[tm * 4u + tn] + resid[idx]; }\\n }\\n }\\n }\\n}\\n\",\n \"matmul_resid_wg\": \"// No-subgroup fallback: split-K GEMV for decode (M=1) with fused residual, workgroup-shared-memory\\n// reduction. One workgroup per output column; WG threads split K and tree-reduce. Used for o_proj/down.\\noverride WG: u32 = 64u;\\nstruct Params { N: u32, K: u32, nb: u32, gridX: u32, _p0: u32, _p1: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\\n@group(0) @binding(4) var<storage, read> resid: array<f32>; // [N]\\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [N]\\nvar<workgroup> sdata: array<f32, 256>;\\n\\n@compute @workgroup_size(WG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\\n let n = wg.y * p.gridX + wg.x;\\n if (n >= p.N) { return; }\\n let tid = lid.x;\\n let wRow = n * (p.K / 32u);\\n let sbase = n * p.nb;\\n let Kvec = p.K / 4u;\\n var acc = 0.0;\\n for (var gi = tid; gi < Kvec; gi = gi + WG) {\\n let k = gi * 4u;\\n let word = signbits[wRow + (k >> 5u)];\\n let bits4 = (word >> (k & 31u)) & 0xfu;\\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\\n acc = acc + dot(x[gi], sv) * scales[sbase + (k / 128u)];\\n }\\n sdata[tid] = acc;\\n workgroupBarrier();\\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\\n if (tid < s) { sdata[tid] = sdata[tid] + sdata[tid + s]; }\\n workgroupBarrier();\\n }\\n if (tid == 0u) { y[n] = sdata[0] + resid[n]; }\\n}\\n\",\n \"matmul_split\": \"// Fused binary matmul writing to up to 3 output buffers (qkv or gate/up in one dispatch).\\n// Weights for the outputs are concatenated along N (rows N0 | N1 | N2). One thread per\\n// output column n routes its result to out0/out1/out2 by range. Vectorized like matmul_binary_vec4.\\nstruct Params { M: u32, K: u32, nb: u32, N0: u32, N1: u32, N2: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4]\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\\n\\n@compute @workgroup_size(64)\\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\\n let Ntot = p.N0 + p.N1 + p.N2;\\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\\n if (idx >= p.M * Ntot) { return; }\\n let row = idx / Ntot;\\n let n = idx % Ntot;\\n let xRow = row * (p.K / 4u);\\n let wRow = n * (p.K / 32u);\\n let sbase = n * p.nb;\\n\\n var acc = 0.0;\\n for (var b = 0u; b < p.nb; b = b + 1u) {\\n var bsum = 0.0;\\n for (var w = 0u; w < 4u; w = w + 1u) {\\n let word = signbits[wRow + b * 4u + w];\\n let xb = xRow + b * 32u + w * 8u;\\n for (var g = 0u; g < 8u; g = g + 1u) {\\n let bits4 = (word >> (g * 4u)) & 0xfu;\\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\\n bsum = bsum + dot(x[xb + g], sv);\\n }\\n }\\n acc = acc + bsum * scales[sbase + b];\\n }\\n\\n if (n < p.N0) { out0[row * p.N0 + n] = acc; }\\n else if (n < p.N0 + p.N1) { out1[row * p.N1 + (n - p.N0)] = acc; }\\n else { out2[row * p.N2 + (n - p.N0 - p.N1)] = acc; }\\n}\\n\",\n \"matmul_split_sg\": \"// Subgroup split-K GEMV for decode (M=1), fused: one subgroup (= one workgroup) per output\\n// column; lanes split the K dimension and reduce with subgroupAdd (register-only, no barriers).\\n// Cuts each matmul's latency ~SG-fold vs one-thread-per-output (the real decode bottleneck:\\n// kernels run at full latency in the dependent chain). Routes to out0/out1/out2 by range (qkv / gate-up).\\nenable subgroups;\\noverride SG: u32 = 32u;\\nstruct Params { K: u32, nb: u32, N0: u32, N1: u32, N2: u32, gridX: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\\n\\n@compute @workgroup_size(SG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\\n let Ntot = p.N0 + p.N1 + p.N2;\\n let n = wg.y * p.gridX + wg.x;\\n if (n >= Ntot) { return; }\\n let wRow = n * (p.K / 32u);\\n let sbase = n * p.nb;\\n let Kvec = p.K / 4u;\\n\\n var acc = 0.0;\\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\\n let k = gi * 4u;\\n let word = signbits[wRow + (k >> 5u)];\\n let bits4 = (word >> (k & 31u)) & 0xfu;\\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\\n acc = acc + dot(x[gi], sv) * scales[sbase + (k / 128u)];\\n }\\n let total = subgroupAdd(acc);\\n if (lane == 0u) {\\n if (n < p.N0) { out0[n] = total; }\\n else if (n < p.N0 + p.N1) { out1[n - p.N0] = total; }\\n else { out2[n - p.N0 - p.N1] = total; }\\n }\\n}\\n\",\n \"matmul_split_sm\": \"// Small-batch (M = 2..9) subgroup split-K GEMV, fused qkv / gate-up. The speculative-decode\\n// verify pass computes M drafted rows in one forward; the scalar prefill kernels re-read the\\n// weights per output thread, so a k-row pass cost ~k GEMVs. Here each weight word is loaded\\n// ONCE per (column, k-chunk) and dotted with all M activation rows (activations are ~8 KB/row,\\n// cache-resident). Per row the loop stride and accumulation expression are IDENTICAL to\\n// matmul_split_sg, so each row's partials - and therefore the subgroupAdd result - match the\\n// M=1 decode path bit-for-bit.\\nenable subgroups;\\noverride SG: u32 = 32u;\\nstruct Params { K: u32, nb: u32, N0: u32, N1: u32, N2: u32, gridX: u32, M: u32, _pad: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4] row-major\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>; // [M, N0]\\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>; // [M, N1]\\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>; // [M, N2]\\n\\n@compute @workgroup_size(SG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\\n let Ntot = p.N0 + p.N1 + p.N2;\\n let n = wg.y * p.gridX + wg.x;\\n if (n >= Ntot) { return; } // uniform per workgroup: the whole subgroup exits together\\n let wRow = n * (p.K / 32u);\\n let sbase = n * p.nb;\\n let Kvec = p.K / 4u;\\n\\n var acc: array<f32, 9>; // M <= 9\\n for (var m = 0u; m < p.M; m = m + 1u) { acc[m] = 0.0; }\\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\\n let k = gi * 4u;\\n let word = signbits[wRow + (k >> 5u)];\\n let bits4 = (word >> (k & 31u)) & 0xfu;\\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\\n let s = scales[sbase + (k / 128u)];\\n for (var m = 0u; m < p.M; m = m + 1u) {\\n acc[m] = acc[m] + dot(x[m * Kvec + gi], sv) * s;\\n }\\n }\\n for (var m = 0u; m < p.M; m = m + 1u) { // p.M is uniform: collective calls stay uniform\\n let total = subgroupAdd(acc[m]);\\n if (lane == 0u) {\\n if (n < p.N0) { out0[m * p.N0 + n] = total; }\\n else if (n < p.N0 + p.N1) { out1[m * p.N1 + (n - p.N0)] = total; }\\n else { out2[m * p.N2 + (n - p.N0 - p.N1)] = total; }\\n }\\n }\\n}\\n\",\n \"matmul_split_tiled\": \"// Tiled register-blocked binary GEMM to 3 outputs (qkv or gate/up), PREFILL (M>1), vec4 K-accum.\\n// Weights concatenated along N (N0|N1|N2); each output element routes individually to\\n// out0/out1/out2 by its global column, so N0/N1/N2 need no alignment. Same vec4 design as\\n// matmul_resid_tiled.\\nconst BM: u32 = 64u;\\nconst BN: u32 = 64u;\\nconst BKV: u32 = 4u; // BK / 4 (BK = 16)\\nstruct Params { M: u32, K: u32, nb: u32, N0: u32, N1: u32, N2: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4]\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\\n\\nvar<workgroup> xs: array<vec4<f32>, 256>;\\nvar<workgroup> ws: array<vec4<f32>, 256>;\\n\\n@compute @workgroup_size(256)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\\n let Ntot = p.N0 + p.N1 + p.N2;\\n let tid = lid.x;\\n let tileM = wg.y * BM;\\n let tileN = wg.x * BN;\\n let tr = (tid / 16u) * 4u;\\n let tc = (tid % 16u) * 4u;\\n let Kv = p.K / 4u;\\n var acc: array<f32, 16>;\\n for (var i = 0u; i < 16u; i = i + 1u) { acc[i] = 0.0; }\\n\\n let Ksteps = Kv / BKV;\\n for (var ks = 0u; ks < Ksteps; ks = ks + 1u) {\\n let k0v = ks * BKV;\\n for (var e = tid; e < BM * BKV; e = e + 256u) {\\n let m = e / BKV; let kv = e % BKV; let gm = tileM + m;\\n xs[e] = select(vec4<f32>(0.0), x[gm * Kv + (k0v + kv)], gm < p.M);\\n }\\n for (var e = tid; e < BN * BKV; e = e + 256u) {\\n let n = e / BKV; let kv = e % BKV; let gn = tileN + n; let k = (k0v + kv) * 4u;\\n var wv = vec4<f32>(0.0);\\n if (gn < Ntot) {\\n let bits4 = (signbits[gn * (p.K / 32u) + (k >> 5u)] >> (k & 31u)) & 0xfu;\\n let s = scales[gn * p.nb + (k / 128u)];\\n wv = vec4<f32>(select(-s, s, (bits4 & 1u) != 0u), select(-s, s, (bits4 & 2u) != 0u),\\n select(-s, s, (bits4 & 4u) != 0u), select(-s, s, (bits4 & 8u) != 0u));\\n }\\n ws[e] = wv;\\n }\\n workgroupBarrier();\\n for (var kv = 0u; kv < BKV; kv = kv + 1u) {\\n var xr: array<vec4<f32>, 4>;\\n for (var tm = 0u; tm < 4u; tm = tm + 1u) { xr[tm] = xs[(tr + tm) * BKV + kv]; }\\n for (var tn = 0u; tn < 4u; tn = tn + 1u) {\\n let w = ws[(tc + tn) * BKV + kv];\\n for (var tm = 0u; tm < 4u; tm = tm + 1u) { acc[tm * 4u + tn] = acc[tm * 4u + tn] + dot(xr[tm], w); }\\n }\\n }\\n workgroupBarrier();\\n }\\n\\n for (var tm = 0u; tm < 4u; tm = tm + 1u) {\\n let gm = tileM + tr + tm;\\n if (gm >= p.M) { continue; }\\n for (var tn = 0u; tn < 4u; tn = tn + 1u) {\\n let gn = tileN + tc + tn;\\n if (gn >= Ntot) { continue; }\\n let v = acc[tm * 4u + tn];\\n if (gn < p.N0) { out0[gm * p.N0 + gn] = v; }\\n else if (gn < p.N0 + p.N1) { out1[gm * p.N1 + (gn - p.N0)] = v; }\\n else { out2[gm * p.N2 + (gn - p.N0 - p.N1)] = v; }\\n }\\n }\\n}\\n\",\n \"matmul_split_wg\": \"// No-subgroup fallback: split-K GEMV for decode (M=1), workgroup-shared-memory reduction instead\\n// of subgroupAdd. One workgroup per output column; WG threads split K and tree-reduce via shared\\n// memory + barriers. ~WG-fold faster than one-thread-per-output (the v1 path). Routes qkv / gate-up.\\noverride WG: u32 = 64u;\\nstruct Params { K: u32, nb: u32, N0: u32, N1: u32, N2: u32, gridX: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\\nvar<workgroup> sdata: array<f32, 256>; // >= max WG\\n\\n@compute @workgroup_size(WG)\\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\\n let Ntot = p.N0 + p.N1 + p.N2;\\n let n = wg.y * p.gridX + wg.x; // uniform across the workgroup -> early return is barrier-safe\\n if (n >= Ntot) { return; }\\n let tid = lid.x;\\n let wRow = n * (p.K / 32u);\\n let sbase = n * p.nb;\\n let Kvec = p.K / 4u;\\n var acc = 0.0;\\n for (var gi = tid; gi < Kvec; gi = gi + WG) {\\n let k = gi * 4u;\\n let word = signbits[wRow + (k >> 5u)];\\n let bits4 = (word >> (k & 31u)) & 0xfu;\\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\\n acc = acc + dot(x[gi], sv) * scales[sbase + (k / 128u)];\\n }\\n sdata[tid] = acc;\\n workgroupBarrier();\\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\\n if (tid < s) { sdata[tid] = sdata[tid] + sdata[tid + s]; }\\n workgroupBarrier();\\n }\\n if (tid == 0u) {\\n let total = sdata[0];\\n if (n < p.N0) { out0[n] = total; }\\n else if (n < p.N0 + p.N1) { out1[n - p.N0] = total; }\\n else { out2[n - p.N0 - p.N1] = total; }\\n }\\n}\\n\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"sampler_penalty\": \"// GPU logits pre-filter for sampling: applies repetition_penalty then no_repeat_ngram bans in place\\n// on the full vocab logit buffer, so only a tiny top-K candidate set has to be read back (not all\\n// ~151k logits). Matches transformers.js exactly: rep_penalty over the DEDUPED prompt+generated id\\n// set (logit<0 ? *penalty : /penalty), then ngram-banned next-tokens set to -Infinity. Both id lists\\n// are computed on the CPU each step (exact, since at syncN=1 the full history is known) and uploaded.\\n// Temperature is NOT applied here: top-k is invariant under the monotonic divide, so temperature is\\n// applied on the CPU to just the K candidate values before softmax (bit-identical, one less pass).\\n// Single workgroup, no subgroup ops -> all devices. The storageBarrier guarantees every penalty\\n// write lands before any ban write, so a token that is both repeated and ngram-banned ends at -inf\\n// (ban wins, matching the reference order rep_penalty -> ngram).\\noverride WG: u32 = 256u;\\n// negInf carries the -Infinity bit pattern (0xff800000) from the host: bitcasting it at RUNTIME yields\\n// -inf, whereas bitcast<f32>(0xff800000u) is a const-expression evaluating to inf, which is a WGSL\\n// shader-creation error. (Runtime inf is fine; only const/override inf/nan is rejected.)\\nstruct Params { affectedLen: u32, banLen: u32, penalty: f32, negInf: u32 };\\n\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> affectedIds: array<u32>; // deduped prompt+generated ids\\n@group(0) @binding(2) var<storage, read> banIds: array<u32>; // ngram-banned next-token ids\\n@group(0) @binding(3) var<storage, read_write> logits: array<f32>; // [vocab], modified in place\\n\\n@compute @workgroup_size(WG)\\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\\n let tid = lid.x;\\n for (var i = tid; i < p.affectedLen; i = i + WG) {\\n let t = affectedIds[i];\\n let v = logits[t];\\n if (v < 0.0) { logits[t] = v * p.penalty; } else { logits[t] = v / p.penalty; }\\n }\\n storageBarrier(); // all penalty writes before any ban write\\n for (var i = tid; i < p.banLen; i = i + WG) {\\n logits[banIds[i]] = bitcast<f32>(p.negInf); // -Infinity (runtime bitcast)\\n }\\n}\\n\",\n \"swiglu\": \"// SwiGLU gate: y[i] = silu(gate[i]) * up[i], silu(g) = g * sigmoid(g). One invocation per element.\\nstruct Params { n: u32, _p0: u32, _p1: u32, _p2: u32 };\\n@group(0) @binding(0) var<uniform> p: Params;\\n@group(0) @binding(1) var<storage, read> gate: array<f32>;\\n@group(0) @binding(2) var<storage, read> up: array<f32>;\\n@group(0) @binding(3) var<storage, read_write> y: array<f32>;\\n\\n@compute @workgroup_size(64)\\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\\n if (i >= p.n) { return; }\\n let g = gate[i];\\n y[i] = (g / (1.0 + exp(-g))) * up[i];\\n}\\n\",\n}\n","/** Thrown when WebGPU is unavailable: no `navigator.gpu` (unsupported browser, or a\n * non-secure context) or no adapter could be acquired. Catch this to render a\n * \"your browser doesn't support WebGPU yet\" fallback instead of crashing. */\nexport class WebGPUUnavailableError extends Error {\n override readonly name = 'WebGPUUnavailableError'\n constructor(message: string) {\n super(message)\n }\n}\n\n/** Thrown when the GPU reports out-of-memory while the engine allocates weights or grows the\n * KV cache. Without this check the allocation \"succeeds\" with invalid buffers and every later\n * generate() returns garbage. Catch it to fall back (smaller maxSeqLen, or a no-LLM mode). */\nexport class GpuOutOfMemoryError extends Error {\n override readonly name = 'GpuOutOfMemoryError'\n constructor(message: string) {\n super(message)\n }\n}\n","// Prompt-lookup drafting (the CPU half of speculative decoding). No draft model: the draft is\n// the continuation that followed the most recent prior occurrence of the sequence's trailing\n// n-gram. High hit rate whenever the model repeats sequence content (quoting RAG context,\n// lists, code); zero cost when nothing matches (no draft -> a normal single-token step).\n\n/** Return up to `maxDraft` draft tokens: the continuation after the most recent prior occurrence\n * of the trailing g-gram, trying g = ngramSize down to 2 (1-grams draft too noisily to pay off).\n * Empty when nothing matches. */\nexport function draftNgram(seq: readonly number[], ngramSize: number, maxDraft: number): number[] {\n if (maxDraft <= 0) return []\n for (let g = Math.min(ngramSize, seq.length - 1); g >= 2; g--) {\n const start = seq.length - g // the trailing g-gram lives at [start, seq.length)\n outer: for (let i = start - 1; i >= 0; i--) {\n for (let j = 0; j < g; j++) if (seq[i + j] !== seq[start + j]) continue outer\n const from = i + g // i <= start-1, so from <= seq.length-1: at least one token follows\n return seq.slice(from, Math.min(from + maxDraft, seq.length))\n }\n }\n return []\n}\n\n/** Number of tokens promptLookup:'auto' emits through the PLD path before deciding whether\n * speculating actually pays on this content. */\nexport const PLD_PROBATION = 24\n\n/** The auto-bail decision after the probation window: keep speculating only when the measured\n * tokens-per-verify-step clears the break-even against PLAIN decoding, which differs by mode.\n * Each PLD step costs one batched verify forward plus a per-step CPU sync; plain GREEDY chains\n * several steps per sync (GPU-resident argmax), so its break-even is high (~2.0 tokens/step,\n * measured), while plain SAMPLED syncs every token anyway (~1.5). Below the bar, the rest of\n * the turn runs the plain path - output is identical either way, only speed changes. */\nexport function pldWorthIt(emitted: number, steps: number, sampled: boolean): boolean {\n if (steps <= 0) return false\n return emitted / steps >= (sampled ? 1.5 : 2.0)\n}\n","// CPU side of the sampler. All the correctness-bearing probability math lives here (not in WGSL) so\n// it can be bit-checked against transformers.js in Node. The GPU only pre-filters logits\n// (repetition_penalty + no_repeat_ngram bans) and reduces to the top-K; this module computes the\n// CPU-side inputs (deduped id set, ngram ban list) and does the final temperature + softmax +\n// multinomial draw over the K candidates. Faithful port of transformers.js v4.2.0 semantics:\n// chain: repetition_penalty -> no_repeat_ngram -> temperature -> top_k -> softmax -> multinomial\n// (top_p, top_k warper, bad_words, min_length are not applied in that version).\n\n/** Mersenne Twister 19937, matching transformers.js utils/random.js (= Python's random.Random). */\nexport class MT19937 {\n private mt = new Uint32Array(624)\n private idx = 625\n\n constructor(seed?: number) {\n this.seed(seed)\n }\n\n seed(n?: number): void {\n if (n === undefined || n === null) {\n const buf = new Uint32Array(1)\n crypto.getRandomValues(buf)\n n = buf[0]\n }\n const mt = this.mt\n const u = (a: number, b: number): number => Math.imul(a, b) >>> 0\n const key: number[] = []\n for (let v = n || 0; v > 0; v = Math.floor(v / 0x100000000)) key.push(v & 0xffffffff)\n if (!key.length) key.push(0)\n mt[0] = 19650218\n for (let k = 1; k < 624; ++k) mt[k] = (u(1812433253, mt[k - 1] ^ (mt[k - 1] >>> 30)) + k) >>> 0\n let i = 1\n let j = 0\n for (let k = Math.max(624, key.length); k > 0; --k, ++i, ++j) {\n if (i >= 624) {\n mt[0] = mt[623]\n i = 1\n }\n if (j >= key.length) j = 0\n mt[i] = ((mt[i] ^ u(mt[i - 1] ^ (mt[i - 1] >>> 30), 1664525)) + key[j] + j) >>> 0\n }\n for (let k = 623; k > 0; --k, ++i) {\n if (i >= 624) {\n mt[0] = mt[623]\n i = 1\n }\n mt[i] = ((mt[i] ^ u(mt[i - 1] ^ (mt[i - 1] >>> 30), 1566083941)) - i) >>> 0\n }\n mt[0] = 0x80000000\n this.idx = 624\n }\n\n private int32(): number {\n const mt = this.mt\n if (this.idx >= 624) {\n for (let k = 0; k < 624; ++k) {\n const y = (mt[k] & 0x80000000) | (mt[(k + 1) % 624] & 0x7fffffff)\n mt[k] = (mt[(k + 397) % 624] ^ (y >>> 1) ^ (y & 1 ? 0x9908b0df : 0)) >>> 0\n }\n this.idx = 0\n }\n let y = mt[this.idx++]\n y ^= y >>> 11\n y ^= (y << 7) & 0x9d2c5680\n y ^= (y << 15) & 0xefc60000\n y ^= y >>> 18\n return y >>> 0\n }\n\n /** Uniform float in [0, 1), matching Python's random.random(). */\n random(): number {\n return ((this.int32() >>> 5) * 67108864.0 + (this.int32() >>> 6)) / 9007199254740992.0\n }\n}\n\n/** Deduped set of token ids that repetition_penalty applies to (the full prompt+generated history). */\nexport function affectedIds(history: number[]): Uint32Array {\n return Uint32Array.from(new Set(history))\n}\n\n/** no_repeat_ngram banned next-tokens for the current step. Faithful port of\n * NoRepeatNGramLogitsProcessor.calcBannedNgramTokens (transformers.js v4.2.0). */\nexport function ngramBans(history: number[], n: number): number[] {\n if (history.length + 1 < n) return []\n const generated = new Map<string, number[]>()\n for (let j = 0; j < history.length + 1 - n; ++j) {\n const ngram: number[] = []\n for (let k = 0; k < n; ++k) ngram.push(history[j + k])\n const key = JSON.stringify(ngram.slice(0, n - 1))\n const arr = generated.get(key) ?? []\n arr.push(ngram[n - 1])\n generated.set(key, arr)\n }\n const idx = history.slice(history.length + 1 - n, history.length)\n return generated.get(JSON.stringify(idx)) ?? []\n}\n\n/** Stable softmax (max-subtract), matching transformers.js utils/maths.js softmax. */\nfunction softmax(arr: Float32Array | number[]): number[] {\n let maxVal = arr[0]\n for (let i = 1; i < arr.length; ++i) if (arr[i] > maxVal) maxVal = arr[i]\n const exps = Array.from(arr, (x) => Math.exp(x - maxVal))\n let sum = 0\n for (const e of exps) sum += e\n return exps.map((x) => x / sum)\n}\n\n/** Final sampling tail. `candVals` are the K largest PENALTY-FILTERED logits (descending), `candIds`\n * their token ids. Applies temperature to the K values, softmaxes, then draws via the exact\n * transformers.js inverse-CDF weighted pick (x = random()*sum; subtract until <0). Returns a token id. */\nexport function sampleFromCandidates(candIds: Uint32Array | number[], candVals: Float32Array | number[], temperature: number, rng: MT19937): number {\n const k = candVals.length\n const tv = new Float32Array(k)\n for (let i = 0; i < k; ++i) tv[i] = candVals[i] / temperature // divide (exact for any T), matches TemperatureLogitsWarper\n const probs = softmax(tv)\n let sum = 0\n for (const pr of probs) sum += pr\n let x = rng.random() * sum\n for (let i = 0; i < k; ++i) {\n x -= probs[i]\n if (x < 0) return candIds[i]\n }\n return candIds[k - 1] // floating-point guard, matches _weightedIndexWith\n}\n","// WebGPU runtime for 1-bit Qwen3-family models (Bonsai 1.7B/4B/8B and any q1 export whose\n// manifest passes the load-time contract). Loads binary (1-bit) weights via the manifest,\n// runs the forward with the validated kernels, keeps a persistent KV cache, and generates\n// autoregressively. Decode is dispatch-overhead-bound, so the matmuls are fused (q/k/v in one\n// dispatch, gate/up in one, the residual add folded into o_proj/down_proj) and the decode loop\n// is GPU-resident (GPU argmax + embedding gather) with deferred CPU sync + pooled resources.\n//\n// This is a faithful port of the validated engine.js: the kernel sequence and numerics are\n// unchanged (bit-exact). Only the shader source (now inlined, not fetched), the configuration\n// (now typed options, not URL params), and the public surface differ.\nimport { SHADERS } from './shaders.generated'\nimport { GpuOutOfMemoryError, WebGPUUnavailableError } from './errors'\nimport { draftNgram, pldWorthIt, PLD_PROBATION } from './pld'\nimport { MT19937, affectedIds, ngramBans, sampleFromCandidates } from './sampler'\nimport type {\n DeviceLostInfo,\n Engine,\n EngineCapabilities,\n EngineOptions,\n ForwardResult,\n GenerateOptions,\n GenerateResult,\n KvSnapshot,\n Manifest,\n ManifestRef as Ref,\n ManifestTensor,\n TokenLogprobs,\n} from './types'\n\ntype Field = ['f' | 'u', number]\n// Manifest / ManifestTensor / ManifestArch / ManifestRef are public types now (src/types.ts):\n// bitgpu/gguf builds manifests in memory, so callers can hold and pass them.\n\ninterface GpuWeight {\n buf?: GPUBuffer\n sign?: GPUBuffer\n scales?: GPUBuffer\n codes?: GPUBuffer\n N?: number\n K?: number\n nb?: number\n N0?: number\n N1?: number\n N2?: number\n zp?: number\n}\n\ninterface RawGenResult {\n prefillMs: number\n decodeMs: number\n tokPerSec: number\n tokens: number[]\n firstArgmax: number\n recMs: number\n gpuMs: number\n rbMs: number\n spec?: { steps: number; drafted: number; accepted: number; bailed?: boolean }\n /** The sampler RNG as it stands after this call - promptLookup:'auto' hands it to the plain\n * continuation so the draw stream continues exactly where the probation left off. */\n rng?: MT19937\n /** Per-emitted-token logprob records (sampled path only, when GenerateOptions.logprobs set). */\n lp?: TokenLogprobs[]\n}\n\n/** Internal engine handle: the public {@link Engine} surface plus diagnostics used by the\n * correctness/benchmark harness. The diagnostics are intentionally not in the public type. */\ninterface EngineInternal extends Engine {\n device: GPUDevice\n adapter: GPUAdapter\n /** Raw decode with the per-kernel profiling switch (`full`) and sync depth exposed. */\n profileDecode(ids: number[], nTokens: number, full?: Set<string> | null, syncN?: number): Promise<RawGenResult>\n /** Differential debug: one decode step through the fast and slow paths, checkpoint by checkpoint. */\n debugDecode(prefillIds: number[]): Promise<{ fast: Record<string, Float32Array>; slow: Record<string, Float32Array> }>\n /** Debug: GPU base + penalized logits + top-K for a prefill, to diff the sampler kernels vs CPU math. */\n debugSampler(ids: number[], genOpts: GenerateOptions): Promise<{ base: Float32Array; penalized: Float32Array; candIds: Uint32Array; candVals: Float32Array }>\n}\n\ntype TypedArrayCtor = Float32ArrayConstructor | Uint8ArrayConstructor | Uint16ArrayConstructor\nconst VIEW: Record<string, TypedArrayCtor> = { FLOAT: Float32Array, UINT8: Uint8Array, FLOAT16: Uint16Array }\nconst WGSLS = ['matmul_split', 'matmul_resid', 'matmul_q2', 'rope', 'swiglu', 'copy']\nconst DEFAULT_MAX_SEQ = 2048\nconst PREFILL_SEG = 256 // prefill segment length; see runPrefill for why prefills are segmented\n\nconst PARAM_AB = new ArrayBuffer(64)\nconst PARAM_DV = new DataView(PARAM_AB)\nconst PARAM_U8 = new Uint8Array(PARAM_AB)\nfunction makeParams(fields: Field[]): Uint8Array {\n // fills a reused buffer (no per-dispatch alloc)\n for (let i = 0; i < fields.length; i++) {\n const f = fields[i]\n if (f[0] === 'f') PARAM_DV.setFloat32(i * 4, f[1], true)\n else PARAM_DV.setUint32(i * 4, f[1] >>> 0, true)\n }\n return PARAM_U8.subarray(0, Math.ceil(fields.length / 4) * 16)\n}\nconst eqBytes = (a: Uint8Array, b: Uint8Array): boolean => {\n for (let i = 0; i < b.length; i++) if (a[i] !== b[i]) return false\n return true\n}\n/** Synthesize f32 rope tables ([positions, head_dim/2]) from arch.rope for manifests without\n * baked caches (v2/GGUF). Plain rope or YaRN (transformers formula: beta_fast 32, beta_slow 1,\n * mscale = 0.1*ln(factor)+1). Angles accumulate in f64 and round once to f32 per entry -\n * tools/reference.py implements the identical recipe for fixture generation. */\nfunction synthRope(A: { head_dim: number; rope?: { rope_theta: number; rope_type?: string; factor?: number; original_max_position_embeddings?: number } }, positions: number): [Float32Array, Float32Array] {\n const half = A.head_dim / 2\n const rope = A.rope!\n const base = rope.rope_theta\n const factor = rope.rope_type === 'yarn' ? (rope.factor ?? 1) : 1\n const inv = new Float64Array(half)\n // YaRN ramp bounds (only used when factor > 1): dims below lo keep the original\n // frequencies (extrapolation), dims above hi interpolate by 1/factor, between them blends.\n const orig = rope.original_max_position_embeddings ?? 0\n const lo = factor === 1 ? 0 : Math.max(0, Math.floor((A.head_dim * Math.log(orig / (32 * 2 * Math.PI))) / (2 * Math.log(base))))\n const hi = factor === 1 ? 0 : Math.min(half - 1, Math.ceil((A.head_dim * Math.log(orig / (2 * Math.PI))) / (2 * Math.log(base))))\n for (let j = 0; j < half; j++) {\n const pf = base ** ((2 * j) / A.head_dim)\n if (factor === 1) {\n inv[j] = 1 / pf\n continue\n }\n const ramp = Math.min(1, Math.max(0, (j - lo) / (hi - lo)))\n inv[j] = (1 / (factor * pf)) * ramp + (1 / pf) * (1 - ramp)\n }\n const mscale = factor === 1 ? 1 : Math.fround(0.1 * Math.log(factor) + 1)\n const cos = new Float32Array(positions * half)\n const sin = new Float32Array(positions * half)\n for (let p = 0; p < positions; p++)\n for (let j = 0; j < half; j++) {\n const a = p * inv[j]\n cos[p * half + j] = Math.fround(Math.cos(a) * mscale)\n sin[p * half + j] = Math.fround(Math.sin(a) * mscale)\n }\n return [cos, sin]\n}\n/** Load a 1-bit model and return an {@link Engine}. Pass a model URL string for defaults. */\nexport async function createEngine(options: EngineOptions | string): Promise<Engine> {\n // Any load failure after the device exists (WGSL compile error, manifest validation, truncated\n // download, allocation OOM) must destroy the device, or the partially-loaded weights stay\n // resident until GC collects the GPUDevice - undermining the catch-OOM-and-retry-smaller advice\n // in errors.ts, since the retry contends with the dead engine's VRAM.\n const holder: { device?: GPUDevice } = {}\n try {\n return await createEngineInner(options, holder)\n } catch (e) {\n holder.device?.destroy()\n throw e\n }\n}\nasync function createEngineInner(options: EngineOptions | string, holder: { device?: GPUDevice }): Promise<Engine> {\n const opts: EngineOptions = typeof options === 'string' ? { modelUrl: options } : options\n const modelDir = opts.modelUrl ? opts.modelUrl.replace(/\\/$/, '') : null\n if (!modelDir && !opts.manifestUrl && !opts.manifest)\n throw new Error('createEngine: provide modelUrl, manifestUrl, or an in-memory manifest')\n if (opts.manifest && !modelDir && !opts.dataUrl)\n throw new Error('createEngine: an in-memory manifest needs dataUrl (or modelUrl) for the weights file')\n const powerPreference = opts.powerPreference ?? 'high-performance'\n const fetchJson =\n opts.fetchJson ??\n (async (url: string) => {\n const res = await fetch(url)\n if (!res.ok) throw new Error(`bitgpu: fetch ${url} failed: HTTP ${res.status}`)\n if ((res.headers.get('content-type') ?? '').includes('text/html'))\n throw new Error(`bitgpu: ${url} returned HTML, not JSON (a SPA fallback is probably serving index.html for missing model files)`)\n return res.json()\n })\n const fetchBytes =\n opts.fetchArrayBuffer ??\n (async (url: string) => {\n const res = await fetch(url)\n if (!res.ok) throw new Error(`bitgpu: fetch ${url} failed: HTTP ${res.status}`)\n const total = Number(res.headers.get('content-length') ?? 0)\n if (!res.body || !total) return res.arrayBuffer()\n // Stream so onProgress can report the (multi-hundred-MB) weights download.\n const reader = res.body.getReader()\n const chunks: Uint8Array[] = []\n let loaded = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n chunks.push(value)\n loaded += value.byteLength\n opts.onProgress?.({ phase: 'weights', loaded, total })\n }\n const out = new Uint8Array(loaded)\n let p = 0\n for (const c of chunks) {\n out.set(c, p)\n p += c.byteLength\n }\n return out.buffer\n })\n\n if (typeof navigator === 'undefined' || !navigator.gpu) {\n throw new WebGPUUnavailableError('WebGPU is not available (no navigator.gpu). Use a WebGPU-capable browser over a secure context.')\n }\n\n opts.onProgress?.({ phase: 'manifest' })\n const manifest = opts.manifest ?? ((await fetchJson(opts.manifestUrl ?? `${modelDir}/manifest.json`)) as Manifest)\n opts.onProgress?.({ phase: 'weights' })\n const dataUrl = opts.dataUrl ?? `${modelDir}/${manifest.data_file}`\n // Only the SMALL aux file (LUTs, ~160KB) is buffered; the ~290MB data file STREAMS through\n // per-tensor routes straight into GPU buffers further down (see the streaming weight loader).\n let aux: ArrayBuffer\n if (opts.aux) {\n // In-memory aux (bitgpu/gguf computes the LUTs instead of fetching them). Normalize a view\n // to a tight ArrayBuffer so the offset math below stays identical to the fetched path.\n aux = opts.aux instanceof Uint8Array ? new Uint8Array(opts.aux).buffer : opts.aux\n } else {\n aux = await fetchBytes(opts.auxUrl ?? `${modelDir}/${manifest.aux_file}`)\n }\n const A = manifest.arch\n const T = manifest.tensors\n // Fail loud on manifests the kernels cannot run, instead of producing silent garbage: the WGSL\n // assumes silu activation, head_dim <= 128 (per-thread register arrays), and 128-wide scale blocks.\n const FINAL_NORM = `layers.${A.layers}.final_norm_layernorm`\n if (A.act !== 'silu') throw new Error(`bitgpu: unsupported activation '${A.act}' (kernels implement silu/SwiGLU)`)\n if (A.head_dim > 128) throw new Error(`bitgpu: unsupported head_dim ${A.head_dim} (kernels assume <= 128)`)\n if (A.heads % A.kv_heads !== 0) throw new Error(`bitgpu: heads ${A.heads} not divisible by kv_heads ${A.kv_heads} (GQA kernels assume an integer group size)`)\n if (!T[FINAL_NORM]) throw new Error(`bitgpu: manifest is missing the final norm tensor '${FINAL_NORM}'`)\n if (manifest.version !== undefined && manifest.version !== 1 && manifest.version !== 2)\n throw new Error(`bitgpu: unsupported manifest version ${manifest.version} (this engine reads versions 1 and 2)`)\n // Rope comes either baked (cos_cache/sin_cache refs, ONNX exports: exact parity with the\n // exporter) or synthesized at load from arch.rope (v2/GGUF manifests, which bake no tables).\n if (!T.cos_cache !== !T.sin_cache) throw new Error('bitgpu: manifest has only one of cos_cache/sin_cache')\n if (!T.cos_cache && !(A.rope && A.rope.rope_theta))\n throw new Error('bitgpu: manifest has neither baked cos_cache/sin_cache RoPE tensors nor arch.rope parameters')\n for (const [name, t] of Object.entries(T)) {\n if (t.block !== undefined && t.block !== 128) throw new Error(`bitgpu: tensor ${name} has block ${t.block} (kernels assume 128)`)\n // v2 container tensors: keep the raw interleaved region aside (q1_0) and synthesize\n // PLANAR weight/scales refs carrying the byte lengths the kernels consume, so all the\n // size computations below (limits, buffer creation, fusion) stay container-blind. The\n // streaming loader demuxes the region into both sinks in-flight (see wireQ10).\n if (t.container === undefined) continue\n if (t.container !== 'q1_0') throw new Error(`bitgpu: tensor ${name} has unknown container '${t.container}'`)\n const N = t.N ?? t.rows\n const K = t.K ?? t.cols\n if (!N || !K || K % 128 !== 0) throw new Error(`bitgpu: tensor ${name}: q1_0 container needs N/K (or rows/cols) with K a multiple of 128`)\n const r = t.weight\n if (!r || r.src !== 'data' || r.len !== N * (K / 128) * 18)\n throw new Error(`bitgpu: tensor ${name}: q1_0 region is ${r?.len} bytes in '${r?.src}', expected ${N * (K / 128) * 18} in the data file`)\n t.q1_0 = r\n t.weight = { dtype: 'UINT8', src: r.src, off: r.off, len: N * (K / 8) }\n t.scales = { dtype: 'FLOAT', src: r.src, off: r.off, len: N * (K / 128) * 4 }\n t.zp = undefined // no zp tensor in the container; the 1-bit recipe's midpoints are constants\n }\n\n const readRef = (ref: Ref): Float32Array | Uint8Array | Uint16Array => {\n if (ref.src !== 'aux') throw new Error('bitgpu: internal - readRef reads aux-file refs; data-file tensors stream through routes')\n if (ref.off + ref.len > aux.byteLength)\n throw new Error(`bitgpu: tensor range ${ref.off}+${ref.len} exceeds the aux file (${aux.byteLength} bytes); the download is truncated or the manifest does not match it`)\n const V = VIEW[ref.dtype]!\n if (V === Uint8Array) return new Uint8Array(aux, ref.off, ref.len)\n const bpe = V.BYTES_PER_ELEMENT\n if (ref.off % bpe === 0) return new V(aux, ref.off, ref.len / bpe)\n return new V(aux.slice(ref.off, ref.off + ref.len))\n }\n const readU8 = (ref: Ref): Uint8Array => readRef(ref) as Uint8Array\n\n const adapter = await navigator.gpu.requestAdapter({ powerPreference }) // pick the discrete GPU on multi-GPU machines, not the weak iGPU\n if (!adapter) throw new WebGPUUnavailableError('No suitable WebGPU adapter was found.')\n const hasSG = adapter.features.has('subgroups' as GPUFeatureName)\n const info = (adapter.info ?? {}) as GPUAdapterInfo & { subgroupMinSize?: number; subgroupMaxSize?: number } // subgroup sizes live on GPUAdapterInfo\n const sgMax = info.subgroupMaxSize ?? 32\n const sgMin = info.subgroupMinSize ?? sgMax\n const forceNoSG = opts.forceNoSubgroups ?? false\n // No-subgroup reduction workgroup size. Snapped to a power of two in [32, 256]: the _wg kernels'\n // tree reductions halve the stride each step, so any other size silently drops partial sums.\n const WG_NS = Math.min(256, Math.max(32, 1 << Math.round(Math.log2(opts.noSubgroupWorkgroupSize ?? 64))))\n const NOTILE = opts.prefillTiling === 'never' // force the scalar prefill GEMM (A/B)\n const FORCETILE = opts.prefillTiling === 'always' // use tiled even for short prompts (validation)\n const tiledPrefill = (S: number): boolean => FORCETILE || (!NOTILE && S >= 64) // tiled GEMM wins only once it fills its 64-row tiles\n const SYNC_N = Math.max(1, opts.syncSteps ?? 4) // decode: chain N steps per CPU sync\n const maxSeqLen = Math.max(1, opts.maxSeqLen ?? DEFAULT_MAX_SEQ) // KV-cache length cap (VRAM ~ maxSeqLen x layers x kv_heads x head_dim x KVB)\n // uniform 16/32/64 (16 = Arm Mali) -> head_dim/SG<=8. The subgroup attention kernel covers\n // dimension lane + t*SG for t in [0, D/SG), so head_dim must divide evenly (128 always does;\n // an exotic head_dim like 80 takes the strided _wg fallback instead of silently dropping dims).\n const useSG = hasSG && sgMin === sgMax && (sgMax === 16 || sgMax === 32 || sgMax === 64) && A.head_dim % sgMax === 0 && !forceNoSG\n // f16 KV STORAGE (math stays f32; one rounding at cache-write). 'f16' silently falls back to\n // f32 where shader-f16 is missing, so callers can request it unconditionally.\n const kv16 = opts.kvCache === 'f16' && adapter.features.has('shader-f16' as GPUFeatureName)\n // q8: packed snorm8 K/V with one f32 scale per 32-element block (q8_0-style). Pure core WGSL\n // (pack4x8snorm), so unlike f16 it needs no adapter feature - available everywhere.\n const kv8 = opts.kvCache === 'q8'\n // Rolling window with attention sinks (StreamingLLM): keys cached UNROPED, rotated at read\n // by cache-relative position, middle evicted in batches. See the attention_*_roll shaders.\n const roll = opts.overflow === 'sinks'\n const SINKS = roll ? Math.max(1, Math.floor(opts.sinkTokens ?? 4)) : 0\n if (roll && maxSeqLen < SINKS + 64)\n throw new Error(`bitgpu: overflow 'sinks' needs maxSeqLen >= sinkTokens + 64 (got ${maxSeqLen} with ${SINKS} sinks)`)\n const KVB = kv16 ? 2 : kv8 ? 1 : 4 // bytes per cached K/V element (q8 block scales tracked separately)\n const features: GPUFeatureName[] = []\n if (useSG) features.push('subgroups' as GPUFeatureName)\n if (kv16) features.push('shader-f16' as GPUFeatureName)\n // ---- device limits negotiation ----\n // Run at WebGPU's guaranteed-minimum limits whenever the model fits them (low-end/mobile devices\n // keep working exactly as before), and request precisely the raised limits a bigger model needs,\n // gated on what the adapter can grant. Every buffer the loader will create is sized here FROM THE\n // MANIFEST, before the device is requested: a model this adapter cannot hold fails loudly now,\n // instead of \"loading fine\" with invalid buffers and generating garbage (binding-limit violations\n // are deferred VALIDATION errors, which no out-of-memory scope ever catches).\n const DEFAULT_BINDING = 134217728 // maxStorageBufferBindingSize guaranteed minimum (128 MiB)\n const DEFAULT_BUFFER = 268435456 // maxBufferSize guaranteed minimum (256 MiB)\n let needBind = 0 // largest single storage buffer/binding the loader will create\n let weightBytes = 0 // total weight VRAM, for the OOM message\n const track = (bytes: number): void => {\n const b = (bytes + 3) & ~3 // gbuf pads to 4\n needBind = Math.max(needBind, b)\n weightBytes += b\n }\n for (const t of Object.values(T)) {\n if (t.kind === 'q2') {\n track(t.weight!.len * 2) // q2 codes expand 1 -> 2 bytes at load (wireQ2)\n track(t.scales!.len)\n } else if (t.kind === 'f32' && t.weight) track(t.weight.len)\n }\n const fusedLen = (names: string[], f: 'weight' | 'scales'): number => names.reduce((n, nm) => n + T[nm][f]!.len, 0)\n for (let li = 0; li < A.layers; li++) {\n const groups = [\n [`layers.${li}.attn.q_proj`, `layers.${li}.attn.k_proj`, `layers.${li}.attn.v_proj`],\n [`layers.${li}.mlp.gate_proj`, `layers.${li}.mlp.up_proj`],\n [`layers.${li}.attn.o_proj`],\n [`layers.${li}.mlp.down_proj`],\n ]\n for (const g of groups) {\n track(fusedLen(g, 'weight'))\n track(fusedLen(g, 'scales'))\n }\n }\n // embed zp: from the manifest ref, or synthesized for container tensors (2 blocks/byte)\n const embZpLen = T.embed_tokens.zp?.len ?? (T.embed_tokens.rows! * (T.embed_tokens.cols! / 128)) / 2\n for (const r of [T.embed_tokens.weight!, T.embed_tokens.scales!, manifest.luts.tgt4]) track(r.len)\n track(embZpLen)\n if (kv8 && A.head_dim % 32 !== 0)\n throw new Error(`bitgpu: kvCache 'q8' needs head_dim divisible by 32 (got ${A.head_dim}); use 'f16' or 'f32' for this model`)\n // Non-weight bindings that also count against the limit: a per-layer KV buffer at full\n // maxSeqLen capacity, the largest prefill-segment activation, and the widest logits scratch.\n const kvLayerBytes = maxSeqLen * A.kv_heads * A.head_dim * KVB\n needBind = Math.max(needBind, kvLayerBytes, PREFILL_SEG * Math.max(A.heads * A.head_dim, A.intermediate) * 4, 32 * A.vocab * 4)\n const requiredLimits: Record<string, number> = {}\n if (needBind > DEFAULT_BINDING) {\n if (needBind > adapter.limits.maxStorageBufferBindingSize)\n throw new GpuOutOfMemoryError(\n `this model needs a ${Math.ceil(needBind / 1048576)} MiB storage binding but the adapter's maxStorageBufferBindingSize is ${Math.floor(adapter.limits.maxStorageBufferBindingSize / 1048576)} MiB`,\n )\n requiredLimits.maxStorageBufferBindingSize = needBind\n }\n if (needBind > DEFAULT_BUFFER) {\n if (needBind > adapter.limits.maxBufferSize)\n throw new GpuOutOfMemoryError(\n `this model needs a ${Math.ceil(needBind / 1048576)} MiB buffer but the adapter's maxBufferSize is ${Math.floor(adapter.limits.maxBufferSize / 1048576)} MiB`,\n )\n requiredLimits.maxBufferSize = needBind\n }\n const device = await adapter.requestDevice({\n requiredFeatures: features,\n requiredLimits: Object.keys(requiredLimits).length ? requiredLimits : undefined,\n })\n holder.device = device // createEngine destroys it if anything below throws\n // awareness: shared mem <=8KB < 16KB min, WG <=256; binding sizes negotiated above\n\n // Surface device loss (driver reset, OS reclaim) instead of hanging: consumers get a promise +\n // an optional callback. dispose() also resolves it, with reason 'destroyed' (no callback then).\n const lost: Promise<DeviceLostInfo> = device.lost.then((info) => {\n const li = { reason: String(info.reason ?? 'unknown'), message: info.message }\n if (li.reason !== 'destroyed') opts.onDeviceLost?.(li)\n return li\n })\n device.addEventListener('uncapturederror', (ev) => {\n console.error(`[bitgpu] uncaptured WebGPU error: ${(ev as GPUUncapturedErrorEvent).error.message}`)\n })\n\n opts.onProgress?.({ phase: 'pipelines' })\n const pipelines: Record<string, GPUComputePipeline> = {}\n // async pipeline creation: compile in parallel, non-blocking -> faster, stall-free cold start (MDN-recommended)\n const mkPipe = async (name: string, constants?: Record<string, number>): Promise<void> => {\n const code = SHADERS[name]\n if (code === undefined) throw new Error(`shader not found: ${name}`)\n const module = device.createShaderModule({ code, label: name }) // label so errors name the shader\n const info = await module.getCompilationInfo()\n const err = info.messages.find((m) => m.type === 'error')\n if (err) throw new Error(`WGSL compile error in ${name} (L${err.lineNum}:${err.linePos}): ${err.message}`)\n pipelines[name] = await device.createComputePipelineAsync({ layout: 'auto', compute: { module, entryPoint: 'main', constants } })\n }\n const ROWS_MR = 4 // output rows per workgroup in the multi-row GEMV\n const specs: Array<[string, Record<string, number>?]> = [...WGSLS.map((n): [string] => [n]), ['matmul_split_tiled'], ['matmul_resid_tiled'], ['argmax'], ['embed_gather'], ['embed_gather_batch'], ['sampler_penalty'], ['argmax_masked'], ['logsumexp']]\n if (useSG) {\n for (const n of ['rmsnorm_sg', 'attention_sg', 'matmul_split_sg', 'matmul_q2_sg', 'rmsnorm_rope_sg']) specs.push([n, { SG: sgMax }])\n for (const n of ['matmul_split_sm', 'matmul_resid_sm', 'matmul_q2_sm']) specs.push([n, { SG: sgMax }]) // small-batch (M=2..9) verify-pass GEMVs\n for (const n of ['matmul_resid_mr_sg', 'matmul_swiglu_mr_sg']) specs.push([n, { SG: sgMax, ROWS: ROWS_MR }])\n } else {\n for (const n of ['matmul_split_wg', 'matmul_resid_wg', 'matmul_q2_wg', 'rmsnorm_wg']) specs.push([n, { WG: WG_NS }])\n specs.push(['attention_wg']) // fixed 64-thread workgroup (per-thread acc covers head_dim <= 128)\n }\n if (kv16) {\n // f16-KV variants (compiled only when the device has shader-f16; `enable f16;` fails otherwise)\n specs.push(['copy_kv16'])\n if (useSG) for (const n of ['attention_sg_kv16', 'rmsnorm_rope_sg_kv16']) specs.push([n, { SG: sgMax }])\n else specs.push(['attention_wg_kv16'])\n }\n if (kv8) {\n // q8-KV variants (pure core WGSL: pack4x8snorm; no adapter feature needed)\n specs.push(['copy_kv8'])\n if (useSG) for (const n of ['attention_sg_kv8', 'rmsnorm_rope_sg_kv8']) specs.push([n, { SG: sgMax }])\n else specs.push(['attention_wg_kv8'])\n }\n // Rolling-window (sinks) attention reads rotate K at read time, so it has its own kernel per\n // mode+path. The sg roll kernels keep the rotate partner in-lane only when SG <= head_dim/2;\n // outside that geometry the wg roll kernel takes over (attention only - everything else\n // keeps the sg path).\n const rollSG = useSG && sgMax <= A.head_dim / 2\n if (roll) {\n const rollAtt = kv16 ? 'attention_sg_kv16_roll' : kv8 ? 'attention_sg_kv8_roll' : 'attention_sg_roll'\n const rollAttWg = kv16 ? 'attention_wg_kv16_roll' : kv8 ? 'attention_wg_kv8_roll' : 'attention_wg_roll'\n if (rollSG) specs.push([rollAtt, { SG: sgMax }])\n else specs.push([rollAttWg])\n }\n // Cache-touching kernel names resolve once by KV storage mode. q8's writers need extra\n // bindings (the block-scale buffers), so its call sites branch instead of renaming.\n const ATT =\n roll ?\n kv16 ? (rollSG ? 'attention_sg_kv16_roll' : 'attention_wg_kv16_roll')\n : kv8 ? (rollSG ? 'attention_sg_kv8_roll' : 'attention_wg_kv8_roll')\n : rollSG ? 'attention_sg_roll' : 'attention_wg_roll'\n : kv16 ? (useSG ? 'attention_sg_kv16' : 'attention_wg_kv16')\n : kv8 ? (useSG ? 'attention_sg_kv8' : 'attention_wg_kv8')\n : useSG ? 'attention_sg' : 'attention_wg'\n const ROPE_K = kv16 ? 'rmsnorm_rope_sg_kv16' : 'rmsnorm_rope_sg' // fused-path K write into the cache (f32/f16; q8 branches)\n const COPY_KV = kv16 ? 'copy_kv16' : 'copy' // K/V append into the cache (f32/f16; q8 branches)\n await Promise.all(specs.map(([n, c]) => mkPipe(n, c))) // parallel compile of all pipelines\n\n const S_ = GPUBufferUsage.STORAGE,\n CD = GPUBufferUsage.COPY_DST,\n CS = GPUBufferUsage.COPY_SRC,\n U = GPUBufferUsage.UNIFORM\n // Per-call transient tracking: generate/prefill/forward set `transients = []` so every scratch\n // buffer they create (activations, per-dispatch uniforms, prompt embeddings) is destroyed as soon\n // as its submission completes, instead of lingering until GC. A long prefill otherwise holds\n // ~S x 4.3 MB of dead VRAM (2+ GB for a 512-token prompt) - real memory pressure on 8 GB devices.\n let transients: GPUBuffer[] | null = null\n const flushTransients = (): void => {\n if (!transients) return\n for (const b of transients) b.destroy()\n transients = []\n }\n const upload = (typed: ArrayBufferView, usage: number = S_ | CD): GPUBuffer => {\n const b = device.createBuffer({ size: typed.byteLength, usage })\n device.queue.writeBuffer(b, 0, typed as BufferSource)\n transients?.push(b)\n return b\n }\n // Decode resource pool: in the decode loop the dispatch sequence is identical every batch, so reuse\n // the scratch + uniform buffers across batches (createBuffer is the dominant per-token record cost).\n // Counters increment per call and reset per batch, so within a batch every dispatch still gets its\n // own buffer (no aliasing of in-flight work); reuse happens only across batches (after the sync).\n interface DispSlot {\n uni: GPUBuffer\n bg: GPUBindGroup | null\n last: Uint8Array | null\n }\n // NAMED pools: each distinct dispatch sequence gets its own slot array ('decode' = the fused\n // token loop, 'pld1' / 'pldm' = speculative single-token and verify steps). Selecting a pool\n // also resets the slot indices (the old per-batch poolReset).\n interface Pool { buf: GPUBuffer[]; disp: DispSlot[] }\n const pools: Record<string, Pool> = {}\n let pool: Pool | null = null\n let bufIdx = 0\n let dispIdx = 0\n // Verify-step rounding: buffer sizes are S x per-row elements, so rounding S up to a fixed row\n // count gives every draft length identical buffer sizes - and therefore stable buffer\n // identities, which the cached bind groups depend on. n / from * to is exact by construction.\n let poolRoundFrom = 0\n let poolRoundTo = 0\n const poolUse = (name: string | null, roundFrom = 0, roundTo = 0): void => {\n pool = name ? (pools[name] ??= { buf: [], disp: [] }) : null\n poolRoundFrom = roundFrom\n poolRoundTo = roundTo\n bufIdx = 0\n dispIdx = 0\n }\n // The cached bind groups reference this generate() call's buffers (tokBuf/lg/candIds/... are created\n // per call). A later call creates new buffers, so the cache MUST be rebuilt at each decode entry or it\n // would bind the previous call's (dead) buffers - or, across greedy<->sampled, a different pipeline's\n // auto-layout bind group (a validation error). Buffers are stable within a call, so one rebuild suffices.\n const poolInvalidate = (): void => {\n for (const p of Object.values(pools)) {\n for (const s of p.disp) {\n s.bg = null\n s.last = null\n }\n }\n }\n const actBuf = (n: number): GPUBuffer => {\n if (!pool) {\n const b = device.createBuffer({ size: n * 4, usage: S_ | CS | CD })\n transients?.push(b)\n return b\n }\n const alloc = poolRoundFrom > 0 ? (n / poolRoundFrom) * poolRoundTo : n\n let b = pool.buf[bufIdx]\n if (!b || b.size !== alloc * 4) {\n b = device.createBuffer({ size: alloc * 4, usage: S_ | CS | CD })\n pool.buf[bufIdx] = b\n }\n bufIdx++\n return b\n }\n const dummy = device.createBuffer({ size: 16, usage: S_ })\n\n // Cross-turn state. fullHistory is the entire conversation's token sequence (prompt turns + replies),\n // needed because the sampler's repetition_penalty / no_repeat_ngram see the FULL sequence (like\n // transformers.js, independent of the KV cache). Derived from it: the cache fill length is\n // fullHistory.length - 1 (the last token's K/V is never written during decode), and that last token\n // is re-fed when resuming so its K/V gets written. The persistent Kc/Vc (below) hold the cached K/V.\n let fullHistory: number[] = []\n // Sink-mode bookkeeping: filled cache SLOTS. Diverges from fullHistory.length-1 once the\n // window rolls (fullHistory keeps the whole conversation for penalties/PLD; the cache holds\n // sinks + recent). Maintained by the decode loops; meaningless while overflow is 'error'.\n let cacheLen = 0\n const resetCache = (): void => {\n fullHistory = []\n cacheLen = 0\n }\n\n if (manifest.luts.tgt2.src !== 'aux')\n throw new Error('bitgpu: luts.tgt2 must live in the aux file (the streaming loader needs it before the weights arrive)')\n const tgt2 = readU8(manifest.luts.tgt2) // load-time only (sign table + q2 expansion); not captured by any closure\n const signTable = new Uint8Array(256)\n for (let b = 0; b < 256; b++) {\n let bits = 0\n for (let j = 0; j < 8; j++) bits |= ((((tgt2[2 * b + (j >> 2)] >> (2 * (j & 3))) & 3) >> 1) & 1) << j\n signTable[b] = bits\n }\n\n // ---- streaming weight loader ----\n // Every data-file tensor is wired as a ROUTE: a byte range of the file feeding a GPU buffer\n // (optionally through a per-byte transform: the binary sign table, or the 1->2 q2 code\n // expansion) and/or a CPU array. The file then streams through the routes in ONE sequential\n // pass, so the ~290MB download never exists in memory at once. (The old path materialized the\n // whole file plus an expanded lm_head transient: a CPU peak that read as \"loads fine, then the\n // OS kills the tab at the first keyboard\" on phones.) aux-file refs are tiny and feed the same\n // sinks synchronously from the aux buffer at wiring time.\n interface Route { off: number; len: number; push: (b: Uint8Array) => void; finish: () => void }\n const routes: Route[] = []\n const gbuf = (len: number): GPUBuffer => device.createBuffer({ size: (len + 3) & ~3, usage: S_ | CD })\n const gpuSink = (buf: GPUBuffer, base: number): { push: (b: Uint8Array) => void; finish: () => void } => {\n let written = 0\n let carry = new Uint8Array(0) // writeBuffer needs 4-byte-aligned offsets/sizes; chunks split anywhere\n return {\n push(bytes: Uint8Array): void {\n let all = bytes\n if (carry.length) {\n all = new Uint8Array(carry.length + bytes.length)\n all.set(carry)\n all.set(bytes, carry.length)\n }\n const n = all.length & ~3\n if (n) device.queue.writeBuffer(buf, base + written, all, 0, n) // writeBuffer copies synchronously\n carry = all.subarray(n).slice()\n written += n\n },\n finish(): void {\n if (!carry.length) return\n const pad = new Uint8Array(4)\n pad.set(carry)\n device.queue.writeBuffer(buf, base + written, pad) // gbuf pads buffers to 4 bytes\n written += 4\n carry = new Uint8Array(0)\n },\n }\n }\n // Wire a ref to a sink: data-file refs register a stream route; aux refs feed the sink NOW.\n const wire = (ref: Ref, push: (b: Uint8Array) => void, finish: () => void): void => {\n if (ref.src === 'aux') {\n push(new Uint8Array(readRef(ref).buffer, ref.off, ref.len))\n finish()\n } else routes.push({ off: ref.off, len: ref.len, push, finish })\n }\n const wireRaw = (ref: Ref, buf: GPUBuffer, base = 0): void => {\n const s = gpuSink(buf, base)\n wire(ref, s.push, s.finish)\n }\n // Per-byte weight transforms, shared by the planar (ONNX) and q1_0-container (GGUF)\n // routes - the sign-byte stream is identical across the two containers.\n const xfSign =\n (push: (b: Uint8Array) => void) =>\n (b: Uint8Array): void => {\n const o = new Uint8Array(b.length)\n for (let i = 0; i < b.length; i++) o[i] = signTable[b[i]]\n push(o)\n }\n const xfQ2 =\n (push: (b: Uint8Array) => void) =>\n (b: Uint8Array): void => {\n const o = new Uint8Array(b.length * 2)\n for (let i = 0; i < b.length; i++) {\n o[2 * i] = tgt2[2 * b[i]]\n o[2 * i + 1] = tgt2[2 * b[i] + 1]\n }\n push(o)\n }\n const wireSign = (ref: Ref, buf: GPUBuffer, base = 0): void => {\n const s = gpuSink(buf, base)\n wire(ref, xfSign(s.push), s.finish)\n }\n const wireQ2 = (ref: Ref, buf: GPUBuffer): void => {\n const s = gpuSink(buf, 0)\n wire(ref, xfQ2(s.push), s.finish)\n }\n // f16 -> f32, exact (every f16 value is exactly representable in f32)\n const f16f32 = (h: number): number => {\n const s = h & 0x8000 ? -1 : 1\n const e = (h >> 10) & 31\n const m = h & 1023\n if (e === 0) return s * m * 2 ** -24\n if (e === 31) return m ? NaN : s * Infinity\n return s * (1024 + m) * 2 ** (e - 25)\n }\n // container 'q1_0' (GGUF): ONE region streams BOTH planar outputs. Each 18-byte block is\n // [f16 scale][16 sign bytes]; the scale converts to f32 into the scales sink, the sign\n // bytes feed the weight sink (through the same transform the planar path uses). Block\n // phase carries across pushed chunks, which split anywhere - including mid-scale.\n const wireQ10 = (region: Ref, signPush: (b: Uint8Array) => void, signFinish: () => void, scalePush: (b: Uint8Array) => void, scaleFinish: () => void): void => {\n let phase = 0 // byte position inside the current 18-byte block\n let scaleLo = 0 // pending low byte of a scale straddling a chunk boundary\n const push = (b: Uint8Array): void => {\n const signs = new Uint8Array(b.length)\n const scales = new Float32Array((b.length >> 4) + 2)\n let sn = 0\n let cn = 0\n for (let i = 0; i < b.length; i++) {\n if (phase === 0) {\n scaleLo = b[i]\n phase = 1\n } else if (phase === 1) {\n scales[cn++] = f16f32(scaleLo | (b[i] << 8))\n phase = 2\n } else {\n signs[sn++] = b[i]\n phase = phase === 17 ? 0 : phase + 1\n }\n }\n if (sn) signPush(signs.subarray(0, sn))\n if (cn) scalePush(new Uint8Array(scales.buffer, 0, cn * 4))\n }\n routes.push({ off: region.off, len: region.len, push, finish: () => { signFinish(); scaleFinish() } })\n }\n const wireCpu = (ref: Ref): Uint8Array => {\n const dst = new Uint8Array(ref.len)\n let w = 0\n wire(\n ref,\n (b) => {\n dst.set(b, w)\n w += b.length\n },\n () => undefined,\n )\n return dst\n }\n // WebGPU allocation errors are DEFERRED: without an error scope the ~300 MB of weight buffers\n // \"succeed\" as invalid buffers on VRAM-poor devices and every later generate returns garbage.\n // The validation scope backstops the limits negotiation above: any load-time validation error\n // (e.g. a buffer over a granted limit) fails createEngine loudly instead of console noise.\n device.pushErrorScope('validation')\n device.pushErrorScope('out-of-memory')\n const W: Record<string, GpuWeight> = {}\n // Deferred zero-point checks: q2 zp tensors stream with the weights, so their bytes are only\n // complete after the streaming pass; each closure then validates and installs the real value.\n const zpChecks: Array<() => void> = []\n for (const [name, t] of Object.entries(T)) {\n if (t.kind === 'q2') {\n const codes = gbuf(t.weight!.len * 2) // 1 byte of q2 data expands to 2 code bytes\n const scales = gbuf(t.scales!.len)\n if (t.q1_0) {\n const cs = gpuSink(codes, 0)\n const ss = gpuSink(scales, 0)\n wireQ10(t.q1_0, xfQ2(cs.push), cs.finish, ss.push, ss.finish)\n } else {\n wireQ2(t.weight!, codes)\n wireRaw(t.scales!, scales)\n }\n const w: GpuWeight = { N: t.N!, K: t.K!, nb: t.K! / 128, zp: 2, codes, scales }\n // The q2 kernels take ONE zero-point for the whole tensor (a uniform, not a per-block\n // buffer read in the hottest GEMV): the q1 recipe always emits the 2-bit midpoint. Read\n // the manifest's zp tensor and derive the scalar from it, failing loudly on a non-uniform\n // export instead of silently dequantizing with the wrong zero-points.\n if (t.zp) {\n const zpBytes = wireCpu(t.zp)\n zpChecks.push(() => {\n const b0 = zpBytes[0]\n for (let i = 1; i < zpBytes.length; i++)\n if (zpBytes[i] !== b0) throw new Error(`bitgpu: tensor ${name} has non-uniform 2-bit zero-points (the q2 kernels assume one zp for the whole tensor)`)\n const zp = b0 & 3\n if (b0 !== zp * 0b01010101) throw new Error(`bitgpu: tensor ${name} has non-uniform 2-bit zero-points within a byte (the q2 kernels assume one zp for the whole tensor)`)\n w.zp = zp\n })\n }\n W[name] = w\n } else if (t.kind === 'f32' && t.weight) {\n const buf = gbuf(t.weight.len)\n wireRaw(t.weight, buf)\n W[name] = { buf }\n }\n }\n // fuse per-layer matmul weights: qkv (3), gate/up (2); o_proj + down_proj stay individual\n // (residual-folded). Fusion needs no CPU concat: each part streams into its fused-buffer slice.\n const fuse = (parts: ManifestTensor[]): { sign: GPUBuffer; scales: GPUBuffer } => {\n const sign = gbuf(parts.reduce((n, p) => n + p.weight!.len, 0))\n const scales = gbuf(parts.reduce((n, p) => n + p.scales!.len, 0))\n let so = 0\n let co = 0\n for (const p of parts) {\n if (p.q1_0) {\n const ws = gpuSink(sign, so)\n const ss = gpuSink(scales, co)\n wireQ10(p.q1_0, xfSign(ws.push), ws.finish, ss.push, ss.finish)\n } else {\n wireSign(p.weight!, sign, so)\n wireRaw(p.scales!, scales, co)\n }\n so += p.weight!.len\n co += p.scales!.len\n }\n return { sign, scales }\n }\n for (let li = 0; li < A.layers; li++) {\n const q = T[`layers.${li}.attn.q_proj`],\n k = T[`layers.${li}.attn.k_proj`],\n v = T[`layers.${li}.attn.v_proj`]\n W[`layers.${li}.attn.qkv`] = { K: q.K!, nb: q.K! / 128, N0: q.N!, N1: k.N!, N2: v.N!, ...fuse([q, k, v]) }\n const g = T[`layers.${li}.mlp.gate_proj`],\n u = T[`layers.${li}.mlp.up_proj`]\n W[`layers.${li}.mlp.gateup`] = { K: g.K!, nb: g.K! / 128, N0: g.N!, N1: u.N!, N2: 0, ...fuse([g, u]) }\n for (const nm of [`layers.${li}.attn.o_proj`, `layers.${li}.mlp.down_proj`]) {\n const r = T[nm]\n W[nm] = { N: r.N!, K: r.K!, nb: r.K! / 128, ...fuse([r]) }\n }\n }\n\n // Embedding tables are GPU-ONLY: decode gathers one token (embed_gather.wgsl) and prefill\n // gathers a whole segment (embed_gather_batch.wgsl) straight from the packed tables, so no\n // CPU copy exists (~50-100 MB RAM saved per model; uint8 arrays are uploaded as bytes and\n // read as u32, byte-extracted). cos/sin caches are CPU-only.\n const wireGpu = (ref: Ref): GPUBuffer => {\n const buf = gbuf(ref.len)\n wireRaw(ref, buf)\n return buf\n }\n let embWqG: GPUBuffer\n let embScalesG: GPUBuffer\n let embZpG: GPUBuffer\n if (T.embed_tokens.q1_0) {\n embWqG = gbuf(T.embed_tokens.weight!.len)\n embScalesG = gbuf(T.embed_tokens.scales!.len)\n const ws = gpuSink(embWqG, 0)\n const ss = gpuSink(embScalesG, 0)\n wireQ10(T.embed_tokens.q1_0, ws.push, ws.finish, ss.push, ss.finish)\n // q4 zero-points: the 1-bit recipe's 4-bit codes sit at {7,9} around the midpoint 8. A\n // q1_0 container carries no zp tensor, so synthesize the constant table the gather\n // kernels read (two 4-bit 8s per byte, one nibble per 128-wide block).\n embZpG = gbuf(embZpLen)\n device.queue.writeBuffer(embZpG, 0, new Uint8Array((embZpLen + 3) & ~3).fill(0x88))\n } else {\n embWqG = wireGpu(T.embed_tokens.weight!)\n embScalesG = wireGpu(T.embed_tokens.scales!)\n embZpG = wireGpu(T.embed_tokens.zp!)\n }\n const tgt4G = wireGpu(manifest.luts.tgt4)\n let cosCache: Float32Array\n let sinCache: Float32Array\n if (T.cos_cache) {\n const cosBytes = wireCpu(T.cos_cache as Ref)\n const sinBytes = wireCpu(T.sin_cache as Ref)\n cosCache = new Float32Array(cosBytes.buffer)\n sinCache = new Float32Array(sinBytes.buffer)\n // The caches are baked per export ([positions, head_dim/2]); positions beyond them would read\n // undefined -> NaN into every rope buffer, silent garbage. Cap maxSeqLen at load, loudly.\n const ropePositions = cosCache.length / (A.head_dim / 2)\n if (maxSeqLen > ropePositions)\n throw new Error(`bitgpu: maxSeqLen ${maxSeqLen} exceeds the model's baked RoPE cache (${ropePositions} positions); lower maxSeqLen or re-export with a longer cache`)\n } else {\n // v2/GGUF manifests bake no rope tables: synthesize f32 cos/sin for exactly maxSeqLen\n // positions from arch.rope (plain or YaRN) - the same recipe tools/reference.py runs\n // when it generates fixtures, so the reference forward uses the tables the engine uses.\n const cap = A.max_positions ?? 40960\n if (maxSeqLen > cap)\n throw new Error(`bitgpu: maxSeqLen ${maxSeqLen} exceeds the model's max_positions (${cap})`)\n ;[cosCache, sinCache] = synthRope(A, maxSeqLen)\n }\n\n // ONE sequential pass of the data file through the routes. Tied tensors (e.g. lm_head sharing\n // the embedding bytes) produce EXACT-duplicate ranges: those fan out to every consumer; partial\n // overlaps have no defined streaming order and stay fatal.\n routes.sort((a, b) => a.off - b.off || a.len - b.len)\n const merged: Route[] = []\n for (const r of routes) {\n const last = merged[merged.length - 1]\n if (last && last.off === r.off && last.len === r.len) {\n const lp = last.push,\n lf = last.finish\n last.push = (b): void => {\n lp(b)\n r.push(b)\n }\n last.finish = (): void => {\n lf()\n r.finish()\n }\n } else if (last && r.off < last.off + last.len) {\n throw new Error('bitgpu: partially overlapping data-file tensor ranges (unsupported by the streaming loader)')\n } else merged.push(r)\n }\n const needed = merged.length ? merged[merged.length - 1].off + merged[merged.length - 1].len : 0\n const dataStream = opts.fetchStream\n ? await opts.fetchStream(dataUrl)\n : opts.fetchArrayBuffer\n ? (new Response(await opts.fetchArrayBuffer(dataUrl)).body as ReadableStream<Uint8Array>)\n : await (async () => {\n const res = await fetch(dataUrl)\n if (!res.ok) throw new Error(`bitgpu: fetch ${dataUrl} failed: HTTP ${res.status}`)\n return res.body ?? (new Response(await res.arrayBuffer()).body as ReadableStream<Uint8Array>)\n })()\n const reader = dataStream.getReader()\n let cursor = 0\n let ri = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n let bo = 0\n while (bo < value.byteLength && ri < merged.length) {\n const r = merged[ri]\n if (cursor >= r.off + r.len) {\n ri++\n continue\n }\n if (cursor < r.off) {\n const skip = Math.min(r.off - cursor, value.byteLength - bo)\n cursor += skip\n bo += skip\n continue\n }\n const n = Math.min(r.off + r.len - cursor, value.byteLength - bo)\n r.push(value.subarray(bo, bo + n))\n cursor += n\n bo += n\n if (cursor === r.off + r.len) {\n r.finish()\n ri++\n }\n }\n cursor += value.byteLength - bo\n opts.onProgress?.({ phase: 'weights', loaded: Math.min(cursor, needed), total: needed })\n }\n if (cursor < needed)\n throw new Error(`bitgpu: the data file ended at ${cursor} bytes but tensors extend to ${needed}; the download is truncated or the manifest does not match it`)\n for (const check of zpChecks) check()\n zpChecks.length = 0\n aux = null as unknown as ArrayBuffer\n\n // GPU embedding gather for a batch of prompt tokens: upload S u32 ids (bytes, not S*H floats)\n // and dequantize the rows on the GPU (embed_gather_batch.wgsl - same math as the decode\n // gather). The returned activation holds [S, H] and belongs to the caller's transient scope.\n function embedBatch(enc: GPUCommandEncoder, ids: number[]): GPUBuffer {\n const idBuf = upload(new Uint32Array(ids))\n const out = actBuf(ids.length * Hd)\n const pass = enc.beginComputePass()\n run(pass, 'embed_gather_batch', [['u', ids.length], ['u', Hd], ['u', 0], ['u', 0]], [idBuf, embWqG, tgt4G, embScalesG, embZpG], out, ids.length * Hd)\n pass.end()\n return out\n }\n function ropeBufs(posBase: number, S: number): { cos: GPUBuffer; sin: GPUBuffer } {\n const D = A.head_dim,\n R = D / 2, // rotary halves: caches store [seq, D/2]; the full vector is concat(half, half)\n cos = new Float32Array(S * D),\n sin = new Float32Array(S * D)\n for (let s = 0; s < S; s++)\n for (let d = 0; d < D; d++) {\n cos[s * D + d] = cosCache[(posBase + s) * R + (d % R)]\n sin[s * D + d] = sinCache[(posBase + s) * R + (d % R)]\n }\n const cb = actBuf(S * D),\n sb = actBuf(S * D)\n device.queue.writeBuffer(cb, 0, cos)\n device.queue.writeBuffer(sb, 0, sin)\n return { cos: cb, sin: sb }\n }\n\n const KV = A.kv_heads,\n Dh = A.head_dim,\n Hd = A.hidden,\n H = A.heads,\n F = A.intermediate\n // The KV cache GROWS on demand (doubling, up to maxSeqLen) instead of pinning the full maxSeqLen\n // up front: a short conversation keeps a small cache (~KV_INITIAL positions), so idle VRAM stays\n // low on memory-constrained devices (a full 2048-position f32 cache is ~448 MB at 28 layers,\n // ~576 MB at 36; the 512 floor is a quarter of that).\n // ensureKvCapacity() reallocates + copies the existing K/V when a turn needs more room.\n const KV_INITIAL = 512\n let kvCapacity = Math.min(maxSeqLen, KV_INITIAL)\n const Kc: GPUBuffer[] = [],\n Vc: GPUBuffer[] = []\n // q8 block scales: one f32 per 32 cached elements, per layer, alongside Kc/Vc (empty otherwise)\n const Ksc: GPUBuffer[] = [],\n Vsc: GPUBuffer[] = []\n const kvScaleBytes = (cap: number): number => cap * KV * (Dh / 32) * 4\n for (let li = 0; li < A.layers; li++) {\n Kc.push(device.createBuffer({ size: kvCapacity * KV * Dh * KVB, usage: S_ | CS | CD }))\n Vc.push(device.createBuffer({ size: kvCapacity * KV * Dh * KVB, usage: S_ | CS | CD }))\n if (kv8) {\n Ksc.push(device.createBuffer({ size: kvScaleBytes(kvCapacity), usage: S_ | CS | CD }))\n Vsc.push(device.createBuffer({ size: kvScaleBytes(kvCapacity), usage: S_ | CS | CD }))\n }\n }\n // Sink-mode statics: the aux rope tables ([window, Dh/2]) for the read-time K rotation, and\n // cos=1/sin=0 stand-ins so the K WRITE kernels store the un-roped rmsnorm output unchanged\n // (nd*1 + rot*0 == nd; no separate no-rope kernel variants needed).\n let rollCosT: GPUBuffer | null = null,\n rollSinT: GPUBuffer | null = null,\n rollOnes: GPUBuffer | null = null,\n rollZeros: GPUBuffer | null = null\n if (roll) {\n const R2 = Dh / 2\n rollCosT = device.createBuffer({ size: maxSeqLen * R2 * 4, usage: S_ | CD })\n rollSinT = device.createBuffer({ size: maxSeqLen * R2 * 4, usage: S_ | CD })\n device.queue.writeBuffer(rollCosT, 0, cosCache.buffer, cosCache.byteOffset, maxSeqLen * R2 * 4)\n device.queue.writeBuffer(rollSinT, 0, sinCache.buffer, sinCache.byteOffset, maxSeqLen * R2 * 4)\n rollOnes = device.createBuffer({ size: Dh * 4, usage: S_ | CD })\n rollZeros = device.createBuffer({ size: Dh * 4, usage: S_ | CD })\n device.queue.writeBuffer(rollOnes, 0, new Float32Array(Dh).fill(1))\n device.queue.writeBuffer(rollZeros, 0, new Float32Array(Dh))\n }\n const loadOom = await device.popErrorScope()\n const loadVal = await device.popErrorScope()\n if (loadOom) throw new GpuOutOfMemoryError(`GPU allocation failed while loading weights (~${Math.round(weightBytes / 1048576)} MB VRAM needed): ${loadOom.message}`)\n if (loadVal) throw new Error(`bitgpu: WebGPU validation error while loading weights: ${loadVal.message}`)\n // Grow every layer's K/V buffer to hold at least `needed` positions, preserving the cached content\n // (so a cross-turn reuse mid-conversation survives a growth). Rare (only when crossing a capacity\n // threshold); the copy is GPU-side and bounded geometrically. Invalidates cached decode bind groups\n // since they referenced the old buffers.\n async function ensureKvCapacity(needed: number): Promise<void> {\n if (needed <= kvCapacity) return\n const newCap = Math.min(maxSeqLen, Math.max(needed, kvCapacity * 2))\n const copyBytes = kvCapacity * KV * Dh * KVB // preserve all currently-allocated K/V\n const copyScales = kvScaleBytes(kvCapacity)\n device.pushErrorScope('out-of-memory')\n const enc = device.createCommandEncoder()\n // Every cache buffer this layer set held before the growth, in [K, V, (Ksc, Vsc)] groups.\n const per = kv8 ? 4 : 2\n const olds: GPUBuffer[] = []\n for (let li = 0; li < A.layers; li++) {\n const nk = device.createBuffer({ size: newCap * KV * Dh * KVB, usage: S_ | CS | CD })\n const nv = device.createBuffer({ size: newCap * KV * Dh * KVB, usage: S_ | CS | CD })\n enc.copyBufferToBuffer(Kc[li], 0, nk, 0, copyBytes)\n enc.copyBufferToBuffer(Vc[li], 0, nv, 0, copyBytes)\n olds.push(Kc[li], Vc[li])\n Kc[li] = nk\n Vc[li] = nv\n if (kv8) {\n const nks = device.createBuffer({ size: kvScaleBytes(newCap), usage: S_ | CS | CD })\n const nvs = device.createBuffer({ size: kvScaleBytes(newCap), usage: S_ | CS | CD })\n enc.copyBufferToBuffer(Ksc[li], 0, nks, 0, copyScales)\n enc.copyBufferToBuffer(Vsc[li], 0, nvs, 0, copyScales)\n olds.push(Ksc[li], Vsc[li])\n Ksc[li] = nks\n Vsc[li] = nvs\n }\n }\n device.queue.submit([enc.finish()])\n await device.queue.onSubmittedWorkDone()\n const oom = await device.popErrorScope()\n if (oom) {\n // Roll back to the old (still valid) buffers so the engine stays usable at its current size.\n for (let li = 0; li < A.layers; li++) {\n Kc[li].destroy()\n Vc[li].destroy()\n Kc[li] = olds[per * li]\n Vc[li] = olds[per * li + 1]\n if (kv8) {\n Ksc[li].destroy()\n Vsc[li].destroy()\n Ksc[li] = olds[per * li + 2]\n Vsc[li] = olds[per * li + 3]\n }\n }\n poolInvalidate()\n throw new GpuOutOfMemoryError(`KV cache growth to ${newCap} positions failed: ${oom.message}`)\n }\n for (const b of olds) b.destroy()\n kvCapacity = newCap\n poolInvalidate()\n }\n\n // ---- sink-mode eviction (overflow: 'sinks') ----\n // Batched StreamingLLM compaction: keep the SINKS anchor positions plus the most recent\n // block, drop the middle. Cache bytes only MOVE (same-buffer copies are forbidden in WebGPU,\n // so each region bounces through one lazily-kept scratch buffer); nothing is re-roped or\n // requantized - the roll attention kernels rotate K by cache slot at read, so a moved row\n // simply reads as \"closer\". Queue order makes the copies land before any later dispatch, so\n // no CPU sync is needed. Called only from inside a turn (the op is already serialized).\n let evictScratch: GPUBuffer | null = null\n function evict(fill: number, need: number): number {\n // free at least `need` slots plus a quarter-of-recent batch, so events stay rare\n const recent = fill - SINKS\n const batch = Math.min(recent, Math.max(need, Math.ceil((maxSeqLen - SINKS) / 4)))\n const keep = recent - batch\n if (keep <= 0) return SINKS // nothing recent survives (giant need): sinks only\n const rowK = KV * Dh * KVB\n const rowS = kv8 ? KV * (Dh / 32) * 4 : 0\n if (!evictScratch || evictScratch.size < keep * rowK) {\n evictScratch?.destroy()\n evictScratch = device.createBuffer({ size: keep * rowK, usage: CS | CD })\n }\n const enc = device.createCommandEncoder()\n const groups: Array<[GPUBuffer, number]> = []\n for (let li = 0; li < A.layers; li++) {\n groups.push([Kc[li], rowK], [Vc[li], rowK])\n if (kv8) groups.push([Ksc[li], rowS], [Vsc[li], rowS])\n }\n for (const [buf, row] of groups) {\n enc.copyBufferToBuffer(buf, (SINKS + batch) * row, evictScratch, 0, keep * row)\n enc.copyBufferToBuffer(evictScratch, 0, buf, SINKS * row, keep * row)\n }\n device.queue.submit([enc.finish()])\n return SINKS + keep\n }\n // Make room for `n` more rows before recording a batch; returns the (possibly reduced) fill.\n const evictFor = (fill: number, n: number): number => (roll && fill + n > maxSeqLen ? evict(fill, fill + n - maxSeqLen) : fill)\n\n async function readback(buf: GPUBuffer, n: number): Promise<Float32Array> {\n const rb = device.createBuffer({ size: n * 4, usage: GPUBufferUsage.MAP_READ | CD })\n const enc = device.createCommandEncoder()\n enc.copyBufferToBuffer(buf, 0, rb, 0, n * 4)\n device.queue.submit([enc.finish()])\n await rb.mapAsync(GPUMapMode.READ)\n const out = new Float32Array(rb.getMappedRange().slice(0))\n rb.unmap()\n rb.destroy()\n return out\n }\n async function readbackU32(buf: GPUBuffer, n: number): Promise<Uint32Array> {\n const rb = device.createBuffer({ size: n * 4, usage: GPUBufferUsage.MAP_READ | CD })\n const enc = device.createCommandEncoder()\n enc.copyBufferToBuffer(buf, 0, rb, 0, n * 4)\n device.queue.submit([enc.finish()])\n await rb.mapAsync(GPUMapMode.READ)\n const out = new Uint32Array(rb.getMappedRange().slice(0))\n rb.unmap()\n rb.destroy()\n return out\n }\n\n // diagnostic: FULL = null -> every kernel at real size; FULL = Set(names) -> only those at real size,\n // all others dispatched as 1 workgroup. Lets us measure each kernel type's true in-context cost.\n let FULL: Set<string> | null = null\n // embed_gather_batch is exempt from profiling skeletons: it produces the PREFILL INPUT (the\n // CPU used to), and skeleton-skipping it feeds NaN/garbage activations into every profiled\n // kernel - numerically meaningless and, on GPUs with slow non-finite handling, much slower.\n const isFull = (name: string): boolean => FULL === null || FULL.has(name) || name === 'embed_gather_batch'\n // differential debug: FORCE_SLOW routes S=1 through the prefill (known-good) path; DBG0 collects\n // layer-0 checkpoint buffers so a fused step and a slow step can be compared kernel by kernel.\n let FORCE_SLOW = false\n // Small-batch routing: when set to S (2..9, subgroup path only), the matmuls of an S-row pass\n // use the _sm kernels, which read each weight word once for all S rows - the lever that makes\n // the speculative-decode verify pass profitable. 0 = off (scalar/tiled prefill kernels).\n // Set ONLY around the PLD verify-step encode; every shipped non-PLD path keeps its kernels.\n let SMALLM = 0\n let DBG0: Record<string, GPUBuffer> | null = null\n const cap = (li: number, name: string, buf: GPUBuffer): void => {\n if (li === 0 && DBG0) DBG0[name] = buf\n }\n // set pipeline + bind group for a dispatch. When pooling (decode loop), the uniform buffer AND the\n // bind group are cached per dispatch slot, so only writeBuffer of the changed params runs per token.\n function setup(pass: GPUComputePassEncoder, name: string, fields: Field[], ins: GPUBuffer[], outs: GPUBuffer[]): void {\n pass.setPipeline(pipelines[name])\n if (pool) {\n let slot = pool.disp[dispIdx]\n if (!slot) {\n slot = { uni: device.createBuffer({ size: 64, usage: U | CD }), bg: null, last: null }\n pool.disp[dispIdx] = slot\n }\n const data2 = makeParams(fields) // reused view; only writeBuffer when the params changed\n if (!slot.last || !eqBytes(slot.last, data2)) {\n device.queue.writeBuffer(slot.uni, 0, data2 as BufferSource)\n slot.last = data2.slice()\n }\n if (!slot.bg) {\n const entries: GPUBindGroupEntry[] = [{ binding: 0, resource: { buffer: slot.uni } }]\n ins.forEach((b, i) => entries.push({ binding: i + 1, resource: { buffer: b } }))\n outs.forEach((b, i) => entries.push({ binding: 1 + ins.length + i, resource: { buffer: b } }))\n slot.bg = device.createBindGroup({ layout: pipelines[name].getBindGroupLayout(0), entries })\n }\n pass.setBindGroup(0, slot.bg)\n dispIdx++\n } else {\n const entries: GPUBindGroupEntry[] = [{ binding: 0, resource: { buffer: upload(makeParams(fields), U | CD) } }]\n ins.forEach((b, i) => entries.push({ binding: i + 1, resource: { buffer: b } }))\n outs.forEach((b, i) => entries.push({ binding: 1 + ins.length + i, resource: { buffer: b } }))\n pass.setBindGroup(0, device.createBindGroup({ layout: pipelines[name].getBindGroupLayout(0), entries }))\n }\n }\n // Split a 1D workgroup count into a 2D grid so no dimension exceeds WebGPU's 65535 cap (a long\n // prefill can need >65535 workgroups, e.g. the swiglu kernel does ceil(S*6144/64) = S*96). The flat\n // kernels reconstruct the linear index as (wid.y*num_workgroups.x + wid.x)*64 + lid.x, which equals\n // global_invocation_id.x when the grid is 1D (y=1) - so it stays correct for the common small case.\n const grid2d = (wg: number): [number, number] => {\n const y = Math.ceil(wg / 65535)\n return [Math.ceil(wg / y), y]\n }\n function runIO(pass: GPUComputePassEncoder, name: string, fields: Field[], ins: GPUBuffer[], outs: GPUBuffer[], threads: number): void {\n setup(pass, name, fields, ins, outs)\n if (!isFull(name)) return void pass.dispatchWorkgroups(1)\n const [x, y] = grid2d(Math.ceil(threads / 64))\n pass.dispatchWorkgroups(x, y, 1)\n }\n const run = (pass: GPUComputePassEncoder, name: string, fields: Field[], ins: GPUBuffer[], out: GPUBuffer, threads: number): void =>\n runIO(pass, name, fields, ins, [out], threads)\n // dispatch exactly nWG workgroups (subgroup kernels: one workgroup per row / per (query,head))\n function runN(pass: GPUComputePassEncoder, name: string, fields: Field[], ins: GPUBuffer[], out: GPUBuffer, nWG: number): void {\n setup(pass, name, fields, ins, [out])\n pass.dispatchWorkgroups(isFull(name) ? nWG : 1)\n }\n // 2D workgroup dispatch (subgroup GEMV: one workgroup per output column)\n function runWG(pass: GPUComputePassEncoder, name: string, fields: Field[], ins: GPUBuffer[], outs: GPUBuffer[], wgX: number, wgY: number): void {\n setup(pass, name, fields, ins, outs)\n const f = isFull(name)\n pass.dispatchWorkgroups(f ? wgX : 1, f ? wgY : 1, 1)\n }\n const rms = (pass: GPUComputePassEncoder, x: GPUBuffer, g: string, R: number, Dn: number, out: GPUBuffer): void =>\n useSG\n ? runN(pass, 'rmsnorm_sg', [['u', R], ['u', Dn], ['f', A.rms_eps], ['u', 0]], [x, W[g].buf!], out, R)\n : runN(pass, 'rmsnorm_wg', [['u', R], ['u', Dn], ['f', A.rms_eps], ['u', 0]], [x, W[g].buf!], out, R)\n // fused q/k/v or gate/up matmul\n function fusedMM(pass: GPUComputePassEncoder, w: GpuWeight, inBuf: GPUBuffer, S: number, outs: GPUBuffer[]): void {\n const Ntot = w.N0! + w.N1! + w.N2!\n if (useSG && S === 1) {\n const gx = Math.min(Ntot, 65535)\n runWG(pass, 'matmul_split_sg', [['u', w.K!], ['u', w.nb!], ['u', w.N0!], ['u', w.N1!], ['u', w.N2!], ['u', gx]], [inBuf, w.sign!, w.scales!], outs, gx, Math.ceil(Ntot / gx))\n } else if (S === 1) {\n const gx = Math.min(Ntot, 65535) // no-subgroup decode: workgroup-reduction GEMV\n runWG(pass, 'matmul_split_wg', [['u', w.K!], ['u', w.nb!], ['u', w.N0!], ['u', w.N1!], ['u', w.N2!], ['u', gx]], [inBuf, w.sign!, w.scales!], outs, gx, Math.ceil(Ntot / gx))\n } else if (useSG && S === SMALLM) {\n const gx = Math.min(Ntot, 65535) // small-batch GEMV: weights read once for all S rows\n runWG(pass, 'matmul_split_sm', [['u', w.K!], ['u', w.nb!], ['u', w.N0!], ['u', w.N1!], ['u', w.N2!], ['u', gx], ['u', S]], [inBuf, w.sign!, w.scales!], outs, gx, Math.ceil(Ntot / gx))\n } else if (tiledPrefill(S)) {\n runWG(pass, 'matmul_split_tiled', [['u', S], ['u', w.K!], ['u', w.nb!], ['u', w.N0!], ['u', w.N1!], ['u', w.N2!]], [inBuf, w.sign!, w.scales!], outs, Math.ceil(Ntot / 64), Math.ceil(S / 64)) // long-prompt prefill: tiled GEMM\n } else {\n runIO(pass, 'matmul_split', [['u', S], ['u', w.K!], ['u', w.nb!], ['u', w.N0!], ['u', w.N1!], ['u', w.N2!]], [inBuf, w.sign!, w.scales!], outs, S * Ntot)\n }\n }\n // o_proj / down_proj matmul with fused residual add\n function residMM(pass: GPUComputePassEncoder, w: GpuWeight, inBuf: GPUBuffer, resid: GPUBuffer, S: number, out: GPUBuffer): void {\n if (useSG && S === 1) {\n const nwg = Math.ceil(w.N! / ROWS_MR) // multi-row GEMV: ROWS_MR output cols per workgroup\n const gx = Math.min(nwg, 65535)\n runWG(pass, 'matmul_resid_mr_sg', [['u', w.N!], ['u', w.K!], ['u', w.nb!], ['u', gx], ['u', 0], ['u', 0]], [inBuf, w.sign!, w.scales!, resid], [out], gx, Math.ceil(nwg / gx))\n } else if (S === 1) {\n const gx = Math.min(w.N!, 65535) // no-subgroup decode: workgroup-reduction GEMV + residual\n runWG(pass, 'matmul_resid_wg', [['u', w.N!], ['u', w.K!], ['u', w.nb!], ['u', gx], ['u', 0], ['u', 0]], [inBuf, w.sign!, w.scales!, resid], [out], gx, Math.ceil(w.N! / gx))\n } else if (useSG && S === SMALLM) {\n const gx = Math.min(w.N!, 65535) // small-batch GEMV + residual\n runWG(pass, 'matmul_resid_sm', [['u', w.N!], ['u', w.K!], ['u', w.nb!], ['u', gx], ['u', S], ['u', 0]], [inBuf, w.sign!, w.scales!, resid], [out], gx, Math.ceil(w.N! / gx))\n } else if (tiledPrefill(S)) {\n runWG(pass, 'matmul_resid_tiled', [['u', S], ['u', w.N!], ['u', w.K!], ['u', w.nb!], ['u', 0], ['u', 0]], [inBuf, w.sign!, w.scales!, resid], [out], Math.ceil(w.N! / 64), Math.ceil(S / 64)) // long-prompt prefill: tiled GEMM\n } else {\n runIO(pass, 'matmul_resid', [['u', S], ['u', w.N!], ['u', w.K!], ['u', w.nb!], ['u', 128], ['u', 0]], [inBuf, w.sign!, w.scales!, resid], [out], S * w.N!)\n }\n }\n\n // Append `rows` rows of Dh f32 values into layer li's K (which=0) or V (which=1) cache at row\n // dstRow0, quantizing under q8 (copy_kv8 is a per-row workgroup kernel with two outputs, so it\n // cannot ride the flat COPY_KV dispatch).\n function appendKV(pass: GPUComputePassEncoder, src: GPUBuffer, which: 0 | 1, li: number, rows: number, dstRow0: number): void {\n const data = which === 0 ? Kc[li] : Vc[li]\n if (kv8) {\n setup(pass, 'copy_kv8', [['u', rows], ['u', Dh], ['u', dstRow0], ['u', 0]], [src], [data, which === 0 ? Ksc[li] : Vsc[li]])\n pass.dispatchWorkgroups(isFull('copy_kv8') ? rows : 1)\n } else {\n run(pass, COPY_KV, [['u', rows * Dh], ['u', dstRow0 * Dh], ['u', 0], ['u', 0]], [src], data, rows * Dh)\n }\n }\n // The attention kernel's cache bindings by KV mode (q8 adds the block-scale buffers).\n const attIns = (qr: GPUBuffer, li: number): GPUBuffer[] => {\n const ins = kv8 ? [qr, Kc[li], Vc[li], Ksc[li], Vsc[li]] : [qr, Kc[li], Vc[li]]\n if (roll) ins.push(rollCosT!, rollSinT!) // read-time K rotation tables\n return ins\n }\n\n function layer(pass: GPUComputePassEncoder, li: number, h: GPUBuffer, S: number, posBase: number, cos: GPUBuffer, sin: GPUBuffer): GPUBuffer {\n const Ltot = posBase + S\n const n1 = actBuf(S * Hd)\n rms(pass, h, `layers.${li}.input_layernorm`, S, Hd, n1)\n const qkv = W[`layers.${li}.attn.qkv`]\n\n if (useSG && S === 1 && !FORCE_SLOW) {\n // fused decode path: fold copies and elementwise ops into the matmul/norm kernels.\n const q = actBuf(H * Dh),\n k = actBuf(KV * Dh),\n v = actBuf(KV * Dh)\n const Ntot = qkv.N0! + qkv.N1! + qkv.N2!,\n gx = Math.min(Ntot, 65535)\n runWG(pass, 'matmul_split_sg', [['u', qkv.K!], ['u', qkv.nb!], ['u', qkv.N0!], ['u', qkv.N1!], ['u', qkv.N2!], ['u', gx]], [n1, qkv.sign!, qkv.scales!], [q, k, v], gx, Math.ceil(Ntot / gx))\n appendKV(pass, v, 1, li, KV, posBase * KV)\n const qr = actBuf(H * Dh)\n runN(pass, 'rmsnorm_rope_sg', [['u', H], ['u', Dh], ['f', A.rms_eps], ['u', 0], ['u', Dh], ['u', 0]], [q, W[`layers.${li}.attn.q_norm`].buf!, cos, sin], qr, H)\n // Sink mode stores K UNROPED (rotation happens at attention read): bind cos=1/sin=0 so\n // the same write kernels store the plain rmsnorm output.\n const kcos = roll ? rollOnes! : cos,\n ksin = roll ? rollZeros! : sin\n if (kv8) {\n // fused K write, quantizing into the cache (extra scale binding -> its own dispatch)\n setup(pass, 'rmsnorm_rope_sg_kv8', [['u', KV], ['u', Dh], ['f', A.rms_eps], ['u', posBase * KV], ['u', 0], ['u', 0]], [k, W[`layers.${li}.attn.k_norm`].buf!, kcos, ksin], [Kc[li], Ksc[li]])\n pass.dispatchWorkgroups(isFull('rmsnorm_rope_sg_kv8') ? KV : 1)\n } else {\n runN(pass, ROPE_K, [['u', KV], ['u', Dh], ['f', A.rms_eps], ['u', posBase * KV * Dh], ['u', Dh], ['u', 0]], [k, W[`layers.${li}.attn.k_norm`].buf!, kcos, ksin], Kc[li], KV)\n }\n cap(li, 'qr', qr)\n const att = actBuf(H * Dh)\n runN(pass, ATT, [['u', 1], ['u', H], ['u', KV], ['u', Dh], ['u', posBase], ['u', Ltot]], attIns(qr, li), att, H)\n cap(li, 'att', att)\n const o = W[`layers.${li}.attn.o_proj`],\n h2 = actBuf(Hd)\n residMM(pass, o, att, h, 1, h2)\n const n2 = actBuf(Hd)\n rms(pass, h2, `layers.${li}.post_attention_layernorm`, 1, Hd, n2)\n const gu = W[`layers.${li}.mlp.gateup`],\n sw = actBuf(F),\n nwgF = Math.ceil(F / ROWS_MR),\n gxF = Math.min(nwgF, 65535)\n runWG(pass, 'matmul_swiglu_mr_sg', [['u', gu.K!], ['u', gu.nb!], ['u', F], ['u', gxF], ['u', 0], ['u', 0]], [n2, gu.sign!, gu.scales!], [sw], gxF, Math.ceil(nwgF / gxF))\n cap(li, 'sw', sw)\n const d = W[`layers.${li}.mlp.down_proj`],\n hn = actBuf(Hd)\n residMM(pass, d, sw, h2, 1, hn)\n return hn\n }\n\n // prefill / no-subgroup path: separate kernels (kept verbatim; validates correctness end to end)\n const q = actBuf(S * H * Dh),\n k = actBuf(S * KV * Dh),\n v = actBuf(S * KV * Dh)\n fusedMM(pass, qkv, n1, S, [q, k, v])\n const qn = actBuf(S * H * Dh),\n kn = actBuf(S * KV * Dh)\n rms(pass, q, `layers.${li}.attn.q_norm`, S * H, Dh, qn)\n rms(pass, k, `layers.${li}.attn.k_norm`, S * KV, Dh, kn)\n const qr = actBuf(S * H * Dh),\n kr = actBuf(S * KV * Dh)\n run(pass, 'rope', [['u', S], ['u', H], ['u', Dh], ['u', 0]], [qn, cos, sin], qr, S * H * Dh)\n if (!roll) run(pass, 'rope', [['u', S], ['u', KV], ['u', Dh], ['u', 0]], [kn, cos, sin], kr, S * KV * Dh)\n appendKV(pass, roll ? kn : kr, 0, li, S * KV, posBase * KV) // sink mode caches K unroped\n appendKV(pass, v, 1, li, S * KV, posBase * KV)\n cap(li, 'qr', qr)\n const att = actBuf(S * H * Dh)\n const attF: Field[] = [['u', S], ['u', H], ['u', KV], ['u', Dh], ['u', posBase], ['u', Ltot]]\n runN(pass, ATT, attF, attIns(qr, li), att, S * H)\n cap(li, 'att', att)\n const o = W[`layers.${li}.attn.o_proj`],\n h2 = actBuf(S * Hd)\n residMM(pass, o, att, h, S, h2)\n const n2 = actBuf(S * Hd)\n rms(pass, h2, `layers.${li}.post_attention_layernorm`, S, Hd, n2)\n const gu = W[`layers.${li}.mlp.gateup`],\n g = actBuf(S * F),\n u = actBuf(S * F)\n fusedMM(pass, gu, n2, S, [g, u, dummy])\n const sw = actBuf(S * F)\n run(pass, 'swiglu', [['u', S * F], ['u', 0], ['u', 0], ['u', 0]], [g, u], sw, S * F)\n cap(li, 'sw', sw)\n const d = W[`layers.${li}.mlp.down_proj`],\n hn = actBuf(S * Hd)\n residMM(pass, d, sw, h2, S, hn)\n return hn\n }\n function lmHead(pass: GPUComputePassEncoder, fn: GPUBuffer, M: number, out: GPUBuffer): void {\n const lm = W.lm_head\n if (useSG && M === 1) {\n const gx = Math.min(lm.N!, 65535)\n runWG(pass, 'matmul_q2_sg', [['u', lm.N!], ['u', lm.K!], ['u', lm.nb!], ['u', lm.zp!], ['u', gx], ['u', 0]], [fn, lm.codes!, lm.scales!], [out], gx, Math.ceil(lm.N! / gx))\n } else if (M === 1) {\n const gx = Math.min(lm.N!, 65535) // no-subgroup decode: workgroup-reduction 2-bit GEMV\n runWG(pass, 'matmul_q2_wg', [['u', lm.N!], ['u', lm.K!], ['u', lm.nb!], ['u', lm.zp!], ['u', gx], ['u', 0]], [fn, lm.codes!, lm.scales!], [out], gx, Math.ceil(lm.N! / gx))\n } else if (useSG && M === SMALLM) {\n const gx = Math.min(lm.N!, 65535) // small-batch 2-bit GEMV: the code stream read once for all M rows\n runWG(pass, 'matmul_q2_sm', [['u', lm.N!], ['u', lm.K!], ['u', lm.nb!], ['u', lm.zp!], ['u', gx], ['u', M]], [fn, lm.codes!, lm.scales!], [out], gx, Math.ceil(lm.N! / gx))\n } else {\n run(pass, 'matmul_q2', [['u', M], ['u', lm.N!], ['u', lm.K!], ['u', lm.nb!], ['u', 128], ['u', lm.zp!]], [fn, lm.codes!, lm.scales!], out, M * lm.N!)\n }\n }\n\n function stack(enc: GPUCommandEncoder, h: GPUBuffer, S: number, posBase: number): { fn: GPUBuffer; layer0: GPUBuffer | null } {\n const { cos, sin } = ropeBufs(posBase, S)\n const pass = enc.beginComputePass()\n let cur = h,\n layer0: GPUBuffer | null = null\n for (let li = 0; li < A.layers; li++) {\n cur = layer(pass, li, cur, S, posBase, cos, sin)\n if (li === 0) layer0 = cur\n }\n const fn = actBuf(S * Hd)\n rms(pass, cur, FINAL_NORM, S, Hd, fn)\n pass.end()\n return { fn, layer0 }\n }\n\n async function forward(ids: number[]): Promise<ForwardResult> {\n const S = ids.length\n if (S === 0) throw new Error('forward: no tokens to process')\n if (S > maxSeqLen) throw new Error(`forward: sequence length ${S} exceeds maxSeqLen ${maxSeqLen}`)\n // forward() overwrites K/V at positions 0..S-1 of every layer: whatever conversation the cache\n // held is gone, so nothing may reuse it. Same rule as an aborted prefill.\n fullHistory = []\n cacheLen = 0\n await ensureKvCapacity(S)\n const vocab = W.lm_head.N!\n // Segmented like runPrefill (bit-exact by the same composition the reuse gates prove), so a\n // long forward() neither dispatches >65535 workgroups in one dimension (S*heads at full\n // maxSeqLen) nor binds an S x vocab logits buffer beyond the negotiated binding limit.\n const embed = new Float32Array(S * Hd),\n layer0 = new Float32Array(S * Hd),\n finalnorm = new Float32Array(S * Hd),\n logits = new Float32Array(S * vocab)\n transients = []\n try {\n for (let off = 0; off < S; off += PREFILL_SEG) {\n const seg = ids.slice(off, off + PREFILL_SEG)\n const enc = device.createCommandEncoder()\n const embedOut = embedBatch(enc, seg)\n const { fn, layer0: l0 } = stack(enc, embedOut, seg.length, off)\n const lg = device.createBuffer({ size: seg.length * vocab * 4, usage: S_ | CS })\n transients.push(lg)\n const pass = enc.beginComputePass()\n lmHead(pass, fn, seg.length, lg)\n pass.end()\n device.queue.submit([enc.finish()])\n await device.queue.onSubmittedWorkDone()\n embed.set(await readback(embedOut, seg.length * Hd), off * Hd)\n layer0.set(await readback(l0!, seg.length * Hd), off * Hd)\n finalnorm.set(await readback(fn, seg.length * Hd), off * Hd)\n logits.set(await readback(lg, seg.length * vocab), off * vocab)\n flushTransients() // this segment's scratch is dead; the peak stays at one segment\n }\n return { embed, layer0, finalnorm, logits, vocab, sequenceLength: S }\n } finally {\n flushTransients()\n transients = null\n }\n }\n\n // Long prefills run in SEGMENTS. One submission holding all layers' scratch for S tokens keeps\n // ~S x 4.3 MB of VRAM in flight (a 1000-token prompt ~4 GB): on unified-memory devices that\n // stalls the whole system, especially with other models resident. Segments cap the spike at one\n // segment's scratch (flushed between them), stay bit-exact by the same composition the\n // reuse-prefill gates prove (each segment writes K/V at its offset and attends to everything\n // before it), and give an abort a place to land mid-prompt, so a superseded turn no longer\n // blocks the GPU for whole seconds. Returns the LAST segment's final-norm buffer + the final\n // token's row within it, or null when aborted (fullHistory is cleared: K/V is only partially\n // written, so nothing may reuse the sequence).\n async function runPrefill(ids: number[], posBase: number, signal?: AbortSignal): Promise<{ fn: GPUBuffer; lastRow: number } | null> {\n let fn: GPUBuffer | null = null\n let lastRow = 0\n for (let off = 0; off < ids.length; off += PREFILL_SEG) {\n if (off > 0 && signal?.aborted) {\n fullHistory = []\n cacheLen = 0\n return null\n }\n const seg = ids.slice(off, off + PREFILL_SEG)\n const enc = device.createCommandEncoder()\n fn = stack(enc, embedBatch(enc, seg), seg.length, posBase + off).fn\n lastRow = seg.length - 1\n device.queue.submit([enc.finish()])\n if (off + PREFILL_SEG < ids.length) {\n await device.queue.onSubmittedWorkDone()\n flushTransients() // this segment's scratch is dead; the peak stays at one segment\n }\n }\n return { fn: fn!, lastRow }\n }\n\n // GPU-resident decode: argmax + embedding gather run on the GPU so the token id never leaves it;\n // chain syncN steps per CPU sync (deferred readback). Bit-exact: only the readback timing changes.\n async function generateImpl(ids: number[], posBase: number, nTokens: number, full: Set<string> | null = null, syncN: number = SYNC_N, ctl?: { stopTokens?: number[]; onToken?: (id: number) => void; signal?: AbortSignal }): Promise<RawGenResult> {\n await ensureKvCapacity(posBase + ids.length + nTokens)\n FULL = full\n const vocab = W.lm_head.N!\n const tokBuf = device.createBuffer({ size: Math.max(1, nTokens) * 4, usage: S_ | CS }) // GPU-resident token ids\n const embG = device.createBuffer({ size: Hd * 4, usage: S_ | CS | CD }) // GPU embedding of the current token (lives across the whole call)\n const lg = device.createBuffer({ size: vocab * 4, usage: S_ | CS })\n transients = [] // track prefill scratch so it can be destroyed once the prefill completes\n try {\n const t0 = performance.now()\n // prefill (CPU embed of the known prompt, segmented) -> last hidden -> lm_head -> GPU argmax\n const pfx = await runPrefill(ids, posBase, ctl?.signal)\n if (!pfx) return { prefillMs: performance.now() - t0, decodeMs: 0, tokPerSec: 0, tokens: [], firstArgmax: -1, recMs: 0, gpuMs: 0, rbMs: 0 }\n const encP = device.createCommandEncoder()\n const lastP = actBuf(Hd)\n encP.copyBufferToBuffer(pfx.fn, pfx.lastRow * Hd * 4, lastP, 0, Hd * 4)\n let pp = encP.beginComputePass()\n lmHead(pp, lastP, 1, lg)\n pp.end()\n pp = encP.beginComputePass()\n runN(pp, 'argmax', [['u', vocab], ['u', 0], ['u', 0], ['u', 0]], [lg], tokBuf, 1)\n pp.end()\n device.queue.submit([encP.finish()])\n await device.queue.onSubmittedWorkDone()\n const firstTok = (await readbackU32(tokBuf, 1))[0]\n flushTransients() // the last segment's scratch is dead now\n const prefillMs = performance.now() - t0\n\n const gen: number[] = []\n let recMs = 0,\n gpuMs = 0,\n rbMs = 0\n const t1 = performance.now()\n let total = 1 // decode positions consumed (incl. prefill's first)\n const stopSet = ctl?.stopTokens ? new Set(ctl.stopTokens) : null\n let stopped = stopSet?.has(firstTok) ?? false\n if (!stopped) {\n gen.push(firstTok) // a stop token is never emitted, even at position 0\n ctl?.onToken?.(firstTok)\n }\n poolInvalidate() // rebuild cached bind groups against this call's buffers\n let slot = posBase + ids.length // cache slot where the next fed token's K/V lands\n while (total < nTokens && !stopped) {\n if (ctl?.signal?.aborted) break\n const batch = Math.min(syncN, nTokens - total)\n slot = evictFor(slot, batch) // sink mode: roll the window before the batch needs the room\n poolUse('decode') // reuse decode scratch + uniforms across batches; resets the slot indices\n let t = performance.now()\n const enc = device.createCommandEncoder()\n for (let j = 0; j < batch; j++) {\n const idxOut = total + j,\n pos = slot + j\n let pass = enc.beginComputePass()\n runN(pass, 'embed_gather', [['u', Hd], ['u', idxOut - 1], ['u', 0], ['u', 0]], [tokBuf, embWqG, tgt4G, embScalesG, embZpG], embG, 1)\n pass.end()\n const r = stack(enc, embG, 1, pos)\n const last = actBuf(Hd)\n enc.copyBufferToBuffer(r.fn, 0, last, 0, Hd * 4)\n pass = enc.beginComputePass()\n lmHead(pass, last, 1, lg)\n runN(pass, 'argmax', [['u', vocab], ['u', idxOut], ['u', 0], ['u', 0]], [lg], tokBuf, 1)\n pass.end()\n }\n device.queue.submit([enc.finish()])\n recMs += performance.now() - t\n t = performance.now()\n await device.queue.onSubmittedWorkDone()\n gpuMs += performance.now() - t\n t = performance.now()\n const toks = await readbackU32(tokBuf, total + batch)\n rbMs += performance.now() - t\n let fed = batch // slots that belong to the history (EOS discards the rest of the batch)\n for (let j = 0; j < batch; j++) {\n const tk = toks[total + j]\n if (stopSet?.has(tk)) { stopped = true; fed = j; break } // EOS lands at the batch boundary (greedy)\n gen.push(tk)\n ctl?.onToken?.(tk)\n }\n total += batch\n slot += fed\n }\n cacheLen = slot // sink-mode bookkeeping: the last history token's (re-feed) slot\n const decodeMs = performance.now() - t1,\n nd = Math.max(1, gen.length - 1)\n return { prefillMs, decodeMs, tokPerSec: nd / (decodeMs / 1000), tokens: gen, firstArgmax: firstTok, recMs: recMs / nd, gpuMs: gpuMs / nd, rbMs: rbMs / nd }\n } finally {\n // Restore the shared flags even when a step throws (a stuck active pool would corrupt every\n // later call), and release this call's GPU scratch instead of waiting on GC.\n poolUse(null)\n FULL = null\n flushTransients()\n transients = null\n tokBuf.destroy()\n embG.destroy()\n lg.destroy()\n }\n }\n\n // Sampled decode (do_sample): the GPU pre-filters the logits in place (repetition_penalty +\n // no_repeat_ngram bans) and selects the top-K via K masked-argmax passes; only K (id, logit) pairs\n // are read back, and the CPU does temperature + softmax + MT19937 multinomial (exact transformers.js\n // semantics). Per-step (syncN=1) because the chosen token is picked on the CPU and feeds the next\n // step's embed gather. A GREEDY turn with processors (repetition_penalty / no_repeat_ngram) also\n // runs here - the chain filters, then pick() takes the penalized argmax without touching the RNG.\n // Plain greedy decode (generateImpl) is the separate, untouched GPU-resident path.\n async function generateSampledImpl(ids: number[], posBase: number, nTokens: number, genOpts: GenerateOptions, history: number[], rngIn?: MT19937): Promise<RawGenResult> {\n await ensureKvCapacity(posBase + ids.length + nTokens)\n // `ids` = the tokens to prefill this turn (the whole prompt, or [lastToken, ...delta] on reuse).\n // `history` = the FULL conversation token sequence (shared, mutated): the sampler's penalty/ngram\n // see the entire sequence, like transformers.js; generated tokens are pushed onto it.\n const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1\n const vocab = W.lm_head.N!\n const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab))\n // logprobs: run extra argmax rounds when N exceeds the sampling top-K, but NEVER let it widen\n // the sampling pool - the draw stays over the first K candidates, bit-identical with or\n // without logprobs on.\n const lpN = Math.max(0, Math.min(Math.floor(genOpts.logprobs ?? 0), 32, vocab))\n const KT = Math.max(K, lpN)\n const temperature = genOpts.temperature ?? 1\n const penalty = genOpts.repetitionPenalty ?? 1\n const ngramN = genOpts.noRepeatNgramSize ?? 0\n const stopSet = genOpts.stopTokens ? new Set(genOpts.stopTokens) : null\n const onToken = genOpts.onToken\n const signal = genOpts.signal\n const rng = rngIn ?? new MT19937(genOpts.seed)\n\n // persistent buffers (stable across steps for bind-group caching; not via actBuf)\n const tokBuf = device.createBuffer({ size: Math.max(1, nTokens) * 4, usage: S_ | CS | CD })\n const lg = device.createBuffer({ size: vocab * 4, usage: S_ | CS })\n const candIds = device.createBuffer({ size: KT * 4, usage: S_ | CS })\n const candVals = device.createBuffer({ size: KT * 4, usage: S_ | CS })\n const lseBuf = device.createBuffer({ size: 4, usage: S_ | CS }) // log-sum-exp normalizer (logprobs)\n const affBuf = device.createBuffer({ size: maxSeqLen * 4, usage: S_ | CD }) // upper bound = full vocab can't exceed seq len\n const banBuf = device.createBuffer({ size: maxSeqLen * 4, usage: S_ | CD })\n const rbBuf = device.createBuffer({ size: KT * 8 + (lpN ? 4 : 0), usage: GPUBufferUsage.MAP_READ | CD })\n const embG = device.createBuffer({ size: Hd * 4, usage: S_ | CS | CD })\n\n // upload the CPU-computed deduped id set + ngram bans for the current history; return their lengths\n const writeAffBan = (history: number[]): { affLen: number; banLen: number } => {\n const aff = penalty !== 1 ? affectedIds(history) : new Uint32Array(0)\n if (aff.length) device.queue.writeBuffer(affBuf, 0, aff)\n const ban = ngramN > 0 ? ngramBans(history, ngramN) : []\n if (ban.length) device.queue.writeBuffer(banBuf, 0, Uint32Array.from(ban))\n return { affLen: aff.length, banLen: ban.length }\n }\n // penalty pre-filter (+ logprobs normalizer) + KT masked-argmax, all in the given pass (after\n // lm_head wrote lg). The log-sum-exp runs BEFORE the argmax rounds: those mask their winners\n // in lg in place, which would corrupt the sum.\n const samplerChain = (pass: GPUComputePassEncoder, affLen: number, banLen: number): void => {\n setup(pass, 'sampler_penalty', [['u', affLen], ['u', banLen], ['f', penalty], ['u', 0xff800000]], [affBuf, banBuf], [lg])\n pass.dispatchWorkgroups(1)\n if (lpN) {\n setup(pass, 'logsumexp', [['u', vocab], ['u', 0], ['u', 0], ['u', 0]], [lg], [lseBuf])\n pass.dispatchWorkgroups(1)\n }\n for (let r = 0; r < KT; r++) {\n setup(pass, 'argmax_masked', [['u', vocab], ['u', r], ['u', 0], ['u', 0]], [lg], [candIds, candVals])\n pass.dispatchWorkgroups(1)\n }\n }\n const copyCands = (enc: GPUCommandEncoder): void => {\n enc.copyBufferToBuffer(candIds, 0, rbBuf, 0, KT * 4)\n enc.copyBufferToBuffer(candVals, 0, rbBuf, KT * 4, KT * 4)\n if (lpN) enc.copyBufferToBuffer(lseBuf, 0, rbBuf, KT * 8, 4)\n }\n const readCands = async (): Promise<{ ci: Uint32Array; cv: Float32Array; lse: number }> => {\n await rbBuf.mapAsync(GPUMapMode.READ)\n const mapped = rbBuf.getMappedRange()\n const ci = new Uint32Array(mapped.slice(0, KT * 4))\n const cv = new Float32Array(mapped.slice(KT * 4, KT * 8))\n const lse = lpN ? new Float32Array(mapped.slice(KT * 8, KT * 8 + 4))[0] : 0\n rbBuf.unmap()\n return { ci, cv, lse }\n }\n // logprobs bookkeeping: the chosen token's logit (set by every chooseToken path) and the\n // per-emitted-token records (aligned with the returned tokens)\n let chosenLogit = 0\n const lpOut: TokenLogprobs[] | null = lpN ? [] : null\n const recordLp = (ci: Uint32Array, cv: Float32Array, lse: number): void => {\n if (!lpOut) return\n const top: { id: number; logprob: number }[] = []\n for (let i = 0; i < lpN; i++) top.push({ id: ci[i], logprob: cv[i] - lse })\n lpOut.push({ logprob: chosenLogit - lse, top })\n }\n // candidates are descending, so ci[0] is the argmax of the penalized logits (greedy+processors);\n // sampling and filtering see only the first K candidates (KT > K rounds exist for logprobs only)\n const pick = (ciAll: Uint32Array, cvAll: Float32Array): number => {\n const ci = ciAll.subarray(0, K)\n const cv = cvAll.subarray(0, K)\n const tk = sampled ? sampleFromCandidates(ci, cv, temperature, rng) : ci[0]\n chosenLogit = cv[ci.indexOf(tk)]\n return tk\n }\n const filter = genOpts.candidateFilter\n // Constrained pick (candidateFilter): keep the permitted subset in rank order and pick within\n // it - greedy takes the best permitted, sampling renormalizes the draw over them (exactly one\n // RNG draw per emitted token, like the unconstrained path). When the whole top-K is rejected,\n // walk the FULL vocabulary in logit order (rare: valid grammars almost always admit a top-K\n // token) and rebuild up to K permitted candidates; a grammar that admits nothing is a bug in\n // the filter and fails loudly.\n const chooseToken = async (ciAll: Uint32Array, cvAll: Float32Array): Promise<number> => {\n if (!filter) return pick(ciAll, cvAll)\n const ci = ciAll.subarray(0, K)\n const cv = cvAll.subarray(0, K)\n const perm = new Set(filter(ci, cv))\n if (perm.size > 0) {\n const pIds: number[] = []\n const pVals: number[] = []\n for (let i = 0; i < ci.length; i++)\n if (perm.has(ci[i])) {\n pIds.push(ci[i])\n pVals.push(cv[i])\n }\n const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng) : pIds[0]\n chosenLogit = pVals[pIds.indexOf(tk)]\n return tk\n }\n const all = await readback(lg, vocab) // penalized logits; every argmax round masked its winner in place\n // Restore the masked entries from the candidates already read back: the filter-rejected\n // top-K re-check and fail again (filters are deterministic), and the extra logprobs-only\n // rounds (K..KT) must stay reachable or logprobs would change constrained output.\n for (let i = 0; i < ciAll.length; i++) all[ciAll[i]] = cvAll[i]\n const order = Array.from(all.keys()).sort((a, b) => all[b] - all[a] || a - b)\n const pIds: number[] = []\n const pVals: number[] = []\n const B = 512\n for (let i = 0; i < order.length && pIds.length < K; i += B) {\n if (all[order[i]] === -Infinity) break // sorted: only masked/banned entries remain\n const batch = order.slice(i, i + B).filter((id) => all[id] !== -Infinity)\n const ok = new Set(filter(Uint32Array.from(batch), Float32Array.from(batch.map((id) => all[id]))))\n for (const id of batch) {\n if (ok.has(id)) {\n pIds.push(id)\n pVals.push(all[id])\n if (pIds.length >= K) break\n }\n }\n }\n if (pIds.length === 0) throw new Error('bitgpu: candidateFilter permitted no token in the entire vocabulary')\n const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng) : pIds[0]\n chosenLogit = pVals[pIds.indexOf(tk)]\n return tk\n }\n\n transients = [] // track prefill scratch so it can be destroyed once the prefill completes\n try {\n const t0 = performance.now()\n // prefill (segmented) -> last hidden -> lm_head -> sampler chain, CPU samples the first token\n const pfx = await runPrefill(ids, posBase, signal)\n if (!pfx) return { prefillMs: performance.now() - t0, decodeMs: 0, tokPerSec: 0, tokens: [], firstArgmax: -1, recMs: 0, gpuMs: 0, rbMs: 0, rng }\n const encP = device.createCommandEncoder()\n const lastP = actBuf(Hd)\n encP.copyBufferToBuffer(pfx.fn, pfx.lastRow * Hd * 4, lastP, 0, Hd * 4)\n const pf = writeAffBan(history)\n let pass = encP.beginComputePass()\n lmHead(pass, lastP, 1, lg)\n samplerChain(pass, pf.affLen, pf.banLen)\n pass.end()\n copyCands(encP)\n device.queue.submit([encP.finish()])\n const first = await readCands() // mapAsync waits for the submitted work; no separate sync needed\n const firstTok = await chooseToken(first.ci, first.cv)\n flushTransients() // the last segment's scratch is dead now (the map wait proved the GPU is done with it)\n const prefillMs = performance.now() - t0\n\n const gen: number[] = []\n let stopped = stopSet?.has(firstTok) ?? false\n if (!stopped) {\n gen.push(firstTok) // a stop token is never emitted or recorded, even at position 0\n history.push(firstTok)\n recordLp(first.ci, first.cv, first.lse)\n onToken?.(firstTok)\n device.queue.writeBuffer(tokBuf, 0, new Uint32Array([firstTok]))\n }\n\n let recMs = 0, gpuMs = 0, rbMs = 0\n const t1 = performance.now()\n let total = 1\n poolInvalidate() // rebuild cached bind groups against this call's buffers\n let slot = posBase + ids.length // cache slot where the next fed token's K/V lands\n while (total < nTokens && !stopped) {\n if (signal?.aborted) break\n poolUse('decode')\n slot = evictFor(slot, 1) // sink mode: roll the window before this step needs the room\n const idxOut = total, pos = slot\n let t = performance.now()\n const { affLen, banLen } = writeAffBan(history)\n const enc = device.createCommandEncoder()\n let p2 = enc.beginComputePass()\n runN(p2, 'embed_gather', [['u', Hd], ['u', idxOut - 1], ['u', 0], ['u', 0]], [tokBuf, embWqG, tgt4G, embScalesG, embZpG], embG, 1)\n p2.end()\n const r = stack(enc, embG, 1, pos)\n const last = actBuf(Hd)\n enc.copyBufferToBuffer(r.fn, 0, last, 0, Hd * 4)\n p2 = enc.beginComputePass()\n lmHead(p2, last, 1, lg)\n samplerChain(p2, affLen, banLen)\n p2.end()\n copyCands(enc)\n device.queue.submit([enc.finish()])\n recMs += performance.now() - t\n t = performance.now()\n // ONE sync per token: mapAsync on the readback buffer already waits for the submitted\n // work its copy depends on, so a separate onSubmittedWorkDone is a second full CPU-GPU\n // round-trip for nothing. The map wait is dominated by GPU time, so it is attributed to\n // gpuMs; the post-map array slicing is microseconds (rbMs stays for API stability).\n const { ci, cv, lse } = await readCands()\n gpuMs += performance.now() - t\n t = performance.now()\n const tk = await chooseToken(ci, cv)\n rbMs += performance.now() - t\n total += 1\n if (stopSet?.has(tk)) { stopped = true; break } // EOS: stop without emitting the stop token\n gen.push(tk)\n history.push(tk)\n recordLp(ci, cv, lse)\n onToken?.(tk)\n device.queue.writeBuffer(tokBuf, idxOut * 4, new Uint32Array([tk])) // feed the next step's embed gather\n slot += 1\n }\n cacheLen = slot // sink-mode bookkeeping (filled slots; the last emitted token is unfed)\n const decodeMs = performance.now() - t1\n const nd = Math.max(1, gen.length - 1)\n return { prefillMs, decodeMs, tokPerSec: nd / (decodeMs / 1000), tokens: gen, firstArgmax: firstTok, recMs: recMs / nd, gpuMs: gpuMs / nd, rbMs: rbMs / nd, rng, ...(lpOut ? { lp: lpOut } : {}) }\n } finally {\n // Restore the shared flags even when a step throws, and release this call's GPU buffers.\n poolUse(null)\n flushTransients()\n transients = null\n for (const b of [tokBuf, lg, candIds, candVals, lseBuf, affBuf, banBuf, rbBuf, embG]) b.destroy()\n }\n }\n\n // Prompt-lookup speculative decoding, greedy AND sampled. Each step drafts the continuation\n // from an n-gram match in the sequence so far (draftNgram; no draft model), then verifies all\n // drafts in ONE batched forward through the prefill path: it writes K/V for every drafted\n // position and yields logits for every row, so the accepted prefix plus one model-chosen token\n // are emitted for the cost of a single pass. K/V written for rejected positions is overwritten\n // by later steps before anything ever attends to it (attention at position p reads only 0..p).\n // Exactness: row j is only consumed when drafts 0..j-1 were accepted, so its logits (and, when\n // sampling, its penalty/ban lists, computed assuming those drafts) describe the true sequence;\n // the sampler draws sequentially on the CPU, so the MT19937 stream advances exactly one draw\n // per EMITTED token, in order - the output equals non-speculative decoding for the same seed.\n // With no match the step degenerates to a normal single-token pass (S=1 keeps the fused path).\n async function generatePldImpl(ids: number[], posBase: number, nTokens: number, genOpts: GenerateOptions, history: number[], rngIn?: MT19937): Promise<RawGenResult> {\n await ensureKvCapacity(posBase + ids.length + nTokens)\n const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1\n const vocab = W.lm_head.N!\n const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab))\n const temperature = genOpts.temperature ?? 1\n const penalty = genOpts.repetitionPenalty ?? 1\n const ngramN = genOpts.noRepeatNgramSize ?? 0\n const pl = typeof genOpts.promptLookup === 'object' && genOpts.promptLookup !== null ? genOpts.promptLookup : {}\n const ngramSize = Math.max(2, pl.ngramSize ?? 3)\n const maxDraft = Math.max(1, pl.maxDraft ?? 8)\n const stopSet = genOpts.stopTokens ? new Set(genOpts.stopTokens) : null\n const onToken = genOpts.onToken\n const signal = genOpts.signal\n const rng = rngIn ?? new MT19937(genOpts.seed)\n // Greedy with processors (repetition_penalty / no_repeat_ngram) also needs the per-row sampler\n // chain - the penalties see each row's history - but picks the penalized argmax, no RNG draw.\n const useChain = sampled || penalty !== 1 || ngramN > 0\n\n const lg = device.createBuffer({ size: vocab * 4, usage: S_ | CS | CD }) // one row, target of the per-row copy\n const lgAll = device.createBuffer({ size: (maxDraft + 1) * vocab * 4, usage: S_ | CS }) // lm_head over all rows\n const idsOut = device.createBuffer({ size: (maxDraft + 1) * 4, usage: S_ | CS }) // greedy: argmax per row\n const candIds = device.createBuffer({ size: K * 4, usage: S_ | CS })\n const candVals = device.createBuffer({ size: K * 4, usage: S_ | CS })\n const affBuf = device.createBuffer({ size: (maxSeqLen + maxDraft + 1) * 4, usage: S_ | CD })\n const banBuf = device.createBuffer({ size: (maxSeqLen + maxDraft + 1) * 4, usage: S_ | CD })\n const rbAll = device.createBuffer({ size: (maxDraft + 1) * K * 8, usage: GPUBufferUsage.MAP_READ | CD })\n // Step input token ids + their gathered embeddings, written per step (never re-created: the\n // pooled bind groups cache buffer identities, so a per-step upload would go stale the moment\n // it was destroyed). The embeddings are gathered ON the GPU (embed_gather_batch) from the\n // uploaded ids - only S u32s cross the bus per step, and no CPU embedding tables exist.\n const pldIds = device.createBuffer({ size: (maxDraft + 1) * 4, usage: S_ | CD })\n const embIn = device.createBuffer({ size: (maxDraft + 1) * Hd * 4, usage: S_ | CD })\n\n const writeAffBan = (h: number[]): { affLen: number; banLen: number } => {\n const aff = penalty !== 1 ? affectedIds(h) : new Uint32Array(0)\n if (aff.length) device.queue.writeBuffer(affBuf, 0, aff)\n const ban = ngramN > 0 ? ngramBans(h, ngramN) : []\n if (ban.length) device.queue.writeBuffer(banBuf, 0, Uint32Array.from(ban))\n return { affLen: aff.length, banLen: ban.length }\n }\n const samplerChain = (pass: GPUComputePassEncoder, affLen: number, banLen: number): void => {\n setup(pass, 'sampler_penalty', [['u', affLen], ['u', banLen], ['f', penalty], ['u', 0xff800000]], [affBuf, banBuf], [lg])\n pass.dispatchWorkgroups(1)\n for (let r = 0; r < K; r++) {\n setup(pass, 'argmax_masked', [['u', vocab], ['u', r], ['u', 0], ['u', 0]], [lg], [candIds, candVals])\n pass.dispatchWorkgroups(1)\n }\n }\n // draw the row-j candidates from a mapped copy of rbAll (candidates are descending, so\n // index 0 is the penalized argmax for a greedy-with-processors turn - no RNG draw)\n const rowDraw = (m: ArrayBuffer, j: number): number =>\n sampled\n ? sampleFromCandidates(new Uint32Array(m, j * K * 8, K), new Float32Array(m, j * K * 8 + K * 4, K), temperature, rng)\n : new Uint32Array(m, j * K * 8, 1)[0]\n\n transients = []\n try {\n const t0 = performance.now()\n // prefill (segmented) -> last hidden -> lm_head -> argmax (greedy) or sampler chain (sampled)\n const pfx = await runPrefill(ids, posBase, signal)\n if (!pfx) return { prefillMs: performance.now() - t0, decodeMs: 0, tokPerSec: 0, tokens: [], firstArgmax: -1, recMs: 0, gpuMs: 0, rbMs: 0, spec: { steps: 0, drafted: 0, accepted: 0 }, rng }\n const encP = device.createCommandEncoder()\n const lastP = actBuf(Hd)\n encP.copyBufferToBuffer(pfx.fn, pfx.lastRow * Hd * 4, lastP, 0, Hd * 4)\n const pf = useChain ? writeAffBan(history) : null\n let pass = encP.beginComputePass()\n lmHead(pass, lastP, 1, lg)\n if (pf) samplerChain(pass, pf.affLen, pf.banLen)\n else runN(pass, 'argmax', [['u', vocab], ['u', 0], ['u', 0], ['u', 0]], [lg], idsOut, 1)\n pass.end()\n if (pf) {\n encP.copyBufferToBuffer(candIds, 0, rbAll, 0, K * 4)\n encP.copyBufferToBuffer(candVals, 0, rbAll, K * 4, K * 4)\n }\n device.queue.submit([encP.finish()])\n await device.queue.onSubmittedWorkDone()\n let firstTok: number\n if (pf) {\n await rbAll.mapAsync(GPUMapMode.READ)\n const m = rbAll.getMappedRange().slice(0)\n rbAll.unmap()\n firstTok = rowDraw(m, 0)\n } else {\n firstTok = (await readbackU32(idsOut, 1))[0]\n }\n flushTransients()\n const prefillMs = performance.now() - t0\n\n const gen: number[] = []\n let stopped = stopSet?.has(firstTok) ?? false\n if (!stopped) {\n gen.push(firstTok)\n history.push(firstTok)\n onToken?.(firstTok)\n }\n poolInvalidate() // rebuild cached bind groups against THIS call's persistent buffers\n let total = 1\n let tLast = firstTok\n let pos = posBase + ids.length // where tLast's K/V lands on the next step\n let specSteps = 0,\n drafted = 0,\n accepted = 0\n let recMs = 0,\n gpuMs = 0,\n rbMs = 0\n const t1 = performance.now()\n while (total < nTokens && !stopped) {\n if (signal?.aborted) break\n pos = evictFor(pos, maxDraft + 1) // sink mode: roll before a full drafting step needs the room\n const kMax = Math.min(maxDraft, nTokens - total - 1, maxSeqLen - 1 - pos)\n const drafts = kMax > 0 ? draftNgram(history, ngramSize, kMax) : []\n const S = drafts.length + 1\n await ensureKvCapacity(pos + S)\n let t = performance.now()\n // Pools: 'pld1' = the fused single-token sequence, 'pldm' = the verify sequence (identical\n // dispatch order for every S in 2..9; buffers rounded to 9 rows so sizes are S-invariant).\n // S > 9 (a raised maxDraft) falls back to unpooled scalar kernels - correct, just slower.\n if (S === 1) poolUse('pld1')\n else if (useSG && S <= 9) poolUse('pldm', S, 9)\n else poolUse(null)\n device.queue.writeBuffer(pldIds, 0, new Uint32Array([tLast, ...drafts]))\n // shared forward: [tLast, ...drafts] at pos -> K/V for pos..pos+S-1 + logits for every row.\n // Routed through the small-batch kernels (weights read once for all S rows); S=1 keeps\n // the fused decode path via the S===1 branches.\n SMALLM = useSG && S >= 2 && S <= 9 ? S : 0\n const enc = device.createCommandEncoder()\n const gp = enc.beginComputePass()\n run(gp, 'embed_gather_batch', [['u', S], ['u', Hd], ['u', 0], ['u', 0]], [pldIds, embWqG, tgt4G, embScalesG, embZpG], embIn, S * Hd)\n gp.end()\n const r = stack(enc, embIn, S, pos)\n pass = enc.beginComputePass()\n lmHead(pass, r.fn, S, lgAll)\n pass.end()\n SMALLM = 0\n if (!useChain) {\n for (let j = 0; j < S; j++) {\n enc.copyBufferToBuffer(lgAll, j * vocab * 4, lg, 0, vocab * 4)\n const p = enc.beginComputePass()\n runN(p, 'argmax', [['u', vocab], ['u', j], ['u', 0], ['u', 0]], [lg], idsOut, 1)\n p.end()\n }\n device.queue.submit([enc.finish()])\n } else {\n device.queue.submit([enc.finish()])\n // per row: upload that row's penalty state (queue order puts it before the row's\n // dispatches), copy the row into lg, run the chain, stash the K candidates in rbAll\n for (let j = 0; j < S; j++) {\n const rowHist = j === 0 ? history : [...history, ...drafts.slice(0, j)]\n const { affLen, banLen } = writeAffBan(rowHist)\n const e2 = device.createCommandEncoder()\n e2.copyBufferToBuffer(lgAll, j * vocab * 4, lg, 0, vocab * 4)\n const p = e2.beginComputePass()\n samplerChain(p, affLen, banLen)\n p.end()\n e2.copyBufferToBuffer(candIds, 0, rbAll, j * K * 8, K * 4)\n e2.copyBufferToBuffer(candVals, 0, rbAll, j * K * 8 + K * 4, K * 4)\n device.queue.submit([e2.finish()])\n }\n }\n recMs += performance.now() - t\n t = performance.now()\n await device.queue.onSubmittedWorkDone()\n gpuMs += performance.now() - t\n t = performance.now()\n // acceptance: emit row draws in order while they agree with the drafts; the first\n // disagreement is itself a valid emission (it came from the true distribution)\n const emitted: number[] = []\n if (!useChain) {\n const outs = await readbackU32(idsOut, S)\n for (let j = 0; j < S; j++) {\n const tk = outs[j]\n if (stopSet?.has(tk)) { stopped = true; break }\n emitted.push(tk)\n if (j < drafts.length && tk !== drafts[j]) break\n }\n } else {\n await rbAll.mapAsync(GPUMapMode.READ)\n const m = rbAll.getMappedRange().slice(0)\n rbAll.unmap()\n for (let j = 0; j < S; j++) {\n const tk = rowDraw(m, j) // draws only for rows actually reached: one per emitted token\n if (stopSet?.has(tk)) { stopped = true; break }\n emitted.push(tk)\n if (j < drafts.length && tk !== drafts[j]) break\n }\n }\n rbMs += performance.now() - t\n specSteps++\n drafted += drafts.length\n accepted += Math.max(0, emitted.length - 1)\n for (const tk of emitted) {\n gen.push(tk)\n history.push(tk)\n onToken?.(tk)\n }\n total += emitted.length\n flushTransients()\n if (emitted.length === 0) break // stop token at row 0\n pos += emitted.length\n tLast = emitted[emitted.length - 1]\n }\n cacheLen = pos // sink-mode bookkeeping: the last history token's (re-feed) slot\n const decodeMs = performance.now() - t1\n const nd = Math.max(1, gen.length - 1)\n return {\n prefillMs,\n decodeMs,\n tokPerSec: nd / (decodeMs / 1000),\n tokens: gen,\n firstArgmax: firstTok,\n recMs: recMs / nd,\n gpuMs: gpuMs / nd,\n rbMs: rbMs / nd,\n spec: { steps: specSteps, drafted, accepted },\n rng,\n }\n } finally {\n SMALLM = 0 // encode-time flag; a throw mid-encode must not leak it into other paths\n poolUse(null)\n flushTransients()\n transients = null\n for (const b of [lg, lgAll, idsOut, candIds, candVals, affBuf, banBuf, rbAll, embIn, pldIds]) b.destroy()\n }\n }\n\n // Run ONE decode step at the same position through the fused path and the slow (known-good) path\n // and return layer-0 checkpoints + final norm + logits for each, so a divergence pinpoints the\n // first fused kernel that differs.\n async function debugDecode(prefillIds: number[]): Promise<{ fast: Record<string, Float32Array>; slow: Record<string, Float32Array> }> {\n await ensureKvCapacity(prefillIds.length + 1)\n const encP = device.createCommandEncoder()\n stack(encP, embedBatch(encP, prefillIds), prefillIds.length, 0)\n device.queue.submit([encP.finish()])\n await device.queue.onSubmittedWorkDone()\n const pos = prefillIds.length,\n tok = prefillIds[prefillIds.length - 1]\n const runStep = async (forceSlow: boolean): Promise<Record<string, Float32Array>> => {\n FORCE_SLOW = forceSlow\n DBG0 = {}\n const enc = device.createCommandEncoder()\n const r = stack(enc, embedBatch(enc, [tok]), 1, pos)\n const lg = device.createBuffer({ size: W.lm_head.N! * 4, usage: S_ | CS })\n const pass = enc.beginComputePass()\n lmHead(pass, r.fn, 1, lg)\n pass.end()\n device.queue.submit([enc.finish()])\n await device.queue.onSubmittedWorkDone()\n const ck: Record<string, Float32Array> = {}\n for (const [name, b] of Object.entries(DBG0)) ck[name] = await readback(b, b.size / 4)\n const off = pos * KV * Dh\n if (!kv16 && !kv8) {\n // f32-mode only: readback() types the bytes as f32, which is wrong for an f16/q8 cache\n ck.kc = (await readback(Kc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh) // kvCapacity, not maxSeqLen: the cache may not have grown yet\n ck.vc = (await readback(Vc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh)\n }\n ck.fn = await readback(r.fn, Hd)\n ck.logits = await readback(lg, W.lm_head.N!)\n FORCE_SLOW = false\n DBG0 = null\n return ck\n }\n const fast = await runStep(false),\n slow = await runStep(true)\n return { fast, slow }\n }\n\n // Debug hook for the browser harness: run a prefill for `ids` (history = ids), then return the GPU\n // lm_head logits (base, pre-penalty), the GPU penalized logits, and the GPU top-K. The page penalizes\n // `base` on the CPU and diffs vs `penalized` (exact, same input), and compares its top-K vs candIds,\n // validating sampler_penalty.wgsl and argmax_masked.wgsl in isolation against the headless-checked math.\n async function debugSampler(ids: number[], genOpts: GenerateOptions): Promise<{ base: Float32Array; penalized: Float32Array; candIds: Uint32Array; candVals: Float32Array }> {\n const vocab = W.lm_head.N!\n const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab))\n const penalty = genOpts.repetitionPenalty ?? 1\n const ngramN = genOpts.noRepeatNgramSize ?? 0\n const lg = device.createBuffer({ size: vocab * 4, usage: S_ | CS })\n const candIds = device.createBuffer({ size: K * 4, usage: S_ | CS })\n const candVals = device.createBuffer({ size: K * 4, usage: S_ | CS })\n const aff = penalty !== 1 ? affectedIds(ids) : new Uint32Array(0)\n const ban = ngramN > 0 ? ngramBans(ids, ngramN) : []\n const affBuf = upload(aff.length ? aff : new Uint32Array(1), S_ | CD)\n const banBuf = upload(ban.length ? Uint32Array.from(ban) : new Uint32Array(1), S_ | CD)\n // pass 1: prefill -> lm_head -> base logits\n const enc1 = device.createCommandEncoder()\n const { fn } = stack(enc1, embedBatch(enc1, ids), ids.length, 0)\n const lastP = device.createBuffer({ size: Hd * 4, usage: S_ | CS | CD })\n enc1.copyBufferToBuffer(fn, (ids.length - 1) * Hd * 4, lastP, 0, Hd * 4)\n let pass = enc1.beginComputePass()\n lmHead(pass, lastP, 1, lg)\n pass.end()\n device.queue.submit([enc1.finish()])\n await device.queue.onSubmittedWorkDone()\n const base = await readback(lg, vocab)\n // pass 2: penalty (in place on lg) + K masked-argmax\n const enc2 = device.createCommandEncoder()\n pass = enc2.beginComputePass()\n setup(pass, 'sampler_penalty', [['u', aff.length], ['u', ban.length], ['f', penalty], ['u', 0xff800000]], [affBuf, banBuf], [lg])\n pass.dispatchWorkgroups(1)\n for (let r = 0; r < K; r++) {\n setup(pass, 'argmax_masked', [['u', vocab], ['u', r], ['u', 0], ['u', 0]], [lg], [candIds, candVals])\n pass.dispatchWorkgroups(1)\n }\n pass.end()\n device.queue.submit([enc2.finish()])\n await device.queue.onSubmittedWorkDone()\n return { base, penalized: await readback(lg, vocab), candIds: await readbackU32(candIds, K), candVals: await readback(candVals, K) }\n }\n\n const capabilities: EngineCapabilities = {\n useSubgroups: useSG,\n subgroupSize: sgMax,\n kvCache: kv16 ? 'f16' : kv8 ? 'q8' : 'f32',\n overflow: roll ? 'sinks' : 'error',\n maxSeqLen,\n adapter: { vendor: info.vendor, architecture: info.architecture, device: info.device, description: info.description },\n limits: {\n // the DEVICE limits (what dispatches are actually validated against), not the adapter's maximums\n maxStorageBufferBindingSize: Number(device.limits.maxStorageBufferBindingSize),\n maxComputeWorkgroupStorageSize: device.limits.maxComputeWorkgroupStorageSize,\n },\n }\n\n // Public generate: routes to sampled decode when a sampling temperature is set, else greedy.\n // Both honor stopTokens / onToken / signal. With reuseCache, `promptTokenIds` is the DELTA to append\n // to the cached conversation (the prior turn's last token is re-fed so its K/V lands); otherwise the\n // cache resets and `promptTokenIds` is the full prompt. The KV cache lives across calls in Kc/Vc.\n async function generate(promptTokenIds: number[], genOpts: GenerateOptions = {}): Promise<GenerateResult> {\n const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1\n // transformers.js applies repetition_penalty / no_repeat_ngram under greedy search too, so a\n // greedy turn that requests them routes through the sampler-chain path (which picks the\n // penalized argmax instead of drawing); the plain GPU-resident greedy loop can't see history.\n const hasProcessors = (genOpts.repetitionPenalty ?? 1) !== 1 || (genOpts.noRepeatNgramSize ?? 0) > 0\n const reuse = (genOpts.reuseCache ?? false) && fullHistory.length > 0\n if (genOpts.signal?.aborted) {\n // aborted before any work: don't touch fullHistory (the cache still matches it)\n return { tokens: [], prefillMs: 0, decodeMs: 0, tokensPerSecond: 0, timing: { recordMs: 0, gpuMs: 0, readbackMs: 0 } }\n }\n\n // Validate BEFORE mutating fullHistory: a throw must leave the reuse state exactly as it was,\n // or a caller that catches and retries decodes against K/V that was never written.\n // Sink mode: the cache slot no longer tracks fullHistory once the window has rolled, so\n // posBase comes from cacheLen; if the incoming turn does not fit, evict FIRST (the prompt\n // itself must still fit the window - prompt-side trimming stays the caller's job).\n let posBase = reuse ? (roll ? cacheLen : fullHistory.length - 1) : 0 // reuse: the prior last token (uncached) is re-fed, then the delta\n const prefillTokens = reuse ? [fullHistory[fullHistory.length - 1], ...promptTokenIds] : promptTokenIds\n if (prefillTokens.length === 0) throw new Error('generate: no tokens to process')\n if (roll && posBase + prefillTokens.length + 1 > maxSeqLen) {\n if (SINKS + prefillTokens.length + 1 > maxSeqLen)\n throw new Error(`generate: prompt length ${prefillTokens.length} exceeds the rolling window (maxSeqLen ${maxSeqLen} minus ${SINKS} sinks); trim the prompt`)\n await ensureKvCapacity(Math.min(maxSeqLen, posBase + prefillTokens.length)) // eviction copies within allocated rows\n posBase = evict(posBase, posBase + prefillTokens.length + 1 - maxSeqLen)\n cacheLen = posBase\n }\n const room = maxSeqLen - posBase - prefillTokens.length // decode positions left in the KV window\n if (room < 1) throw new Error(`generate: prompt length ${posBase + prefillTokens.length} exceeds maxSeqLen ${maxSeqLen}; trim history or raise maxSeqLen`)\n // In sink mode the window rolls mid-turn, so maxTokens is honored as-is (no window clamp).\n const maxTokens = roll ? (genOpts.maxTokens ?? 256) : Math.min(genOpts.maxTokens ?? 256, room) // clamp instead of throwing: fill the window, stop there\n if (reuse) fullHistory.push(...promptTokenIds) // the delta is now part of the conversation (last token already present)\n else fullHistory = [...promptTokenIds]\n\n if (maxTokens < 1) {\n // maxTokens: 0 - behave like prefill(): write K/V for the prompt (so a later reuseCache\n // turn continues correctly), record the history above, emit nothing. Previously this\n // emitted one token anyway.\n await ensureKvCapacity(posBase + prefillTokens.length)\n transients = []\n try {\n const t0 = performance.now()\n await runPrefill(prefillTokens, posBase, genOpts.signal)\n await device.queue.onSubmittedWorkDone()\n cacheLen = posBase + prefillTokens.length - 1 // sink-mode bookkeeping (last token re-feeds)\n return { tokens: [], prefillMs: performance.now() - t0, decodeMs: 0, tokensPerSecond: 0, timing: { recordMs: 0, gpuMs: 0, readbackMs: 0 } }\n } finally {\n flushTransients()\n transients = null\n }\n }\n\n // A candidateFilter needs the per-step sampler-chain path (candidates on the CPU every\n // token) and cannot speculate (draft verification has no per-row filter state) - so it\n // forces that path and disables promptLookup, as documented on the option. logprobs need\n // the same per-step candidate readback, so they route identically.\n const hasFilter = !!genOpts.candidateFilter || (genOpts.logprobs ?? 0) > 0\n let r: RawGenResult\n if (!hasFilter && genOpts.promptLookup === 'auto' && maxTokens > PLD_PROBATION) {\n // Probation: speculate for the first PLD_PROBATION tokens, then keep PLD only if the\n // measured tokens-per-verify-step clears the plain-decode break-even for this mode;\n // otherwise the rest of the turn runs the plain path. Output is IDENTICAL either way:\n // the continuation re-feeds the last emitted token at its position (the composition the\n // reuse gates prove bit-exact), and a sampled continuation takes over the probation's\n // RNG mid-stream, so the draw sequence is exactly a single run's.\n const r1 = await generatePldImpl(prefillTokens, posBase, PLD_PROBATION, genOpts, fullHistory)\n const E = r1.tokens.length\n if (E < PLD_PROBATION) {\n r = r1 // stopped or aborted inside the window: nothing left to decide\n } else {\n const keep = pldWorthIt(E, r1.spec?.steps ?? 0, sampled || hasProcessors)\n const ids2 = [r1.tokens[E - 1]] // re-feed the last emitted token (its K/V is unwritten)\n const pos2 = posBase + prefillTokens.length + E - 1\n const n2 = maxTokens - E\n let r2: RawGenResult\n if (keep) {\n r2 = await generatePldImpl(ids2, pos2, n2, genOpts, fullHistory, r1.rng)\n } else if (sampled || hasProcessors) {\n r2 = await generateSampledImpl(ids2, pos2, n2, genOpts, fullHistory, r1.rng)\n } else {\n const hist = fullHistory\n r2 = await generateImpl(ids2, pos2, n2, null, SYNC_N, { stopTokens: genOpts.stopTokens, onToken: genOpts.onToken, signal: genOpts.signal })\n hist.push(...r2.tokens) // plain greedy does not touch history; the PLD/sampled impls push their own\n }\n const total = E + r2.tokens.length\n const decodeMs = r1.decodeMs + r2.prefillMs + r2.decodeMs // the 1-token re-feed is decode work\n const w1 = Math.max(1, E - 1)\n const w2 = Math.max(0, r2.tokens.length)\n r = {\n prefillMs: r1.prefillMs,\n decodeMs,\n tokPerSec: Math.max(1, total - 1) / (decodeMs / 1000),\n tokens: [...r1.tokens, ...r2.tokens],\n firstArgmax: r1.firstArgmax,\n recMs: (r1.recMs * w1 + r2.recMs * w2) / (w1 + w2),\n gpuMs: (r1.gpuMs * w1 + r2.gpuMs * w2) / (w1 + w2),\n rbMs: (r1.rbMs * w1 + r2.rbMs * w2) / (w1 + w2),\n spec: {\n steps: (r1.spec?.steps ?? 0) + (r2.spec?.steps ?? 0),\n drafted: (r1.spec?.drafted ?? 0) + (r2.spec?.drafted ?? 0),\n accepted: (r1.spec?.accepted ?? 0) + (r2.spec?.accepted ?? 0),\n bailed: !keep,\n },\n }\n }\n } else if (!hasFilter && genOpts.promptLookup) {\n r = await generatePldImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory) // pushes generated tokens onto fullHistory\n } else if (sampled || hasProcessors || hasFilter) {\n r = await generateSampledImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory) // pushes generated tokens onto fullHistory\n } else {\n // Capture the history array like the sampled/PLD paths do: a resetCache() racing this turn\n // installs a fresh array, and these tokens must land on the OLD one (then next turn falls\n // back to a clean full prefill) instead of populating the reset history against stale K/V.\n const hist = fullHistory\n r = await generateImpl(prefillTokens, posBase, maxTokens, null, SYNC_N, { stopTokens: genOpts.stopTokens, onToken: genOpts.onToken, signal: genOpts.signal })\n hist.push(...r.tokens) // greedy doesn't touch history; record the generated tokens for the next turn\n }\n return {\n tokens: r.tokens,\n prefillMs: r.prefillMs,\n decodeMs: r.decodeMs,\n tokensPerSecond: r.tokPerSec,\n timing: { recordMs: r.recMs, gpuMs: r.gpuMs, readbackMs: r.rbMs },\n ...(r.spec ? { speculation: r.spec } : {}),\n ...(r.lp ? { logprobs: r.lp } : {}),\n }\n }\n\n // Prefill a prompt PREFIX into the KV cache without decoding, then stop. A later\n // generate(delta, {reuseCache:true}) continues from it, so a static system prompt can be warmed at\n // load and the user's first turn becomes a cheap cache-append instead of a full prefill. Like a\n // non-reuse generate's prefill it resets the cache (this prefix becomes the whole history); it\n // writes K/V for EVERY prefilled position, so the reuse path's re-fed last token just overwrites\n // position len-1 idempotently and the result is identical to a cold full prefill.\n async function prefill(ids: number[]): Promise<{ prefillMs: number }> {\n if (ids.length === 0) throw new Error('prefill: no tokens to process')\n if (ids.length > maxSeqLen) throw new Error(`prefill: sequence length ${ids.length} exceeds maxSeqLen ${maxSeqLen}`)\n await ensureKvCapacity(ids.length)\n transients = []\n try {\n const t0 = performance.now()\n await runPrefill(ids, 0) // posBase 0: fresh prefix; writes K/V for every position (segmented)\n await device.queue.onSubmittedWorkDone()\n fullHistory = [...ids]\n cacheLen = ids.length - 1 // sink-mode bookkeeping (last token re-feeds)\n return { prefillMs: performance.now() - t0 }\n } finally {\n flushTransients()\n transients = null\n }\n }\n\n // ---- KV snapshot / restore ----\n // The engine's entire cross-turn state is fullHistory plus the first (fullHistory.length - 1)\n // cached positions of each layer's K/V (the last token's K/V is re-written by the reuse path's\n // re-fed token; see the fullHistory comment). A snapshot captures exactly that, packed into one\n // ArrayBuffer, so restoring it - into this engine or a fresh one on the same model + mode - is\n // bit-identical to having kept the conversation alive. Layout: per layer, K then V region\n // (then Ksc, Vsc under q8), each sized len positions; all region sizes are multiples of 4.\n const kvRowBytes = KV * Dh * KVB // one position of K (or V), per layer\n const scRowBytes = kv8 ? KV * (Dh / 32) * 4 : 0 // one position of q8 block scales\n const snapshotBytes = (len: number): number => A.layers * 2 * len * (kvRowBytes + scRowBytes)\n\n async function saveCache(): Promise<KvSnapshot | null> {\n if (fullHistory.length === 0) return null\n const len = roll ? cacheLen : fullHistory.length - 1 // rolled cache: slots, not history\n const data = new ArrayBuffer(snapshotBytes(len))\n if (len > 0) {\n const rb = device.createBuffer({ size: snapshotBytes(len), usage: GPUBufferUsage.MAP_READ | CD })\n const enc = device.createCommandEncoder()\n let off = 0\n for (let li = 0; li < A.layers; li++) {\n enc.copyBufferToBuffer(Kc[li], 0, rb, off, len * kvRowBytes)\n off += len * kvRowBytes\n enc.copyBufferToBuffer(Vc[li], 0, rb, off, len * kvRowBytes)\n off += len * kvRowBytes\n if (kv8) {\n enc.copyBufferToBuffer(Ksc[li], 0, rb, off, len * scRowBytes)\n off += len * scRowBytes\n enc.copyBufferToBuffer(Vsc[li], 0, rb, off, len * scRowBytes)\n off += len * scRowBytes\n }\n }\n device.queue.submit([enc.finish()])\n await rb.mapAsync(GPUMapMode.READ)\n new Uint8Array(data).set(new Uint8Array(rb.getMappedRange()))\n rb.unmap()\n rb.destroy()\n }\n return {\n version: roll ? 2 : 1, // v2 = unroped keys + rolled window; only restores into sink mode\n kvCache: capabilities.kvCache,\n model: { layers: A.layers, kvHeads: KV, headDim: Dh, hidden: Hd, vocab: A.vocab },\n ids: [...fullHistory],\n ...(roll ? { roll: { sinkTokens: SINKS, cacheLen } } : {}),\n data,\n }\n }\n\n async function restoreCache(snap: KvSnapshot): Promise<void> {\n if (!snap || (snap.version !== 1 && snap.version !== 2)) throw new Error(`restoreCache: unsupported snapshot version ${snap?.version}`)\n if ((snap.version === 2) !== roll)\n throw new Error(\n snap.version === 2 ?\n \"restoreCache: snapshot was saved under overflow 'sinks' (unroped keys); this engine runs overflow 'error'\"\n : \"restoreCache: snapshot was saved under overflow 'error' (roped keys); this engine runs overflow 'sinks'\",\n )\n if (snap.version === 2 && snap.roll?.sinkTokens !== SINKS)\n throw new Error(`restoreCache: snapshot uses ${snap.roll?.sinkTokens} sink tokens but this engine uses ${SINKS}`)\n if (snap.kvCache !== capabilities.kvCache)\n throw new Error(`restoreCache: snapshot was saved under kvCache '${snap.kvCache}' but this engine runs '${capabilities.kvCache}' - snapshots do not convert across modes`)\n const m = snap.model\n if (!m || m.layers !== A.layers || m.kvHeads !== KV || m.headDim !== Dh || m.hidden !== Hd || m.vocab !== A.vocab)\n throw new Error('restoreCache: snapshot is from a different model (architecture mismatch)')\n if (!Array.isArray(snap.ids) || snap.ids.length === 0) throw new Error('restoreCache: snapshot holds no tokens')\n const len = snap.version === 2 ? snap.roll!.cacheLen : snap.ids.length - 1\n if (len + 1 > maxSeqLen)\n throw new Error(`restoreCache: snapshot needs ${len + 1} cache slots but maxSeqLen is ${maxSeqLen}`)\n if (snap.data.byteLength !== snapshotBytes(len))\n throw new Error(`restoreCache: snapshot data is ${snap.data.byteLength} bytes, expected ${snapshotBytes(len)}`)\n await ensureKvCapacity(len)\n let off = 0\n for (let li = 0; li < A.layers; li++) {\n device.queue.writeBuffer(Kc[li], 0, snap.data, off, len * kvRowBytes)\n off += len * kvRowBytes\n device.queue.writeBuffer(Vc[li], 0, snap.data, off, len * kvRowBytes)\n off += len * kvRowBytes\n if (kv8) {\n device.queue.writeBuffer(Ksc[li], 0, snap.data, off, len * scRowBytes)\n off += len * scRowBytes\n device.queue.writeBuffer(Vsc[li], 0, snap.data, off, len * scRowBytes)\n off += len * scRowBytes\n }\n }\n fullHistory = [...snap.ids]\n cacheLen = len\n }\n\n // The engine shares one KV cache, buffer pool, and flag set across calls, so concurrent\n // generate/prefill/forward would corrupt each other. Serialize them: overlapping calls queue\n // instead of interleaving (npm consumers do not all have the app's single-flight worker).\n let opChain: Promise<unknown> = Promise.resolve()\n const serialize = <Args extends unknown[], R>(fn: (...args: Args) => Promise<R>): ((...args: Args) => Promise<R>) => {\n return (...args: Args) => {\n const run = opChain.then(\n () => fn(...args),\n () => fn(...args), // a failed predecessor must not poison the queue\n )\n opChain = run.catch(() => undefined)\n return run\n }\n }\n\n const api: EngineInternal = {\n generate: serialize(generate),\n prefill: serialize(prefill),\n forward: serialize(forward),\n saveCache: serialize(saveCache),\n restoreCache: serialize(restoreCache),\n resetCache,\n capabilities,\n lost,\n dispose: () => device.destroy(),\n device,\n adapter,\n profileDecode: (ids, nTokens, full = null, syncN = SYNC_N) => generateImpl(ids, 0, nTokens, full, syncN),\n debugDecode,\n debugSampler,\n }\n return api\n}\n"],"mappings":";AACA,MAAa,UAAkC;CAC7C,OAAO;CACP,UAAU;CACV,iBAAiB;CACjB,gBAAgB;CAChB,qBAAqB;CACrB,0BAA0B;CAC1B,oBAAoB;CACpB,yBAAyB;CACzB,qBAAqB;CACrB,gBAAgB;CAChB,qBAA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