bitgpu 0.4.0 → 0.5.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/README.md CHANGED
@@ -3,10 +3,13 @@
3
3
  A fast, dependency-free WebGPU runtime for **low-bit LLMs** in the browser.
4
4
 
5
5
  Today it runs **1-bit (binary-weight)** models.
6
- Reference target is Bonsai-1.7B (Qwen3 architecture, sign-packed binary linear weights + 2/4-bit tied
7
- embeddings). Bit-exact with the reference forward, GPU-resident decode (greedy or sampled), streaming,
8
- EOS stop, `AbortSignal`, and cross-turn KV-cache reuse. Runs the fast subgroup path on Apple / NVIDIA /
6
+ Reference targets are Bonsai **1.7B, 4B and 8B** (Qwen3 architecture, sign-packed binary linear
7
+ weights + 2/4-bit embeddings, tied or untied lm_head) - every size is gated bit-exact against the
8
+ reference forward on real hardware. GPU-resident decode (greedy or sampled), streaming, EOS stop,
9
+ `AbortSignal`, and cross-turn KV-cache reuse. Runs the fast subgroup path on Apple / NVIDIA /
9
10
  recent AMD and falls back to a workgroup-reduction path everywhere else WebGPU is available.
11
+ Device limits are negotiated from the manifest, so the 8B's ~148 MiB lm_head binding is requested
12
+ only when that model needs it and smaller models keep running at WebGPU's guaranteed minimums.
10
13
 
11
14
  ## Install
12
15
 
@@ -50,6 +53,33 @@ engine.dispose()
50
53
  Tokenization is intentionally out of scope: the engine operates on token ids, so you can pair it
51
54
  with any tokenizer.
52
55
 
56
+ ## Bring your own model
57
+
58
+ bitgpu loads its own small format instead of parsing ONNX at runtime: a `manifest.json` (the
59
+ architecture contract + every tensor mapped to a byte range) and a ~30 KB aux file, both
60
+ produced ONCE, offline, from a standard export - while the big weights file is used
61
+ byte-for-byte unchanged, so it can keep streaming from wherever it already lives (e.g. the
62
+ Hugging Face Hub). Same one-time-conversion model as GGUF/llama.cpp or MLX.
63
+
64
+ ```sh
65
+ python tools/convert.py --model <dir with config.json + the q1 .onnx + its data file>
66
+ ```
67
+
68
+ Host the two small files anywhere (they're static), point `createEngine` at them, done:
69
+
70
+ ```ts
71
+ createEngine({
72
+ manifestUrl: 'https://your-site.example/model/manifest.json',
73
+ auxUrl: 'https://your-site.example/model/model_q1.aux.bin',
74
+ dataUrl: 'https://huggingface.co/<repo>/resolve/main/onnx/model_q1.onnx_data',
75
+ })
76
+ ```
77
+
78
+ Compatibility envelope: Qwen3-family models quantized with the onnx-community 1-bit ("q1")
79
+ recipe (silu/SwiGLU, head_dim <= 128, 128-wide scale blocks) - the engine validates the
80
+ manifest loudly at load. Format spec: [docs/FORMAT.md](docs/FORMAT.md); the full pipeline
81
+ including regenerating the verification fixtures for a new model: [tools/README.md](tools/README.md).
82
+
53
83
  ## API
54
84
 
55
85
  - `createEngine(options: EngineOptions | string): Promise<Engine>` - load a model. A bare string is
@@ -122,6 +152,16 @@ Or open `http://localhost:8000/examples/verify.html` in a WebGPU browser and cli
122
152
  gate on real hardware before every release; CI covers only the CPU-checkable parts (types, sampler
123
153
  math, drafter, packaging).
124
154
 
155
+ The gate is model-parametric: `verify.html?model=<tag>` loads `examples/model-<tag>` against
156
+ `test-fixtures/forward-<tag>`, and the headless driver automatically runs every staged variant.
157
+ Fixture sets for all three Bonsai sizes are committed - `forward` (1.7B, hidden 2048),
158
+ `forward-4b` (4B, hidden 2560) and `forward-8b` (8B, hidden 4096, untied lm_head, raised
159
+ device limits) - so engine changes are checked against three geometries; stage the extra
160
+ weights with `ln -s /path/to/bonsai-<size> examples/model-<size>`. To add fixtures for another
161
+ model, run `tools/golden.py` then `tools/reference.py --dump test-fixtures/forward-<tag>` on the
162
+ converted work dir and record the engine's greedy continuation as `known_good` in that set's
163
+ `params.json`.
164
+
125
165
  ### Releasing
126
166
 
127
167
  Publishing runs through GitHub Actions with npm trusted publishing (OIDC + provenance, no token).
package/dist/index.d.ts CHANGED
@@ -69,7 +69,8 @@ interface DeviceLostInfo {
69
69
  * to sample; otherwise decoding is greedy (argmax). Sampling matches transformers.js v4.2.0 exactly
70
70
  * (repetition_penalty, no_repeat_ngram, temperature, top_k, multinomial via a Mersenne-Twister RNG). */
71
71
  interface GenerateOptions {
72
- /** Maximum number of new tokens to generate. Default `256`. */
72
+ /** Maximum number of new tokens to generate. Default `256`. `0` prefills the prompt into the
73
+ * KV cache and emits nothing (like {@link Engine.prefill}, but composable with `reuseCache`). */
73
74
  maxTokens?: number;
74
75
  /** Reuse the KV cache from the previous turn: treat the passed token ids as the DELTA to append to
75
76
  * the cached conversation (not a full prompt), prefilling only those tokens. Requires a prior
@@ -83,13 +84,16 @@ interface GenerateOptions {
83
84
  signal?: AbortSignal;
84
85
  /** Softmax temperature. A value other than 0 or 1 enables sampling; 0 or 1 (or unset) is greedy. */
85
86
  temperature?: number;
86
- /** Top-k sampling cutoff (candidate count). Default `20` when sampling. */
87
+ /** Top-k sampling cutoff (candidate count). Default `20` when sampling; clamped to `[1, vocab]`
88
+ * (the GPU reduces the logits to this many candidates, so `0` cannot mean "disabled"). */
87
89
  topK?: number;
88
90
  /** Top-p (nucleus) cutoff. Accepted for API compatibility but not applied (a no-op, matching transformers.js v4.2.0). */
89
91
  topP?: number;
90
- /** Repetition penalty over the deduped prompt+generated id set (`logit<0 ? *p : /p`). Default `1` (off). */
92
+ /** Repetition penalty over the deduped prompt+generated id set (`logit<0 ? *p : /p`). Default `1`
93
+ * (off). Applied under greedy decoding too (the penalized argmax), matching transformers.js. */
91
94
  repetitionPenalty?: number;
92
- /** Block any n-gram of this size from repeating. Default `0` (off). */
95
+ /** Block any n-gram of this size from repeating. Default `0` (off). Applied under greedy decoding
96
+ * too, matching transformers.js. */
93
97
  noRepeatNgramSize?: number;
94
98
  /** Seed for the sampler RNG. Omit to seed from entropy (non-deterministic, like production). */
95
99
  seed?: number;
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ const SHADERS = {
9
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",
10
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
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",
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",
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 * H/8] packed\n@group(0) @binding(3) var<storage, read> tgt4: array<u32>; // uint8 [256*4] packed (1 src byte -> 4)\n@group(0) @binding(4) var<storage, read> embScales: array<f32>;// [vocab * H/128]\n@group(0) @binding(5) var<storage, read> embZp: array<u32>; // uint8 [vocab * ceil(H/256)] packed\n@group(0) @binding(6) var<storage, read_write> out: array<f32>;// [H]\n\n@compute @workgroup_size(WG)\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\n let id = tokenId[p.srcIdx];\n // Per-row strides derived from H: rowBytes source bytes, scaleRow f32 scales,\n // zpRow packed zero-point bytes (H=2048 -> 256/16/8, H=2560 -> 320/20/10).\n let rowBytes = p.H >> 3u;\n let scaleRow = p.H >> 7u;\n let zpRow = (scaleRow + 1u) >> 1u;\n for (var k = lid.x; k < p.H; k = k + WG) {\n let i = k >> 3u;\n let qd = (k >> 1u) & 3u;\n let c = k & 1u;\n let wqIdx = id * rowBytes + i;\n let e = (embWq[wqIdx >> 2u] >> (8u * (wqIdx & 3u))) & 0xffu; // source byte 0..255\n let tIdx = 4u * e + qd;\n let t = (tgt4[tIdx >> 2u] >> (8u * (tIdx & 3u))) & 0xffu; // expanded byte (2 codes)\n let code = (t >> (4u * c)) & 0xfu;\n let blk = k >> 7u;\n let zpIdx = id * zpRow + (blk >> 1u);\n let zpByte = (embZp[zpIdx >> 2u] >> (8u * (zpIdx & 3u))) & 0xffu;\n let zp = (zpByte >> (4u * (blk & 1u))) & 0xfu;\n out[k] = (f32(code) - f32(zp)) * embScales[id * scaleRow + blk];\n }\n}\n",
13
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",
14
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",
15
15
  "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",
@@ -23,7 +23,7 @@ const SHADERS = {
23
23
  "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",
24
24
  "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",
25
25
  "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",
26
- "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",
26
+ "matmul_split_tiled": "// Tiled register-blocked binary GEMM to 3 outputs (qkv or gate/up), PREFILL (M>1), vec4 K-accum.\n// Weights concatenated along N (N0|N1|N2); each output element routes individually to\n// out0/out1/out2 by its global column, so N0/N1/N2 need no alignment. Same vec4 design as\n// matmul_resid_tiled.\nconst BM: u32 = 64u;\nconst BN: u32 = 64u;\nconst BKV: u32 = 4u; // BK / 4 (BK = 16)\nstruct Params { M: u32, K: u32, nb: u32, N0: u32, N1: u32, N2: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4]\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\n\nvar<workgroup> xs: array<vec4<f32>, 256>;\nvar<workgroup> ws: array<vec4<f32>, 256>;\n\n@compute @workgroup_size(256)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let Ntot = p.N0 + p.N1 + p.N2;\n let tid = lid.x;\n let tileM = wg.y * BM;\n let tileN = wg.x * BN;\n let tr = (tid / 16u) * 4u;\n let tc = (tid % 16u) * 4u;\n let Kv = p.K / 4u;\n var acc: array<f32, 16>;\n for (var i = 0u; i < 16u; i = i + 1u) { acc[i] = 0.0; }\n\n let Ksteps = Kv / BKV;\n for (var ks = 0u; ks < Ksteps; ks = ks + 1u) {\n let k0v = ks * BKV;\n for (var e = tid; e < BM * BKV; e = e + 256u) {\n let m = e / BKV; let kv = e % BKV; let gm = tileM + m;\n xs[e] = select(vec4<f32>(0.0), x[gm * Kv + (k0v + kv)], gm < p.M);\n }\n for (var e = tid; e < BN * BKV; e = e + 256u) {\n let n = e / BKV; let kv = e % BKV; let gn = tileN + n; let k = (k0v + kv) * 4u;\n var wv = vec4<f32>(0.0);\n if (gn < Ntot) {\n let bits4 = (signbits[gn * (p.K / 32u) + (k >> 5u)] >> (k & 31u)) & 0xfu;\n let s = scales[gn * p.nb + (k / 128u)];\n wv = vec4<f32>(select(-s, s, (bits4 & 1u) != 0u), select(-s, s, (bits4 & 2u) != 0u),\n select(-s, s, (bits4 & 4u) != 0u), select(-s, s, (bits4 & 8u) != 0u));\n }\n ws[e] = wv;\n }\n workgroupBarrier();\n for (var kv = 0u; kv < BKV; kv = kv + 1u) {\n var xr: array<vec4<f32>, 4>;\n for (var tm = 0u; tm < 4u; tm = tm + 1u) { xr[tm] = xs[(tr + tm) * BKV + kv]; }\n for (var tn = 0u; tn < 4u; tn = tn + 1u) {\n let w = ws[(tc + tn) * BKV + kv];\n for (var tm = 0u; tm < 4u; tm = tm + 1u) { acc[tm * 4u + tn] = acc[tm * 4u + tn] + dot(xr[tm], w); }\n }\n }\n workgroupBarrier();\n }\n\n for (var tm = 0u; tm < 4u; tm = tm + 1u) {\n let gm = tileM + tr + tm;\n if (gm >= p.M) { continue; }\n for (var tn = 0u; tn < 4u; tn = tn + 1u) {\n let gn = tileN + tc + tn;\n if (gn >= Ntot) { continue; }\n let v = acc[tm * 4u + tn];\n if (gn < p.N0) { out0[gm * p.N0 + gn] = v; }\n else if (gn < p.N0 + p.N1) { out1[gm * p.N1 + (gn - p.N0)] = v; }\n else { out2[gm * p.N2 + (gn - p.N0 - p.N1)] = v; }\n }\n }\n}\n",
27
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",
28
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",
29
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",
@@ -196,6 +196,7 @@ const WGSLS = [
196
196
  "copy"
197
197
  ];
198
198
  const DEFAULT_MAX_SEQ = 2048;
199
+ const PREFILL_SEG = 256;
199
200
  const PARAM_AB = /* @__PURE__ */ new ArrayBuffer(64);
200
201
  const PARAM_DV = new DataView(PARAM_AB);
201
202
  const PARAM_U8 = new Uint8Array(PARAM_AB);
@@ -213,6 +214,15 @@ const eqBytes = (a, b) => {
213
214
  };
214
215
  /** Load a 1-bit model and return an {@link Engine}. Pass a model URL string for defaults. */
215
216
  async function createEngine(options) {
217
+ const holder = {};
218
+ try {
219
+ return await createEngineInner(options, holder);
220
+ } catch (e) {
221
+ holder.device?.destroy();
222
+ throw e;
223
+ }
224
+ }
225
+ async function createEngineInner(options, holder) {
216
226
  const opts = typeof options === "string" ? { modelUrl: options } : options;
217
227
  const modelDir = opts.modelUrl ? opts.modelUrl.replace(/\/$/, "") : null;
218
228
  if (!modelDir && !opts.manifestUrl) throw new Error("createEngine: provide modelUrl or manifestUrl");
@@ -261,7 +271,9 @@ async function createEngine(options) {
261
271
  const FINAL_NORM = `layers.${A.layers}.final_norm_layernorm`;
262
272
  if (A.act !== "silu") throw new Error(`bitgpu: unsupported activation '${A.act}' (kernels implement silu/SwiGLU)`);
263
273
  if (A.head_dim > 128) throw new Error(`bitgpu: unsupported head_dim ${A.head_dim} (kernels assume <= 128)`);
274
+ if (A.heads % A.kv_heads !== 0) throw new Error(`bitgpu: heads ${A.heads} not divisible by kv_heads ${A.kv_heads} (GQA kernels assume an integer group size)`);
264
275
  if (!T[FINAL_NORM]) throw new Error(`bitgpu: manifest is missing the final norm tensor '${FINAL_NORM}'`);
276
+ if (!T.cos_cache || !T.sin_cache) throw new Error("bitgpu: manifest is missing the baked cos_cache/sin_cache RoPE tensors");
265
277
  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)`);
266
278
  const readRef = (ref) => {
267
279
  if (ref.src !== "aux") throw new Error("bitgpu: internal - readRef reads aux-file refs; data-file tensors stream through routes");
@@ -286,13 +298,64 @@ async function createEngine(options) {
286
298
  const tiledPrefill = (S) => FORCETILE || !NOTILE && S >= 64;
287
299
  const SYNC_N = Math.max(1, opts.syncSteps ?? 4);
288
300
  const maxSeqLen = Math.max(1, opts.maxSeqLen ?? DEFAULT_MAX_SEQ);
289
- const useSG = hasSG && sgMin === sgMax && (sgMax === 16 || sgMax === 32 || sgMax === 64) && !forceNoSG;
301
+ const useSG = hasSG && sgMin === sgMax && (sgMax === 16 || sgMax === 32 || sgMax === 64) && A.head_dim % sgMax === 0 && !forceNoSG;
290
302
  const kv16 = opts.kvCache === "f16" && adapter.features.has("shader-f16");
291
303
  const KVB = kv16 ? 2 : 4;
292
304
  const features = [];
293
305
  if (useSG) features.push("subgroups");
294
306
  if (kv16) features.push("shader-f16");
295
- const device = await adapter.requestDevice({ requiredFeatures: features });
307
+ const DEFAULT_BINDING = 134217728;
308
+ const DEFAULT_BUFFER = 268435456;
309
+ let needBind = 0;
310
+ let weightBytes = 0;
311
+ const track = (bytes) => {
312
+ const b = bytes + 3 & -4;
313
+ needBind = Math.max(needBind, b);
314
+ weightBytes += b;
315
+ };
316
+ for (const t of Object.values(T)) if (t.kind === "q2") {
317
+ track(t.weight.len * 2);
318
+ track(t.scales.len);
319
+ } else if (t.kind === "f32" && t.weight) track(t.weight.len);
320
+ const fusedLen = (names, f) => names.reduce((n, nm) => n + T[nm][f].len, 0);
321
+ for (let li = 0; li < A.layers; li++) {
322
+ const groups = [
323
+ [
324
+ `layers.${li}.attn.q_proj`,
325
+ `layers.${li}.attn.k_proj`,
326
+ `layers.${li}.attn.v_proj`
327
+ ],
328
+ [`layers.${li}.mlp.gate_proj`, `layers.${li}.mlp.up_proj`],
329
+ [`layers.${li}.attn.o_proj`],
330
+ [`layers.${li}.mlp.down_proj`]
331
+ ];
332
+ for (const g of groups) {
333
+ track(fusedLen(g, "weight"));
334
+ track(fusedLen(g, "scales"));
335
+ }
336
+ }
337
+ for (const r of [
338
+ T.embed_tokens.weight,
339
+ T.embed_tokens.scales,
340
+ T.embed_tokens.zp,
341
+ manifest.luts.tgt4
342
+ ]) track(r.len);
343
+ const kvLayerBytes = maxSeqLen * A.kv_heads * A.head_dim * KVB;
344
+ needBind = Math.max(needBind, kvLayerBytes, PREFILL_SEG * Math.max(A.heads * A.head_dim, A.intermediate) * 4, 32 * A.vocab * 4);
345
+ const requiredLimits = {};
346
+ if (needBind > DEFAULT_BINDING) {
347
+ if (needBind > adapter.limits.maxStorageBufferBindingSize) throw new GpuOutOfMemoryError(`this model needs a ${Math.ceil(needBind / 1048576)} MiB storage binding but the adapter's maxStorageBufferBindingSize is ${Math.floor(adapter.limits.maxStorageBufferBindingSize / 1048576)} MiB`);
348
+ requiredLimits.maxStorageBufferBindingSize = needBind;
349
+ }
350
+ if (needBind > DEFAULT_BUFFER) {
351
+ if (needBind > adapter.limits.maxBufferSize) throw new GpuOutOfMemoryError(`this model needs a ${Math.ceil(needBind / 1048576)} MiB buffer but the adapter's maxBufferSize is ${Math.floor(adapter.limits.maxBufferSize / 1048576)} MiB`);
352
+ requiredLimits.maxBufferSize = needBind;
353
+ }
354
+ const device = await adapter.requestDevice({
355
+ requiredFeatures: features,
356
+ requiredLimits: Object.keys(requiredLimits).length ? requiredLimits : void 0
357
+ });
358
+ holder.device = device;
296
359
  const lost = device.lost.then((info) => {
297
360
  const li = {
298
361
  reason: String(info.reason ?? "unknown"),
@@ -533,14 +596,16 @@ async function createEngine(options) {
533
596
  buf
534
597
  };
535
598
  };
599
+ device.pushErrorScope("validation");
536
600
  device.pushErrorScope("out-of-memory");
537
601
  const W = {};
602
+ const zpChecks = [];
538
603
  for (const [name, t] of Object.entries(T)) if (t.kind === "q2") {
539
604
  const codes = gbuf(t.weight.len * 2);
540
605
  wireQ2(t.weight, codes);
541
606
  const scales = gbuf(t.scales.len);
542
607
  wireRaw(t.scales, scales);
543
- W[name] = {
608
+ const w = {
544
609
  N: t.N,
545
610
  K: t.K,
546
611
  nb: t.K / 128,
@@ -548,6 +613,17 @@ async function createEngine(options) {
548
613
  codes,
549
614
  scales
550
615
  };
616
+ if (t.zp) {
617
+ const zpBytes = wireCpu(t.zp);
618
+ zpChecks.push(() => {
619
+ const b0 = zpBytes[0];
620
+ for (let i = 1; i < zpBytes.length; i++) if (zpBytes[i] !== b0) throw new Error(`bitgpu: tensor ${name} has non-uniform 2-bit zero-points (the q2 kernels assume one zp for the whole tensor)`);
621
+ const zp = b0 & 3;
622
+ if (b0 !== zp * 85) throw new Error(`bitgpu: tensor ${name} has non-uniform 2-bit zero-points within a byte (the q2 kernels assume one zp for the whole tensor)`);
623
+ w.zp = zp;
624
+ });
625
+ }
626
+ W[name] = w;
551
627
  } else if (t.kind === "f32" && t.weight) {
552
628
  const buf = gbuf(t.weight.len);
553
629
  wireRaw(t.weight, buf);
@@ -614,6 +690,8 @@ async function createEngine(options) {
614
690
  const tgt4 = tgt4W.cpu;
615
691
  const cosCache = new Float32Array(cosBytes.buffer);
616
692
  const sinCache = new Float32Array(sinBytes.buffer);
693
+ const ropePositions = cosCache.length / (A.head_dim / 2);
694
+ if (maxSeqLen > ropePositions) throw new Error(`bitgpu: maxSeqLen ${maxSeqLen} exceeds the model's baked RoPE cache (${ropePositions} positions); lower maxSeqLen or re-export with a longer cache`);
617
695
  const embWqG = embW.buf, tgt4G = tgt4W.buf, embScalesG = embS.buf, embZpG = embZ.buf;
618
696
  routes.sort((a, b) => a.off - b.off || a.len - b.len);
619
697
  const merged = [];
@@ -673,17 +751,20 @@ async function createEngine(options) {
673
751
  });
674
752
  }
675
753
  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`);
754
+ for (const check of zpChecks) check();
755
+ zpChecks.length = 0;
676
756
  aux = null;
677
757
  function embedDequant(ids) {
678
758
  const Hh = A.hidden, out = new Float32Array(ids.length * Hh);
759
+ const rowBytes = Hh >> 3, scaleRow = Hh >> 7, zpRow = scaleRow + 1 >> 1;
679
760
  for (let r = 0; r < ids.length; r++) {
680
761
  const id = ids[r];
681
- for (let i = 0; i < 256; i++) for (let qd = 0; qd < 4; qd++) {
682
- const byte = tgt4[4 * embWq[id * 256 + i] + qd], baseK = (i * 4 + qd) * 2;
762
+ for (let i = 0; i < rowBytes; i++) for (let qd = 0; qd < 4; qd++) {
763
+ const byte = tgt4[4 * embWq[id * rowBytes + i] + qd], baseK = (i * 4 + qd) * 2;
683
764
  for (let c = 0; c < 2; c++) {
684
765
  const k = baseK + c, code = byte >> 4 * c & 15, blk = k / 128 | 0;
685
- const zp = embZp[id * 8 + (blk / 2 | 0)] >> 4 * (blk & 1) & 15;
686
- out[r * Hh + k] = (code - zp) * embScales[id * 16 + blk];
766
+ const zp = embZp[id * zpRow + (blk / 2 | 0)] >> 4 * (blk & 1) & 15;
767
+ out[r * Hh + k] = (code - zp) * embScales[id * scaleRow + blk];
687
768
  }
688
769
  }
689
770
  }
@@ -717,7 +798,9 @@ async function createEngine(options) {
717
798
  }));
718
799
  }
719
800
  const loadOom = await device.popErrorScope();
720
- if (loadOom) throw new GpuOutOfMemoryError(`GPU allocation failed while loading weights (~350 MB VRAM needed): ${loadOom.message}`);
801
+ const loadVal = await device.popErrorScope();
802
+ if (loadOom) throw new GpuOutOfMemoryError(`GPU allocation failed while loading weights (~${Math.round(weightBytes / 1048576)} MB VRAM needed): ${loadOom.message}`);
803
+ if (loadVal) throw new Error(`bitgpu: WebGPU validation error while loading weights: ${loadVal.message}`);
721
804
  async function ensureKvCapacity(needed) {
722
805
  if (needed <= kvCapacity) return;
723
806
  const newCap = Math.min(maxSeqLen, Math.max(needed, kvCapacity * 2));
@@ -1275,28 +1358,41 @@ async function createEngine(options) {
1275
1358
  }
1276
1359
  async function forward(ids) {
1277
1360
  const S = ids.length;
1361
+ if (S === 0) throw new Error("forward: no tokens to process");
1362
+ if (S > maxSeqLen) throw new Error(`forward: sequence length ${S} exceeds maxSeqLen ${maxSeqLen}`);
1363
+ fullHistory = [];
1278
1364
  await ensureKvCapacity(S);
1365
+ const vocab = W.lm_head.N;
1366
+ const embed = new Float32Array(S * Hd), layer0 = new Float32Array(S * Hd), finalnorm = new Float32Array(S * Hd), logits = new Float32Array(S * vocab);
1279
1367
  transients = [];
1280
1368
  try {
1281
- const embedOut = upload(embedDequant(ids), S_ | CD | CS);
1282
- const enc = device.createCommandEncoder();
1283
- const { fn, layer0 } = stack(enc, embedOut, S, 0);
1284
- const logits = device.createBuffer({
1285
- size: S * W.lm_head.N * 4,
1286
- usage: S_ | CS
1287
- });
1288
- transients.push(logits);
1289
- const pass = enc.beginComputePass();
1290
- lmHead(pass, fn, S, logits);
1291
- pass.end();
1292
- device.queue.submit([enc.finish()]);
1293
- await device.queue.onSubmittedWorkDone();
1369
+ for (let off = 0; off < S; off += PREFILL_SEG) {
1370
+ const seg = ids.slice(off, off + PREFILL_SEG);
1371
+ const embedOut = upload(embedDequant(seg), S_ | CD | CS);
1372
+ const enc = device.createCommandEncoder();
1373
+ const { fn, layer0: l0 } = stack(enc, embedOut, seg.length, off);
1374
+ const lg = device.createBuffer({
1375
+ size: seg.length * vocab * 4,
1376
+ usage: S_ | CS
1377
+ });
1378
+ transients.push(lg);
1379
+ const pass = enc.beginComputePass();
1380
+ lmHead(pass, fn, seg.length, lg);
1381
+ pass.end();
1382
+ device.queue.submit([enc.finish()]);
1383
+ await device.queue.onSubmittedWorkDone();
1384
+ embed.set(await readback(embedOut, seg.length * Hd), off * Hd);
1385
+ layer0.set(await readback(l0, seg.length * Hd), off * Hd);
1386
+ finalnorm.set(await readback(fn, seg.length * Hd), off * Hd);
1387
+ logits.set(await readback(lg, seg.length * vocab), off * vocab);
1388
+ flushTransients();
1389
+ }
1294
1390
  return {
1295
- embed: await readback(embedOut, S * Hd),
1296
- layer0: await readback(layer0, S * Hd),
1297
- finalnorm: await readback(fn, S * Hd),
1298
- logits: await readback(logits, S * W.lm_head.N),
1299
- vocab: W.lm_head.N,
1391
+ embed,
1392
+ layer0,
1393
+ finalnorm,
1394
+ logits,
1395
+ vocab,
1300
1396
  sequenceLength: S
1301
1397
  };
1302
1398
  } finally {
@@ -1304,7 +1400,6 @@ async function createEngine(options) {
1304
1400
  transients = null;
1305
1401
  }
1306
1402
  }
1307
- const PREFILL_SEG = 256;
1308
1403
  async function runPrefill(ids, posBase, signal) {
1309
1404
  let fn = null;
1310
1405
  let lastRow = 0;
@@ -1465,6 +1560,7 @@ async function createEngine(options) {
1465
1560
  }
1466
1561
  async function generateSampledImpl(ids, posBase, nTokens, genOpts, history) {
1467
1562
  await ensureKvCapacity(posBase + ids.length + nTokens);
1563
+ const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1;
1468
1564
  const vocab = W.lm_head.N;
1469
1565
  const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab));
1470
1566
  const temperature = genOpts.temperature ?? 1;
@@ -1545,6 +1641,7 @@ async function createEngine(options) {
1545
1641
  cv
1546
1642
  };
1547
1643
  };
1644
+ const pick = (ci, cv) => sampled ? sampleFromCandidates(ci, cv, temperature, rng) : ci[0];
1548
1645
  transients = [];
1549
1646
  try {
1550
1647
  const t0 = performance.now();
@@ -1572,7 +1669,7 @@ async function createEngine(options) {
1572
1669
  device.queue.submit([encP.finish()]);
1573
1670
  await device.queue.onSubmittedWorkDone();
1574
1671
  const first = await readCands();
1575
- const firstTok = sampleFromCandidates(first.ci, first.cv, temperature, rng);
1672
+ const firstTok = pick(first.ci, first.cv);
1576
1673
  flushTransients();
1577
1674
  const prefillMs = performance.now() - t0;
1578
1675
  const gen = [];
@@ -1625,7 +1722,7 @@ async function createEngine(options) {
1625
1722
  t = performance.now();
1626
1723
  const { ci, cv } = await readCands();
1627
1724
  rbMs += performance.now() - t;
1628
- const tk = sampleFromCandidates(ci, cv, temperature, rng);
1725
+ const tk = pick(ci, cv);
1629
1726
  total += 1;
1630
1727
  if (stopSet?.has(tk)) {
1631
1728
  stopped = true;
@@ -1679,6 +1776,7 @@ async function createEngine(options) {
1679
1776
  const onToken = genOpts.onToken;
1680
1777
  const signal = genOpts.signal;
1681
1778
  const rng = new MT19937(genOpts.seed);
1779
+ const useChain = sampled || penalty !== 1 || ngramN > 0;
1682
1780
  const lg = device.createBuffer({
1683
1781
  size: vocab * 4,
1684
1782
  usage: S_ | CS | CD
@@ -1743,7 +1841,7 @@ async function createEngine(options) {
1743
1841
  pass.dispatchWorkgroups(1);
1744
1842
  }
1745
1843
  };
1746
- const rowDraw = (m, j) => sampleFromCandidates(new Uint32Array(m, j * K * 8, K), new Float32Array(m, j * K * 8 + K * 4, K), temperature, rng);
1844
+ const rowDraw = (m, j) => sampled ? sampleFromCandidates(new Uint32Array(m, j * K * 8, K), new Float32Array(m, j * K * 8 + K * 4, K), temperature, rng) : new Uint32Array(m, j * K * 8, 1)[0];
1747
1845
  transients = [];
1748
1846
  try {
1749
1847
  const t0 = performance.now();
@@ -1766,7 +1864,7 @@ async function createEngine(options) {
1766
1864
  const encP = device.createCommandEncoder();
1767
1865
  const lastP = actBuf(Hd);
1768
1866
  encP.copyBufferToBuffer(pfx.fn, pfx.lastRow * Hd * 4, lastP, 0, Hd * 4);
1769
- const pf = sampled ? writeAffBan(history) : null;
1867
+ const pf = useChain ? writeAffBan(history) : null;
1770
1868
  let pass = encP.beginComputePass();
1771
1869
  lmHead(pass, lastP, 1, lg);
1772
1870
  if (pf) samplerChain(pass, pf.affLen, pf.banLen);
@@ -1824,7 +1922,7 @@ async function createEngine(options) {
1824
1922
  lmHead(pass, r.fn, S, lgAll);
1825
1923
  pass.end();
1826
1924
  SMALLM = 0;
1827
- if (!sampled) {
1925
+ if (!useChain) {
1828
1926
  for (let j = 0; j < S; j++) {
1829
1927
  enc.copyBufferToBuffer(lgAll, j * vocab * 4, lg, 0, vocab * 4);
1830
1928
  const p = enc.beginComputePass();
@@ -1857,7 +1955,7 @@ async function createEngine(options) {
1857
1955
  gpuMs += performance.now() - t;
1858
1956
  t = performance.now();
1859
1957
  const emitted = [];
1860
- if (!sampled) {
1958
+ if (!useChain) {
1861
1959
  const outs = await readbackU32(idsOut, S);
1862
1960
  for (let j = 0; j < S; j++) {
1863
1961
  const tk = outs[j];
@@ -2050,6 +2148,7 @@ async function createEngine(options) {
2050
2148
  };
2051
2149
  async function generate(promptTokenIds, genOpts = {}) {
2052
2150
  const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1;
2151
+ const hasProcessors = (genOpts.repetitionPenalty ?? 1) !== 1 || (genOpts.noRepeatNgramSize ?? 0) > 0;
2053
2152
  const reuse = (genOpts.reuseCache ?? false) && fullHistory.length > 0;
2054
2153
  if (genOpts.signal?.aborted) return {
2055
2154
  tokens: [],
@@ -2070,16 +2169,40 @@ async function createEngine(options) {
2070
2169
  const maxTokens = Math.min(genOpts.maxTokens ?? 256, room);
2071
2170
  if (reuse) fullHistory.push(...promptTokenIds);
2072
2171
  else fullHistory = [...promptTokenIds];
2172
+ if (maxTokens < 1) {
2173
+ await ensureKvCapacity(posBase + prefillTokens.length);
2174
+ transients = [];
2175
+ try {
2176
+ const t0 = performance.now();
2177
+ await runPrefill(prefillTokens, posBase, genOpts.signal);
2178
+ await device.queue.onSubmittedWorkDone();
2179
+ return {
2180
+ tokens: [],
2181
+ prefillMs: performance.now() - t0,
2182
+ decodeMs: 0,
2183
+ tokensPerSecond: 0,
2184
+ timing: {
2185
+ recordMs: 0,
2186
+ gpuMs: 0,
2187
+ readbackMs: 0
2188
+ }
2189
+ };
2190
+ } finally {
2191
+ flushTransients();
2192
+ transients = null;
2193
+ }
2194
+ }
2073
2195
  let r;
2074
2196
  if (genOpts.promptLookup) r = await generatePldImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
2075
- else if (sampled) r = await generateSampledImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
2197
+ else if (sampled || hasProcessors) r = await generateSampledImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
2076
2198
  else {
2199
+ const hist = fullHistory;
2077
2200
  r = await generateImpl(prefillTokens, posBase, maxTokens, null, SYNC_N, {
2078
2201
  stopTokens: genOpts.stopTokens,
2079
2202
  onToken: genOpts.onToken,
2080
2203
  signal: genOpts.signal
2081
2204
  });
2082
- fullHistory.push(...r.tokens);
2205
+ hist.push(...r.tokens);
2083
2206
  }
2084
2207
  return {
2085
2208
  tokens: r.tokens,