bitgpu 0.1.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 ADDED
@@ -0,0 +1,1981 @@
1
+ //#region src/shaders.generated.ts
2
+ const SHADERS = {
3
+ "add": "// Elementwise residual add: y[i] = a[i] + b[i].\nstruct Params { n: u32, _p0: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> a: array<f32>;\n@group(0) @binding(2) var<storage, read> b: array<f32>;\n@group(0) @binding(3) var<storage, read_write> y: array<f32>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.n) { return; }\n y[i] = a[i] + b[i];\n}\n",
4
+ "argmax": "// GPU argmax over the logits, writing one token id into a GPU buffer so the token never leaves the\n// GPU (enables the deferred-sync decode loop). Single workgroup, WG threads strided-scan the N\n// logits tracking (maxVal, maxIdx), then a shared-mem tree reduction. Tie-break = LOWEST index, to\n// match the CPU argmax (strict > keeps the first max). No subgroup ops -> all devices.\noverride WG: u32 = 256u;\nstruct Params { N: u32, outIdx: u32, _0: u32, _1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> logits: array<f32>;\n@group(0) @binding(2) var<storage, read_write> outTok: array<u32>; // outTok[p.outIdx] = argmax\n\nvar<workgroup> sval: array<f32, 256>;\nvar<workgroup> sidx: array<u32, 256>;\n\n@compute @workgroup_size(WG)\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\n let tid = lid.x;\n var bv = -3.4e38;\n var bi = 0u;\n for (var i = tid; i < p.N; i = i + WG) {\n let v = logits[i];\n if (v > bv) { bv = v; bi = i; } // strict > keeps the lowest index within this thread's stride\n }\n sval[tid] = bv; sidx[tid] = bi;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s) {\n let ov = sval[tid + s]; let oi = sidx[tid + s];\n if (ov > sval[tid] || (ov == sval[tid] && oi < sidx[tid])) { sval[tid] = ov; sidx[tid] = oi; }\n }\n workgroupBarrier();\n }\n if (tid == 0u) { outTok[p.outIdx] = sidx[0]; }\n}\n",
5
+ "argmax_masked": "// Masked argmax: like argmax.wgsl but skips any id already chosen in a prior round, and writes BOTH\n// the winning id and its logit value. Calling it K times (roundCount = 0..K-1, all in one compute\n// pass so each round sees the prior rounds' writes) yields the exact top-K (id, logit) pairs in\n// descending order = ONNX TopK over the (penalty-filtered) logits, which is what the transformers.js\n// sampler consumes. Then only K pairs are read back (not the full vocab), and the CPU does\n// temperature + softmax + multinomial. Single workgroup, no subgroup ops -> all devices. Tie-break =\n// lowest index (strict >), matching argmax.wgsl / ORT TopK in practice.\noverride WG: u32 = 256u;\nstruct Params { N: u32, roundCount: u32, _0: u32, _1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> logits: array<f32>;\n@group(0) @binding(2) var<storage, read_write> candIds: array<u32>; // [K]; reads 0..roundCount-1, writes [roundCount]\n@group(0) @binding(3) var<storage, read_write> candVals: array<f32>; // [K]; writes [roundCount]\n\nvar<workgroup> sval: array<f32, 256>;\nvar<workgroup> sidx: array<u32, 256>;\n\n@compute @workgroup_size(WG)\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\n let tid = lid.x;\n var bv = -3.4e38;\n var bi = 0u;\n for (var i = tid; i < p.N; i = i + WG) {\n let v = logits[i];\n if (v > bv) {\n var skip = false;\n for (var r = 0u; r < p.roundCount; r = r + 1u) { if (candIds[r] == i) { skip = true; break; } }\n if (!skip) { bv = v; bi = i; } // strict > keeps the lowest index within this thread's stride\n }\n }\n sval[tid] = bv; sidx[tid] = bi;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s) {\n let ov = sval[tid + s]; let oi = sidx[tid + s];\n if (ov > sval[tid] || (ov == sval[tid] && oi < sidx[tid])) { sval[tid] = ov; sidx[tid] = oi; }\n }\n workgroupBarrier();\n }\n if (tid == 0u) { candIds[p.roundCount] = sidx[0]; candVals[p.roundCount] = sval[0]; }\n}\n",
6
+ "attention_cache": "// Causal GQA attention reading K/V from the persistent cache. Handles both prefill\n// (S queries at positions posBase..posBase+S-1) and decode (S=1). Query head h reads\n// KV head h/(H/KV). Each query at absolute position pos attends to cache[0..pos].\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(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) { 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 invscale = 1.0 / sqrt(f32(p.D));\n let qbase = (qi * p.H + h) * p.D;\n\n var m = -1e30;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n var dot = 0.0;\n for (var d = 0u; d < p.D; d = d + 1u) { dot = dot + q[qbase + d] * Kc[kb + d]; }\n m = max(m, dot * invscale);\n }\n\n var acc: array<f32, 128>;\n for (var d = 0u; d < p.D; d = d + 1u) { acc[d] = 0.0; }\n var denom = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n var dot = 0.0;\n for (var d = 0u; d < p.D; d = d + 1u) { dot = dot + q[qbase + d] * Kc[kb + d]; }\n let w = exp(dot * invscale - m);\n denom = denom + w;\n for (var d = 0u; d < p.D; d = d + 1u) { acc[d] = acc[d] + w * Vc[kb + d]; }\n }\n\n let ob = (qi * p.H + h) * p.D;\n for (var d = 0u; d < p.D; d = d + 1u) { out[ob + d] = acc[d] / denom; }\n}\n",
7
+ "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 (>=32 so head_dim/SG <= 4). 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; // <= 4 for SG>=32, D=128\n\n var acc: array<f32, 4>;\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",
8
+ "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",
9
+ "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*256] 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*16]\n@group(0) @binding(5) var<storage, read> embZp: array<u32>; // uint8 [vocab*8] 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 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 * 256u + 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 * 8u + (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 * 16u + blk];\n }\n}\n",
10
+ "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",
11
+ "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",
12
+ "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",
13
+ "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",
14
+ "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",
15
+ "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",
16
+ "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",
17
+ "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",
18
+ "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",
19
+ "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",
20
+ "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",
21
+ "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",
22
+ "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",
23
+ "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 64-wide tile lies in one range (N0,N1 multiples of 64)\n// so a workgroup routes its whole tile to out0/out1/out2. Same vec4 design as 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",
24
+ "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",
25
+ "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",
26
+ "rmsnorm": "// RMSNorm: y[r,d] = x[r,d] / sqrt(mean_d(x^2) + eps) * gamma[d]. One invocation per row.\nstruct Params { R: u32, D: u32, eps: f32, _pad: u32 };\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]\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 r = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (r >= p.R) { return; }\n let base = r * p.D;\n var ss = 0.0;\n for (var d = 0u; d < p.D; d = d + 1u) {\n let v = x[base + d];\n ss = ss + v * v;\n }\n let inv = inverseSqrt(ss / f32(p.D) + p.eps);\n for (var d = 0u; d < p.D; d = d + 1u) {\n y[base + d] = x[base + d] * inv * gamma[d];\n }\n}\n",
27
+ "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",
28
+ "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",
29
+ "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",
30
+ "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",
31
+ "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"
32
+ };
33
+ //#endregion
34
+ //#region src/errors.ts
35
+ /** Thrown when WebGPU is unavailable: no `navigator.gpu` (unsupported browser, or a
36
+ * non-secure context) or no adapter could be acquired. Catch this to render a
37
+ * "your browser doesn't support WebGPU yet" fallback instead of crashing. */
38
+ var WebGPUUnavailableError = class extends Error {
39
+ name = "WebGPUUnavailableError";
40
+ constructor(message) {
41
+ super(message);
42
+ }
43
+ };
44
+ /** Thrown when the GPU reports out-of-memory while the engine allocates weights or grows the
45
+ * KV cache. Without this check the allocation "succeeds" with invalid buffers and every later
46
+ * generate() returns garbage. Catch it to fall back (smaller maxSeqLen, or a no-LLM mode). */
47
+ var GpuOutOfMemoryError = class extends Error {
48
+ name = "GpuOutOfMemoryError";
49
+ constructor(message) {
50
+ super(message);
51
+ }
52
+ };
53
+ //#endregion
54
+ //#region src/pld.ts
55
+ /** Return up to `maxDraft` draft tokens: the continuation after the most recent prior occurrence
56
+ * of the trailing g-gram, trying g = ngramSize down to 2 (1-grams draft too noisily to pay off).
57
+ * Empty when nothing matches. */
58
+ function draftNgram(seq, ngramSize, maxDraft) {
59
+ if (maxDraft <= 0) return [];
60
+ for (let g = Math.min(ngramSize, seq.length - 1); g >= 2; g--) {
61
+ const start = seq.length - g;
62
+ outer: for (let i = start - 1; i >= 0; i--) {
63
+ for (let j = 0; j < g; j++) if (seq[i + j] !== seq[start + j]) continue outer;
64
+ const from = i + g;
65
+ return seq.slice(from, Math.min(from + maxDraft, seq.length));
66
+ }
67
+ }
68
+ return [];
69
+ }
70
+ //#endregion
71
+ //#region src/sampler.ts
72
+ /** Mersenne Twister 19937, matching transformers.js utils/random.js (= Python's random.Random). */
73
+ var MT19937 = class {
74
+ mt = /* @__PURE__ */ new Uint32Array(624);
75
+ idx = 625;
76
+ constructor(seed) {
77
+ this.seed(seed);
78
+ }
79
+ seed(n) {
80
+ if (n === void 0 || n === null) {
81
+ const buf = /* @__PURE__ */ new Uint32Array(1);
82
+ crypto.getRandomValues(buf);
83
+ n = buf[0];
84
+ }
85
+ const mt = this.mt;
86
+ const u = (a, b) => Math.imul(a, b) >>> 0;
87
+ const key = [];
88
+ for (let v = n || 0; v > 0; v = Math.floor(v / 4294967296)) key.push(v & 4294967295);
89
+ if (!key.length) key.push(0);
90
+ mt[0] = 19650218;
91
+ for (let k = 1; k < 624; ++k) mt[k] = u(1812433253, mt[k - 1] ^ mt[k - 1] >>> 30) + k >>> 0;
92
+ let i = 1;
93
+ let j = 0;
94
+ for (let k = Math.max(624, key.length); k > 0; --k, ++i, ++j) {
95
+ if (i >= 624) {
96
+ mt[0] = mt[623];
97
+ i = 1;
98
+ }
99
+ if (j >= key.length) j = 0;
100
+ mt[i] = (mt[i] ^ u(mt[i - 1] ^ mt[i - 1] >>> 30, 1664525)) + key[j] + j >>> 0;
101
+ }
102
+ for (let k = 623; k > 0; --k, ++i) {
103
+ if (i >= 624) {
104
+ mt[0] = mt[623];
105
+ i = 1;
106
+ }
107
+ mt[i] = (mt[i] ^ u(mt[i - 1] ^ mt[i - 1] >>> 30, 1566083941)) - i >>> 0;
108
+ }
109
+ mt[0] = 2147483648;
110
+ this.idx = 624;
111
+ }
112
+ int32() {
113
+ const mt = this.mt;
114
+ if (this.idx >= 624) {
115
+ for (let k = 0; k < 624; ++k) {
116
+ const y = mt[k] & 2147483648 | mt[(k + 1) % 624] & 2147483647;
117
+ mt[k] = (mt[(k + 397) % 624] ^ y >>> 1 ^ (y & 1 ? 2567483615 : 0)) >>> 0;
118
+ }
119
+ this.idx = 0;
120
+ }
121
+ let y = mt[this.idx++];
122
+ y ^= y >>> 11;
123
+ y ^= y << 7 & 2636928640;
124
+ y ^= y << 15 & 4022730752;
125
+ y ^= y >>> 18;
126
+ return y >>> 0;
127
+ }
128
+ /** Uniform float in [0, 1), matching Python's random.random(). */
129
+ random() {
130
+ return ((this.int32() >>> 5) * 67108864 + (this.int32() >>> 6)) / 9007199254740992;
131
+ }
132
+ };
133
+ /** Deduped set of token ids that repetition_penalty applies to (the full prompt+generated history). */
134
+ function affectedIds(history) {
135
+ return Uint32Array.from(new Set(history));
136
+ }
137
+ /** no_repeat_ngram banned next-tokens for the current step. Faithful port of
138
+ * NoRepeatNGramLogitsProcessor.calcBannedNgramTokens (transformers.js v4.2.0). */
139
+ function ngramBans(history, n) {
140
+ if (history.length + 1 < n) return [];
141
+ const generated = /* @__PURE__ */ new Map();
142
+ for (let j = 0; j < history.length + 1 - n; ++j) {
143
+ const ngram = [];
144
+ for (let k = 0; k < n; ++k) ngram.push(history[j + k]);
145
+ const key = JSON.stringify(ngram.slice(0, n - 1));
146
+ const arr = generated.get(key) ?? [];
147
+ arr.push(ngram[n - 1]);
148
+ generated.set(key, arr);
149
+ }
150
+ const idx = history.slice(history.length + 1 - n, history.length);
151
+ return generated.get(JSON.stringify(idx)) ?? [];
152
+ }
153
+ /** Stable softmax (max-subtract), matching transformers.js utils/maths.js softmax. */
154
+ function softmax(arr) {
155
+ let maxVal = arr[0];
156
+ for (let i = 1; i < arr.length; ++i) if (arr[i] > maxVal) maxVal = arr[i];
157
+ const exps = Array.from(arr, (x) => Math.exp(x - maxVal));
158
+ let sum = 0;
159
+ for (const e of exps) sum += e;
160
+ return exps.map((x) => x / sum);
161
+ }
162
+ /** Final sampling tail. `candVals` are the K largest PENALTY-FILTERED logits (descending), `candIds`
163
+ * their token ids. Applies temperature to the K values, softmaxes, then draws via the exact
164
+ * transformers.js inverse-CDF weighted pick (x = random()*sum; subtract until <0). Returns a token id. */
165
+ function sampleFromCandidates(candIds, candVals, temperature, rng) {
166
+ const k = candVals.length;
167
+ const tv = new Float32Array(k);
168
+ for (let i = 0; i < k; ++i) tv[i] = candVals[i] / temperature;
169
+ const probs = softmax(tv);
170
+ let sum = 0;
171
+ for (const pr of probs) sum += pr;
172
+ let x = rng.random() * sum;
173
+ for (let i = 0; i < k; ++i) {
174
+ x -= probs[i];
175
+ if (x < 0) return candIds[i];
176
+ }
177
+ return candIds[k - 1];
178
+ }
179
+ //#endregion
180
+ //#region src/engine.ts
181
+ const VIEW = {
182
+ FLOAT: Float32Array,
183
+ UINT8: Uint8Array,
184
+ FLOAT16: Uint16Array
185
+ };
186
+ const WGSLS = [
187
+ "matmul_split",
188
+ "matmul_resid",
189
+ "matmul_q2",
190
+ "rmsnorm",
191
+ "rope",
192
+ "swiglu",
193
+ "attention_cache",
194
+ "copy"
195
+ ];
196
+ const DEFAULT_MAX_SEQ = 2048;
197
+ const PARAM_AB = /* @__PURE__ */ new ArrayBuffer(64);
198
+ const PARAM_DV = new DataView(PARAM_AB);
199
+ const PARAM_U8 = new Uint8Array(PARAM_AB);
200
+ function makeParams(fields) {
201
+ for (let i = 0; i < fields.length; i++) {
202
+ const f = fields[i];
203
+ if (f[0] === "f") PARAM_DV.setFloat32(i * 4, f[1], true);
204
+ else PARAM_DV.setUint32(i * 4, f[1] >>> 0, true);
205
+ }
206
+ return PARAM_U8.subarray(0, Math.ceil(fields.length / 4) * 16);
207
+ }
208
+ const eqBytes = (a, b) => {
209
+ for (let i = 0; i < b.length; i++) if (a[i] !== b[i]) return false;
210
+ return true;
211
+ };
212
+ function concat(Cls, arrs) {
213
+ let n = 0;
214
+ for (const a of arrs) n += a.length;
215
+ const o = new Cls(n);
216
+ let p = 0;
217
+ for (const a of arrs) {
218
+ o.set(a, p);
219
+ p += a.length;
220
+ }
221
+ return o;
222
+ }
223
+ /** Load a 1-bit model and return an {@link Engine}. Pass a model URL string for defaults. */
224
+ async function createEngine(options) {
225
+ const opts = typeof options === "string" ? { modelUrl: options } : options;
226
+ const modelDir = opts.modelUrl ? opts.modelUrl.replace(/\/$/, "") : null;
227
+ if (!modelDir && !opts.manifestUrl) throw new Error("createEngine: provide modelUrl or manifestUrl");
228
+ const powerPreference = opts.powerPreference ?? "high-performance";
229
+ const fetchJson = opts.fetchJson ?? (async (url) => {
230
+ const res = await fetch(url);
231
+ if (!res.ok) throw new Error(`bitgpu: fetch ${url} failed: HTTP ${res.status}`);
232
+ if ((res.headers.get("content-type") ?? "").includes("text/html")) throw new Error(`bitgpu: ${url} returned HTML, not JSON (a SPA fallback is probably serving index.html for missing model files)`);
233
+ return res.json();
234
+ });
235
+ const fetchBytes = opts.fetchArrayBuffer ?? (async (url) => {
236
+ const res = await fetch(url);
237
+ if (!res.ok) throw new Error(`bitgpu: fetch ${url} failed: HTTP ${res.status}`);
238
+ const total = Number(res.headers.get("content-length") ?? 0);
239
+ if (!res.body || !total) return res.arrayBuffer();
240
+ const reader = res.body.getReader();
241
+ const chunks = [];
242
+ let loaded = 0;
243
+ for (;;) {
244
+ const { done, value } = await reader.read();
245
+ if (done) break;
246
+ chunks.push(value);
247
+ loaded += value.byteLength;
248
+ opts.onProgress?.({
249
+ phase: "weights",
250
+ loaded,
251
+ total
252
+ });
253
+ }
254
+ const out = new Uint8Array(loaded);
255
+ let p = 0;
256
+ for (const c of chunks) {
257
+ out.set(c, p);
258
+ p += c.byteLength;
259
+ }
260
+ return out.buffer;
261
+ });
262
+ if (typeof navigator === "undefined" || !navigator.gpu) throw new WebGPUUnavailableError("WebGPU is not available (no navigator.gpu). Use a WebGPU-capable browser over a secure context.");
263
+ opts.onProgress?.({ phase: "manifest" });
264
+ const manifest = await fetchJson(opts.manifestUrl ?? `${modelDir}/manifest.json`);
265
+ opts.onProgress?.({ phase: "weights" });
266
+ const dataUrl = opts.dataUrl ?? `${modelDir}/${manifest.data_file}`;
267
+ const auxUrl = opts.auxUrl ?? `${modelDir}/${manifest.aux_file}`;
268
+ let [data, aux] = await Promise.all([fetchBytes(dataUrl), fetchBytes(auxUrl)]);
269
+ const A = manifest.arch;
270
+ const T = manifest.tensors;
271
+ const FINAL_NORM = `layers.${A.layers}.final_norm_layernorm`;
272
+ if (A.act !== "silu") throw new Error(`bitgpu: unsupported activation '${A.act}' (kernels implement silu/SwiGLU)`);
273
+ if (A.head_dim > 128) throw new Error(`bitgpu: unsupported head_dim ${A.head_dim} (kernels assume <= 128)`);
274
+ if (!T[FINAL_NORM]) throw new Error(`bitgpu: manifest is missing the final norm tensor '${FINAL_NORM}'`);
275
+ for (const [name, t] of Object.entries(T)) if (t.block !== void 0 && t.block !== 128) throw new Error(`bitgpu: tensor ${name} has block ${t.block} (kernels assume 128)`);
276
+ const readRef = (ref) => {
277
+ const src = ref.src === "aux" ? aux : data;
278
+ if (ref.off + ref.len > src.byteLength) throw new Error(`bitgpu: tensor range ${ref.off}+${ref.len} exceeds the ${ref.src === "aux" ? "aux" : "data"} file (${src.byteLength} bytes); the download is truncated or the manifest does not match it`);
279
+ const V = VIEW[ref.dtype];
280
+ if (V === Uint8Array) return new Uint8Array(src, ref.off, ref.len);
281
+ const bpe = V.BYTES_PER_ELEMENT;
282
+ if (ref.off % bpe === 0) return new V(src, ref.off, ref.len / bpe);
283
+ return new V(src.slice(ref.off, ref.off + ref.len));
284
+ };
285
+ const readU8 = (ref) => readRef(ref);
286
+ const readF32 = (ref) => readRef(ref);
287
+ const adapter = await navigator.gpu.requestAdapter({ powerPreference });
288
+ if (!adapter) throw new WebGPUUnavailableError("No suitable WebGPU adapter was found.");
289
+ const hasSG = adapter.features.has("subgroups");
290
+ const info = adapter.info ?? {};
291
+ const sgMax = info.subgroupMaxSize ?? 32;
292
+ const sgMin = info.subgroupMinSize ?? sgMax;
293
+ const forceNoSG = opts.forceNoSubgroups ?? false;
294
+ const WG_NS = Math.min(256, Math.max(32, 1 << Math.round(Math.log2(opts.noSubgroupWorkgroupSize ?? 64))));
295
+ const NOTILE = opts.prefillTiling === "never";
296
+ const FORCETILE = opts.prefillTiling === "always";
297
+ const tiledPrefill = (S) => FORCETILE || !NOTILE && S >= 64;
298
+ const SYNC_N = Math.max(1, opts.syncSteps ?? 4);
299
+ const maxSeqLen = Math.max(1, opts.maxSeqLen ?? DEFAULT_MAX_SEQ);
300
+ const useSG = hasSG && sgMin === sgMax && (sgMax === 32 || sgMax === 64) && !forceNoSG;
301
+ const device = await adapter.requestDevice({ requiredFeatures: useSG ? ["subgroups"] : [] });
302
+ const lost = device.lost.then((info) => {
303
+ const li = {
304
+ reason: String(info.reason ?? "unknown"),
305
+ message: info.message
306
+ };
307
+ if (li.reason !== "destroyed") opts.onDeviceLost?.(li);
308
+ return li;
309
+ });
310
+ device.addEventListener("uncapturederror", (ev) => {
311
+ console.error(`[bitgpu] uncaptured WebGPU error: ${ev.error.message}`);
312
+ });
313
+ opts.onProgress?.({ phase: "pipelines" });
314
+ const pipelines = {};
315
+ const mkPipe = async (name, constants) => {
316
+ const code = SHADERS[name];
317
+ if (code === void 0) throw new Error(`shader not found: ${name}`);
318
+ const module = device.createShaderModule({
319
+ code,
320
+ label: name
321
+ });
322
+ const err = (await module.getCompilationInfo()).messages.find((m) => m.type === "error");
323
+ if (err) throw new Error(`WGSL compile error in ${name} (L${err.lineNum}:${err.linePos}): ${err.message}`);
324
+ pipelines[name] = await device.createComputePipelineAsync({
325
+ layout: "auto",
326
+ compute: {
327
+ module,
328
+ entryPoint: "main",
329
+ constants
330
+ }
331
+ });
332
+ };
333
+ const ROWS_MR = 4;
334
+ const specs = [
335
+ ...WGSLS.map((n) => [n]),
336
+ ["matmul_split_tiled"],
337
+ ["matmul_resid_tiled"],
338
+ ["argmax"],
339
+ ["embed_gather"],
340
+ ["sampler_penalty"],
341
+ ["argmax_masked"]
342
+ ];
343
+ if (useSG) {
344
+ for (const n of [
345
+ "rmsnorm_sg",
346
+ "attention_sg",
347
+ "matmul_split_sg",
348
+ "matmul_q2_sg",
349
+ "rmsnorm_rope_sg"
350
+ ]) specs.push([n, { SG: sgMax }]);
351
+ for (const n of [
352
+ "matmul_split_sm",
353
+ "matmul_resid_sm",
354
+ "matmul_q2_sm"
355
+ ]) specs.push([n, { SG: sgMax }]);
356
+ for (const n of ["matmul_resid_mr_sg", "matmul_swiglu_mr_sg"]) specs.push([n, {
357
+ SG: sgMax,
358
+ ROWS: ROWS_MR
359
+ }]);
360
+ } else for (const n of [
361
+ "matmul_split_wg",
362
+ "matmul_resid_wg",
363
+ "matmul_q2_wg"
364
+ ]) specs.push([n, { WG: WG_NS }]);
365
+ await Promise.all(specs.map(([n, c]) => mkPipe(n, c)));
366
+ const S_ = GPUBufferUsage.STORAGE, CD = GPUBufferUsage.COPY_DST, CS = GPUBufferUsage.COPY_SRC, U = GPUBufferUsage.UNIFORM;
367
+ let transients = null;
368
+ const flushTransients = () => {
369
+ if (!transients) return;
370
+ for (const b of transients) b.destroy();
371
+ transients = [];
372
+ };
373
+ const upload = (typed, usage = S_ | CD) => {
374
+ const b = device.createBuffer({
375
+ size: typed.byteLength,
376
+ usage
377
+ });
378
+ device.queue.writeBuffer(b, 0, typed);
379
+ transients?.push(b);
380
+ return b;
381
+ };
382
+ const pools = {};
383
+ let pool = null;
384
+ let bufIdx = 0;
385
+ let dispIdx = 0;
386
+ let poolRoundFrom = 0;
387
+ let poolRoundTo = 0;
388
+ const poolUse = (name, roundFrom = 0, roundTo = 0) => {
389
+ pool = name ? pools[name] ??= {
390
+ buf: [],
391
+ disp: []
392
+ } : null;
393
+ poolRoundFrom = roundFrom;
394
+ poolRoundTo = roundTo;
395
+ bufIdx = 0;
396
+ dispIdx = 0;
397
+ };
398
+ const poolInvalidate = () => {
399
+ for (const p of Object.values(pools)) for (const s of p.disp) {
400
+ s.bg = null;
401
+ s.last = null;
402
+ }
403
+ };
404
+ const actBuf = (n) => {
405
+ if (!pool) {
406
+ const b = device.createBuffer({
407
+ size: n * 4,
408
+ usage: S_ | CS | CD
409
+ });
410
+ transients?.push(b);
411
+ return b;
412
+ }
413
+ const alloc = poolRoundFrom > 0 ? n / poolRoundFrom * poolRoundTo : n;
414
+ let b = pool.buf[bufIdx];
415
+ if (!b || b.size !== alloc * 4) {
416
+ b = device.createBuffer({
417
+ size: alloc * 4,
418
+ usage: S_ | CS | CD
419
+ });
420
+ pool.buf[bufIdx] = b;
421
+ }
422
+ bufIdx++;
423
+ return b;
424
+ };
425
+ const dummy = device.createBuffer({
426
+ size: 16,
427
+ usage: S_
428
+ });
429
+ let fullHistory = [];
430
+ const resetCache = () => {
431
+ fullHistory = [];
432
+ };
433
+ const tgt2 = readU8(manifest.luts.tgt2);
434
+ let tgt4 = readU8(manifest.luts.tgt4);
435
+ const signTable = /* @__PURE__ */ new Uint8Array(256);
436
+ for (let b = 0; b < 256; b++) {
437
+ let bits = 0;
438
+ for (let j = 0; j < 8; j++) bits |= ((tgt2[2 * b + (j >> 2)] >> 2 * (j & 3) & 3) >> 1 & 1) << j;
439
+ signTable[b] = bits;
440
+ }
441
+ const rawBin = (name) => {
442
+ const t = T[name];
443
+ const wq = readU8(t.weight);
444
+ const sign = new Uint8Array(wq.length);
445
+ for (let i = 0; i < wq.length; i++) sign[i] = signTable[wq[i]];
446
+ return {
447
+ sign,
448
+ scales: readF32(t.scales),
449
+ N: t.N,
450
+ K: t.K,
451
+ nb: t.K / 128
452
+ };
453
+ };
454
+ device.pushErrorScope("out-of-memory");
455
+ const W = {};
456
+ for (const [name, t] of Object.entries(T)) if (t.kind === "q2") {
457
+ const wq = readU8(t.weight), codes = new Uint8Array(wq.length * 2);
458
+ for (let i = 0; i < wq.length; i++) {
459
+ codes[2 * i] = tgt2[2 * wq[i]];
460
+ codes[2 * i + 1] = tgt2[2 * wq[i] + 1];
461
+ }
462
+ W[name] = {
463
+ N: t.N,
464
+ K: t.K,
465
+ nb: t.K / 128,
466
+ zp: 2,
467
+ codes: upload(codes),
468
+ scales: upload(readF32(t.scales))
469
+ };
470
+ } else if (t.kind === "f32" && t.weight) W[name] = { buf: upload(readRef(t.weight)) };
471
+ for (let li = 0; li < A.layers; li++) {
472
+ const q = rawBin(`layers.${li}.attn.q_proj`), k = rawBin(`layers.${li}.attn.k_proj`), v = rawBin(`layers.${li}.attn.v_proj`);
473
+ W[`layers.${li}.attn.qkv`] = {
474
+ K: q.K,
475
+ nb: q.nb,
476
+ N0: q.N,
477
+ N1: k.N,
478
+ N2: v.N,
479
+ sign: upload(concat(Uint8Array, [
480
+ q.sign,
481
+ k.sign,
482
+ v.sign
483
+ ])),
484
+ scales: upload(concat(Float32Array, [
485
+ q.scales,
486
+ k.scales,
487
+ v.scales
488
+ ]))
489
+ };
490
+ const g = rawBin(`layers.${li}.mlp.gate_proj`), u = rawBin(`layers.${li}.mlp.up_proj`);
491
+ W[`layers.${li}.mlp.gateup`] = {
492
+ K: g.K,
493
+ nb: g.nb,
494
+ N0: g.N,
495
+ N1: u.N,
496
+ N2: 0,
497
+ sign: upload(concat(Uint8Array, [g.sign, u.sign])),
498
+ scales: upload(concat(Float32Array, [g.scales, u.scales]))
499
+ };
500
+ for (const nm of [`layers.${li}.attn.o_proj`, `layers.${li}.mlp.down_proj`]) {
501
+ const r = rawBin(nm);
502
+ W[nm] = {
503
+ N: r.N,
504
+ K: r.K,
505
+ nb: r.nb,
506
+ sign: upload(r.sign),
507
+ scales: upload(r.scales)
508
+ };
509
+ }
510
+ }
511
+ let embWq = readU8(T.embed_tokens.weight), embScales = readF32(T.embed_tokens.scales), embZp = readU8(T.embed_tokens.zp);
512
+ let cosCache = readF32(T.cos_cache), sinCache = readF32(T.sin_cache);
513
+ const embWqG = upload(embWq), tgt4G = upload(tgt4), embScalesG = upload(embScales), embZpG = upload(embZp);
514
+ embWq = embWq.slice();
515
+ embScales = embScales.slice();
516
+ embZp = embZp.slice();
517
+ cosCache = cosCache.slice();
518
+ sinCache = sinCache.slice();
519
+ tgt4 = tgt4.slice();
520
+ data = null;
521
+ aux = null;
522
+ function embedDequant(ids) {
523
+ const Hh = A.hidden, out = new Float32Array(ids.length * Hh);
524
+ for (let r = 0; r < ids.length; r++) {
525
+ const id = ids[r];
526
+ for (let i = 0; i < 256; i++) for (let qd = 0; qd < 4; qd++) {
527
+ const byte = tgt4[4 * embWq[id * 256 + i] + qd], baseK = (i * 4 + qd) * 2;
528
+ for (let c = 0; c < 2; c++) {
529
+ const k = baseK + c, code = byte >> 4 * c & 15, blk = k / 128 | 0;
530
+ const zp = embZp[id * 8 + (blk / 2 | 0)] >> 4 * (blk & 1) & 15;
531
+ out[r * Hh + k] = (code - zp) * embScales[id * 16 + blk];
532
+ }
533
+ }
534
+ }
535
+ return out;
536
+ }
537
+ function ropeBufs(posBase, S) {
538
+ const D = A.head_dim, R = D / 2, cos = new Float32Array(S * D), sin = new Float32Array(S * D);
539
+ for (let s = 0; s < S; s++) for (let d = 0; d < D; d++) {
540
+ cos[s * D + d] = cosCache[(posBase + s) * R + d % R];
541
+ sin[s * D + d] = sinCache[(posBase + s) * R + d % R];
542
+ }
543
+ const cb = actBuf(S * D), sb = actBuf(S * D);
544
+ device.queue.writeBuffer(cb, 0, cos);
545
+ device.queue.writeBuffer(sb, 0, sin);
546
+ return {
547
+ cos: cb,
548
+ sin: sb
549
+ };
550
+ }
551
+ const KV = A.kv_heads, Dh = A.head_dim, Hd = A.hidden, H = A.heads, F = A.intermediate;
552
+ let kvCapacity = Math.min(maxSeqLen, 512);
553
+ const Kc = [], Vc = [];
554
+ for (let li = 0; li < A.layers; li++) {
555
+ Kc.push(actBuf(kvCapacity * KV * Dh));
556
+ Vc.push(actBuf(kvCapacity * KV * Dh));
557
+ }
558
+ const loadOom = await device.popErrorScope();
559
+ if (loadOom) throw new GpuOutOfMemoryError(`GPU allocation failed while loading weights (~350 MB VRAM needed): ${loadOom.message}`);
560
+ async function ensureKvCapacity(needed) {
561
+ if (needed <= kvCapacity) return;
562
+ const newCap = Math.min(maxSeqLen, Math.max(needed, kvCapacity * 2));
563
+ const copyBytes = kvCapacity * KV * Dh * 4;
564
+ device.pushErrorScope("out-of-memory");
565
+ const enc = device.createCommandEncoder();
566
+ const olds = [];
567
+ for (let li = 0; li < A.layers; li++) {
568
+ const nk = device.createBuffer({
569
+ size: newCap * KV * Dh * 4,
570
+ usage: S_ | CS | CD
571
+ });
572
+ const nv = device.createBuffer({
573
+ size: newCap * KV * Dh * 4,
574
+ usage: S_ | CS | CD
575
+ });
576
+ enc.copyBufferToBuffer(Kc[li], 0, nk, 0, copyBytes);
577
+ enc.copyBufferToBuffer(Vc[li], 0, nv, 0, copyBytes);
578
+ olds.push(Kc[li], Vc[li]);
579
+ Kc[li] = nk;
580
+ Vc[li] = nv;
581
+ }
582
+ device.queue.submit([enc.finish()]);
583
+ await device.queue.onSubmittedWorkDone();
584
+ const oom = await device.popErrorScope();
585
+ if (oom) {
586
+ for (let li = 0; li < A.layers; li++) {
587
+ Kc[li].destroy();
588
+ Vc[li].destroy();
589
+ Kc[li] = olds[2 * li];
590
+ Vc[li] = olds[2 * li + 1];
591
+ }
592
+ poolInvalidate();
593
+ throw new GpuOutOfMemoryError(`KV cache growth to ${newCap} positions failed: ${oom.message}`);
594
+ }
595
+ for (const b of olds) b.destroy();
596
+ kvCapacity = newCap;
597
+ poolInvalidate();
598
+ }
599
+ async function readback(buf, n) {
600
+ const rb = device.createBuffer({
601
+ size: n * 4,
602
+ usage: GPUBufferUsage.MAP_READ | CD
603
+ });
604
+ const enc = device.createCommandEncoder();
605
+ enc.copyBufferToBuffer(buf, 0, rb, 0, n * 4);
606
+ device.queue.submit([enc.finish()]);
607
+ await rb.mapAsync(GPUMapMode.READ);
608
+ const out = new Float32Array(rb.getMappedRange().slice(0));
609
+ rb.unmap();
610
+ rb.destroy();
611
+ return out;
612
+ }
613
+ async function readbackU32(buf, n) {
614
+ const rb = device.createBuffer({
615
+ size: n * 4,
616
+ usage: GPUBufferUsage.MAP_READ | CD
617
+ });
618
+ const enc = device.createCommandEncoder();
619
+ enc.copyBufferToBuffer(buf, 0, rb, 0, n * 4);
620
+ device.queue.submit([enc.finish()]);
621
+ await rb.mapAsync(GPUMapMode.READ);
622
+ const out = new Uint32Array(rb.getMappedRange().slice(0));
623
+ rb.unmap();
624
+ rb.destroy();
625
+ return out;
626
+ }
627
+ let FULL = null;
628
+ const isFull = (name) => FULL === null || FULL.has(name);
629
+ let FORCE_SLOW = false;
630
+ let SMALLM = 0;
631
+ let DBG0 = null;
632
+ const cap = (li, name, buf) => {
633
+ if (li === 0 && DBG0) DBG0[name] = buf;
634
+ };
635
+ function setup(pass, name, fields, ins, outs) {
636
+ pass.setPipeline(pipelines[name]);
637
+ if (pool) {
638
+ let slot = pool.disp[dispIdx];
639
+ if (!slot) {
640
+ slot = {
641
+ uni: device.createBuffer({
642
+ size: 64,
643
+ usage: U | CD
644
+ }),
645
+ bg: null,
646
+ last: null
647
+ };
648
+ pool.disp[dispIdx] = slot;
649
+ }
650
+ const data2 = makeParams(fields);
651
+ if (!slot.last || !eqBytes(slot.last, data2)) {
652
+ device.queue.writeBuffer(slot.uni, 0, data2);
653
+ slot.last = data2.slice();
654
+ }
655
+ if (!slot.bg) {
656
+ const entries = [{
657
+ binding: 0,
658
+ resource: { buffer: slot.uni }
659
+ }];
660
+ ins.forEach((b, i) => entries.push({
661
+ binding: i + 1,
662
+ resource: { buffer: b }
663
+ }));
664
+ outs.forEach((b, i) => entries.push({
665
+ binding: 1 + ins.length + i,
666
+ resource: { buffer: b }
667
+ }));
668
+ slot.bg = device.createBindGroup({
669
+ layout: pipelines[name].getBindGroupLayout(0),
670
+ entries
671
+ });
672
+ }
673
+ pass.setBindGroup(0, slot.bg);
674
+ dispIdx++;
675
+ } else {
676
+ const entries = [{
677
+ binding: 0,
678
+ resource: { buffer: upload(makeParams(fields), U | CD) }
679
+ }];
680
+ ins.forEach((b, i) => entries.push({
681
+ binding: i + 1,
682
+ resource: { buffer: b }
683
+ }));
684
+ outs.forEach((b, i) => entries.push({
685
+ binding: 1 + ins.length + i,
686
+ resource: { buffer: b }
687
+ }));
688
+ pass.setBindGroup(0, device.createBindGroup({
689
+ layout: pipelines[name].getBindGroupLayout(0),
690
+ entries
691
+ }));
692
+ }
693
+ }
694
+ const grid2d = (wg) => {
695
+ const y = Math.ceil(wg / 65535);
696
+ return [Math.ceil(wg / y), y];
697
+ };
698
+ function runIO(pass, name, fields, ins, outs, threads) {
699
+ setup(pass, name, fields, ins, outs);
700
+ if (!isFull(name)) return void pass.dispatchWorkgroups(1);
701
+ const [x, y] = grid2d(Math.ceil(threads / 64));
702
+ pass.dispatchWorkgroups(x, y, 1);
703
+ }
704
+ const run = (pass, name, fields, ins, out, threads) => runIO(pass, name, fields, ins, [out], threads);
705
+ function runN(pass, name, fields, ins, out, nWG) {
706
+ setup(pass, name, fields, ins, [out]);
707
+ pass.dispatchWorkgroups(isFull(name) ? nWG : 1);
708
+ }
709
+ function runWG(pass, name, fields, ins, outs, wgX, wgY) {
710
+ setup(pass, name, fields, ins, outs);
711
+ const f = isFull(name);
712
+ pass.dispatchWorkgroups(f ? wgX : 1, f ? wgY : 1, 1);
713
+ }
714
+ const rms = (pass, x, g, R, Dn, out) => useSG ? runN(pass, "rmsnorm_sg", [
715
+ ["u", R],
716
+ ["u", Dn],
717
+ ["f", A.rms_eps],
718
+ ["u", 0]
719
+ ], [x, W[g].buf], out, R) : run(pass, "rmsnorm", [
720
+ ["u", R],
721
+ ["u", Dn],
722
+ ["f", A.rms_eps],
723
+ ["u", 0]
724
+ ], [x, W[g].buf], out, R);
725
+ function fusedMM(pass, w, inBuf, S, outs) {
726
+ const Ntot = w.N0 + w.N1 + w.N2;
727
+ if (useSG && S === 1) {
728
+ const gx = Math.min(Ntot, 65535);
729
+ runWG(pass, "matmul_split_sg", [
730
+ ["u", w.K],
731
+ ["u", w.nb],
732
+ ["u", w.N0],
733
+ ["u", w.N1],
734
+ ["u", w.N2],
735
+ ["u", gx]
736
+ ], [
737
+ inBuf,
738
+ w.sign,
739
+ w.scales
740
+ ], outs, gx, Math.ceil(Ntot / gx));
741
+ } else if (S === 1) {
742
+ const gx = Math.min(Ntot, 65535);
743
+ runWG(pass, "matmul_split_wg", [
744
+ ["u", w.K],
745
+ ["u", w.nb],
746
+ ["u", w.N0],
747
+ ["u", w.N1],
748
+ ["u", w.N2],
749
+ ["u", gx]
750
+ ], [
751
+ inBuf,
752
+ w.sign,
753
+ w.scales
754
+ ], outs, gx, Math.ceil(Ntot / gx));
755
+ } else if (useSG && S === SMALLM) {
756
+ const gx = Math.min(Ntot, 65535);
757
+ runWG(pass, "matmul_split_sm", [
758
+ ["u", w.K],
759
+ ["u", w.nb],
760
+ ["u", w.N0],
761
+ ["u", w.N1],
762
+ ["u", w.N2],
763
+ ["u", gx],
764
+ ["u", S]
765
+ ], [
766
+ inBuf,
767
+ w.sign,
768
+ w.scales
769
+ ], outs, gx, Math.ceil(Ntot / gx));
770
+ } else if (tiledPrefill(S)) runWG(pass, "matmul_split_tiled", [
771
+ ["u", S],
772
+ ["u", w.K],
773
+ ["u", w.nb],
774
+ ["u", w.N0],
775
+ ["u", w.N1],
776
+ ["u", w.N2]
777
+ ], [
778
+ inBuf,
779
+ w.sign,
780
+ w.scales
781
+ ], outs, Math.ceil(Ntot / 64), Math.ceil(S / 64));
782
+ else runIO(pass, "matmul_split", [
783
+ ["u", S],
784
+ ["u", w.K],
785
+ ["u", w.nb],
786
+ ["u", w.N0],
787
+ ["u", w.N1],
788
+ ["u", w.N2]
789
+ ], [
790
+ inBuf,
791
+ w.sign,
792
+ w.scales
793
+ ], outs, S * Ntot);
794
+ }
795
+ function residMM(pass, w, inBuf, resid, S, out) {
796
+ if (useSG && S === 1) {
797
+ const nwg = Math.ceil(w.N / ROWS_MR);
798
+ const gx = Math.min(nwg, 65535);
799
+ runWG(pass, "matmul_resid_mr_sg", [
800
+ ["u", w.N],
801
+ ["u", w.K],
802
+ ["u", w.nb],
803
+ ["u", gx],
804
+ ["u", 0],
805
+ ["u", 0]
806
+ ], [
807
+ inBuf,
808
+ w.sign,
809
+ w.scales,
810
+ resid
811
+ ], [out], gx, Math.ceil(nwg / gx));
812
+ } else if (S === 1) {
813
+ const gx = Math.min(w.N, 65535);
814
+ runWG(pass, "matmul_resid_wg", [
815
+ ["u", w.N],
816
+ ["u", w.K],
817
+ ["u", w.nb],
818
+ ["u", gx],
819
+ ["u", 0],
820
+ ["u", 0]
821
+ ], [
822
+ inBuf,
823
+ w.sign,
824
+ w.scales,
825
+ resid
826
+ ], [out], gx, Math.ceil(w.N / gx));
827
+ } else if (useSG && S === SMALLM) {
828
+ const gx = Math.min(w.N, 65535);
829
+ runWG(pass, "matmul_resid_sm", [
830
+ ["u", w.N],
831
+ ["u", w.K],
832
+ ["u", w.nb],
833
+ ["u", gx],
834
+ ["u", S],
835
+ ["u", 0]
836
+ ], [
837
+ inBuf,
838
+ w.sign,
839
+ w.scales,
840
+ resid
841
+ ], [out], gx, Math.ceil(w.N / gx));
842
+ } else if (tiledPrefill(S)) runWG(pass, "matmul_resid_tiled", [
843
+ ["u", S],
844
+ ["u", w.N],
845
+ ["u", w.K],
846
+ ["u", w.nb],
847
+ ["u", 0],
848
+ ["u", 0]
849
+ ], [
850
+ inBuf,
851
+ w.sign,
852
+ w.scales,
853
+ resid
854
+ ], [out], Math.ceil(w.N / 64), Math.ceil(S / 64));
855
+ else runIO(pass, "matmul_resid", [
856
+ ["u", S],
857
+ ["u", w.N],
858
+ ["u", w.K],
859
+ ["u", w.nb],
860
+ ["u", 128],
861
+ ["u", 0]
862
+ ], [
863
+ inBuf,
864
+ w.sign,
865
+ w.scales,
866
+ resid
867
+ ], [out], S * w.N);
868
+ }
869
+ function layer(pass, li, h, S, posBase, cos, sin) {
870
+ const Ltot = posBase + S;
871
+ const n1 = actBuf(S * Hd);
872
+ rms(pass, h, `layers.${li}.input_layernorm`, S, Hd, n1);
873
+ const qkv = W[`layers.${li}.attn.qkv`];
874
+ if (useSG && S === 1 && !FORCE_SLOW) {
875
+ const q = actBuf(H * Dh), k = actBuf(KV * Dh), v = actBuf(KV * Dh);
876
+ const Ntot = qkv.N0 + qkv.N1 + qkv.N2, gx = Math.min(Ntot, 65535);
877
+ runWG(pass, "matmul_split_sg", [
878
+ ["u", qkv.K],
879
+ ["u", qkv.nb],
880
+ ["u", qkv.N0],
881
+ ["u", qkv.N1],
882
+ ["u", qkv.N2],
883
+ ["u", gx]
884
+ ], [
885
+ n1,
886
+ qkv.sign,
887
+ qkv.scales
888
+ ], [
889
+ q,
890
+ k,
891
+ v
892
+ ], gx, Math.ceil(Ntot / gx));
893
+ run(pass, "copy", [
894
+ ["u", KV * Dh],
895
+ ["u", posBase * KV * Dh],
896
+ ["u", 0],
897
+ ["u", 0]
898
+ ], [v], Vc[li], KV * Dh);
899
+ const qr = actBuf(H * Dh);
900
+ runN(pass, "rmsnorm_rope_sg", [
901
+ ["u", H],
902
+ ["u", Dh],
903
+ ["f", A.rms_eps],
904
+ ["u", 0],
905
+ ["u", Dh],
906
+ ["u", 0]
907
+ ], [
908
+ q,
909
+ W[`layers.${li}.attn.q_norm`].buf,
910
+ cos,
911
+ sin
912
+ ], qr, H);
913
+ runN(pass, "rmsnorm_rope_sg", [
914
+ ["u", KV],
915
+ ["u", Dh],
916
+ ["f", A.rms_eps],
917
+ ["u", posBase * KV * Dh],
918
+ ["u", Dh],
919
+ ["u", 0]
920
+ ], [
921
+ k,
922
+ W[`layers.${li}.attn.k_norm`].buf,
923
+ cos,
924
+ sin
925
+ ], Kc[li], KV);
926
+ cap(li, "qr", qr);
927
+ const att = actBuf(H * Dh);
928
+ runN(pass, "attention_sg", [
929
+ ["u", 1],
930
+ ["u", H],
931
+ ["u", KV],
932
+ ["u", Dh],
933
+ ["u", posBase],
934
+ ["u", Ltot]
935
+ ], [
936
+ qr,
937
+ Kc[li],
938
+ Vc[li]
939
+ ], att, H);
940
+ cap(li, "att", att);
941
+ const o = W[`layers.${li}.attn.o_proj`], h2 = actBuf(Hd);
942
+ residMM(pass, o, att, h, 1, h2);
943
+ const n2 = actBuf(Hd);
944
+ rms(pass, h2, `layers.${li}.post_attention_layernorm`, 1, Hd, n2);
945
+ const gu = W[`layers.${li}.mlp.gateup`], sw = actBuf(F), nwgF = Math.ceil(F / ROWS_MR), gxF = Math.min(nwgF, 65535);
946
+ runWG(pass, "matmul_swiglu_mr_sg", [
947
+ ["u", gu.K],
948
+ ["u", gu.nb],
949
+ ["u", F],
950
+ ["u", gxF],
951
+ ["u", 0],
952
+ ["u", 0]
953
+ ], [
954
+ n2,
955
+ gu.sign,
956
+ gu.scales
957
+ ], [sw], gxF, Math.ceil(nwgF / gxF));
958
+ cap(li, "sw", sw);
959
+ const d = W[`layers.${li}.mlp.down_proj`], hn = actBuf(Hd);
960
+ residMM(pass, d, sw, h2, 1, hn);
961
+ return hn;
962
+ }
963
+ const q = actBuf(S * H * Dh), k = actBuf(S * KV * Dh), v = actBuf(S * KV * Dh);
964
+ fusedMM(pass, qkv, n1, S, [
965
+ q,
966
+ k,
967
+ v
968
+ ]);
969
+ const qn = actBuf(S * H * Dh), kn = actBuf(S * KV * Dh);
970
+ rms(pass, q, `layers.${li}.attn.q_norm`, S * H, Dh, qn);
971
+ rms(pass, k, `layers.${li}.attn.k_norm`, S * KV, Dh, kn);
972
+ const qr = actBuf(S * H * Dh), kr = actBuf(S * KV * Dh);
973
+ run(pass, "rope", [
974
+ ["u", S],
975
+ ["u", H],
976
+ ["u", Dh],
977
+ ["u", 0]
978
+ ], [
979
+ qn,
980
+ cos,
981
+ sin
982
+ ], qr, S * H * Dh);
983
+ run(pass, "rope", [
984
+ ["u", S],
985
+ ["u", KV],
986
+ ["u", Dh],
987
+ ["u", 0]
988
+ ], [
989
+ kn,
990
+ cos,
991
+ sin
992
+ ], kr, S * KV * Dh);
993
+ run(pass, "copy", [
994
+ ["u", S * KV * Dh],
995
+ ["u", posBase * KV * Dh],
996
+ ["u", 0],
997
+ ["u", 0]
998
+ ], [kr], Kc[li], S * KV * Dh);
999
+ run(pass, "copy", [
1000
+ ["u", S * KV * Dh],
1001
+ ["u", posBase * KV * Dh],
1002
+ ["u", 0],
1003
+ ["u", 0]
1004
+ ], [v], Vc[li], S * KV * Dh);
1005
+ cap(li, "qr", qr);
1006
+ const att = actBuf(S * H * Dh);
1007
+ const attF = [
1008
+ ["u", S],
1009
+ ["u", H],
1010
+ ["u", KV],
1011
+ ["u", Dh],
1012
+ ["u", posBase],
1013
+ ["u", Ltot]
1014
+ ];
1015
+ if (useSG) runN(pass, "attention_sg", attF, [
1016
+ qr,
1017
+ Kc[li],
1018
+ Vc[li]
1019
+ ], att, S * H);
1020
+ else run(pass, "attention_cache", attF, [
1021
+ qr,
1022
+ Kc[li],
1023
+ Vc[li]
1024
+ ], att, S * H);
1025
+ cap(li, "att", att);
1026
+ const o = W[`layers.${li}.attn.o_proj`], h2 = actBuf(S * Hd);
1027
+ residMM(pass, o, att, h, S, h2);
1028
+ const n2 = actBuf(S * Hd);
1029
+ rms(pass, h2, `layers.${li}.post_attention_layernorm`, S, Hd, n2);
1030
+ const gu = W[`layers.${li}.mlp.gateup`], g = actBuf(S * F), u = actBuf(S * F);
1031
+ fusedMM(pass, gu, n2, S, [
1032
+ g,
1033
+ u,
1034
+ dummy
1035
+ ]);
1036
+ const sw = actBuf(S * F);
1037
+ run(pass, "swiglu", [
1038
+ ["u", S * F],
1039
+ ["u", 0],
1040
+ ["u", 0],
1041
+ ["u", 0]
1042
+ ], [g, u], sw, S * F);
1043
+ cap(li, "sw", sw);
1044
+ const d = W[`layers.${li}.mlp.down_proj`], hn = actBuf(S * Hd);
1045
+ residMM(pass, d, sw, h2, S, hn);
1046
+ return hn;
1047
+ }
1048
+ function lmHead(pass, fn, M, out) {
1049
+ const lm = W.lm_head;
1050
+ if (useSG && M === 1) {
1051
+ const gx = Math.min(lm.N, 65535);
1052
+ runWG(pass, "matmul_q2_sg", [
1053
+ ["u", lm.N],
1054
+ ["u", lm.K],
1055
+ ["u", lm.nb],
1056
+ ["u", lm.zp],
1057
+ ["u", gx],
1058
+ ["u", 0]
1059
+ ], [
1060
+ fn,
1061
+ lm.codes,
1062
+ lm.scales
1063
+ ], [out], gx, Math.ceil(lm.N / gx));
1064
+ } else if (M === 1) {
1065
+ const gx = Math.min(lm.N, 65535);
1066
+ runWG(pass, "matmul_q2_wg", [
1067
+ ["u", lm.N],
1068
+ ["u", lm.K],
1069
+ ["u", lm.nb],
1070
+ ["u", lm.zp],
1071
+ ["u", gx],
1072
+ ["u", 0]
1073
+ ], [
1074
+ fn,
1075
+ lm.codes,
1076
+ lm.scales
1077
+ ], [out], gx, Math.ceil(lm.N / gx));
1078
+ } else if (useSG && M === SMALLM) {
1079
+ const gx = Math.min(lm.N, 65535);
1080
+ runWG(pass, "matmul_q2_sm", [
1081
+ ["u", lm.N],
1082
+ ["u", lm.K],
1083
+ ["u", lm.nb],
1084
+ ["u", lm.zp],
1085
+ ["u", gx],
1086
+ ["u", M]
1087
+ ], [
1088
+ fn,
1089
+ lm.codes,
1090
+ lm.scales
1091
+ ], [out], gx, Math.ceil(lm.N / gx));
1092
+ } else run(pass, "matmul_q2", [
1093
+ ["u", M],
1094
+ ["u", lm.N],
1095
+ ["u", lm.K],
1096
+ ["u", lm.nb],
1097
+ ["u", 128],
1098
+ ["u", lm.zp]
1099
+ ], [
1100
+ fn,
1101
+ lm.codes,
1102
+ lm.scales
1103
+ ], out, M * lm.N);
1104
+ }
1105
+ function stack(enc, h, S, posBase) {
1106
+ const { cos, sin } = ropeBufs(posBase, S);
1107
+ const pass = enc.beginComputePass();
1108
+ let cur = h, layer0 = null;
1109
+ for (let li = 0; li < A.layers; li++) {
1110
+ cur = layer(pass, li, cur, S, posBase, cos, sin);
1111
+ if (li === 0) layer0 = cur;
1112
+ }
1113
+ const fn = actBuf(S * Hd);
1114
+ rms(pass, cur, FINAL_NORM, S, Hd, fn);
1115
+ pass.end();
1116
+ return {
1117
+ fn,
1118
+ layer0
1119
+ };
1120
+ }
1121
+ async function forward(ids) {
1122
+ const S = ids.length;
1123
+ await ensureKvCapacity(S);
1124
+ transients = [];
1125
+ try {
1126
+ const embedOut = upload(embedDequant(ids), S_ | CD | CS);
1127
+ const enc = device.createCommandEncoder();
1128
+ const { fn, layer0 } = stack(enc, embedOut, S, 0);
1129
+ const logits = device.createBuffer({
1130
+ size: S * W.lm_head.N * 4,
1131
+ usage: S_ | CS
1132
+ });
1133
+ transients.push(logits);
1134
+ const pass = enc.beginComputePass();
1135
+ lmHead(pass, fn, S, logits);
1136
+ pass.end();
1137
+ device.queue.submit([enc.finish()]);
1138
+ await device.queue.onSubmittedWorkDone();
1139
+ return {
1140
+ embed: await readback(embedOut, S * Hd),
1141
+ layer0: await readback(layer0, S * Hd),
1142
+ finalnorm: await readback(fn, S * Hd),
1143
+ logits: await readback(logits, S * W.lm_head.N),
1144
+ vocab: W.lm_head.N,
1145
+ sequenceLength: S
1146
+ };
1147
+ } finally {
1148
+ flushTransients();
1149
+ transients = null;
1150
+ }
1151
+ }
1152
+ const PREFILL_SEG = 256;
1153
+ async function runPrefill(ids, posBase, signal) {
1154
+ let fn = null;
1155
+ let lastRow = 0;
1156
+ for (let off = 0; off < ids.length; off += PREFILL_SEG) {
1157
+ if (off > 0 && signal?.aborted) {
1158
+ fullHistory = [];
1159
+ return null;
1160
+ }
1161
+ const seg = ids.slice(off, off + PREFILL_SEG);
1162
+ const enc = device.createCommandEncoder();
1163
+ fn = stack(enc, upload(embedDequant(seg), S_ | CD), seg.length, posBase + off).fn;
1164
+ lastRow = seg.length - 1;
1165
+ device.queue.submit([enc.finish()]);
1166
+ if (off + PREFILL_SEG < ids.length) {
1167
+ await device.queue.onSubmittedWorkDone();
1168
+ flushTransients();
1169
+ }
1170
+ }
1171
+ return {
1172
+ fn,
1173
+ lastRow
1174
+ };
1175
+ }
1176
+ async function generateImpl(ids, posBase, nTokens, full = null, syncN = SYNC_N, ctl) {
1177
+ await ensureKvCapacity(posBase + ids.length + nTokens);
1178
+ FULL = full;
1179
+ const vocab = W.lm_head.N;
1180
+ const tokBuf = device.createBuffer({
1181
+ size: Math.max(1, nTokens) * 4,
1182
+ usage: S_ | CS
1183
+ });
1184
+ const embG = device.createBuffer({
1185
+ size: Hd * 4,
1186
+ usage: S_ | CS | CD
1187
+ });
1188
+ const lg = device.createBuffer({
1189
+ size: vocab * 4,
1190
+ usage: S_ | CS
1191
+ });
1192
+ transients = [];
1193
+ try {
1194
+ const t0 = performance.now();
1195
+ const pfx = await runPrefill(ids, posBase, ctl?.signal);
1196
+ if (!pfx) return {
1197
+ prefillMs: performance.now() - t0,
1198
+ decodeMs: 0,
1199
+ tokPerSec: 0,
1200
+ tokens: [],
1201
+ firstArgmax: -1,
1202
+ recMs: 0,
1203
+ gpuMs: 0,
1204
+ rbMs: 0
1205
+ };
1206
+ const encP = device.createCommandEncoder();
1207
+ const lastP = actBuf(Hd);
1208
+ encP.copyBufferToBuffer(pfx.fn, pfx.lastRow * Hd * 4, lastP, 0, Hd * 4);
1209
+ let pp = encP.beginComputePass();
1210
+ lmHead(pp, lastP, 1, lg);
1211
+ pp.end();
1212
+ pp = encP.beginComputePass();
1213
+ runN(pp, "argmax", [
1214
+ ["u", vocab],
1215
+ ["u", 0],
1216
+ ["u", 0],
1217
+ ["u", 0]
1218
+ ], [lg], tokBuf, 1);
1219
+ pp.end();
1220
+ device.queue.submit([encP.finish()]);
1221
+ await device.queue.onSubmittedWorkDone();
1222
+ const firstTok = (await readbackU32(tokBuf, 1))[0];
1223
+ flushTransients();
1224
+ const prefillMs = performance.now() - t0;
1225
+ const gen = [];
1226
+ let recMs = 0, gpuMs = 0, rbMs = 0;
1227
+ const t1 = performance.now();
1228
+ let total = 1;
1229
+ const stopSet = ctl?.stopTokens ? new Set(ctl.stopTokens) : null;
1230
+ let stopped = stopSet?.has(firstTok) ?? false;
1231
+ if (!stopped) {
1232
+ gen.push(firstTok);
1233
+ ctl?.onToken?.(firstTok);
1234
+ }
1235
+ poolInvalidate();
1236
+ while (total < nTokens && !stopped) {
1237
+ if (ctl?.signal?.aborted) break;
1238
+ const batch = Math.min(syncN, nTokens - total);
1239
+ poolUse("decode");
1240
+ let t = performance.now();
1241
+ const enc = device.createCommandEncoder();
1242
+ for (let j = 0; j < batch; j++) {
1243
+ const idxOut = total + j, pos = posBase + ids.length + idxOut - 1;
1244
+ let pass = enc.beginComputePass();
1245
+ runN(pass, "embed_gather", [
1246
+ ["u", Hd],
1247
+ ["u", idxOut - 1],
1248
+ ["u", 0],
1249
+ ["u", 0]
1250
+ ], [
1251
+ tokBuf,
1252
+ embWqG,
1253
+ tgt4G,
1254
+ embScalesG,
1255
+ embZpG
1256
+ ], embG, 1);
1257
+ pass.end();
1258
+ const r = stack(enc, embG, 1, pos);
1259
+ const last = actBuf(Hd);
1260
+ enc.copyBufferToBuffer(r.fn, 0, last, 0, Hd * 4);
1261
+ pass = enc.beginComputePass();
1262
+ lmHead(pass, last, 1, lg);
1263
+ runN(pass, "argmax", [
1264
+ ["u", vocab],
1265
+ ["u", idxOut],
1266
+ ["u", 0],
1267
+ ["u", 0]
1268
+ ], [lg], tokBuf, 1);
1269
+ pass.end();
1270
+ }
1271
+ device.queue.submit([enc.finish()]);
1272
+ recMs += performance.now() - t;
1273
+ t = performance.now();
1274
+ await device.queue.onSubmittedWorkDone();
1275
+ gpuMs += performance.now() - t;
1276
+ t = performance.now();
1277
+ const toks = await readbackU32(tokBuf, total + batch);
1278
+ rbMs += performance.now() - t;
1279
+ for (let j = 0; j < batch; j++) {
1280
+ const tk = toks[total + j];
1281
+ if (stopSet?.has(tk)) {
1282
+ stopped = true;
1283
+ break;
1284
+ }
1285
+ gen.push(tk);
1286
+ ctl?.onToken?.(tk);
1287
+ }
1288
+ total += batch;
1289
+ }
1290
+ const decodeMs = performance.now() - t1, nd = Math.max(1, gen.length - 1);
1291
+ return {
1292
+ prefillMs,
1293
+ decodeMs,
1294
+ tokPerSec: nd / (decodeMs / 1e3),
1295
+ tokens: gen,
1296
+ firstArgmax: firstTok,
1297
+ recMs: recMs / nd,
1298
+ gpuMs: gpuMs / nd,
1299
+ rbMs: rbMs / nd
1300
+ };
1301
+ } finally {
1302
+ poolUse(null);
1303
+ FULL = null;
1304
+ flushTransients();
1305
+ transients = null;
1306
+ tokBuf.destroy();
1307
+ embG.destroy();
1308
+ lg.destroy();
1309
+ }
1310
+ }
1311
+ async function generateSampledImpl(ids, posBase, nTokens, genOpts, history) {
1312
+ await ensureKvCapacity(posBase + ids.length + nTokens);
1313
+ const vocab = W.lm_head.N;
1314
+ const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab));
1315
+ const temperature = genOpts.temperature ?? 1;
1316
+ const penalty = genOpts.repetitionPenalty ?? 1;
1317
+ const ngramN = genOpts.noRepeatNgramSize ?? 0;
1318
+ const stopSet = genOpts.stopTokens ? new Set(genOpts.stopTokens) : null;
1319
+ const onToken = genOpts.onToken;
1320
+ const signal = genOpts.signal;
1321
+ const rng = new MT19937(genOpts.seed);
1322
+ const tokBuf = device.createBuffer({
1323
+ size: Math.max(1, nTokens) * 4,
1324
+ usage: S_ | CS | CD
1325
+ });
1326
+ const lg = device.createBuffer({
1327
+ size: vocab * 4,
1328
+ usage: S_ | CS
1329
+ });
1330
+ const candIds = device.createBuffer({
1331
+ size: K * 4,
1332
+ usage: S_ | CS
1333
+ });
1334
+ const candVals = device.createBuffer({
1335
+ size: K * 4,
1336
+ usage: S_ | CS
1337
+ });
1338
+ const affBuf = device.createBuffer({
1339
+ size: maxSeqLen * 4,
1340
+ usage: S_ | CD
1341
+ });
1342
+ const banBuf = device.createBuffer({
1343
+ size: maxSeqLen * 4,
1344
+ usage: S_ | CD
1345
+ });
1346
+ const rbBuf = device.createBuffer({
1347
+ size: K * 8,
1348
+ usage: GPUBufferUsage.MAP_READ | CD
1349
+ });
1350
+ const embG = device.createBuffer({
1351
+ size: Hd * 4,
1352
+ usage: S_ | CS | CD
1353
+ });
1354
+ const writeAffBan = (history) => {
1355
+ const aff = penalty !== 1 ? affectedIds(history) : /* @__PURE__ */ new Uint32Array(0);
1356
+ if (aff.length) device.queue.writeBuffer(affBuf, 0, aff);
1357
+ const ban = ngramN > 0 ? ngramBans(history, ngramN) : [];
1358
+ if (ban.length) device.queue.writeBuffer(banBuf, 0, Uint32Array.from(ban));
1359
+ return {
1360
+ affLen: aff.length,
1361
+ banLen: ban.length
1362
+ };
1363
+ };
1364
+ const samplerChain = (pass, affLen, banLen) => {
1365
+ setup(pass, "sampler_penalty", [
1366
+ ["u", affLen],
1367
+ ["u", banLen],
1368
+ ["f", penalty],
1369
+ ["u", 4286578688]
1370
+ ], [affBuf, banBuf], [lg]);
1371
+ pass.dispatchWorkgroups(1);
1372
+ for (let r = 0; r < K; r++) {
1373
+ setup(pass, "argmax_masked", [
1374
+ ["u", vocab],
1375
+ ["u", r],
1376
+ ["u", 0],
1377
+ ["u", 0]
1378
+ ], [lg], [candIds, candVals]);
1379
+ pass.dispatchWorkgroups(1);
1380
+ }
1381
+ };
1382
+ const readCands = async () => {
1383
+ await rbBuf.mapAsync(GPUMapMode.READ);
1384
+ const mapped = rbBuf.getMappedRange();
1385
+ const ci = new Uint32Array(mapped.slice(0, K * 4));
1386
+ const cv = new Float32Array(mapped.slice(K * 4, K * 8));
1387
+ rbBuf.unmap();
1388
+ return {
1389
+ ci,
1390
+ cv
1391
+ };
1392
+ };
1393
+ transients = [];
1394
+ try {
1395
+ const t0 = performance.now();
1396
+ const pfx = await runPrefill(ids, posBase, signal);
1397
+ if (!pfx) return {
1398
+ prefillMs: performance.now() - t0,
1399
+ decodeMs: 0,
1400
+ tokPerSec: 0,
1401
+ tokens: [],
1402
+ firstArgmax: -1,
1403
+ recMs: 0,
1404
+ gpuMs: 0,
1405
+ rbMs: 0
1406
+ };
1407
+ const encP = device.createCommandEncoder();
1408
+ const lastP = actBuf(Hd);
1409
+ encP.copyBufferToBuffer(pfx.fn, pfx.lastRow * Hd * 4, lastP, 0, Hd * 4);
1410
+ const pf = writeAffBan(history);
1411
+ let pass = encP.beginComputePass();
1412
+ lmHead(pass, lastP, 1, lg);
1413
+ samplerChain(pass, pf.affLen, pf.banLen);
1414
+ pass.end();
1415
+ encP.copyBufferToBuffer(candIds, 0, rbBuf, 0, K * 4);
1416
+ encP.copyBufferToBuffer(candVals, 0, rbBuf, K * 4, K * 4);
1417
+ device.queue.submit([encP.finish()]);
1418
+ await device.queue.onSubmittedWorkDone();
1419
+ const first = await readCands();
1420
+ const firstTok = sampleFromCandidates(first.ci, first.cv, temperature, rng);
1421
+ flushTransients();
1422
+ const prefillMs = performance.now() - t0;
1423
+ const gen = [];
1424
+ let stopped = stopSet?.has(firstTok) ?? false;
1425
+ if (!stopped) {
1426
+ gen.push(firstTok);
1427
+ history.push(firstTok);
1428
+ onToken?.(firstTok);
1429
+ device.queue.writeBuffer(tokBuf, 0, new Uint32Array([firstTok]));
1430
+ }
1431
+ let recMs = 0, gpuMs = 0, rbMs = 0;
1432
+ const t1 = performance.now();
1433
+ let total = 1;
1434
+ poolInvalidate();
1435
+ while (total < nTokens && !stopped) {
1436
+ if (signal?.aborted) break;
1437
+ poolUse("decode");
1438
+ const idxOut = total, pos = posBase + ids.length + idxOut - 1;
1439
+ let t = performance.now();
1440
+ const { affLen, banLen } = writeAffBan(history);
1441
+ const enc = device.createCommandEncoder();
1442
+ let p2 = enc.beginComputePass();
1443
+ runN(p2, "embed_gather", [
1444
+ ["u", Hd],
1445
+ ["u", idxOut - 1],
1446
+ ["u", 0],
1447
+ ["u", 0]
1448
+ ], [
1449
+ tokBuf,
1450
+ embWqG,
1451
+ tgt4G,
1452
+ embScalesG,
1453
+ embZpG
1454
+ ], embG, 1);
1455
+ p2.end();
1456
+ const r = stack(enc, embG, 1, pos);
1457
+ const last = actBuf(Hd);
1458
+ enc.copyBufferToBuffer(r.fn, 0, last, 0, Hd * 4);
1459
+ p2 = enc.beginComputePass();
1460
+ lmHead(p2, last, 1, lg);
1461
+ samplerChain(p2, affLen, banLen);
1462
+ p2.end();
1463
+ enc.copyBufferToBuffer(candIds, 0, rbBuf, 0, K * 4);
1464
+ enc.copyBufferToBuffer(candVals, 0, rbBuf, K * 4, K * 4);
1465
+ device.queue.submit([enc.finish()]);
1466
+ recMs += performance.now() - t;
1467
+ t = performance.now();
1468
+ await device.queue.onSubmittedWorkDone();
1469
+ gpuMs += performance.now() - t;
1470
+ t = performance.now();
1471
+ const { ci, cv } = await readCands();
1472
+ rbMs += performance.now() - t;
1473
+ const tk = sampleFromCandidates(ci, cv, temperature, rng);
1474
+ total += 1;
1475
+ if (stopSet?.has(tk)) {
1476
+ stopped = true;
1477
+ break;
1478
+ }
1479
+ gen.push(tk);
1480
+ history.push(tk);
1481
+ onToken?.(tk);
1482
+ device.queue.writeBuffer(tokBuf, idxOut * 4, new Uint32Array([tk]));
1483
+ }
1484
+ const decodeMs = performance.now() - t1;
1485
+ const nd = Math.max(1, gen.length - 1);
1486
+ return {
1487
+ prefillMs,
1488
+ decodeMs,
1489
+ tokPerSec: nd / (decodeMs / 1e3),
1490
+ tokens: gen,
1491
+ firstArgmax: firstTok,
1492
+ recMs: recMs / nd,
1493
+ gpuMs: gpuMs / nd,
1494
+ rbMs: rbMs / nd
1495
+ };
1496
+ } finally {
1497
+ poolUse(null);
1498
+ flushTransients();
1499
+ transients = null;
1500
+ for (const b of [
1501
+ tokBuf,
1502
+ lg,
1503
+ candIds,
1504
+ candVals,
1505
+ affBuf,
1506
+ banBuf,
1507
+ rbBuf,
1508
+ embG
1509
+ ]) b.destroy();
1510
+ }
1511
+ }
1512
+ async function generatePldImpl(ids, posBase, nTokens, genOpts, history) {
1513
+ await ensureKvCapacity(posBase + ids.length + nTokens);
1514
+ const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1;
1515
+ const vocab = W.lm_head.N;
1516
+ const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab));
1517
+ const temperature = genOpts.temperature ?? 1;
1518
+ const penalty = genOpts.repetitionPenalty ?? 1;
1519
+ const ngramN = genOpts.noRepeatNgramSize ?? 0;
1520
+ const pl = typeof genOpts.promptLookup === "object" && genOpts.promptLookup !== null ? genOpts.promptLookup : {};
1521
+ const ngramSize = Math.max(2, pl.ngramSize ?? 3);
1522
+ const maxDraft = Math.max(1, pl.maxDraft ?? 8);
1523
+ const stopSet = genOpts.stopTokens ? new Set(genOpts.stopTokens) : null;
1524
+ const onToken = genOpts.onToken;
1525
+ const signal = genOpts.signal;
1526
+ const rng = new MT19937(genOpts.seed);
1527
+ const lg = device.createBuffer({
1528
+ size: vocab * 4,
1529
+ usage: S_ | CS | CD
1530
+ });
1531
+ const lgAll = device.createBuffer({
1532
+ size: (maxDraft + 1) * vocab * 4,
1533
+ usage: S_ | CS
1534
+ });
1535
+ const idsOut = device.createBuffer({
1536
+ size: (maxDraft + 1) * 4,
1537
+ usage: S_ | CS
1538
+ });
1539
+ const candIds = device.createBuffer({
1540
+ size: K * 4,
1541
+ usage: S_ | CS
1542
+ });
1543
+ const candVals = device.createBuffer({
1544
+ size: K * 4,
1545
+ usage: S_ | CS
1546
+ });
1547
+ const affBuf = device.createBuffer({
1548
+ size: (maxSeqLen + maxDraft + 1) * 4,
1549
+ usage: S_ | CD
1550
+ });
1551
+ const banBuf = device.createBuffer({
1552
+ size: (maxSeqLen + maxDraft + 1) * 4,
1553
+ usage: S_ | CD
1554
+ });
1555
+ const rbAll = device.createBuffer({
1556
+ size: (maxDraft + 1) * K * 8,
1557
+ usage: GPUBufferUsage.MAP_READ | CD
1558
+ });
1559
+ const embIn = device.createBuffer({
1560
+ size: (maxDraft + 1) * Hd * 4,
1561
+ usage: S_ | CD
1562
+ });
1563
+ const writeAffBan = (h) => {
1564
+ const aff = penalty !== 1 ? affectedIds(h) : /* @__PURE__ */ new Uint32Array(0);
1565
+ if (aff.length) device.queue.writeBuffer(affBuf, 0, aff);
1566
+ const ban = ngramN > 0 ? ngramBans(h, ngramN) : [];
1567
+ if (ban.length) device.queue.writeBuffer(banBuf, 0, Uint32Array.from(ban));
1568
+ return {
1569
+ affLen: aff.length,
1570
+ banLen: ban.length
1571
+ };
1572
+ };
1573
+ const samplerChain = (pass, affLen, banLen) => {
1574
+ setup(pass, "sampler_penalty", [
1575
+ ["u", affLen],
1576
+ ["u", banLen],
1577
+ ["f", penalty],
1578
+ ["u", 4286578688]
1579
+ ], [affBuf, banBuf], [lg]);
1580
+ pass.dispatchWorkgroups(1);
1581
+ for (let r = 0; r < K; r++) {
1582
+ setup(pass, "argmax_masked", [
1583
+ ["u", vocab],
1584
+ ["u", r],
1585
+ ["u", 0],
1586
+ ["u", 0]
1587
+ ], [lg], [candIds, candVals]);
1588
+ pass.dispatchWorkgroups(1);
1589
+ }
1590
+ };
1591
+ const rowDraw = (m, j) => sampleFromCandidates(new Uint32Array(m, j * K * 8, K), new Float32Array(m, j * K * 8 + K * 4, K), temperature, rng);
1592
+ transients = [];
1593
+ try {
1594
+ const t0 = performance.now();
1595
+ const pfx = await runPrefill(ids, posBase, signal);
1596
+ if (!pfx) return {
1597
+ prefillMs: performance.now() - t0,
1598
+ decodeMs: 0,
1599
+ tokPerSec: 0,
1600
+ tokens: [],
1601
+ firstArgmax: -1,
1602
+ recMs: 0,
1603
+ gpuMs: 0,
1604
+ rbMs: 0,
1605
+ spec: {
1606
+ steps: 0,
1607
+ drafted: 0,
1608
+ accepted: 0
1609
+ }
1610
+ };
1611
+ const encP = device.createCommandEncoder();
1612
+ const lastP = actBuf(Hd);
1613
+ encP.copyBufferToBuffer(pfx.fn, pfx.lastRow * Hd * 4, lastP, 0, Hd * 4);
1614
+ const pf = sampled ? writeAffBan(history) : null;
1615
+ let pass = encP.beginComputePass();
1616
+ lmHead(pass, lastP, 1, lg);
1617
+ if (pf) samplerChain(pass, pf.affLen, pf.banLen);
1618
+ else runN(pass, "argmax", [
1619
+ ["u", vocab],
1620
+ ["u", 0],
1621
+ ["u", 0],
1622
+ ["u", 0]
1623
+ ], [lg], idsOut, 1);
1624
+ pass.end();
1625
+ if (pf) {
1626
+ encP.copyBufferToBuffer(candIds, 0, rbAll, 0, K * 4);
1627
+ encP.copyBufferToBuffer(candVals, 0, rbAll, K * 4, K * 4);
1628
+ }
1629
+ device.queue.submit([encP.finish()]);
1630
+ await device.queue.onSubmittedWorkDone();
1631
+ let firstTok;
1632
+ if (pf) {
1633
+ await rbAll.mapAsync(GPUMapMode.READ);
1634
+ const m = rbAll.getMappedRange().slice(0);
1635
+ rbAll.unmap();
1636
+ firstTok = rowDraw(m, 0);
1637
+ } else firstTok = (await readbackU32(idsOut, 1))[0];
1638
+ flushTransients();
1639
+ const prefillMs = performance.now() - t0;
1640
+ const gen = [];
1641
+ let stopped = stopSet?.has(firstTok) ?? false;
1642
+ if (!stopped) {
1643
+ gen.push(firstTok);
1644
+ history.push(firstTok);
1645
+ onToken?.(firstTok);
1646
+ }
1647
+ poolInvalidate();
1648
+ let total = 1;
1649
+ let tLast = firstTok;
1650
+ let pos = posBase + ids.length;
1651
+ let specSteps = 0, drafted = 0, accepted = 0;
1652
+ let recMs = 0, gpuMs = 0, rbMs = 0;
1653
+ const t1 = performance.now();
1654
+ while (total < nTokens && !stopped) {
1655
+ if (signal?.aborted) break;
1656
+ const kMax = Math.min(maxDraft, nTokens - total - 1, maxSeqLen - 1 - pos);
1657
+ const drafts = kMax > 0 ? draftNgram(history, ngramSize, kMax) : [];
1658
+ const S = drafts.length + 1;
1659
+ await ensureKvCapacity(pos + S);
1660
+ let t = performance.now();
1661
+ if (S === 1) poolUse("pld1");
1662
+ else if (useSG && S <= 9) poolUse("pldm", S, 9);
1663
+ else poolUse(null);
1664
+ device.queue.writeBuffer(embIn, 0, embedDequant([tLast, ...drafts]));
1665
+ SMALLM = useSG && S >= 2 && S <= 9 ? S : 0;
1666
+ const enc = device.createCommandEncoder();
1667
+ const r = stack(enc, embIn, S, pos);
1668
+ pass = enc.beginComputePass();
1669
+ lmHead(pass, r.fn, S, lgAll);
1670
+ pass.end();
1671
+ SMALLM = 0;
1672
+ if (!sampled) {
1673
+ for (let j = 0; j < S; j++) {
1674
+ enc.copyBufferToBuffer(lgAll, j * vocab * 4, lg, 0, vocab * 4);
1675
+ const p = enc.beginComputePass();
1676
+ runN(p, "argmax", [
1677
+ ["u", vocab],
1678
+ ["u", j],
1679
+ ["u", 0],
1680
+ ["u", 0]
1681
+ ], [lg], idsOut, 1);
1682
+ p.end();
1683
+ }
1684
+ device.queue.submit([enc.finish()]);
1685
+ } else {
1686
+ device.queue.submit([enc.finish()]);
1687
+ for (let j = 0; j < S; j++) {
1688
+ const { affLen, banLen } = writeAffBan(j === 0 ? history : [...history, ...drafts.slice(0, j)]);
1689
+ const e2 = device.createCommandEncoder();
1690
+ e2.copyBufferToBuffer(lgAll, j * vocab * 4, lg, 0, vocab * 4);
1691
+ const p = e2.beginComputePass();
1692
+ samplerChain(p, affLen, banLen);
1693
+ p.end();
1694
+ e2.copyBufferToBuffer(candIds, 0, rbAll, j * K * 8, K * 4);
1695
+ e2.copyBufferToBuffer(candVals, 0, rbAll, j * K * 8 + K * 4, K * 4);
1696
+ device.queue.submit([e2.finish()]);
1697
+ }
1698
+ }
1699
+ recMs += performance.now() - t;
1700
+ t = performance.now();
1701
+ await device.queue.onSubmittedWorkDone();
1702
+ gpuMs += performance.now() - t;
1703
+ t = performance.now();
1704
+ const emitted = [];
1705
+ if (!sampled) {
1706
+ const outs = await readbackU32(idsOut, S);
1707
+ for (let j = 0; j < S; j++) {
1708
+ const tk = outs[j];
1709
+ if (stopSet?.has(tk)) {
1710
+ stopped = true;
1711
+ break;
1712
+ }
1713
+ emitted.push(tk);
1714
+ if (j < drafts.length && tk !== drafts[j]) break;
1715
+ }
1716
+ } else {
1717
+ await rbAll.mapAsync(GPUMapMode.READ);
1718
+ const m = rbAll.getMappedRange().slice(0);
1719
+ rbAll.unmap();
1720
+ for (let j = 0; j < S; j++) {
1721
+ const tk = rowDraw(m, j);
1722
+ if (stopSet?.has(tk)) {
1723
+ stopped = true;
1724
+ break;
1725
+ }
1726
+ emitted.push(tk);
1727
+ if (j < drafts.length && tk !== drafts[j]) break;
1728
+ }
1729
+ }
1730
+ rbMs += performance.now() - t;
1731
+ specSteps++;
1732
+ drafted += drafts.length;
1733
+ accepted += Math.max(0, emitted.length - 1);
1734
+ for (const tk of emitted) {
1735
+ gen.push(tk);
1736
+ history.push(tk);
1737
+ onToken?.(tk);
1738
+ }
1739
+ total += emitted.length;
1740
+ flushTransients();
1741
+ if (emitted.length === 0) break;
1742
+ pos += emitted.length;
1743
+ tLast = emitted[emitted.length - 1];
1744
+ }
1745
+ const decodeMs = performance.now() - t1;
1746
+ const nd = Math.max(1, gen.length - 1);
1747
+ return {
1748
+ prefillMs,
1749
+ decodeMs,
1750
+ tokPerSec: nd / (decodeMs / 1e3),
1751
+ tokens: gen,
1752
+ firstArgmax: firstTok,
1753
+ recMs: recMs / nd,
1754
+ gpuMs: gpuMs / nd,
1755
+ rbMs: rbMs / nd,
1756
+ spec: {
1757
+ steps: specSteps,
1758
+ drafted,
1759
+ accepted
1760
+ }
1761
+ };
1762
+ } finally {
1763
+ SMALLM = 0;
1764
+ poolUse(null);
1765
+ flushTransients();
1766
+ transients = null;
1767
+ for (const b of [
1768
+ lg,
1769
+ lgAll,
1770
+ idsOut,
1771
+ candIds,
1772
+ candVals,
1773
+ affBuf,
1774
+ banBuf,
1775
+ rbAll,
1776
+ embIn
1777
+ ]) b.destroy();
1778
+ }
1779
+ }
1780
+ async function debugDecode(prefillIds) {
1781
+ await ensureKvCapacity(prefillIds.length + 1);
1782
+ const encP = device.createCommandEncoder();
1783
+ stack(encP, upload(embedDequant(prefillIds), S_ | CD), prefillIds.length, 0);
1784
+ device.queue.submit([encP.finish()]);
1785
+ await device.queue.onSubmittedWorkDone();
1786
+ const pos = prefillIds.length, tok = prefillIds[prefillIds.length - 1];
1787
+ const runStep = async (forceSlow) => {
1788
+ FORCE_SLOW = forceSlow;
1789
+ DBG0 = {};
1790
+ const enc = device.createCommandEncoder();
1791
+ const r = stack(enc, upload(embedDequant([tok]), S_ | CD), 1, pos);
1792
+ const lg = device.createBuffer({
1793
+ size: W.lm_head.N * 4,
1794
+ usage: S_ | CS
1795
+ });
1796
+ const pass = enc.beginComputePass();
1797
+ lmHead(pass, r.fn, 1, lg);
1798
+ pass.end();
1799
+ device.queue.submit([enc.finish()]);
1800
+ await device.queue.onSubmittedWorkDone();
1801
+ const ck = {};
1802
+ for (const [name, b] of Object.entries(DBG0)) ck[name] = await readback(b, b.size / 4);
1803
+ const off = pos * KV * Dh;
1804
+ ck.kc = (await readback(Kc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
1805
+ ck.vc = (await readback(Vc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
1806
+ ck.fn = await readback(r.fn, Hd);
1807
+ ck.logits = await readback(lg, W.lm_head.N);
1808
+ FORCE_SLOW = false;
1809
+ DBG0 = null;
1810
+ return ck;
1811
+ };
1812
+ return {
1813
+ fast: await runStep(false),
1814
+ slow: await runStep(true)
1815
+ };
1816
+ }
1817
+ async function debugSampler(ids, genOpts) {
1818
+ const vocab = W.lm_head.N;
1819
+ const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab));
1820
+ const penalty = genOpts.repetitionPenalty ?? 1;
1821
+ const ngramN = genOpts.noRepeatNgramSize ?? 0;
1822
+ const lg = device.createBuffer({
1823
+ size: vocab * 4,
1824
+ usage: S_ | CS
1825
+ });
1826
+ const candIds = device.createBuffer({
1827
+ size: K * 4,
1828
+ usage: S_ | CS
1829
+ });
1830
+ const candVals = device.createBuffer({
1831
+ size: K * 4,
1832
+ usage: S_ | CS
1833
+ });
1834
+ const aff = penalty !== 1 ? affectedIds(ids) : /* @__PURE__ */ new Uint32Array(0);
1835
+ const ban = ngramN > 0 ? ngramBans(ids, ngramN) : [];
1836
+ const affBuf = upload(aff.length ? aff : /* @__PURE__ */ new Uint32Array(1), S_ | CD);
1837
+ const banBuf = upload(ban.length ? Uint32Array.from(ban) : /* @__PURE__ */ new Uint32Array(1), S_ | CD);
1838
+ const enc1 = device.createCommandEncoder();
1839
+ const { fn } = stack(enc1, upload(embedDequant(ids), S_ | CD), ids.length, 0);
1840
+ const lastP = device.createBuffer({
1841
+ size: Hd * 4,
1842
+ usage: S_ | CS | CD
1843
+ });
1844
+ enc1.copyBufferToBuffer(fn, (ids.length - 1) * Hd * 4, lastP, 0, Hd * 4);
1845
+ let pass = enc1.beginComputePass();
1846
+ lmHead(pass, lastP, 1, lg);
1847
+ pass.end();
1848
+ device.queue.submit([enc1.finish()]);
1849
+ await device.queue.onSubmittedWorkDone();
1850
+ const base = await readback(lg, vocab);
1851
+ const enc2 = device.createCommandEncoder();
1852
+ pass = enc2.beginComputePass();
1853
+ setup(pass, "sampler_penalty", [
1854
+ ["u", aff.length],
1855
+ ["u", ban.length],
1856
+ ["f", penalty],
1857
+ ["u", 4286578688]
1858
+ ], [affBuf, banBuf], [lg]);
1859
+ pass.dispatchWorkgroups(1);
1860
+ for (let r = 0; r < K; r++) {
1861
+ setup(pass, "argmax_masked", [
1862
+ ["u", vocab],
1863
+ ["u", r],
1864
+ ["u", 0],
1865
+ ["u", 0]
1866
+ ], [lg], [candIds, candVals]);
1867
+ pass.dispatchWorkgroups(1);
1868
+ }
1869
+ pass.end();
1870
+ device.queue.submit([enc2.finish()]);
1871
+ await device.queue.onSubmittedWorkDone();
1872
+ return {
1873
+ base,
1874
+ penalized: await readback(lg, vocab),
1875
+ candIds: await readbackU32(candIds, K),
1876
+ candVals: await readback(candVals, K)
1877
+ };
1878
+ }
1879
+ const capabilities = {
1880
+ useSubgroups: useSG,
1881
+ subgroupSize: sgMax,
1882
+ adapter: {
1883
+ vendor: info.vendor,
1884
+ architecture: info.architecture,
1885
+ device: info.device,
1886
+ description: info.description
1887
+ },
1888
+ limits: {
1889
+ maxStorageBufferBindingSize: Number(device.limits.maxStorageBufferBindingSize),
1890
+ maxComputeWorkgroupStorageSize: device.limits.maxComputeWorkgroupStorageSize
1891
+ }
1892
+ };
1893
+ async function generate(promptTokenIds, genOpts = {}) {
1894
+ const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1;
1895
+ const reuse = (genOpts.reuseCache ?? false) && fullHistory.length > 0;
1896
+ if (genOpts.signal?.aborted) return {
1897
+ tokens: [],
1898
+ prefillMs: 0,
1899
+ decodeMs: 0,
1900
+ tokensPerSecond: 0,
1901
+ timing: {
1902
+ recordMs: 0,
1903
+ gpuMs: 0,
1904
+ readbackMs: 0
1905
+ }
1906
+ };
1907
+ const posBase = reuse ? fullHistory.length - 1 : 0;
1908
+ const prefillTokens = reuse ? [fullHistory[fullHistory.length - 1], ...promptTokenIds] : promptTokenIds;
1909
+ if (prefillTokens.length === 0) throw new Error("generate: no tokens to process");
1910
+ const room = maxSeqLen - posBase - prefillTokens.length;
1911
+ if (room < 1) throw new Error(`generate: prompt length ${posBase + prefillTokens.length} exceeds maxSeqLen ${maxSeqLen}; trim history or raise maxSeqLen`);
1912
+ const maxTokens = Math.min(genOpts.maxTokens ?? 256, room);
1913
+ if (reuse) fullHistory.push(...promptTokenIds);
1914
+ else fullHistory = [...promptTokenIds];
1915
+ let r;
1916
+ if (genOpts.promptLookup) r = await generatePldImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
1917
+ else if (sampled) r = await generateSampledImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
1918
+ else {
1919
+ r = await generateImpl(prefillTokens, posBase, maxTokens, null, SYNC_N, {
1920
+ stopTokens: genOpts.stopTokens,
1921
+ onToken: genOpts.onToken,
1922
+ signal: genOpts.signal
1923
+ });
1924
+ fullHistory.push(...r.tokens);
1925
+ }
1926
+ return {
1927
+ tokens: r.tokens,
1928
+ prefillMs: r.prefillMs,
1929
+ decodeMs: r.decodeMs,
1930
+ tokensPerSecond: r.tokPerSec,
1931
+ timing: {
1932
+ recordMs: r.recMs,
1933
+ gpuMs: r.gpuMs,
1934
+ readbackMs: r.rbMs
1935
+ },
1936
+ ...r.spec ? { speculation: r.spec } : {}
1937
+ };
1938
+ }
1939
+ async function prefill(ids) {
1940
+ if (ids.length === 0) throw new Error("prefill: no tokens to process");
1941
+ if (ids.length > maxSeqLen) throw new Error(`prefill: sequence length ${ids.length} exceeds maxSeqLen ${maxSeqLen}`);
1942
+ await ensureKvCapacity(ids.length);
1943
+ transients = [];
1944
+ try {
1945
+ const t0 = performance.now();
1946
+ await runPrefill(ids, 0);
1947
+ await device.queue.onSubmittedWorkDone();
1948
+ fullHistory = [...ids];
1949
+ return { prefillMs: performance.now() - t0 };
1950
+ } finally {
1951
+ flushTransients();
1952
+ transients = null;
1953
+ }
1954
+ }
1955
+ let opChain = Promise.resolve();
1956
+ const serialize = (fn) => {
1957
+ return (...args) => {
1958
+ const run = opChain.then(() => fn(...args), () => fn(...args));
1959
+ opChain = run.catch(() => void 0);
1960
+ return run;
1961
+ };
1962
+ };
1963
+ return {
1964
+ generate: serialize(generate),
1965
+ prefill: serialize(prefill),
1966
+ forward: serialize(forward),
1967
+ resetCache,
1968
+ capabilities,
1969
+ lost,
1970
+ dispose: () => device.destroy(),
1971
+ device,
1972
+ adapter,
1973
+ profileDecode: (ids, nTokens, full = null, syncN = SYNC_N) => generateImpl(ids, 0, nTokens, full, syncN),
1974
+ debugDecode,
1975
+ debugSampler
1976
+ };
1977
+ }
1978
+ //#endregion
1979
+ export { GpuOutOfMemoryError, WebGPUUnavailableError, createEngine };
1980
+
1981
+ //# sourceMappingURL=index.js.map