bitgpu 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -24,6 +24,13 @@ interface EngineOptions {
24
24
  fetchJson?: (url: string) => Promise<unknown>;
25
25
  /** Fetch binary (data/aux). Override to add caching (e.g. OPFS) for the ~290MB data file. Default: `fetch(url).arrayBuffer()`. */
26
26
  fetchArrayBuffer?: (url: string) => Promise<ArrayBuffer>;
27
+ /** Stream the big weights DATA file: chunks flow straight into GPU buffers, so the whole
28
+ * ~290MB file never sits in memory at once (critical on phones, where the buffered peak gets
29
+ * the tab killed). Used for the data file only (manifest/aux stay on fetchJson/fetchArrayBuffer);
30
+ * when set it takes precedence over fetchArrayBuffer for that file. Point it at a cache stream,
31
+ * e.g. an OPFS file's `stream()`. Default: the data file streams from `fetch(url).body`
32
+ * (or through `fetchArrayBuffer` when that override is provided, for back compatibility). */
33
+ fetchStream?: (url: string) => Promise<ReadableStream<Uint8Array>>;
27
34
  /** GPU power preference. Default `'high-performance'` (picks the discrete GPU on multi-GPU machines).
28
35
  * (Spelled out rather than `GPUPowerPreference` so the published d.ts resolves without @webgpu/types.) */
29
36
  powerPreference?: 'low-power' | 'high-performance';
@@ -35,8 +42,16 @@ interface EngineOptions {
35
42
  syncSteps?: number;
36
43
  /** Prefill GEMM tiling: `'auto'` tiles once a prompt fills the 64-row tiles, `'always'`/`'never'` force it. Default `'auto'`. */
37
44
  prefillTiling?: 'auto' | 'always' | 'never';
38
- /** Max KV-cache length (prompt + generated positions). Caps VRAM (~`maxSeqLen` x 224 KB). Default `2048`. */
45
+ /** Max KV-cache length (prompt + generated positions). Caps VRAM (~`maxSeqLen` x 224 KB at f32,
46
+ * half that with `kvCache: 'f16'`). Default `2048`. */
39
47
  maxSeqLen?: number;
48
+ /** KV-cache STORAGE precision. `'f16'` halves KV memory (the industry-standard choice: all
49
+ * arithmetic stays f32; each cached K/V value is rounded once at cache-write). Outputs are no
50
+ * longer guaranteed bit-identical to f32 mode, though within f16 mode decoding stays exact and
51
+ * deterministic (same seed -> same tokens; cache reuse == full prefill). Falls back to `'f32'`
52
+ * silently when the adapter lacks `shader-f16` (see `capabilities.kvCache` for what's active).
53
+ * Default `'f32'`. */
54
+ kvCache?: 'f32' | 'f16';
40
55
  /** Called as the model loads. */
41
56
  onProgress?: (progress: LoadProgress) => void;
42
57
  /** Called if the GPU device is lost after creation (driver reset, OS reclaim, tab backgrounding
@@ -129,6 +144,8 @@ interface EngineCapabilities {
129
144
  useSubgroups: boolean;
130
145
  /** Subgroup width when the subgroup path is active. */
131
146
  subgroupSize: number;
147
+ /** Active KV-cache storage precision ('f16' only when requested AND the adapter has shader-f16). */
148
+ kvCache: 'f32' | 'f16';
132
149
  /** Adapter identification, when the browser exposes it. */
133
150
  adapter: {
134
151
  vendor?: string;
package/dist/index.js CHANGED
@@ -4,8 +4,11 @@ const SHADERS = {
4
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
5
  "argmax_masked": "// Masked argmax: like argmax.wgsl but skips any id already chosen in a prior round, and writes BOTH\n// the winning id and its logit value. Calling it K times (roundCount = 0..K-1, all in one compute\n// pass so each round sees the prior rounds' writes) yields the exact top-K (id, logit) pairs in\n// descending order = ONNX TopK over the (penalty-filtered) logits, which is what the transformers.js\n// sampler consumes. Then only K pairs are read back (not the full vocab), and the CPU does\n// temperature + softmax + multinomial. Single workgroup, no subgroup ops -> all devices. Tie-break =\n// lowest index (strict >), matching argmax.wgsl / ORT TopK in practice.\noverride WG: u32 = 256u;\nstruct Params { N: u32, roundCount: u32, _0: u32, _1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> logits: array<f32>;\n@group(0) @binding(2) var<storage, read_write> candIds: array<u32>; // [K]; reads 0..roundCount-1, writes [roundCount]\n@group(0) @binding(3) var<storage, read_write> candVals: array<f32>; // [K]; writes [roundCount]\n\nvar<workgroup> sval: array<f32, 256>;\nvar<workgroup> sidx: array<u32, 256>;\n\n@compute @workgroup_size(WG)\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\n let tid = lid.x;\n var bv = -3.4e38;\n var bi = 0u;\n for (var i = tid; i < p.N; i = i + WG) {\n let v = logits[i];\n if (v > bv) {\n var skip = false;\n for (var r = 0u; r < p.roundCount; r = r + 1u) { if (candIds[r] == i) { skip = true; break; } }\n if (!skip) { bv = v; bi = i; } // strict > keeps the lowest index within this thread's stride\n }\n }\n sval[tid] = bv; sidx[tid] = bi;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s) {\n let ov = sval[tid + s]; let oi = sidx[tid + s];\n if (ov > sval[tid] || (ov == sval[tid] && oi < sidx[tid])) { sval[tid] = ov; sidx[tid] = oi; }\n }\n workgroupBarrier();\n }\n if (tid == 0u) { candIds[p.roundCount] = sidx[0]; candVals[p.roundCount] = sval[0]; }\n}\n",
6
6
  "attention_sg": "// Causal GQA attention, subgroup-parallel: one subgroup (= one workgroup) per (query, head).\n// Lanes split head_dim; flash-style online softmax over the cached positions; the per-position\n// score (q.k) is reduced with subgroupAdd. Fixes the decode bottleneck where attention ran only\n// H threads. SG = device subgroup size (16/32/64, so head_dim/SG <= 8). Reads K/V from the cache.\nenable subgroups;\noverride SG: u32 = 32u;\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> Kc: array<f32>; // [Ltot, KV, D]\n@group(0) @binding(3) var<storage, read> Vc: array<f32>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read_write> out: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let idx = wg.x;\n if (idx >= p.S * p.H) { return; }\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n let dper = p.D / SG; // <= 8 for SG>=16, D=128\n\n var acc: array<f32, 8>;\n for (var t = 0u; t < dper; t = t + 1u) { acc[t] = 0.0; }\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n var part = 0.0;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; part = part + q[qb + d] * Kc[kb + d]; }\n let score = subgroupAdd(part) * inv; // full q.k dot, broadcast to all lanes\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let w = exp(score - mnew);\n l = l * corr + w;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; acc[t] = acc[t] * corr + w * Vc[kb + d]; }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; out[ob + d] = acc[t] / l; }\n}\n",
7
+ "attention_sg_kv16": "// attention_sg with an f16-STORAGE KV cache (kvCache: 'f16'). Keep in lockstep with\n// attention_sg.wgsl: the ONLY difference is Kc/Vc are array<f16> and each cached value is\n// widened to f32 at the read. All arithmetic (dot, softmax, accumulation) stays f32, so the\n// precision loss is exactly one rounding of K/V at cache-write time, nothing compounding.\nenable subgroups;\nenable f16;\noverride SG: u32 = 32u;\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> Kc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(3) var<storage, read> Vc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read_write> out: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let idx = wg.x;\n if (idx >= p.S * p.H) { return; }\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n let dper = p.D / SG;\n\n var acc: array<f32, 8>;\n for (var t = 0u; t < dper; t = t + 1u) { acc[t] = 0.0; }\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n var part = 0.0;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; part = part + q[qb + d] * f32(Kc[kb + d]); }\n let score = subgroupAdd(part) * inv;\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let w = exp(score - mnew);\n l = l * corr + w;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; acc[t] = acc[t] * corr + w * f32(Vc[kb + d]); }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; out[ob + d] = acc[t] / l; }\n}\n",
7
8
  "attention_wg": "// Causal GQA attention, no-subgroup fallback: one workgroup per (query, head); threads split\n// head_dim; flash-style online softmax over the cached positions; the per-position q.k score\n// is tree-reduced via shared memory. Replaces attention_cache on this path: its single thread\n// per (query, head) walked the WHOLE context serially, so fallback decode degraded linearly\n// with conversation length and prefill attention was latency-bound. Mirrors attention_sg with\n// subgroupAdd swapped for the shared-memory reduction. Fixed workgroup of 64: the per-thread\n// accumulator covers head_dim <= 128 (enforced at manifest validation) in 2 strides.\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> Kc: array<f32>; // [Ltot, KV, D]\n@group(0) @binding(3) var<storage, read> Vc: array<f32>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read_write> out: array<f32>; // [S, H, D]\nvar<workgroup> red: array<f32, 64>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (idx >= p.S * p.H) { return; }\n let tid = lid.x;\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n\n var acc: array<f32, 2>;\n acc[0] = 0.0;\n acc[1] = 0.0;\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n var part = 0.0;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { part = part + q[qb + d] * Kc[kb + d]; }\n }\n red[tid] = part;\n workgroupBarrier();\n for (var s = 32u; s > 0u; s = s >> 1u) {\n if (tid < s) { red[tid] = red[tid] + red[tid + s]; }\n workgroupBarrier();\n }\n let score = red[0] * inv; // full q.k dot, visible to all threads\n workgroupBarrier(); // red[0] consumed before the next position overwrites it\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let w = exp(score - mnew);\n l = l * corr + w;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { acc[t] = acc[t] * corr + w * Vc[kb + d]; }\n }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { out[ob + d] = acc[t] / l; }\n }\n}\n",
9
+ "attention_wg_kv16": "// attention_wg with an f16-STORAGE KV cache (kvCache: 'f16'). Keep in lockstep with\n// attention_wg.wgsl: the ONLY difference is Kc/Vc are array<f16>, widened to f32 at the read.\nenable f16;\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> Kc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(3) var<storage, read> Vc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read_write> out: array<f32>; // [S, H, D]\nvar<workgroup> red: array<f32, 64>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (idx >= p.S * p.H) { return; }\n let tid = lid.x;\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n\n var acc: array<f32, 2>;\n acc[0] = 0.0;\n acc[1] = 0.0;\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n var part = 0.0;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { part = part + q[qb + d] * f32(Kc[kb + d]); }\n }\n red[tid] = part;\n workgroupBarrier();\n for (var s = 32u; s > 0u; s = s >> 1u) {\n if (tid < s) { red[tid] = red[tid] + red[tid + s]; }\n workgroupBarrier();\n }\n let score = red[0] * inv;\n workgroupBarrier();\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let w = exp(score - mnew);\n l = l * corr + w;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { acc[t] = acc[t] * corr + w * f32(Vc[kb + d]); }\n }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { out[ob + d] = acc[t] / l; }\n }\n}\n",
8
10
  "copy": "// Copy src[0..n) into dst[dstOff..dstOff+n). Used to append K/V into the persistent cache.\nstruct Params { n: u32, dstOff: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>;\n@group(0) @binding(2) var<storage, read_write> dst: array<f32>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.n) { return; }\n dst[p.dstOff + i] = src[i];\n}\n",
11
+ "copy_kv16": "// copy with an f16-STORAGE destination (kvCache: 'f16'): appends f32 K/V rows into the f16\n// cache (one f32 -> f16 rounding per value). Keep in lockstep with copy.wgsl.\nenable f16;\nstruct Params { n: u32, dstOff: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>;\n@group(0) @binding(2) var<storage, read_write> dst: array<f16>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.n) { return; }\n dst[p.dstOff + i] = f16(src[i]);\n}\n",
9
12
  "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
13
  "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
14
  "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",
@@ -24,6 +27,7 @@ const SHADERS = {
24
27
  "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
28
  "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
29
  "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",
30
+ "rmsnorm_rope_sg_kv16": "// rmsnorm_rope_sg writing into an f16-STORAGE KV cache (kvCache: 'f16'): used ONLY for the K\n// projection on the fused decode path, where the normed+roped K is written straight into the\n// cache. Keep in lockstep with rmsnorm_rope_sg.wgsl: the ONLY difference is y is array<f16>\n// (one f32 -> f16 rounding at the write). The q call keeps the f32 kernel.\nenable subgroups;\nenable f16;\noverride SG: u32 = 32u;\nstruct Params { R: u32, D: u32, eps: f32, outOff: u32, outStride: u32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [R, D]\n@group(0) @binding(2) var<storage, read> gamma: array<f32>; // [D]\n@group(0) @binding(3) var<storage, read> cos: array<f32>; // [D]\n@group(0) @binding(4) var<storage, read> sin: array<f32>; // [D]\n@group(0) @binding(5) var<storage, read_write> y: array<f16>; // [outOff + R*outStride]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let row = wg.x;\n if (row >= p.R) { return; }\n let base = row * p.D;\n var s = 0.0;\n for (var i = lane; i < p.D; i = i + SG) { let v = x[base + i]; s = s + v * v; }\n let inv = inverseSqrt(subgroupAdd(s) / f32(p.D) + p.eps);\n let half = p.D / 2u;\n let ob = p.outOff + row * p.outStride;\n for (var i = lane; i < p.D; i = i + SG) {\n let nd = x[base + i] * inv * gamma[i];\n var pd: u32; var sgn: f32;\n if (i < half) { pd = i + half; sgn = -1.0; } else { pd = i - half; sgn = 1.0; }\n let rot = sgn * (x[base + pd] * inv * gamma[pd]);\n y[ob + i] = f16(nd * cos[i] + rot * sin[i]);\n }\n}\n",
27
31
  "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",
28
32
  "rmsnorm_wg": "// RMSNorm, no-subgroup fallback: one workgroup per row; threads split D and tree-reduce the\n// sum of squares via shared memory. Replaces the one-thread-per-row kernel on this path: at\n// decode (R=1) that kernel walked 2xD elements serially on a single thread, latency-bound,\n// and it ran twice per layer - the dominant cost of the whole fallback decode step.\n// Mirrors rmsnorm_sg exactly, with subgroupAdd swapped for the shared-memory reduction.\noverride WG: u32 = 64u;\nstruct Params { R: u32, D: u32, eps: f32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [R, D]\n@group(0) @binding(2) var<storage, read> gamma: array<f32>; // [D]\n@group(0) @binding(3) var<storage, read_write> y: array<f32>; // [R, D]\nvar<workgroup> sdata: array<f32, 256>; // >= max WG\n\n@compute @workgroup_size(WG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let row = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (row >= p.R) { return; }\n let tid = lid.x;\n let base = row * p.D;\n var s = 0.0;\n for (var i = tid; i < p.D; i = i + WG) { let v = x[base + i]; s = s + v * v; }\n sdata[tid] = s;\n workgroupBarrier();\n for (var st = WG / 2u; st > 0u; st = st >> 1u) {\n if (tid < st) { sdata[tid] = sdata[tid] + sdata[tid + st]; }\n workgroupBarrier();\n }\n let inv = inverseSqrt(sdata[0] / f32(p.D) + p.eps);\n for (var i = tid; i < p.D; i = i + WG) { y[base + i] = x[base + i] * inv * gamma[i]; }\n}\n",
29
33
  "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",
@@ -207,17 +211,6 @@ const eqBytes = (a, b) => {
207
211
  for (let i = 0; i < b.length; i++) if (a[i] !== b[i]) return false;
208
212
  return true;
209
213
  };
210
- function concat(Cls, arrs) {
211
- let n = 0;
212
- for (const a of arrs) n += a.length;
213
- const o = new Cls(n);
214
- let p = 0;
215
- for (const a of arrs) {
216
- o.set(a, p);
217
- p += a.length;
218
- }
219
- return o;
220
- }
221
214
  /** Load a 1-bit model and return an {@link Engine}. Pass a model URL string for defaults. */
222
215
  async function createEngine(options) {
223
216
  const opts = typeof options === "string" ? { modelUrl: options } : options;
@@ -262,8 +255,7 @@ async function createEngine(options) {
262
255
  const manifest = await fetchJson(opts.manifestUrl ?? `${modelDir}/manifest.json`);
263
256
  opts.onProgress?.({ phase: "weights" });
264
257
  const dataUrl = opts.dataUrl ?? `${modelDir}/${manifest.data_file}`;
265
- const auxUrl = opts.auxUrl ?? `${modelDir}/${manifest.aux_file}`;
266
- let [data, aux] = await Promise.all([fetchBytes(dataUrl), fetchBytes(auxUrl)]);
258
+ let aux = await fetchBytes(opts.auxUrl ?? `${modelDir}/${manifest.aux_file}`);
267
259
  const A = manifest.arch;
268
260
  const T = manifest.tensors;
269
261
  const FINAL_NORM = `layers.${A.layers}.final_norm_layernorm`;
@@ -272,16 +264,15 @@ async function createEngine(options) {
272
264
  if (!T[FINAL_NORM]) throw new Error(`bitgpu: manifest is missing the final norm tensor '${FINAL_NORM}'`);
273
265
  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)`);
274
266
  const readRef = (ref) => {
275
- const src = ref.src === "aux" ? aux : data;
276
- 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`);
267
+ if (ref.src !== "aux") throw new Error("bitgpu: internal - readRef reads aux-file refs; data-file tensors stream through routes");
268
+ if (ref.off + ref.len > aux.byteLength) throw new Error(`bitgpu: tensor range ${ref.off}+${ref.len} exceeds the aux file (${aux.byteLength} bytes); the download is truncated or the manifest does not match it`);
277
269
  const V = VIEW[ref.dtype];
278
- if (V === Uint8Array) return new Uint8Array(src, ref.off, ref.len);
270
+ if (V === Uint8Array) return new Uint8Array(aux, ref.off, ref.len);
279
271
  const bpe = V.BYTES_PER_ELEMENT;
280
- if (ref.off % bpe === 0) return new V(src, ref.off, ref.len / bpe);
281
- return new V(src.slice(ref.off, ref.off + ref.len));
272
+ if (ref.off % bpe === 0) return new V(aux, ref.off, ref.len / bpe);
273
+ return new V(aux.slice(ref.off, ref.off + ref.len));
282
274
  };
283
275
  const readU8 = (ref) => readRef(ref);
284
- const readF32 = (ref) => readRef(ref);
285
276
  const adapter = await navigator.gpu.requestAdapter({ powerPreference });
286
277
  if (!adapter) throw new WebGPUUnavailableError("No suitable WebGPU adapter was found.");
287
278
  const hasSG = adapter.features.has("subgroups");
@@ -296,7 +287,12 @@ async function createEngine(options) {
296
287
  const SYNC_N = Math.max(1, opts.syncSteps ?? 4);
297
288
  const maxSeqLen = Math.max(1, opts.maxSeqLen ?? DEFAULT_MAX_SEQ);
298
289
  const useSG = hasSG && sgMin === sgMax && (sgMax === 16 || sgMax === 32 || sgMax === 64) && !forceNoSG;
299
- const device = await adapter.requestDevice({ requiredFeatures: useSG ? ["subgroups"] : [] });
290
+ const kv16 = opts.kvCache === "f16" && adapter.features.has("shader-f16");
291
+ const KVB = kv16 ? 2 : 4;
292
+ const features = [];
293
+ if (useSG) features.push("subgroups");
294
+ if (kv16) features.push("shader-f16");
295
+ const device = await adapter.requestDevice({ requiredFeatures: features });
300
296
  const lost = device.lost.then((info) => {
301
297
  const li = {
302
298
  reason: String(info.reason ?? "unknown"),
@@ -364,6 +360,14 @@ async function createEngine(options) {
364
360
  ]) specs.push([n, { WG: WG_NS }]);
365
361
  specs.push(["attention_wg"]);
366
362
  }
363
+ if (kv16) {
364
+ specs.push(["copy_kv16"]);
365
+ if (useSG) for (const n of ["attention_sg_kv16", "rmsnorm_rope_sg_kv16"]) specs.push([n, { SG: sgMax }]);
366
+ else specs.push(["attention_wg_kv16"]);
367
+ }
368
+ const ATT = kv16 ? useSG ? "attention_sg_kv16" : "attention_wg_kv16" : useSG ? "attention_sg" : "attention_wg";
369
+ const ROPE_K = kv16 ? "rmsnorm_rope_sg_kv16" : "rmsnorm_rope_sg";
370
+ const COPY_KV = kv16 ? "copy_kv16" : "copy";
367
371
  await Promise.all(specs.map(([n, c]) => mkPipe(n, c)));
368
372
  const S_ = GPUBufferUsage.STORAGE, CD = GPUBufferUsage.COPY_DST, CS = GPUBufferUsage.COPY_SRC, U = GPUBufferUsage.UNIFORM;
369
373
  let transients = null;
@@ -432,94 +436,243 @@ async function createEngine(options) {
432
436
  const resetCache = () => {
433
437
  fullHistory = [];
434
438
  };
439
+ if (manifest.luts.tgt2.src !== "aux") throw new Error("bitgpu: luts.tgt2 must live in the aux file (the streaming loader needs it before the weights arrive)");
435
440
  const tgt2 = readU8(manifest.luts.tgt2);
436
- let tgt4 = readU8(manifest.luts.tgt4);
437
441
  const signTable = /* @__PURE__ */ new Uint8Array(256);
438
442
  for (let b = 0; b < 256; b++) {
439
443
  let bits = 0;
440
444
  for (let j = 0; j < 8; j++) bits |= ((tgt2[2 * b + (j >> 2)] >> 2 * (j & 3) & 3) >> 1 & 1) << j;
441
445
  signTable[b] = bits;
442
446
  }
443
- const rawBin = (name) => {
444
- const t = T[name];
445
- const wq = readU8(t.weight);
446
- const sign = new Uint8Array(wq.length);
447
- for (let i = 0; i < wq.length; i++) sign[i] = signTable[wq[i]];
447
+ const routes = [];
448
+ const gbuf = (len) => device.createBuffer({
449
+ size: len + 3 & -4,
450
+ usage: S_ | CD
451
+ });
452
+ const gpuSink = (buf, base) => {
453
+ let written = 0;
454
+ let carry = /* @__PURE__ */ new Uint8Array(0);
448
455
  return {
449
- sign,
450
- scales: readF32(t.scales),
451
- N: t.N,
452
- K: t.K,
453
- nb: t.K / 128
456
+ push(bytes) {
457
+ let all = bytes;
458
+ if (carry.length) {
459
+ all = new Uint8Array(carry.length + bytes.length);
460
+ all.set(carry);
461
+ all.set(bytes, carry.length);
462
+ }
463
+ const n = all.length & -4;
464
+ if (n) device.queue.writeBuffer(buf, base + written, all, 0, n);
465
+ carry = all.subarray(n).slice();
466
+ written += n;
467
+ },
468
+ finish() {
469
+ if (!carry.length) return;
470
+ const pad = /* @__PURE__ */ new Uint8Array(4);
471
+ pad.set(carry);
472
+ device.queue.writeBuffer(buf, base + written, pad);
473
+ written += 4;
474
+ carry = /* @__PURE__ */ new Uint8Array(0);
475
+ }
476
+ };
477
+ };
478
+ const wire = (ref, push, finish) => {
479
+ if (ref.src === "aux") {
480
+ push(new Uint8Array(readRef(ref).buffer, ref.off, ref.len));
481
+ finish();
482
+ } else routes.push({
483
+ off: ref.off,
484
+ len: ref.len,
485
+ push,
486
+ finish
487
+ });
488
+ };
489
+ const wireRaw = (ref, buf, base = 0) => {
490
+ const s = gpuSink(buf, base);
491
+ wire(ref, s.push, s.finish);
492
+ };
493
+ const wireSign = (ref, buf, base = 0) => {
494
+ const s = gpuSink(buf, base);
495
+ wire(ref, (b) => {
496
+ const o = new Uint8Array(b.length);
497
+ for (let i = 0; i < b.length; i++) o[i] = signTable[b[i]];
498
+ s.push(o);
499
+ }, s.finish);
500
+ };
501
+ const wireQ2 = (ref, buf) => {
502
+ const s = gpuSink(buf, 0);
503
+ wire(ref, (b) => {
504
+ const o = new Uint8Array(b.length * 2);
505
+ for (let i = 0; i < b.length; i++) {
506
+ o[2 * i] = tgt2[2 * b[i]];
507
+ o[2 * i + 1] = tgt2[2 * b[i] + 1];
508
+ }
509
+ s.push(o);
510
+ }, s.finish);
511
+ };
512
+ const wireCpu = (ref) => {
513
+ const dst = new Uint8Array(ref.len);
514
+ let w = 0;
515
+ wire(ref, (b) => {
516
+ dst.set(b, w);
517
+ w += b.length;
518
+ }, () => void 0);
519
+ return dst;
520
+ };
521
+ const wireCpuGpu = (ref) => {
522
+ const buf = gbuf(ref.len);
523
+ const s = gpuSink(buf, 0);
524
+ const dst = new Uint8Array(ref.len);
525
+ let w = 0;
526
+ wire(ref, (b) => {
527
+ dst.set(b, w);
528
+ w += b.length;
529
+ s.push(b);
530
+ }, s.finish);
531
+ return {
532
+ cpu: dst,
533
+ buf
454
534
  };
455
535
  };
456
536
  device.pushErrorScope("out-of-memory");
457
537
  const W = {};
458
538
  for (const [name, t] of Object.entries(T)) if (t.kind === "q2") {
459
- const wq = readU8(t.weight), codes = new Uint8Array(wq.length * 2);
460
- for (let i = 0; i < wq.length; i++) {
461
- codes[2 * i] = tgt2[2 * wq[i]];
462
- codes[2 * i + 1] = tgt2[2 * wq[i] + 1];
463
- }
539
+ const codes = gbuf(t.weight.len * 2);
540
+ wireQ2(t.weight, codes);
541
+ const scales = gbuf(t.scales.len);
542
+ wireRaw(t.scales, scales);
464
543
  W[name] = {
465
544
  N: t.N,
466
545
  K: t.K,
467
546
  nb: t.K / 128,
468
547
  zp: 2,
469
- codes: upload(codes),
470
- scales: upload(readF32(t.scales))
548
+ codes,
549
+ scales
550
+ };
551
+ } else if (t.kind === "f32" && t.weight) {
552
+ const buf = gbuf(t.weight.len);
553
+ wireRaw(t.weight, buf);
554
+ W[name] = { buf };
555
+ }
556
+ const fuse = (parts) => {
557
+ const sign = gbuf(parts.reduce((n, p) => n + p.weight.len, 0));
558
+ const scales = gbuf(parts.reduce((n, p) => n + p.scales.len, 0));
559
+ let so = 0;
560
+ let co = 0;
561
+ for (const p of parts) {
562
+ wireSign(p.weight, sign, so);
563
+ so += p.weight.len;
564
+ wireRaw(p.scales, scales, co);
565
+ co += p.scales.len;
566
+ }
567
+ return {
568
+ sign,
569
+ scales
471
570
  };
472
- } else if (t.kind === "f32" && t.weight) W[name] = { buf: upload(readRef(t.weight)) };
571
+ };
473
572
  for (let li = 0; li < A.layers; li++) {
474
- const q = rawBin(`layers.${li}.attn.q_proj`), k = rawBin(`layers.${li}.attn.k_proj`), v = rawBin(`layers.${li}.attn.v_proj`);
573
+ const q = T[`layers.${li}.attn.q_proj`], k = T[`layers.${li}.attn.k_proj`], v = T[`layers.${li}.attn.v_proj`];
475
574
  W[`layers.${li}.attn.qkv`] = {
476
575
  K: q.K,
477
- nb: q.nb,
576
+ nb: q.K / 128,
478
577
  N0: q.N,
479
578
  N1: k.N,
480
579
  N2: v.N,
481
- sign: upload(concat(Uint8Array, [
482
- q.sign,
483
- k.sign,
484
- v.sign
485
- ])),
486
- scales: upload(concat(Float32Array, [
487
- q.scales,
488
- k.scales,
489
- v.scales
490
- ]))
580
+ ...fuse([
581
+ q,
582
+ k,
583
+ v
584
+ ])
491
585
  };
492
- const g = rawBin(`layers.${li}.mlp.gate_proj`), u = rawBin(`layers.${li}.mlp.up_proj`);
586
+ const g = T[`layers.${li}.mlp.gate_proj`], u = T[`layers.${li}.mlp.up_proj`];
493
587
  W[`layers.${li}.mlp.gateup`] = {
494
588
  K: g.K,
495
- nb: g.nb,
589
+ nb: g.K / 128,
496
590
  N0: g.N,
497
591
  N1: u.N,
498
592
  N2: 0,
499
- sign: upload(concat(Uint8Array, [g.sign, u.sign])),
500
- scales: upload(concat(Float32Array, [g.scales, u.scales]))
593
+ ...fuse([g, u])
501
594
  };
502
595
  for (const nm of [`layers.${li}.attn.o_proj`, `layers.${li}.mlp.down_proj`]) {
503
- const r = rawBin(nm);
596
+ const r = T[nm];
504
597
  W[nm] = {
505
598
  N: r.N,
506
599
  K: r.K,
507
- nb: r.nb,
508
- sign: upload(r.sign),
509
- scales: upload(r.scales)
600
+ nb: r.K / 128,
601
+ ...fuse([r])
510
602
  };
511
603
  }
512
604
  }
513
- let embWq = readU8(T.embed_tokens.weight), embScales = readF32(T.embed_tokens.scales), embZp = readU8(T.embed_tokens.zp);
514
- let cosCache = readF32(T.cos_cache), sinCache = readF32(T.sin_cache);
515
- const embWqG = upload(embWq), tgt4G = upload(tgt4), embScalesG = upload(embScales), embZpG = upload(embZp);
516
- embWq = embWq.slice();
517
- embScales = embScales.slice();
518
- embZp = embZp.slice();
519
- cosCache = cosCache.slice();
520
- sinCache = sinCache.slice();
521
- tgt4 = tgt4.slice();
522
- data = null;
605
+ const embW = wireCpuGpu(T.embed_tokens.weight);
606
+ const embS = wireCpuGpu(T.embed_tokens.scales);
607
+ const embZ = wireCpuGpu(T.embed_tokens.zp);
608
+ const tgt4W = wireCpuGpu(manifest.luts.tgt4);
609
+ const cosBytes = wireCpu(T.cos_cache);
610
+ const sinBytes = wireCpu(T.sin_cache);
611
+ const embWq = embW.cpu;
612
+ const embScales = new Float32Array(embS.cpu.buffer);
613
+ const embZp = embZ.cpu;
614
+ const tgt4 = tgt4W.cpu;
615
+ const cosCache = new Float32Array(cosBytes.buffer);
616
+ const sinCache = new Float32Array(sinBytes.buffer);
617
+ const embWqG = embW.buf, tgt4G = tgt4W.buf, embScalesG = embS.buf, embZpG = embZ.buf;
618
+ routes.sort((a, b) => a.off - b.off || a.len - b.len);
619
+ const merged = [];
620
+ for (const r of routes) {
621
+ const last = merged[merged.length - 1];
622
+ if (last && last.off === r.off && last.len === r.len) {
623
+ const lp = last.push, lf = last.finish;
624
+ last.push = (b) => {
625
+ lp(b);
626
+ r.push(b);
627
+ };
628
+ last.finish = () => {
629
+ lf();
630
+ r.finish();
631
+ };
632
+ } else if (last && r.off < last.off + last.len) throw new Error("bitgpu: partially overlapping data-file tensor ranges (unsupported by the streaming loader)");
633
+ else merged.push(r);
634
+ }
635
+ const needed = merged.length ? merged[merged.length - 1].off + merged[merged.length - 1].len : 0;
636
+ const reader = (opts.fetchStream ? await opts.fetchStream(dataUrl) : opts.fetchArrayBuffer ? new Response(await opts.fetchArrayBuffer(dataUrl)).body : await (async () => {
637
+ const res = await fetch(dataUrl);
638
+ if (!res.ok) throw new Error(`bitgpu: fetch ${dataUrl} failed: HTTP ${res.status}`);
639
+ return res.body ?? new Response(await res.arrayBuffer()).body;
640
+ })()).getReader();
641
+ let cursor = 0;
642
+ let ri = 0;
643
+ for (;;) {
644
+ const { done, value } = await reader.read();
645
+ if (done) break;
646
+ let bo = 0;
647
+ while (bo < value.byteLength && ri < merged.length) {
648
+ const r = merged[ri];
649
+ if (cursor >= r.off + r.len) {
650
+ ri++;
651
+ continue;
652
+ }
653
+ if (cursor < r.off) {
654
+ const skip = Math.min(r.off - cursor, value.byteLength - bo);
655
+ cursor += skip;
656
+ bo += skip;
657
+ continue;
658
+ }
659
+ const n = Math.min(r.off + r.len - cursor, value.byteLength - bo);
660
+ r.push(value.subarray(bo, bo + n));
661
+ cursor += n;
662
+ bo += n;
663
+ if (cursor === r.off + r.len) {
664
+ r.finish();
665
+ ri++;
666
+ }
667
+ }
668
+ cursor += value.byteLength - bo;
669
+ opts.onProgress?.({
670
+ phase: "weights",
671
+ loaded: Math.min(cursor, needed),
672
+ total: needed
673
+ });
674
+ }
675
+ if (cursor < needed) throw new Error(`bitgpu: the data file ended at ${cursor} bytes but tensors extend to ${needed}; the download is truncated or the manifest does not match it`);
523
676
  aux = null;
524
677
  function embedDequant(ids) {
525
678
  const Hh = A.hidden, out = new Float32Array(ids.length * Hh);
@@ -554,25 +707,31 @@ async function createEngine(options) {
554
707
  let kvCapacity = Math.min(maxSeqLen, 512);
555
708
  const Kc = [], Vc = [];
556
709
  for (let li = 0; li < A.layers; li++) {
557
- Kc.push(actBuf(kvCapacity * KV * Dh));
558
- Vc.push(actBuf(kvCapacity * KV * Dh));
710
+ Kc.push(device.createBuffer({
711
+ size: kvCapacity * KV * Dh * KVB,
712
+ usage: S_ | CS | CD
713
+ }));
714
+ Vc.push(device.createBuffer({
715
+ size: kvCapacity * KV * Dh * KVB,
716
+ usage: S_ | CS | CD
717
+ }));
559
718
  }
560
719
  const loadOom = await device.popErrorScope();
561
720
  if (loadOom) throw new GpuOutOfMemoryError(`GPU allocation failed while loading weights (~350 MB VRAM needed): ${loadOom.message}`);
562
721
  async function ensureKvCapacity(needed) {
563
722
  if (needed <= kvCapacity) return;
564
723
  const newCap = Math.min(maxSeqLen, Math.max(needed, kvCapacity * 2));
565
- const copyBytes = kvCapacity * KV * Dh * 4;
724
+ const copyBytes = kvCapacity * KV * Dh * KVB;
566
725
  device.pushErrorScope("out-of-memory");
567
726
  const enc = device.createCommandEncoder();
568
727
  const olds = [];
569
728
  for (let li = 0; li < A.layers; li++) {
570
729
  const nk = device.createBuffer({
571
- size: newCap * KV * Dh * 4,
730
+ size: newCap * KV * Dh * KVB,
572
731
  usage: S_ | CS | CD
573
732
  });
574
733
  const nv = device.createBuffer({
575
- size: newCap * KV * Dh * 4,
734
+ size: newCap * KV * Dh * KVB,
576
735
  usage: S_ | CS | CD
577
736
  });
578
737
  enc.copyBufferToBuffer(Kc[li], 0, nk, 0, copyBytes);
@@ -892,7 +1051,7 @@ async function createEngine(options) {
892
1051
  k,
893
1052
  v
894
1053
  ], gx, Math.ceil(Ntot / gx));
895
- run(pass, "copy", [
1054
+ run(pass, COPY_KV, [
896
1055
  ["u", KV * Dh],
897
1056
  ["u", posBase * KV * Dh],
898
1057
  ["u", 0],
@@ -912,7 +1071,7 @@ async function createEngine(options) {
912
1071
  cos,
913
1072
  sin
914
1073
  ], qr, H);
915
- runN(pass, "rmsnorm_rope_sg", [
1074
+ runN(pass, ROPE_K, [
916
1075
  ["u", KV],
917
1076
  ["u", Dh],
918
1077
  ["f", A.rms_eps],
@@ -927,7 +1086,7 @@ async function createEngine(options) {
927
1086
  ], Kc[li], KV);
928
1087
  cap(li, "qr", qr);
929
1088
  const att = actBuf(H * Dh);
930
- runN(pass, "attention_sg", [
1089
+ runN(pass, ATT, [
931
1090
  ["u", 1],
932
1091
  ["u", H],
933
1092
  ["u", KV],
@@ -992,13 +1151,13 @@ async function createEngine(options) {
992
1151
  cos,
993
1152
  sin
994
1153
  ], kr, S * KV * Dh);
995
- run(pass, "copy", [
1154
+ run(pass, COPY_KV, [
996
1155
  ["u", S * KV * Dh],
997
1156
  ["u", posBase * KV * Dh],
998
1157
  ["u", 0],
999
1158
  ["u", 0]
1000
1159
  ], [kr], Kc[li], S * KV * Dh);
1001
- run(pass, "copy", [
1160
+ run(pass, COPY_KV, [
1002
1161
  ["u", S * KV * Dh],
1003
1162
  ["u", posBase * KV * Dh],
1004
1163
  ["u", 0],
@@ -1006,20 +1165,14 @@ async function createEngine(options) {
1006
1165
  ], [v], Vc[li], S * KV * Dh);
1007
1166
  cap(li, "qr", qr);
1008
1167
  const att = actBuf(S * H * Dh);
1009
- const attF = [
1168
+ runN(pass, ATT, [
1010
1169
  ["u", S],
1011
1170
  ["u", H],
1012
1171
  ["u", KV],
1013
1172
  ["u", Dh],
1014
1173
  ["u", posBase],
1015
1174
  ["u", Ltot]
1016
- ];
1017
- if (useSG) runN(pass, "attention_sg", attF, [
1018
- qr,
1019
- Kc[li],
1020
- Vc[li]
1021
- ], att, S * H);
1022
- else runN(pass, "attention_wg", attF, [
1175
+ ], [
1023
1176
  qr,
1024
1177
  Kc[li],
1025
1178
  Vc[li]
@@ -1803,8 +1956,10 @@ async function createEngine(options) {
1803
1956
  const ck = {};
1804
1957
  for (const [name, b] of Object.entries(DBG0)) ck[name] = await readback(b, b.size / 4);
1805
1958
  const off = pos * KV * Dh;
1806
- ck.kc = (await readback(Kc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
1807
- ck.vc = (await readback(Vc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
1959
+ if (!kv16) {
1960
+ ck.kc = (await readback(Kc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
1961
+ ck.vc = (await readback(Vc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
1962
+ }
1808
1963
  ck.fn = await readback(r.fn, Hd);
1809
1964
  ck.logits = await readback(lg, W.lm_head.N);
1810
1965
  FORCE_SLOW = false;
@@ -1881,6 +2036,7 @@ async function createEngine(options) {
1881
2036
  const capabilities = {
1882
2037
  useSubgroups: useSG,
1883
2038
  subgroupSize: sgMax,
2039
+ kvCache: kv16 ? "f16" : "f32",
1884
2040
  adapter: {
1885
2041
  vendor: info.vendor,
1886
2042
  architecture: info.architecture,