bitgpu 0.5.0 → 0.7.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
@@ -1,192 +1,5 @@
1
- //#region src/types.d.ts
2
- /** Progress event emitted while a model loads. */
3
- interface LoadProgress {
4
- phase: 'manifest' | 'weights' | 'pipelines';
5
- /** Bytes fetched so far (weights phase only). */
6
- loaded?: number;
7
- /** Total bytes to fetch (weights phase only). */
8
- total?: number;
9
- }
10
- /** Options for {@link createEngine}. Pass a string to use defaults with just a model URL.
11
- * Provide either `modelUrl` (a directory holding manifest.json + the data/aux files) or the explicit
12
- * `manifestUrl`/`dataUrl`/`auxUrl` (which lets the large data file come from one host, e.g. the HF Hub,
13
- * and the small manifest/aux from another). The explicit URLs win over the `modelUrl`-relative ones. */
14
- interface EngineOptions {
15
- /** Base URL of the model directory containing `manifest.json` and its data/aux files. */
16
- modelUrl?: string;
17
- /** Explicit URL for manifest.json (overrides `${modelUrl}/manifest.json`). */
18
- manifestUrl?: string;
19
- /** Explicit URL for the weights data file (overrides `${modelUrl}/<data_file>`). */
20
- dataUrl?: string;
21
- /** Explicit URL for the aux file (overrides `${modelUrl}/<aux_file>`). */
22
- auxUrl?: string;
23
- /** Fetch JSON (manifest). Override to add caching. Default: `fetch(url).json()`. */
24
- fetchJson?: (url: string) => Promise<unknown>;
25
- /** Fetch binary (data/aux). Override to add caching (e.g. OPFS) for the ~290MB data file. Default: `fetch(url).arrayBuffer()`. */
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>>;
34
- /** GPU power preference. Default `'high-performance'` (picks the discrete GPU on multi-GPU machines).
35
- * (Spelled out rather than `GPUPowerPreference` so the published d.ts resolves without @webgpu/types.) */
36
- powerPreference?: 'low-power' | 'high-performance';
37
- /** Force the no-subgroup reduction path (for testing the fallback). Default `false`. */
38
- forceNoSubgroups?: boolean;
39
- /** Workgroup size for the no-subgroup reduction kernels. Default `64`. */
40
- noSubgroupWorkgroupSize?: number;
41
- /** Decode steps chained per CPU sync (deferred readback). Higher hides latency; default `4`. */
42
- syncSteps?: number;
43
- /** Prefill GEMM tiling: `'auto'` tiles once a prompt fills the 64-row tiles, `'always'`/`'never'` force it. Default `'auto'`. */
44
- prefillTiling?: 'auto' | 'always' | 'never';
45
- /** Max KV-cache length (prompt + generated positions). Caps VRAM (~`maxSeqLen` x 224 KB at f32,
46
- * half that with `kvCache: 'f16'`). Default `2048`. */
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';
55
- /** Called as the model loads. */
56
- onProgress?: (progress: LoadProgress) => void;
57
- /** Called if the GPU device is lost after creation (driver reset, OS reclaim, tab backgrounding
58
- * on some platforms). The engine is unusable afterward; create a new one to recover. Not called
59
- * for the intentional loss caused by {@link Engine.dispose}. */
60
- onDeviceLost?: (info: DeviceLostInfo) => void;
61
- }
62
- /** Why the GPU device went away. Mirrors GPUDeviceLostInfo without requiring @webgpu/types. */
63
- interface DeviceLostInfo {
64
- /** 'destroyed' when {@link Engine.dispose} caused it, otherwise the platform reason ('unknown', ...). */
65
- reason: string;
66
- message: string;
67
- }
68
- /** Options for a single {@link Engine.generate} call. Set `temperature` to a value other than 0 or 1
69
- * to sample; otherwise decoding is greedy (argmax). Sampling matches transformers.js v4.2.0 exactly
70
- * (repetition_penalty, no_repeat_ngram, temperature, top_k, multinomial via a Mersenne-Twister RNG). */
71
- interface GenerateOptions {
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`). */
74
- maxTokens?: number;
75
- /** Reuse the KV cache from the previous turn: treat the passed token ids as the DELTA to append to
76
- * the cached conversation (not a full prompt), prefilling only those tokens. Requires a prior
77
- * generate on this engine (else it falls back to a full prefill). Default `false` (reset + full prefill). */
78
- reuseCache?: boolean;
79
- /** Token ids that end generation when produced (e.g. EOS). The stop token is not emitted. */
80
- stopTokens?: number[];
81
- /** Called with each generated token id as it is produced (per-token when sampling). */
82
- onToken?: (tokenId: number) => void;
83
- /** Aborts generation when signaled (checked at each step). */
84
- signal?: AbortSignal;
85
- /** Softmax temperature. A value other than 0 or 1 enables sampling; 0 or 1 (or unset) is greedy. */
86
- temperature?: number;
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"). */
89
- topK?: number;
90
- /** Top-p (nucleus) cutoff. Accepted for API compatibility but not applied (a no-op, matching transformers.js v4.2.0). */
91
- topP?: number;
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. */
94
- repetitionPenalty?: number;
95
- /** Block any n-gram of this size from repeating. Default `0` (off). Applied under greedy decoding
96
- * too, matching transformers.js. */
97
- noRepeatNgramSize?: number;
98
- /** Seed for the sampler RNG. Omit to seed from entropy (non-deterministic, like production). */
99
- seed?: number;
100
- /** EXPERIMENTAL. Prompt-lookup speculative decoding: draft the continuation from an n-gram
101
- * match in the sequence so far and verify every draft in ONE batched forward. Output is
102
- * identical to normal decoding, greedy AND sampled (each emitted token still comes from its
103
- * true penalized distribution, and the RNG advances one draw per emitted token, in order).
104
- * INCOMPATIBLE with `noRepeatNgramSize`: a prompt-lookup draft is the continuation of a
105
- * repeated n-gram, which is exactly what the ngram ban forbids, so acceptance is ~zero when
106
- * both are on (measured 0/320). Use with greedy decoding or ngram-ban-free sampling. No
107
- * draft model, no extra VRAM. `true` = `{ ngramSize: 3, maxDraft: 8 }`. Default `false`. */
108
- promptLookup?: boolean | {
109
- ngramSize?: number;
110
- maxDraft?: number;
111
- };
112
- }
113
- /** Result of a {@link Engine.generate} call. */
114
- interface GenerateResult {
115
- /** Generated token ids (excludes the prompt). */
116
- tokens: number[];
117
- /** Time to first token (prefill of the prompt), in milliseconds. */
118
- prefillMs: number;
119
- /** Decode time for the remaining tokens, in milliseconds. */
120
- decodeMs: number;
121
- /** Decode throughput (tokens / second), excluding prefill. */
122
- tokensPerSecond: number;
123
- /** Per-token decode timing breakdown, in milliseconds. */
124
- timing: {
125
- recordMs: number;
126
- gpuMs: number;
127
- readbackMs: number;
128
- };
129
- /** Present when prompt-lookup decoding ran: verify steps taken, tokens drafted, drafts accepted. */
130
- speculation?: {
131
- steps: number;
132
- drafted: number;
133
- accepted: number;
134
- };
135
- }
136
- /** Diagnostic result of {@link Engine.forward}: hidden states + logits for a single forward pass. */
137
- interface ForwardResult {
138
- embed: Float32Array;
139
- layer0: Float32Array;
140
- finalnorm: Float32Array;
141
- logits: Float32Array;
142
- vocab: number;
143
- sequenceLength: number;
144
- }
145
- /** What the engine detected about the host GPU and which code path it selected. */
146
- interface EngineCapabilities {
147
- /** Whether the fast subgroup path is in use (false = the workgroup-reduction fallback). */
148
- useSubgroups: boolean;
149
- /** Subgroup width when the subgroup path is active. */
150
- subgroupSize: number;
151
- /** Active KV-cache storage precision ('f16' only when requested AND the adapter has shader-f16). */
152
- kvCache: 'f32' | 'f16';
153
- /** Adapter identification, when the browser exposes it. */
154
- adapter: {
155
- vendor?: string;
156
- architecture?: string;
157
- device?: string;
158
- description?: string;
159
- };
160
- /** Relevant adapter limits the engine codes against. */
161
- limits: {
162
- maxStorageBufferBindingSize: number;
163
- maxComputeWorkgroupStorageSize: number;
164
- };
165
- }
166
- /** A loaded model ready to generate. Create one with {@link createEngine}. */
167
- interface Engine {
168
- /** Generate tokens from a prompt given as token ids. */
169
- generate(promptTokenIds: number[], options?: GenerateOptions): Promise<GenerateResult>;
170
- /** Prefill a prompt PREFIX into the KV cache without decoding, so a later
171
- * `generate(delta, { reuseCache: true })` continues from it. Use to warm a static system prompt
172
- * at load time so the first real turn is a cheap cache-append, not a full prefill. Resets any
173
- * existing cache (the prefix becomes the whole history). Returns the prefill wall-time. */
174
- prefill(promptTokenIds: number[]): Promise<{
175
- prefillMs: number;
176
- }>;
177
- /** Run a single forward pass and return hidden states + logits (diagnostic / correctness checks). */
178
- forward(tokenIds: number[]): Promise<ForwardResult>;
179
- /** Clear the cross-turn KV cache and token history (start a fresh conversation). */
180
- resetCache(): void;
181
- /** Detected GPU capabilities and selected code path. */
182
- readonly capabilities: EngineCapabilities;
183
- /** Resolves when the GPU device is lost (including via {@link dispose}, with reason 'destroyed').
184
- * After an unexpected loss the engine is dead; create a new one to recover. */
185
- readonly lost: Promise<DeviceLostInfo>;
186
- /** Release GPU resources. The engine is unusable afterward. */
187
- dispose(): void;
188
- }
189
- //#endregion
1
+ import { a as ForwardResult, c as LoadProgress, i as EngineOptions, n as Engine, o as GenerateOptions, r as EngineCapabilities, s as GenerateResult, t as DeviceLostInfo } from "./types-CsoJYJlG.js";
2
+
190
3
  //#region src/engine.d.ts
191
4
  /** Load a 1-bit model and return an {@link Engine}. Pass a model URL string for defaults. */
192
5
  declare function createEngine(options: EngineOptions | string): Promise<Engine>;
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ const SHADERS = {
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
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
+ "embed_gather_batch": "// Batched GPU embedding gather + 4-bit dequant for PROMPT tokens: one invocation per output\n// element writes out[s*H + k] for tokenIds[s]. A prefill segment uploads S u32 token ids\n// instead of S*H dequantized floats, so the CPU-side embedding tables are not needed at all\n// (~50-100 MB RAM per model). Same per-row stride math and dequant as embed_gather.wgsl\n// (H=2048 -> 256/16/8 strides); uint8 sources read as u32 and byte-extracted (little-endian).\nstruct Params { S: u32, H: u32, _0: u32, _1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> tokenIds: array<u32>; // [S]\n@group(0) @binding(2) var<storage, read> embWq: array<u32>; // uint8 [vocab * H/8] packed\n@group(0) @binding(3) var<storage, read> tgt4: array<u32>; // uint8 [256*4] packed (1 src byte -> 4)\n@group(0) @binding(4) var<storage, read> embScales: array<f32>; // [vocab * H/128]\n@group(0) @binding(5) var<storage, read> embZp: array<u32>; // uint8 [vocab * ceil(H/256)] packed\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S * H]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let gi = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (gi >= p.S * p.H) { return; }\n let k = gi % p.H;\n let id = tokenIds[gi / p.H];\n let rowBytes = p.H >> 3u;\n let scaleRow = p.H >> 7u;\n let zpRow = (scaleRow + 1u) >> 1u;\n let i = k >> 3u;\n let qd = (k >> 1u) & 3u;\n let c = k & 1u;\n let wqIdx = id * rowBytes + i;\n let e = (embWq[wqIdx >> 2u] >> (8u * (wqIdx & 3u))) & 0xffu; // source byte 0..255\n let tIdx = 4u * e + qd;\n let t = (tgt4[tIdx >> 2u] >> (8u * (tIdx & 3u))) & 0xffu; // expanded byte (2 codes)\n let code = (t >> (4u * c)) & 0xfu;\n let blk = k >> 7u;\n let zpIdx = id * zpRow + (blk >> 1u);\n let zpByte = (embZp[zpIdx >> 2u] >> (8u * (zpIdx & 3u))) & 0xffu;\n let zp = (zpByte >> (4u * (blk & 1u))) & 0xfu;\n out[gi] = (f32(code) - f32(zp)) * embScales[id * scaleRow + blk];\n}\n",
13
14
  "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
15
  "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
16
  "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",
@@ -71,6 +72,16 @@ function draftNgram(seq, ngramSize, maxDraft) {
71
72
  }
72
73
  return [];
73
74
  }
75
+ /** The auto-bail decision after the probation window: keep speculating only when the measured
76
+ * tokens-per-verify-step clears the break-even against PLAIN decoding, which differs by mode.
77
+ * Each PLD step costs one batched verify forward plus a per-step CPU sync; plain GREEDY chains
78
+ * several steps per sync (GPU-resident argmax), so its break-even is high (~2.0 tokens/step,
79
+ * measured), while plain SAMPLED syncs every token anyway (~1.5). Below the bar, the rest of
80
+ * the turn runs the plain path - output is identical either way, only speed changes. */
81
+ function pldWorthIt(emitted, steps, sampled) {
82
+ if (steps <= 0) return false;
83
+ return emitted / steps >= (sampled ? 1.5 : 2);
84
+ }
74
85
  //#endregion
75
86
  //#region src/sampler.ts
76
87
  /** Mersenne Twister 19937, matching transformers.js utils/random.js (= Python's random.Random). */
@@ -394,6 +405,7 @@ async function createEngineInner(options, holder) {
394
405
  ["matmul_resid_tiled"],
395
406
  ["argmax"],
396
407
  ["embed_gather"],
408
+ ["embed_gather_batch"],
397
409
  ["sampler_penalty"],
398
410
  ["argmax_masked"]
399
411
  ];
@@ -581,21 +593,6 @@ async function createEngineInner(options, holder) {
581
593
  }, () => void 0);
582
594
  return dst;
583
595
  };
584
- const wireCpuGpu = (ref) => {
585
- const buf = gbuf(ref.len);
586
- const s = gpuSink(buf, 0);
587
- const dst = new Uint8Array(ref.len);
588
- let w = 0;
589
- wire(ref, (b) => {
590
- dst.set(b, w);
591
- w += b.length;
592
- s.push(b);
593
- }, s.finish);
594
- return {
595
- cpu: dst,
596
- buf
597
- };
598
- };
599
596
  device.pushErrorScope("validation");
600
597
  device.pushErrorScope("out-of-memory");
601
598
  const W = {};
@@ -678,21 +675,21 @@ async function createEngineInner(options, holder) {
678
675
  };
679
676
  }
680
677
  }
681
- const embW = wireCpuGpu(T.embed_tokens.weight);
682
- const embS = wireCpuGpu(T.embed_tokens.scales);
683
- const embZ = wireCpuGpu(T.embed_tokens.zp);
684
- const tgt4W = wireCpuGpu(manifest.luts.tgt4);
678
+ const wireGpu = (ref) => {
679
+ const buf = gbuf(ref.len);
680
+ wireRaw(ref, buf);
681
+ return buf;
682
+ };
683
+ const embWqG = wireGpu(T.embed_tokens.weight);
684
+ const embScalesG = wireGpu(T.embed_tokens.scales);
685
+ const embZpG = wireGpu(T.embed_tokens.zp);
686
+ const tgt4G = wireGpu(manifest.luts.tgt4);
685
687
  const cosBytes = wireCpu(T.cos_cache);
686
688
  const sinBytes = wireCpu(T.sin_cache);
687
- const embWq = embW.cpu;
688
- const embScales = new Float32Array(embS.cpu.buffer);
689
- const embZp = embZ.cpu;
690
- const tgt4 = tgt4W.cpu;
691
689
  const cosCache = new Float32Array(cosBytes.buffer);
692
690
  const sinCache = new Float32Array(sinBytes.buffer);
693
691
  const ropePositions = cosCache.length / (A.head_dim / 2);
694
692
  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`);
695
- const embWqG = embW.buf, tgt4G = tgt4W.buf, embScalesG = embS.buf, embZpG = embZ.buf;
696
693
  routes.sort((a, b) => a.off - b.off || a.len - b.len);
697
694
  const merged = [];
698
695
  for (const r of routes) {
@@ -754,20 +751,23 @@ async function createEngineInner(options, holder) {
754
751
  for (const check of zpChecks) check();
755
752
  zpChecks.length = 0;
756
753
  aux = null;
757
- function embedDequant(ids) {
758
- const Hh = A.hidden, out = new Float32Array(ids.length * Hh);
759
- const rowBytes = Hh >> 3, scaleRow = Hh >> 7, zpRow = scaleRow + 1 >> 1;
760
- for (let r = 0; r < ids.length; r++) {
761
- const id = ids[r];
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;
764
- for (let c = 0; c < 2; c++) {
765
- const k = baseK + c, code = byte >> 4 * c & 15, blk = k / 128 | 0;
766
- const zp = embZp[id * zpRow + (blk / 2 | 0)] >> 4 * (blk & 1) & 15;
767
- out[r * Hh + k] = (code - zp) * embScales[id * scaleRow + blk];
768
- }
769
- }
770
- }
754
+ function embedBatch(enc, ids) {
755
+ const idBuf = upload(new Uint32Array(ids));
756
+ const out = actBuf(ids.length * Hd);
757
+ const pass = enc.beginComputePass();
758
+ run(pass, "embed_gather_batch", [
759
+ ["u", ids.length],
760
+ ["u", Hd],
761
+ ["u", 0],
762
+ ["u", 0]
763
+ ], [
764
+ idBuf,
765
+ embWqG,
766
+ tgt4G,
767
+ embScalesG,
768
+ embZpG
769
+ ], out, ids.length * Hd);
770
+ pass.end();
771
771
  return out;
772
772
  }
773
773
  function ropeBufs(posBase, S) {
@@ -869,7 +869,7 @@ async function createEngineInner(options, holder) {
869
869
  return out;
870
870
  }
871
871
  let FULL = null;
872
- const isFull = (name) => FULL === null || FULL.has(name);
872
+ const isFull = (name) => FULL === null || FULL.has(name) || name === "embed_gather_batch";
873
873
  let FORCE_SLOW = false;
874
874
  let SMALLM = 0;
875
875
  let DBG0 = null;
@@ -1368,8 +1368,8 @@ async function createEngineInner(options, holder) {
1368
1368
  try {
1369
1369
  for (let off = 0; off < S; off += PREFILL_SEG) {
1370
1370
  const seg = ids.slice(off, off + PREFILL_SEG);
1371
- const embedOut = upload(embedDequant(seg), S_ | CD | CS);
1372
1371
  const enc = device.createCommandEncoder();
1372
+ const embedOut = embedBatch(enc, seg);
1373
1373
  const { fn, layer0: l0 } = stack(enc, embedOut, seg.length, off);
1374
1374
  const lg = device.createBuffer({
1375
1375
  size: seg.length * vocab * 4,
@@ -1410,7 +1410,7 @@ async function createEngineInner(options, holder) {
1410
1410
  }
1411
1411
  const seg = ids.slice(off, off + PREFILL_SEG);
1412
1412
  const enc = device.createCommandEncoder();
1413
- fn = stack(enc, upload(embedDequant(seg), S_ | CD), seg.length, posBase + off).fn;
1413
+ fn = stack(enc, embedBatch(enc, seg), seg.length, posBase + off).fn;
1414
1414
  lastRow = seg.length - 1;
1415
1415
  device.queue.submit([enc.finish()]);
1416
1416
  if (off + PREFILL_SEG < ids.length) {
@@ -1558,7 +1558,7 @@ async function createEngineInner(options, holder) {
1558
1558
  lg.destroy();
1559
1559
  }
1560
1560
  }
1561
- async function generateSampledImpl(ids, posBase, nTokens, genOpts, history) {
1561
+ async function generateSampledImpl(ids, posBase, nTokens, genOpts, history, rngIn) {
1562
1562
  await ensureKvCapacity(posBase + ids.length + nTokens);
1563
1563
  const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1;
1564
1564
  const vocab = W.lm_head.N;
@@ -1569,7 +1569,7 @@ async function createEngineInner(options, holder) {
1569
1569
  const stopSet = genOpts.stopTokens ? new Set(genOpts.stopTokens) : null;
1570
1570
  const onToken = genOpts.onToken;
1571
1571
  const signal = genOpts.signal;
1572
- const rng = new MT19937(genOpts.seed);
1572
+ const rng = rngIn ?? new MT19937(genOpts.seed);
1573
1573
  const tokBuf = device.createBuffer({
1574
1574
  size: Math.max(1, nTokens) * 4,
1575
1575
  usage: S_ | CS | CD
@@ -1642,6 +1642,37 @@ async function createEngineInner(options, holder) {
1642
1642
  };
1643
1643
  };
1644
1644
  const pick = (ci, cv) => sampled ? sampleFromCandidates(ci, cv, temperature, rng) : ci[0];
1645
+ const filter = genOpts.candidateFilter;
1646
+ const chooseToken = async (ci, cv) => {
1647
+ if (!filter) return pick(ci, cv);
1648
+ const perm = new Set(filter(ci, cv));
1649
+ if (perm.size > 0) {
1650
+ const pIds = [];
1651
+ const pVals = [];
1652
+ for (let i = 0; i < ci.length; i++) if (perm.has(ci[i])) {
1653
+ pIds.push(ci[i]);
1654
+ pVals.push(cv[i]);
1655
+ }
1656
+ return sampled ? sampleFromCandidates(pIds, pVals, temperature, rng) : pIds[0];
1657
+ }
1658
+ const all = await readback(lg, vocab);
1659
+ const order = Array.from(all.keys()).sort((a, b) => all[b] - all[a] || a - b);
1660
+ const pIds = [];
1661
+ const pVals = [];
1662
+ const B = 512;
1663
+ for (let i = 0; i < order.length && pIds.length < K; i += B) {
1664
+ if (all[order[i]] === -Infinity) break;
1665
+ const batch = order.slice(i, i + B).filter((id) => all[id] !== -Infinity);
1666
+ const ok = new Set(filter(Uint32Array.from(batch), Float32Array.from(batch.map((id) => all[id]))));
1667
+ for (const id of batch) if (ok.has(id)) {
1668
+ pIds.push(id);
1669
+ pVals.push(all[id]);
1670
+ if (pIds.length >= K) break;
1671
+ }
1672
+ }
1673
+ if (pIds.length === 0) throw new Error("bitgpu: candidateFilter permitted no token in the entire vocabulary");
1674
+ return sampled ? sampleFromCandidates(pIds, pVals, temperature, rng) : pIds[0];
1675
+ };
1645
1676
  transients = [];
1646
1677
  try {
1647
1678
  const t0 = performance.now();
@@ -1654,7 +1685,8 @@ async function createEngineInner(options, holder) {
1654
1685
  firstArgmax: -1,
1655
1686
  recMs: 0,
1656
1687
  gpuMs: 0,
1657
- rbMs: 0
1688
+ rbMs: 0,
1689
+ rng
1658
1690
  };
1659
1691
  const encP = device.createCommandEncoder();
1660
1692
  const lastP = actBuf(Hd);
@@ -1667,9 +1699,8 @@ async function createEngineInner(options, holder) {
1667
1699
  encP.copyBufferToBuffer(candIds, 0, rbBuf, 0, K * 4);
1668
1700
  encP.copyBufferToBuffer(candVals, 0, rbBuf, K * 4, K * 4);
1669
1701
  device.queue.submit([encP.finish()]);
1670
- await device.queue.onSubmittedWorkDone();
1671
1702
  const first = await readCands();
1672
- const firstTok = pick(first.ci, first.cv);
1703
+ const firstTok = await chooseToken(first.ci, first.cv);
1673
1704
  flushTransients();
1674
1705
  const prefillMs = performance.now() - t0;
1675
1706
  const gen = [];
@@ -1717,12 +1748,11 @@ async function createEngineInner(options, holder) {
1717
1748
  device.queue.submit([enc.finish()]);
1718
1749
  recMs += performance.now() - t;
1719
1750
  t = performance.now();
1720
- await device.queue.onSubmittedWorkDone();
1751
+ const { ci, cv } = await readCands();
1721
1752
  gpuMs += performance.now() - t;
1722
1753
  t = performance.now();
1723
- const { ci, cv } = await readCands();
1754
+ const tk = await chooseToken(ci, cv);
1724
1755
  rbMs += performance.now() - t;
1725
- const tk = pick(ci, cv);
1726
1756
  total += 1;
1727
1757
  if (stopSet?.has(tk)) {
1728
1758
  stopped = true;
@@ -1743,7 +1773,8 @@ async function createEngineInner(options, holder) {
1743
1773
  firstArgmax: firstTok,
1744
1774
  recMs: recMs / nd,
1745
1775
  gpuMs: gpuMs / nd,
1746
- rbMs: rbMs / nd
1776
+ rbMs: rbMs / nd,
1777
+ rng
1747
1778
  };
1748
1779
  } finally {
1749
1780
  poolUse(null);
@@ -1761,7 +1792,7 @@ async function createEngineInner(options, holder) {
1761
1792
  ]) b.destroy();
1762
1793
  }
1763
1794
  }
1764
- async function generatePldImpl(ids, posBase, nTokens, genOpts, history) {
1795
+ async function generatePldImpl(ids, posBase, nTokens, genOpts, history, rngIn) {
1765
1796
  await ensureKvCapacity(posBase + ids.length + nTokens);
1766
1797
  const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1;
1767
1798
  const vocab = W.lm_head.N;
@@ -1775,7 +1806,7 @@ async function createEngineInner(options, holder) {
1775
1806
  const stopSet = genOpts.stopTokens ? new Set(genOpts.stopTokens) : null;
1776
1807
  const onToken = genOpts.onToken;
1777
1808
  const signal = genOpts.signal;
1778
- const rng = new MT19937(genOpts.seed);
1809
+ const rng = rngIn ?? new MT19937(genOpts.seed);
1779
1810
  const useChain = sampled || penalty !== 1 || ngramN > 0;
1780
1811
  const lg = device.createBuffer({
1781
1812
  size: vocab * 4,
@@ -1809,6 +1840,10 @@ async function createEngineInner(options, holder) {
1809
1840
  size: (maxDraft + 1) * K * 8,
1810
1841
  usage: GPUBufferUsage.MAP_READ | CD
1811
1842
  });
1843
+ const pldIds = device.createBuffer({
1844
+ size: (maxDraft + 1) * 4,
1845
+ usage: S_ | CD
1846
+ });
1812
1847
  const embIn = device.createBuffer({
1813
1848
  size: (maxDraft + 1) * Hd * 4,
1814
1849
  usage: S_ | CD
@@ -1859,7 +1894,8 @@ async function createEngineInner(options, holder) {
1859
1894
  steps: 0,
1860
1895
  drafted: 0,
1861
1896
  accepted: 0
1862
- }
1897
+ },
1898
+ rng
1863
1899
  };
1864
1900
  const encP = device.createCommandEncoder();
1865
1901
  const lastP = actBuf(Hd);
@@ -1914,9 +1950,23 @@ async function createEngineInner(options, holder) {
1914
1950
  if (S === 1) poolUse("pld1");
1915
1951
  else if (useSG && S <= 9) poolUse("pldm", S, 9);
1916
1952
  else poolUse(null);
1917
- device.queue.writeBuffer(embIn, 0, embedDequant([tLast, ...drafts]));
1953
+ device.queue.writeBuffer(pldIds, 0, new Uint32Array([tLast, ...drafts]));
1918
1954
  SMALLM = useSG && S >= 2 && S <= 9 ? S : 0;
1919
1955
  const enc = device.createCommandEncoder();
1956
+ const gp = enc.beginComputePass();
1957
+ run(gp, "embed_gather_batch", [
1958
+ ["u", S],
1959
+ ["u", Hd],
1960
+ ["u", 0],
1961
+ ["u", 0]
1962
+ ], [
1963
+ pldIds,
1964
+ embWqG,
1965
+ tgt4G,
1966
+ embScalesG,
1967
+ embZpG
1968
+ ], embIn, S * Hd);
1969
+ gp.end();
1920
1970
  const r = stack(enc, embIn, S, pos);
1921
1971
  pass = enc.beginComputePass();
1922
1972
  lmHead(pass, r.fn, S, lgAll);
@@ -2010,7 +2060,8 @@ async function createEngineInner(options, holder) {
2010
2060
  steps: specSteps,
2011
2061
  drafted,
2012
2062
  accepted
2013
- }
2063
+ },
2064
+ rng
2014
2065
  };
2015
2066
  } finally {
2016
2067
  SMALLM = 0;
@@ -2026,14 +2077,15 @@ async function createEngineInner(options, holder) {
2026
2077
  affBuf,
2027
2078
  banBuf,
2028
2079
  rbAll,
2029
- embIn
2080
+ embIn,
2081
+ pldIds
2030
2082
  ]) b.destroy();
2031
2083
  }
2032
2084
  }
2033
2085
  async function debugDecode(prefillIds) {
2034
2086
  await ensureKvCapacity(prefillIds.length + 1);
2035
2087
  const encP = device.createCommandEncoder();
2036
- stack(encP, upload(embedDequant(prefillIds), S_ | CD), prefillIds.length, 0);
2088
+ stack(encP, embedBatch(encP, prefillIds), prefillIds.length, 0);
2037
2089
  device.queue.submit([encP.finish()]);
2038
2090
  await device.queue.onSubmittedWorkDone();
2039
2091
  const pos = prefillIds.length, tok = prefillIds[prefillIds.length - 1];
@@ -2041,7 +2093,7 @@ async function createEngineInner(options, holder) {
2041
2093
  FORCE_SLOW = forceSlow;
2042
2094
  DBG0 = {};
2043
2095
  const enc = device.createCommandEncoder();
2044
- const r = stack(enc, upload(embedDequant([tok]), S_ | CD), 1, pos);
2096
+ const r = stack(enc, embedBatch(enc, [tok]), 1, pos);
2045
2097
  const lg = device.createBuffer({
2046
2098
  size: W.lm_head.N * 4,
2047
2099
  usage: S_ | CS
@@ -2091,7 +2143,7 @@ async function createEngineInner(options, holder) {
2091
2143
  const affBuf = upload(aff.length ? aff : /* @__PURE__ */ new Uint32Array(1), S_ | CD);
2092
2144
  const banBuf = upload(ban.length ? Uint32Array.from(ban) : /* @__PURE__ */ new Uint32Array(1), S_ | CD);
2093
2145
  const enc1 = device.createCommandEncoder();
2094
- const { fn } = stack(enc1, upload(embedDequant(ids), S_ | CD), ids.length, 0);
2146
+ const { fn } = stack(enc1, embedBatch(enc1, ids), ids.length, 0);
2095
2147
  const lastP = device.createBuffer({
2096
2148
  size: Hd * 4,
2097
2149
  usage: S_ | CS | CD
@@ -2135,6 +2187,7 @@ async function createEngineInner(options, holder) {
2135
2187
  useSubgroups: useSG,
2136
2188
  subgroupSize: sgMax,
2137
2189
  kvCache: kv16 ? "f16" : "f32",
2190
+ maxSeqLen,
2138
2191
  adapter: {
2139
2192
  vendor: info.vendor,
2140
2193
  architecture: info.architecture,
@@ -2192,9 +2245,52 @@ async function createEngineInner(options, holder) {
2192
2245
  transients = null;
2193
2246
  }
2194
2247
  }
2248
+ const hasFilter = !!genOpts.candidateFilter;
2195
2249
  let r;
2196
- if (genOpts.promptLookup) r = await generatePldImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
2197
- else if (sampled || hasProcessors) r = await generateSampledImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
2250
+ if (!hasFilter && genOpts.promptLookup === "auto" && maxTokens > 24) {
2251
+ const r1 = await generatePldImpl(prefillTokens, posBase, 24, genOpts, fullHistory);
2252
+ const E = r1.tokens.length;
2253
+ if (E < 24) r = r1;
2254
+ else {
2255
+ const keep = pldWorthIt(E, r1.spec?.steps ?? 0, sampled || hasProcessors);
2256
+ const ids2 = [r1.tokens[E - 1]];
2257
+ const pos2 = posBase + prefillTokens.length + E - 1;
2258
+ const n2 = maxTokens - E;
2259
+ let r2;
2260
+ if (keep) r2 = await generatePldImpl(ids2, pos2, n2, genOpts, fullHistory, r1.rng);
2261
+ else if (sampled || hasProcessors) r2 = await generateSampledImpl(ids2, pos2, n2, genOpts, fullHistory, r1.rng);
2262
+ else {
2263
+ const hist = fullHistory;
2264
+ r2 = await generateImpl(ids2, pos2, n2, null, SYNC_N, {
2265
+ stopTokens: genOpts.stopTokens,
2266
+ onToken: genOpts.onToken,
2267
+ signal: genOpts.signal
2268
+ });
2269
+ hist.push(...r2.tokens);
2270
+ }
2271
+ const total = E + r2.tokens.length;
2272
+ const decodeMs = r1.decodeMs + r2.prefillMs + r2.decodeMs;
2273
+ const w1 = Math.max(1, E - 1);
2274
+ const w2 = Math.max(0, r2.tokens.length);
2275
+ r = {
2276
+ prefillMs: r1.prefillMs,
2277
+ decodeMs,
2278
+ tokPerSec: Math.max(1, total - 1) / (decodeMs / 1e3),
2279
+ tokens: [...r1.tokens, ...r2.tokens],
2280
+ firstArgmax: r1.firstArgmax,
2281
+ recMs: (r1.recMs * w1 + r2.recMs * w2) / (w1 + w2),
2282
+ gpuMs: (r1.gpuMs * w1 + r2.gpuMs * w2) / (w1 + w2),
2283
+ rbMs: (r1.rbMs * w1 + r2.rbMs * w2) / (w1 + w2),
2284
+ spec: {
2285
+ steps: (r1.spec?.steps ?? 0) + (r2.spec?.steps ?? 0),
2286
+ drafted: (r1.spec?.drafted ?? 0) + (r2.spec?.drafted ?? 0),
2287
+ accepted: (r1.spec?.accepted ?? 0) + (r2.spec?.accepted ?? 0),
2288
+ bailed: !keep
2289
+ }
2290
+ };
2291
+ }
2292
+ } else if (!hasFilter && genOpts.promptLookup) r = await generatePldImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
2293
+ else if (sampled || hasProcessors || hasFilter) r = await generateSampledImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
2198
2294
  else {
2199
2295
  const hist = fullHistory;
2200
2296
  r = await generateImpl(prefillTokens, posBase, maxTokens, null, SYNC_N, {