bitgpu 0.4.0 → 0.6.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.
@@ -0,0 +1,191 @@
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
190
+ export { ForwardResult as a, LoadProgress as c, EngineOptions as i, Engine as n, GenerateOptions as o, EngineCapabilities as r, GenerateResult as s, DeviceLostInfo as t };
191
+ //# sourceMappingURL=types-C3FWn4rd.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bitgpu",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Fast WebGPU runtime for 1-bit (binary-weight) LLMs in the browser. Bit-exact, zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -26,12 +26,17 @@
26
26
  "sideEffects": false,
27
27
  "files": [
28
28
  "dist",
29
- "LICENSE"
29
+ "LICENSE",
30
+ "THIRD_PARTY_LICENSES.md"
30
31
  ],
31
32
  "exports": {
32
33
  ".": {
33
34
  "types": "./dist/index.d.ts",
34
35
  "default": "./dist/index.js"
36
+ },
37
+ "./chat": {
38
+ "types": "./dist/chat.d.ts",
39
+ "default": "./dist/chat.js"
35
40
  }
36
41
  },
37
42
  "scripts": {
@@ -41,6 +46,7 @@
41
46
  "typecheck": "npm run gen:shaders && tsc -p tsconfig.json --noEmit && tsc -p tsconfig.node.json --noEmit",
42
47
  "test:sampler": "tsx scripts/verify-sampler.ts",
43
48
  "test:pld": "tsx scripts/verify-pld.ts",
49
+ "test:chat": "tsx scripts/verify-chat.ts",
44
50
  "verify:headless": "node scripts/headless-verify.mjs",
45
51
  "check:publish": "publint --strict && attw --pack . --profile esm-only",
46
52
  "prepare": "npm run build",
@@ -48,13 +54,15 @@
48
54
  },
49
55
  "devDependencies": {
50
56
  "@arethetypeswrong/cli": "0.18.4",
57
+ "@huggingface/jinja": "0.5.9",
58
+ "@huggingface/tokenizers": "0.1.3",
51
59
  "@huggingface/transformers": "4.2.0",
52
- "@types/node": "26.0.0",
53
- "@webgpu/types": "0.1.70",
60
+ "@types/node": "26.1.0",
61
+ "@webgpu/types": "0.1.71",
54
62
  "playwright-core": "1.61.1",
55
63
  "publint": "0.3.21",
56
64
  "tsdown": "0.22.3",
57
- "tsx": "4.22.4",
65
+ "tsx": "4.23.0",
58
66
  "typescript": "6.0.3"
59
67
  }
60
68
  }